OSDN Git Service

デフォルト管理画面用スキンの修正
[nucleus-jp/nucleus-next.git] / nucleus / libs / globalfunctions.php
1 <?php\r
2 \r
3 /*\r
4  * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)\r
5  * Copyright (C) 2002-2012 The Nucleus Group\r
6  *\r
7  * This program is free software; you can redistribute it and/or\r
8  * modify it under the terms of the GNU General Public License\r
9  * as published by the Free Software Foundation; either version 2\r
10  * of the License, or (at your option) any later version.\r
11  * (see nucleus/documentation/index.html#license for more info)\r
12  */\r
13 /**\r
14  * @license http://nucleuscms.org/license.txt GNU General Public License\r
15  * @copyright Copyright (C) 2002-2012 The Nucleus Group\r
16  * @version $Id: globalfunctions.php 1727 2012-04-07 02:54:22Z sakamocchi $\r
17  */\r
18 \r
19 /* needed if we include globalfunctions from install.php */\r
20 global $nucleus, $CONF, $DIR_LIBS, $DIR_LOCALES, $manager, $member;\r
21 \r
22 $nucleus['version'] = 'v4.00 SVN';\r
23 $nucleus['codename'] = '';\r
24 \r
25 /* check and die if someone is trying to override internal globals (when register_globals turn on) */\r
26 checkVars(array('nucleus', 'CONF', 'DIR_LIBS', 'MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE', 'DIR_LOCALES', 'DIR_PLUGINS', 'HTTP_GET_VARS', 'HTTP_POST_VARS', 'HTTP_COOKIE_VARS', 'HTTP_ENV_VARS', 'HTTP_SESSION_VARS', 'HTTP_POST_FILES', 'HTTP_SERVER_VARS', 'GLOBALS', 'argv', 'argc', '_GET', '_POST', '_COOKIE', '_ENV', '_SESSION', '_SERVER', '_FILES'));\r
27 \r
28 /* debug mode */\r
29 if ( !isset($CONF) )\r
30 {\r
31         $CONF = array();\r
32 }\r
33 if ( array_key_exists('debug', $CONF) && $CONF['debug'] )\r
34 {\r
35         /* report all errors! */\r
36         error_reporting(E_ALL);\r
37 }\r
38 else\r
39 {\r
40         ini_set('display_errors','0');\r
41         error_reporting(E_ERROR | E_WARNING | E_PARSE);\r
42 }\r
43 \r
44 /*\r
45  * FIXME: This is for compatibility since 4.0, should be obsoleted at future release.\r
46  */\r
47 if ( !isset($DIR_LOCALES) )\r
48 {\r
49         $DIR_LOCALES = $DIR_NUCLEUS . 'locales/';\r
50 }\r
51 global $DIR_LANG;\r
52 if ( !isset($DIR_LANG) )\r
53 {\r
54         $DIR_LANG = $DIR_LOCALES;\r
55 }\r
56 \r
57 /*\r
58  * load and initialize i18n class\r
59  */\r
60 if (!class_exists('i18n', FALSE))\r
61 {\r
62         include($DIR_LIBS . 'i18n.php');\r
63 }\r
64 if ( !i18n::init('UTF-8', $DIR_LOCALES) )\r
65 {\r
66         exit('Fail to initialize i18n class.');\r
67 }\r
68 /*\r
69  * FIXME: This is for compatibility since 4.0, should be obsoleted at future release.\r
70  */\r
71 define('_CHARSET', i18n::get_current_charset());\r
72 \r
73 /*\r
74  * Indicates when Nucleus should display startup errors. Set to 1 if you want\r
75  * the error enabled (default), false otherwise\r
76  *\r
77  * alertOnHeadersSent\r
78  *  Displays an error when visiting a public Nucleus page and headers have\r
79  *  been sent out to early. This usually indicates an error in either a\r
80  *  configuration file or a translation file, and could cause Nucleus to\r
81  *  malfunction\r
82  * alertOnSecurityRisk\r
83  * Displays an error only when visiting the admin area, and when one or\r
84  *  more of the installation files (install.php, install.sql, upgrades/\r
85  *  directory) are still on the server.\r
86  */\r
87 if ( !array_key_exists('alertOnHeadersSent', $CONF) || $CONF['alertOnHeadersSent'] !== 0 )\r
88 {\r
89         $CONF['alertOnHeadersSent'] = 1;\r
90 }\r
91 $CONF['alertOnSecurityRisk'] = 1;\r
92 /*\r
93  * NOTE: this should be removed when releasing 4.0\r
94 $CONF['ItemURL']           = $CONF['Self'];\r
95 $CONF['ArchiveURL']          = $CONF['Self'];\r
96 $CONF['ArchiveListURL']      = $CONF['Self'];\r
97 $CONF['MemberURL']           = $CONF['Self'];\r
98 $CONF['SearchURL']           = $CONF['Self'];\r
99 $CONF['BlogURL']             = $CONF['Self'];\r
100 $CONF['CategoryURL']         = $CONF['Self'];\r
101 */\r
102 \r
103 /*\r
104  * Set these to 1 to allow viewing of future items or draft items\r
105  * Should really never do this, but can be useful for some plugins that might need to\r
106  * Could cause some other issues if you use future posts otr drafts\r
107  * So use with care\r
108  */\r
109 $CONF['allowDrafts'] = 0;\r
110 $CONF['allowFuture'] = 0;\r
111 \r
112 if ( getNucleusPatchLevel() > 0 )\r
113 {\r
114         $nucleus['version'] .= '/' . getNucleusPatchLevel();\r
115 }\r
116 \r
117 /* Avoid notices */\r
118 if ( !isset($CONF['installscript']) )\r
119 {\r
120         $CONF['installscript'] = 0;\r
121 }\r
122 \r
123 /* we will use postVar, getVar, ... methods instead of $_GET, $_POST ...*/\r
124 if ( $CONF['installscript'] != 1 )\r
125 {\r
126         /* vars were already included in install.php */\r
127         include_once($DIR_LIBS . 'vars4.1.0.php');\r
128 }\r
129 \r
130 /* sanitize option */\r
131 $bLoggingSanitizedResult=0;\r
132 $bSanitizeAndContinue=0;\r
133 \r
134 $orgRequestURI = serverVar('REQUEST_URI');\r
135 sanitizeParams();\r
136 \r
137 /* get all variables that can come from the request and put them in the global scope */\r
138 $blogid       = requestVar('blogid');\r
139 $itemid       = intRequestVar('itemid');\r
140 $catid        = intRequestVar('catid');\r
141 $skinid       = requestVar('skinid');\r
142 $memberid     = requestVar('memberid');\r
143 $archivelist  = requestVar('archivelist');\r
144 $imagepopup   = requestVar('imagepopup');\r
145 $archive      = requestVar('archive');\r
146 $query        = requestVar('query');\r
147 $highlight    = requestVar('highlight');\r
148 $amount       = requestVar('amount');\r
149 $action       = requestVar('action');\r
150 $nextaction   = requestVar('nextaction');\r
151 $maxresults   = requestVar('maxresults');\r
152 $startpos     = intRequestVar('startpos');\r
153 $errormessage = '';\r
154 $error        = '';\r
155 $special      = requestVar('special');\r
156 $virtualpath  = ((getVar('virtualpath') != null) ? getVar('virtualpath') : serverVar('PATH_INFO'));\r
157 \r
158 if ( !headers_sent() )\r
159 {\r
160         header('Generator: Nucleus CMS ' . $nucleus['version']);\r
161 }\r
162 \r
163 /*\r
164  * NOTE: Since 4.0 release, Entity class becomes to be important class\r
165  *  with some wrapper functions for htmlspechalchars/htmlentity PHP's built-in function\r
166 */\r
167 include($DIR_LIBS . 'ENTITY.php');\r
168 \r
169 /* include core classes that are needed for login & plugin handling */\r
170 include_once($DIR_LIBS . 'mysql.php');\r
171 /* added for 3.5 sql_* wrapper */\r
172 global $MYSQL_HANDLER;\r
173 if ( !isset($MYSQL_HANDLER) )\r
174 {\r
175         $MYSQL_HANDLER = array('mysql','');\r
176 }\r
177 if ( $MYSQL_HANDLER[0] == '' )\r
178 {\r
179         $MYSQL_HANDLER[0] = 'mysql';\r
180 }\r
181 include_once($DIR_LIBS . 'sql/'.$MYSQL_HANDLER[0].'.php');\r
182 /* end new for 3.5 sql_* wrapper */\r
183 include($DIR_LIBS . 'MEMBER.php');\r
184 include($DIR_LIBS . 'ACTIONLOG.php');\r
185 include($DIR_LIBS . 'MANAGER.php');\r
186 include($DIR_LIBS . 'PLUGIN.php');\r
187 \r
188 $manager =& Manager::instance();\r
189 \r
190 /*\r
191  * make sure there's no unnecessary escaping:\r
192  * set_magic_quotes_runtime(0);\r
193  */\r
194 if ( version_compare(PHP_VERSION, '5.3.0', '<') )\r
195 {\r
196         ini_set('magic_quotes_runtime', '0');\r
197 }\r
198 \r
199 /* Avoid notices */\r
200 if ( !array_key_exists('UsingAdminArea', $CONF) )\r
201 {\r
202         $CONF['UsingAdminArea'] = 0;\r
203 }\r
204 \r
205 /* only needed when updating logs */\r
206 if ( $CONF['UsingAdminArea'] )\r
207 {\r
208         /* XML-RPC client classes */\r
209         include($DIR_LIBS . 'xmlrpc.inc.php');\r
210         include_once($DIR_LIBS . 'ADMIN.php');\r
211 }\r
212 \r
213 /* connect to database */\r
214 sql_connect();\r
215 $SQLCount = 0;\r
216 \r
217 /* logs sanitized result if need */\r
218 if ( $orgRequestURI!==serverVar('REQUEST_URI') )\r
219 {\r
220         $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";\r
221         $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');\r
222         if ( $bLoggingSanitizedResult )\r
223         {\r
224         addToLog(WARNING, $msg);\r
225         }\r
226         if ( !$bSanitizeAndContinue )\r
227         {\r
228                 die("");\r
229         }\r
230 }\r
231 \r
232 /* makes sure database connection gets closed on script termination */\r
233 register_shutdown_function('sql_disconnect');\r
234 \r
235 /* read config */\r
236 getConfig();\r
237 \r
238 /*\r
239  * FIXME: This is for backward compatibility, should be obsoleted near future.\r
240  */\r
241 if ( !preg_match('#^(.+)_(.+)_(.+)$#', $CONF['Locale'])\r
242   && ($CONF['Locale'] = i18n::convert_old_language_file_name_to_locale($CONF['Locale'])) === FALSE )\r
243 {\r
244         $CONF['Locale'] = 'en_Latn_US';\r
245 }\r
246 if ( !array_key_exists('Language', $CONF) )\r
247 {\r
248         $CONF['Language'] = i18n::convert_locale_to_old_language_file_name($CONF['Locale']);\r
249 }\r
250 $locale = $CONF['Locale'];\r
251 \r
252 /* Properly set $CONF['Self'] and others if it's not set...\r
253  * usually when we are access from admin menu\r
254  */\r
255 if ( !array_key_exists('Self', $CONF) )\r
256 {\r
257         $CONF['Self'] = $CONF['IndexURL'];\r
258         /* strip trailing */\r
259         if ( $CONF['Self'][i18n::strlen($CONF['Self']) -1] == "/" )\r
260         {\r
261                 $CONF['Self'] = i18n::substr($CONF['Self'], 0, i18n::strlen($CONF['Self']) -1);\r
262         }\r
263 }\r
264 \r
265 $CONF['ItemURL'] = $CONF['Self'];\r
266 $CONF['ArchiveURL'] = $CONF['Self'];\r
267 $CONF['ArchiveListURL'] = $CONF['Self'];\r
268 $CONF['MemberURL'] = $CONF['Self'];\r
269 $CONF['SearchURL'] = $CONF['Self'];\r
270 $CONF['BlogURL'] = $CONF['Self'];\r
271 $CONF['CategoryURL'] = $CONF['Self'];\r
272 \r
273 /*\r
274  *switch URLMode back to normal when $CONF['Self'] ends in .php\r
275  * this avoids urls like index.php/item/13/index.php/item/15\r
276  */\r
277 if ( !array_key_exists('URLMode', $CONF)\r
278  || (($CONF['URLMode'] == 'pathinfo')\r
279   && (i18n::substr($CONF['Self'], i18n::strlen($CONF['Self']) - 4) == '.php')) )\r
280 {\r
281         $CONF['URLMode'] = 'normal';\r
282 }\r
283 \r
284 /* automatically use simpler toolbar for mozilla */\r
285 if ( ($CONF['DisableJsTools'] == 0)\r
286    && i18n::strpos(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0') !== FALSE\r
287    && i18n::strpos(serverVar('HTTP_USER_AGENT'), 'Gecko') !== FALSE )\r
288 {\r
289         $CONF['DisableJsTools'] = 2;\r
290 }\r
291 \r
292 $member = new Member();\r
293 \r
294 if ( $action == 'login' )\r
295 {\r
296         $login = postVar('login');\r
297         $password = postVar('password');\r
298         $shared = intPostVar('shared');\r
299         $member->login($login, $password, $shared);\r
300 }\r
301 elseif ( ($action == 'logout') )\r
302 {\r
303         $member->logout();\r
304 }\r
305 else\r
306 {\r
307         $member->cookielogin();\r
308 }\r
309 \r
310 /* NOTE: include translation file and set locale */\r
311 if ( $member->isLoggedIn() && $member->getLocale())\r
312 {\r
313         $locale = $member->getLocale();\r
314 }\r
315 include_translation($locale);\r
316 i18n::set_current_locale($locale);\r
317 \r
318 /* login completed */\r
319 $manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );\r
320 \r
321 /* next action */\r
322 if ( $member->isLoggedIn() && $nextaction )\r
323 {\r
324         $action = $nextaction;\r
325 }\r
326 \r
327 /*\r
328  * Release ticket for plugin\r
329  */\r
330 ticketForPlugin();\r
331 \r
332 /* first, let's see if the site is disabled or not. always allow admin area access. */\r
333 if ( $CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea'] )\r
334 {\r
335         redirect($CONF['DisableSiteURL']);\r
336         exit;\r
337 }\r
338 \r
339 /* load other classes */\r
340 include($DIR_LIBS . 'PARSER.php');\r
341 include($DIR_LIBS . 'SKIN.php');\r
342 include($DIR_LIBS . 'TEMPLATE.php');\r
343 include($DIR_LIBS . 'BLOG.php');\r
344 include($DIR_LIBS . 'BODYACTIONS.php');\r
345 include($DIR_LIBS . 'COMMENTS.php');\r
346 include($DIR_LIBS . 'COMMENT.php');\r
347 include($DIR_LIBS . 'NOTIFICATION.php');\r
348 include($DIR_LIBS . 'BAN.php');\r
349 include($DIR_LIBS . 'SEARCH.php');\r
350 include($DIR_LIBS . 'LINK.php');\r
351 \r
352 /* set lastVisit cookie (if allowed) */\r
353 if ( !headers_sent() )\r
354 {\r
355         if ( $CONF['LastVisit'] )\r
356         {\r
357                 setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);\r
358         }\r
359         else\r
360         {\r
361                 setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);\r
362         }\r
363 }\r
364 \r
365 if ( !defined('_ARCHIVETYPE_MONTH') )\r
366 {\r
367         define('_ARCHIVETYPE_DAY', 'day');\r
368         define('_ARCHIVETYPE_MONTH', 'month');\r
369         define('_ARCHIVETYPE_YEAR', 'year');\r
370 }\r
371 \r
372 /* decode path_info */\r
373 if ( $CONF['URLMode'] == 'pathinfo' )\r
374 {\r
375         /* initialize keywords if this hasn't been done before */\r
376         if ( !isset($CONF['ItemKey']) || $CONF['ItemKey'] == '' )\r
377         {\r
378                 $CONF['ItemKey'] = 'item';\r
379         }\r
380         \r
381         if ( !isset($CONF['ArchiveKey']) || $CONF['ArchiveKey'] == '' )\r
382         {\r
383                 $CONF['ArchiveKey'] = 'archive';\r
384         }\r
385         \r
386         if ( !isset($CONF['ArchivesKey']) || $CONF['ArchivesKey'] == '' )\r
387         {\r
388                 $CONF['ArchivesKey'] = 'archives';\r
389         }\r
390         \r
391         if ( !isset($CONF['MemberKey']) || $CONF['MemberKey'] == '' )\r
392         {\r
393                 $CONF['MemberKey'] = 'member';\r
394         }\r
395         \r
396         if ( !isset($CONF['BlogKey']) || $CONF['BlogKey'] == '' )\r
397         {\r
398                 $CONF['BlogKey'] = 'blog';\r
399         }\r
400         \r
401         if ( !isset($CONF['CategoryKey']) || $CONF['CategoryKey'] == '' )\r
402         {\r
403                 $CONF['CategoryKey'] = 'category';\r
404         }\r
405         \r
406         if ( !isset($CONF['SpecialskinKey']) || $CONF['SpecialskinKey'] == '' )\r
407         {\r
408                 $CONF['SpecialskinKey'] = 'special';\r
409         }\r
410         \r
411         $parsed = false;\r
412         $manager->notify(\r
413                 'ParseURL',\r
414                 array(\r
415                         /* e.g. item, blog, ... */\r
416                         'type' => basename(serverVar('SCRIPT_NAME') ),\r
417                         'info' => $virtualpath,\r
418                         'complete' => &$parsed\r
419                 )\r
420         );\r
421         \r
422         if ( !$parsed )\r
423         {\r
424                 /* default implementation */\r
425                 $data = preg_split("#/#", $virtualpath );\r
426                 for ( $i = 0; $i < sizeof($data); $i++ )\r
427                 {\r
428                         switch ( $data[$i] )\r
429                         {\r
430                                 /* item/1 (blogid) */\r
431                                 case $CONF['ItemKey']:\r
432                                         $i++;\r
433                                         \r
434                                         if ( $i < sizeof($data) )\r
435                                         {\r
436                                                 $itemid = intval($data[$i]);\r
437                                         }\r
438                                         break;\r
439                                 \r
440                                 /* archives/1 (blogid) */\r
441                                 case $CONF['ArchivesKey']:\r
442                                                 $i++;\r
443                                                 if ( $i < sizeof($data) )\r
444                                                 {\r
445                                                         $archivelist = intval($data[$i]);\r
446                                                 }\r
447                                                 break;\r
448                                         \r
449                                 /* two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid) */\r
450                                 case $CONF['ArchiveKey']:\r
451                                         if ( (($i + 1) < sizeof($data) ) && (i18n::strpos($data[$i + 1], '-') === FALSE ) )\r
452                                         {\r
453                                                 $blogid = (integer) $data[++$i];\r
454                                         }\r
455                                         $i++;\r
456                                         if ( $i < sizeof($data) )\r
457                                         {\r
458                                                 $archive = $data[$i];\r
459                                         }\r
460                                         break;\r
461                                         \r
462                                 /* blogid/1 */\r
463                                 case 'blogid':\r
464                                 /* blog/1 */\r
465                                 case $CONF['BlogKey']:\r
466                                         $i++;\r
467                                         if ( $i < sizeof($data) )\r
468                                         {\r
469                                                 $blogid = intval($data[$i]);\r
470                                         }\r
471                                         break;\r
472                                 \r
473                                 /* category/1 (catid) */\r
474                                 case $CONF['CategoryKey']:\r
475                                 case 'catid':\r
476                                         $i++;\r
477                                         if ( $i < sizeof($data) )\r
478                                         {\r
479                                                 $catid = intval($data[$i]);\r
480                                         }\r
481                                         break;\r
482                                 \r
483                                 case $CONF['MemberKey']:\r
484                                         $i++;\r
485                                         if ( $i < sizeof($data) )\r
486                                         {\r
487                                                 $memberid = intval($data[$i]);\r
488                                         }\r
489                                         break;\r
490                                 \r
491                                 case $CONF['SpecialskinKey']:\r
492                                         $i++;\r
493                                         if ( $i < sizeof($data) )\r
494                                         {\r
495                                                 $special = $data[$i];\r
496                                                 $_REQUEST['special'] = $special;\r
497                                         }\r
498                                         break;\r
499                                 \r
500                                 default:\r
501                                         // skip...\r
502                         }\r
503                 }\r
504         }\r
505 }\r
506 \r
507 /*\r
508  * PostParseURL is a place to cleanup any of the path-related global variables before the selector function is run.\r
509  * It has 2 values in the data in case the original virtualpath is needed, but most the use will be in tweaking\r
510  * global variables to clean up (scrub out catid or add catid) or to set someother global variable based on\r
511  * the values of something like catid or itemid\r
512  * New in 3.60\r
513  */\r
514 $manager->notify(\r
515         'PostParseURL',\r
516         array(\r
517                 /* e.g. item, blog, ... */\r
518                 'type' => basename(serverVar('SCRIPT_NAME') ),\r
519                 'info' => $virtualpath\r
520         )\r
521 );\r
522 \r
523 /*\r
524  * NOTE: Here is the end of initialization\r
525  */\r
526 \r
527         /**\r
528          * This function includes or requires the specified library file\r
529          * @param string $file\r
530          * @param bool $once use the _once() version\r
531          * @param bool $require use require() instead of include()\r
532          */\r
533         function include_libs($file, $once = TRUE, $require = TRUE)\r
534         {\r
535                 global $DIR_LIBS;\r
536 \r
537                 // begin if: $DIR_LIBS isn't a directory\r
538                 if ( !is_dir($DIR_LIBS) )\r
539                 {\r
540                         exit;\r
541                 } // end if\r
542 \r
543                 $lib_path = $DIR_LIBS . $file;\r
544 \r
545                 // begin if: \r
546                 if ( $once && $require )\r
547                 {\r
548                         require_once($lib_path);\r
549                 }\r
550                 else if ( $once && !$require )\r
551                 {\r
552                         include_once($lib_path);\r
553                 }\r
554                 else if ( $require )\r
555                 {\r
556                         require($lib_path);\r
557                 }\r
558                 else\r
559                 {\r
560                         include($lib_path);\r
561                 } // end if\r
562 \r
563         }\r
564 \r
565 \r
566         /**\r
567          * This function includes or requires the specified plugin file\r
568          * @param string $file\r
569          * @param bool $once use the _once() version\r
570          * @param bool $require use require() instead of include()\r
571          */\r
572         function include_plugins($file, $once = TRUE, $require = TRUE)\r
573         {\r
574                 global $DIR_PLUGINS;\r
575 \r
576                 // begin if: $DIR_LIBS isn't a directory\r
577                 if ( !is_dir($DIR_PLUGINS) )\r
578                 {\r
579                         exit;\r
580                 } // end if\r
581 \r
582                 $plugin_path = $DIR_PLUGINS . $file;\r
583 \r
584                 // begin if: \r
585                 if ( $once && $require )\r
586                 {\r
587                         require_once($plugin_path);\r
588                 }\r
589                 else if ( $once && !$require )\r
590                 {\r
591                         include_once($plugin_path);\r
592                 }\r
593                 elseif ( $require )\r
594                 {\r
595                         require($plugin_path);\r
596                 }\r
597                 else\r
598                 {\r
599                         include($plugin_path);\r
600                 }\r
601         }\r
602         \r
603         /**\r
604          * This function decide which locale is used and include translation\r
605          * @param       string  $locale locale name referring to 'language tags' defined in RFC 5646\r
606          * @return      Void\r
607          */\r
608         function include_translation(&$locale)\r
609         {\r
610                 global $DIR_LOCALES;\r
611                 \r
612                 $translation_file = $DIR_LOCALES . $locale . '.' . i18n::get_current_charset() . '.php';\r
613                 if ( !file_exists($translation_file) )\r
614                 {\r
615                         $locale = 'en_Latn_US';\r
616                         $translation_file = $DIR_LOCALES . 'en_Latn_US.ISO-8859-1.php';\r
617                 }\r
618                 include($translation_file);\r
619                 return;\r
620         }\r
621         \r
622         /**\r
623          * This function returns the integer value of $_POST for the variable $name\r
624          * @param string $name field to get the integer value of\r
625          * @return int\r
626          */\r
627         function intPostVar($name)\r
628         {\r
629                 return intval(postVar($name));\r
630         }\r
631 \r
632 \r
633         /**\r
634          * This function returns the integer value of $_GET for the variable $name\r
635          * @param string $name field to get the integer value of\r
636          * @return int\r
637          */\r
638         function intGetVar($name)\r
639         {\r
640                 return intval(getVar($name));\r
641         }\r
642 \r
643 \r
644         /**\r
645          * This function returns the integer value of $_REQUEST for the variable $name. Also checks $_GET and $_POST if not found in $_REQUEST\r
646          * @param string $name field to get the integer value of\r
647          * @return int\r
648          */\r
649         function intRequestVar($name)\r
650         {\r
651                 return intval(requestVar($name));\r
652         }\r
653 \r
654 \r
655         /**\r
656          * This function returns the integer value of $_COOKIE for the variable $name\r
657          * @param string $name field to get the integer value of\r
658          * @return int\r
659          */\r
660         function intCookieVar($name)\r
661         {\r
662                 return intval(cookieVar($name));\r
663         }\r
664 \r
665 \r
666         /**\r
667          * This function returns the current Nucleus version (100 = 1.00, 101 = 1.01, etc...)\r
668          * @return int\r
669          */\r
670         function getNucleusVersion()\r
671         {\r
672                 return 400;\r
673         }\r
674 \r
675 \r
676         /**\r
677          * TODO: Better description of this function.\r
678          *\r
679          * Power users can install patches in between nucleus releases. These patches\r
680          * usually add new functionality in the plugin API and allow those to\r
681          * be tested without having to install CVS.\r
682          *\r
683          * @return int\r
684          */\r
685         function getNucleusPatchLevel()\r
686         {\r
687                 return 0;\r
688         }\r
689 \r
690 \r
691         /**\r
692          * This function returns the latest Nucleus version available for download from nucleuscms.org or FALSE if unable to attain data\r
693          * Format will be major.minor/patachlevel e.g. 3.41 or 3.41/02\r
694          * @return string|bool\r
695          */\r
696         function getLatestVersion()\r
697         {\r
698                 // begin if: cURL is not available in this PHP installation\r
699                 if ( !function_exists('curl_init') )\r
700                 {\r
701                         return FALSE;\r
702                 } // end if\r
703 \r
704                 $curl = curl_init();\r
705                 $timeout = 5;\r
706                 curl_setopt ($curl, CURLOPT_URL, 'http://nucleuscms.org/version_check.php');\r
707                 curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);\r
708                 curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);\r
709                 $return = curl_exec($curl);\r
710                 curl_close($curl);\r
711                 return $return;\r
712         }\r
713 \r
714 \r
715         /**\r
716          * This function returns a Nucleus table name with the appropriate prefix\r
717          * @param string $name\r
718          * @return string\r
719          */\r
720         function sql_table($name)\r
721         {\r
722                 global $MYSQL_PREFIX;\r
723 \r
724                 // begin if: no MySQL prefix\r
725                 if ( empty($MYSQL_PREFIX) )\r
726                 {\r
727                         return 'nucleus_' . $name;\r
728                 }\r
729                 // else: use MySQL prefix\r
730                 else\r
731                 {\r
732                         return $MYSQL_PREFIX . 'nucleus_' . $name;\r
733                 } // end if\r
734 \r
735         }\r
736 \r
737 \r
738         /**\r
739          * TODO: This function should be changed to send_content_type() per the Coding Guidelines. Ensure this change is compatible with rest of core.\r
740          *\r
741          * This function sends the Content-Type header if headers have not already been sent\r
742          * It also determines if the browser can accept application/xhtml+xml and sends it only to those that can.\r
743          * @param string $content_type\r
744          * @param string $page_type\r
745          * @param string $charset Deprecated. This has no meaning.\r
746          */\r
747         function sendContentType($content_type, $page_type = '', $charset = _CHARSET)\r
748         {\r
749                 global $manager, $CONF;\r
750                 \r
751                 if ( !headers_sent() )\r
752                 {\r
753                         // if content type is application/xhtml+xml, only send it to browsers\r
754                         // that can handle it (IE6 cannot). Otherwise, send text/html\r
755 \r
756                         // v2.5: For admin area pages, keep sending text/html (unless it's a debug version)\r
757                         //       application/xhtml+xml still causes too much problems with the javascript implementations\r
758 \r
759                         // v3.3: ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,\r
760                         //       application/xhtml+xml seems to be working, so we're going to use it if we can.\r
761 \r
762                         if ( ($content_type == 'application/xhtml+xml')\r
763                                 && (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') ) )\r
764                         {\r
765                                 $content_type = 'text/html';\r
766                         } // end if\r
767 \r
768                         $manager->notify(\r
769                                 'PreSendContentType',\r
770                                 array(\r
771                                         'contentType' => &$content_type,\r
772                                         'charset' => i18n::get_current_charset(),\r
773                                         'pageType' => $page_type\r
774                                 )\r
775                         );\r
776 \r
777                         // strip strange characters\r
778                         $content_type = preg_replace('|[^a-z0-9-+./]|i', '', $content_type);\r
779                         header('Content-Type: ' . $content_type . '; charset=' . i18n::get_current_charset());\r
780                 } // end if\r
781 \r
782         }\r
783 \r
784 \r
785         /**\r
786          * This function parses a query into an array of expressions that can be passed on to the highlight method\r
787          * @param string $query\r
788          */\r
789         function parseHighlight($query)\r
790         {\r
791                 // TODO: add more intelligent splitting logic\r
792                 \r
793                 // get rid of quotes\r
794                 $query = preg_replace('/\'|"/', '', $query);\r
795                 \r
796                 if ( !$query )\r
797                 {\r
798                         return array();\r
799                 }\r
800                 \r
801                 $aHighlight = preg_split('# #', $query);\r
802                 \r
803                 for ( $i = 0; $i < count($aHighlight); $i++ )\r
804                 {\r
805                         $aHighlight[$i] = trim($aHighlight[$i]);\r
806                         \r
807                         if ( i18n::strlen($aHighlight[$i]) < 3 )\r
808                         {\r
809                                 unset($aHighlight[$i]);\r
810                         }\r
811                 }\r
812                 \r
813                 if ( count($aHighlight) == 1 )\r
814                 {\r
815                         return $aHighlight[0];\r
816                 }\r
817                 else\r
818                 {\r
819                         return $aHighlight;\r
820                 }\r
821         }\r
822 \r
823 \r
824         /**\r
825          * This function gets the blog ID from the blog name\r
826          * @param string $name\r
827          * @return\r
828          */\r
829         function getBlogIDFromName($name)\r
830         {\r
831                 return quickQuery('SELECT bnumber AS result FROM ' . sql_table('blog') . ' WHERE bshortname = "' . sql_real_escape_string($name) . '"');\r
832         }\r
833 \r
834 \r
835         /**\r
836          * This function gets the blog name from the blog ID\r
837          * @param int $id\r
838          * @return object\r
839          */\r
840         function getBlogNameFromID($id)\r
841         {\r
842                 return quickQuery('SELECT bname AS result FROM ' . sql_table('blog') . ' WHERE bnumber = ' . intval($id));\r
843         }\r
844 \r
845 \r
846         /**\r
847          * This function gets the blog ID from the item ID\r
848          * @param int $item_id\r
849          * @return object\r
850          */\r
851         function getBlogIDFromItemID($item_id)\r
852         {\r
853                 return quickQuery('SELECT iblog AS result FROM ' . sql_table('item') . ' WHERE inumber = ' . intval($item_id));\r
854         }\r
855 \r
856 \r
857         /**\r
858          * This function gets the blog ID from the comment ID\r
859          * @param int $comment_id\r
860          * @return object\r
861          */\r
862         function getBlogIDFromCommentID($comment_id)\r
863         {\r
864                 return quickQuery('SELECT cblog AS result FROM ' . sql_table('comment') . ' WHERE cnumber = ' . intval($comment_id));\r
865         }\r
866 \r
867 \r
868         /**\r
869          * This function gets the blog ID from the category ID\r
870          * @param int $category_id\r
871          * @return object\r
872          */\r
873         function getBlogIDFromCatID($category_id)\r
874         {\r
875                 return quickQuery('SELECT cblog AS result FROM ' . sql_table('category') . ' WHERE catid = ' . intval($category_id));\r
876         }\r
877 \r
878 \r
879         /**\r
880          * This function gets the category ID from the category name\r
881          * @param int $name\r
882          * @return object\r
883          */\r
884         function getCatIDFromName($name)\r
885         {\r
886                 return quickQuery('SELECT catid AS result FROM ' . sql_table('category') . ' WHERE cname = "' . sql_real_escape_string($name) . '"');\r
887         }\r
888 \r
889 \r
890         /**\r
891          * This function performs a quick SQL query\r
892          * @param string $query\r
893          * @return object\r
894          */\r
895         function quickQuery($query)\r
896         {\r
897                 $res = sql_query($query);\r
898                 $obj = sql_fetch_object($res);\r
899                 return (is_object($obj)) ? $obj->result : FALSE;\r
900         }\r
901 \r
902 function getPluginNameFromPid($pid) {\r
903     $res = sql_query('SELECT pfile FROM ' . sql_table('plugin') . ' WHERE pid=' . intval($pid) );\r
904     $obj = sql_fetch_object($res);\r
905     return $obj->pfile;\r
906 //    return isset($obj->pfile) ? $obj->pfile : false;\r
907 }\r
908 \r
909 function selector()\r
910 {\r
911         global $itemid, $blogid, $memberid, $query, $amount, $archivelist, $maxresults;\r
912         global $archive, $skinid, $blog, $memberinfo, $CONF, $member;\r
913         global $imagepopup, $catid, $special;\r
914         global $manager;\r
915         \r
916         $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');\r
917         $action = requestVar('action');\r
918         \r
919         if ( in_array($action, $actionNames) )\r
920         {\r
921                 global $DIR_LIBS, $errormessage;\r
922                 include_once($DIR_LIBS . 'ACTION.php');\r
923                 $a = new Action();\r
924                 $errorInfo = $a->doAction($action);\r
925                 \r
926                 if ( $errorInfo )\r
927                 {\r
928                         $errormessage = $errorInfo['message'];\r
929                 }\r
930         }\r
931         \r
932         // show error when headers already sent out\r
933         if ( headers_sent() && $CONF['alertOnHeadersSent'] )\r
934         {\r
935                 // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)\r
936                 if ( function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') )\r
937                 {\r
938                         headers_sent($hsFile, $hsLine);\r
939                         $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';\r
940                 }\r
941                 else\r
942                 {\r
943                         $extraInfo = '';\r
944                 }\r
945                 \r
946                 startUpError(\r
947                         '<p>The page headers have already been sent out' . $extraInfo . '. This could cause Nucleus not to work in the expected way.</p><p>Usually, this is caused by spaces or newlines at the end of the <code>config.php</code> file, at the end of the translation file or at the end of a plugin file. Please check this and try again.</p><p>If you don\'t want to see this error message again, without solving the problem, set <code>$CONF[\'alertOnHeadersSent\']</code> in <code>globalfunctions.php</code> to <code>0</code></p>',\r
948                         'Page headers already sent'\r
949                 );\r
950                 exit;\r
951         }\r
952         \r
953         // make is so ?archivelist without blogname or blogid shows the archivelist\r
954         // for the default weblog\r
955         if ( serverVar('QUERY_STRING') == 'archivelist' )\r
956         {\r
957                 $archivelist = $CONF['DefaultBlog'];\r
958         }\r
959         \r
960         // now decide which type of skin we need\r
961         if ( $itemid )\r
962         {\r
963                 // itemid given -> only show that item\r
964                 $type = 'item';\r
965                 \r
966                 if ( !$manager->existsItem($itemid,intval($CONF['allowFuture']),intval($CONF['allowDrafts'])) )\r
967                 {\r
968                         doError(_ERROR_NOSUCHITEM);\r
969                 }\r
970                 \r
971                 global $itemidprev, $itemidnext, $catid, $itemtitlenext, $itemtitleprev;\r
972                 \r
973                 // 1. get timestamp, blogid and catid for item\r
974                 $query = 'SELECT itime, iblog, icat FROM %s WHERE inumber=%d';\r
975                 $query = sprintf($query, sql_table('item'), (integer) $itemid);\r
976                 $res = sql_query($query);\r
977                 $obj = sql_fetch_object($res);\r
978                 \r
979                 // if a different blog id has been set through the request or selectBlog(),\r
980                 // deny access\r
981                 \r
982                 if ( $blogid && (intval($blogid) != $obj->iblog) )\r
983                 {\r
984                         doError(_ERROR_NOSUCHITEM);\r
985                 }\r
986                 \r
987                 // if a category has been selected which doesn't match the item, ignore the\r
988                 // category. #85\r
989                 if ( ($catid != 0) && ($catid != $obj->icat) )\r
990                 {\r
991                         $catid = 0;\r
992                 }\r
993                 \r
994                 $blogid = $obj->iblog;\r
995                 $timestamp = strtotime($obj->itime);\r
996                 \r
997                 $b =& $manager->getBlog($blogid);\r
998                 \r
999                 if ( !$b->isValidCategory($catid) )\r
1000                 {\r
1001                         $query = "SELECT inumber, ititle FROM %s WHERE itime<'%s' AND idraft=0 AND iblog=%d ORDER BY itime DESC LIMIT 1";\r
1002                         $query = sprintf($query, sql_table('item'), i18n::formatted_datetime('mysql', $timestamp), $blogid);\r
1003                 }\r
1004                 else\r
1005                 {\r
1006                         $query = "SELECT inumber, ititle FROM %s WHERE itime<'%s' AND idraft=0 AND iblog=%d AND icat=%d ORDER BY itime DESC LIMIT 1";\r
1007                         $query = sprintf($query, sql_table('item'), i18n::formatted_datetime('mysql', $timestamp), $blogid, $catid);\r
1008                 }\r
1009                 \r
1010                 $res = sql_query($query);\r
1011                 $obj = sql_fetch_object($res);\r
1012                 \r
1013                 if ( $obj )\r
1014                 {\r
1015                         $itemidprev = $obj->inumber;\r
1016                         $itemtitleprev = $obj->ititle;\r
1017                 }\r
1018                 \r
1019                 // get next itemid and title\r
1020                 if ( !$b->isValidCategory($catid) )\r
1021                 {\r
1022                         $query = "SELECT inumber, ititle FROM %s WHERE itime>'%s' AND itime<='%s' AND idraft=0 AND iblog=%d ORDER BY itime ASC LIMIT 1";\r
1023                         $query = sprintf($query, sql_table('item'), i18n::formatted_datetime('mysql', $timestamp), i18n::formatted_datetime('mysql', $b->getCorrectTime()), $blogid);\r
1024                 }\r
1025                 else\r
1026                 {\r
1027                         $query = "SELECT inumber, ititle FROM %s WHERE itime>'%s' AND itime<='%s' AND idraft=0 AND iblog=%d AND icat=%d ORDER BY itime ASC LIMIT 1";\r
1028                         $query = sprintf($query, sql_table('item'), i18n::formatted_datetime('mysql', $timestamp), i18n::formatted_datetime('mysql', $b->getCorrectTime()), $blogid, $catid);\r
1029                 }\r
1030                 $res = sql_query($query);\r
1031                 \r
1032                 $obj = sql_fetch_object($res);\r
1033                 \r
1034                 if ( $obj )\r
1035                 {\r
1036                         $itemidnext = $obj->inumber;\r
1037                         $itemtitlenext = $obj->ititle;\r
1038                 }\r
1039         }\r
1040         elseif ( $archive )\r
1041         {\r
1042                 // show archive\r
1043                 $type = 'archive';\r
1044                 \r
1045                 // get next and prev month links ...\r
1046                 global $archivenext, $archiveprev, $archivetype, $archivenextexists, $archiveprevexists;\r
1047                 \r
1048                 // sql queries for the timestamp of the first and the last published item\r
1049                 $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 ORDER BY itime ASC";\r
1050                 $first_timestamp=quickQuery ($query);\r
1051                 $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 ORDER BY itime DESC";\r
1052                 $last_timestamp=quickQuery ($query);\r
1053                 \r
1054                 sscanf($archive, '%d-%d-%d', $y, $m, $d);\r
1055                 \r
1056                 if ( $d != 0 )\r
1057                 {\r
1058                         $archivetype = _ARCHIVETYPE_DAY;\r
1059                         $t = mktime(0, 0, 0, $m, $d, $y);\r
1060                         // one day has 24 * 60 * 60 = 86400 seconds\r
1061                         $archiveprev = i18n::formatted_datetime('%Y-%m-%d', $t - 86400 );\r
1062                         // check for published items\r
1063                         if ( $t > $first_timestamp )\r
1064                         {\r
1065                                 $archiveprevexists = true;\r
1066                         }\r
1067                         else\r
1068                         {\r
1069                                 $archiveprevexists = false;\r
1070                         }\r
1071                         \r
1072                         // one day later\r
1073                         $t += 86400;\r
1074                         $archivenext = i18n::formatted_datetime('%Y-%m-%d', $t);\r
1075                         if ( $t < $last_timestamp )\r
1076                         {\r
1077                                 $archivenextexists = true;\r
1078                         }\r
1079                         else\r
1080                         {\r
1081                                 $archivenextexists = false;\r
1082                         }\r
1083                 }\r
1084                 elseif ( $m == 0 )\r
1085                 {\r
1086                         $archivetype = _ARCHIVETYPE_YEAR;\r
1087                         $t = mktime(0, 0, 0, 12, 31, $y - 1);\r
1088                         // one day before is in the previous year\r
1089                         $archiveprev = i18n::formatted_datetime('%Y', $t);\r
1090                         if ( $t > $first_timestamp )\r
1091                         {\r
1092                                 $archiveprevexists = true;\r
1093                         }\r
1094                         else\r
1095                         {\r
1096                                 $archiveprevexists = false;\r
1097                         }\r
1098 \r
1099                         // timestamp for the next year\r
1100                         $t = mktime(0, 0, 0, 1, 1, $y + 1);\r
1101                         $archivenext = i18n::formatted_datetime('%Y', $t);\r
1102                         if ( $t < $last_timestamp )\r
1103                         {\r
1104                                 $archivenextexists = true;\r
1105                         }\r
1106                         else\r
1107                         {\r
1108                                 $archivenextexists = false;\r
1109                         }\r
1110                 }\r
1111                 else\r
1112                 {\r
1113                         $archivetype = _ARCHIVETYPE_MONTH;\r
1114                         $t = mktime(0, 0, 0, $m, 1, $y);\r
1115                         // one day before is in the previous month\r
1116                         $archiveprev = i18n::formatted_datetime('%Y-%m', $t - 86400);\r
1117                         if ( $t > $first_timestamp )\r
1118                         {\r
1119                                 $archiveprevexists = true;\r
1120                         }\r
1121                         else\r
1122                         {\r
1123                                 $archiveprevexists = false;\r
1124                         }\r
1125                         \r
1126                         // timestamp for the next month\r
1127                         $t = mktime(0, 0, 0, $m+1, 1, $y);\r
1128                         $archivenext = i18n::formatted_datetime('%Y-%m', $t);\r
1129                         if ( $t < $last_timestamp )\r
1130                         {\r
1131                                 $archivenextexists = true;\r
1132                         }\r
1133                         else\r
1134                         {\r
1135                                 $archivenextexists = false;\r
1136                         }\r
1137                 }\r
1138         }\r
1139         elseif ( $archivelist )\r
1140         {\r
1141                 $type = 'archivelist';\r
1142                 \r
1143                 if ( is_numeric($archivelist) )\r
1144                 {\r
1145                         $blogid = intVal($archivelist);\r
1146                 }\r
1147                 else\r
1148                 {\r
1149                         $blogid = getBlogIDFromName($archivelist);\r
1150                 }\r
1151         \r
1152                 if ( !$blogid )\r
1153                 {\r
1154                         doError(_ERROR_NOSUCHBLOG);\r
1155                 }\r
1156         }\r
1157         elseif ( $query )\r
1158         {\r
1159                 global $startpos;\r
1160                 $type = 'search';\r
1161                 $query = stripslashes($query);\r
1162                 \r
1163                 if ( is_numeric($blogid) )\r
1164                 {\r
1165                         $blogid = intVal($blogid);\r
1166                 }\r
1167                 else\r
1168                 {\r
1169                         $blogid = getBlogIDFromName($blogid);\r
1170                 }\r
1171                 \r
1172                 if ( !$blogid )\r
1173                 {\r
1174                         doError(_ERROR_NOSUCHBLOG);\r
1175                 }\r
1176         }\r
1177         elseif ( $memberid )\r
1178         {\r
1179                 $type = 'member';\r
1180                 \r
1181                 if ( !Member::existsID($memberid) )\r
1182                 {\r
1183                         doError(_ERROR_NOSUCHMEMBER);\r
1184                 }\r
1185                 $memberinfo = $manager->getMember($memberid);\r
1186         }\r
1187         elseif ( $imagepopup )\r
1188         {\r
1189                 // media object (images etc.)\r
1190                 $type = 'imagepopup';\r
1191                 \r
1192                 // TODO: check if media-object exists\r
1193                 // TODO: set some vars?\r
1194         }\r
1195         else\r
1196         {\r
1197                 // show regular index page\r
1198                 global $startpos;\r
1199                 $type = 'index';\r
1200         }\r
1201         \r
1202         // any type of skin with catid\r
1203         if ( $catid && !$blogid )\r
1204         {\r
1205                 $blogid = getBlogIDFromCatID($catid);\r
1206         }\r
1207         \r
1208         // decide which blog should be displayed\r
1209         if ( !$blogid )\r
1210         {\r
1211                 $blogid = $CONF['DefaultBlog'];\r
1212         }\r
1213         \r
1214         $b =& $manager->getBlog($blogid);\r
1215         $blog = $b; // references can't be placed in global variables?\r
1216         \r
1217         if ( !$blog->isValid )\r
1218         {\r
1219                 doError(_ERROR_NOSUCHBLOG);\r
1220         }\r
1221         \r
1222         // set catid if necessary\r
1223         if ( $catid )\r
1224         {\r
1225                 // check if the category is valid\r
1226                 if ( !$blog->isValidCategory($catid) )\r
1227                 {\r
1228                         doError(_ERROR_NOSUCHCATEGORY);\r
1229                 }\r
1230                 else\r
1231                 {\r
1232                         $blog->setSelectedCategory($catid);\r
1233                 }\r
1234         }\r
1235         \r
1236         // decide which skin should be used\r
1237         if ( $skinid != '' && ($skinid == 0) )\r
1238         {\r
1239                 selectSkin($skinid);\r
1240         }\r
1241         \r
1242         if ( !$skinid )\r
1243         {\r
1244                 $skinid = $blog->getDefaultSkin();\r
1245         }\r
1246         \r
1247         //$special = requestVar('special'); //get at top of file as global\r
1248         if ( !empty($special) && isValidShortName($special) )\r
1249         {\r
1250                 $type = strtolower($special);\r
1251         }\r
1252         \r
1253         $skin = new SKIN($skinid);\r
1254         \r
1255         if ( !$skin->isValid() )\r
1256         {\r
1257                 doError(_ERROR_NOSUCHSKIN);\r
1258         }\r
1259         \r
1260         // set global skinpart variable so can determine quickly what is being parsed from any plugin or phpinclude\r
1261         global $skinpart;\r
1262         $skinpart = $type;\r
1263         \r
1264         // parse the skin\r
1265         $skin->parse($type);\r
1266         \r
1267         // check to see we should throw JustPosted event\r
1268         $blog->checkJustPosted();\r
1269         return;\r
1270 }\r
1271 \r
1272 /**\r
1273   * Show error skin with given message. An optional skin-object to use can be given\r
1274   */\r
1275 function doError($msg, $skin = '')\r
1276 {\r
1277         global $errormessage, $CONF, $skinid, $blogid, $manager;\r
1278         \r
1279         if ( $skin == '' )\r
1280         {\r
1281                 if ( Skin::existsID($skinid) )\r
1282                 {\r
1283                         $id = $skinid;\r
1284                 }\r
1285                 elseif ( $manager->existsBlogID($blogid) )\r
1286                 {\r
1287                         $blog =& $manager->getBlog($blogid);\r
1288                         $id = $blog->getDefaultSkin();\r
1289                 }\r
1290                 elseif ($CONF['DefaultBlog'] )\r
1291                 {\r
1292                         $blog =& $manager->getBlog($CONF['DefaultBlog']);\r
1293                         $id = $blog->getDefaultSkin();\r
1294                 }\r
1295                 else\r
1296                 {\r
1297                         // this statement should actually never be executed\r
1298                         $id = $CONF['BaseSkin'];\r
1299                 }\r
1300                 $skin = new Skin($id);\r
1301         }\r
1302         \r
1303         $skinid = $skin->getID();\r
1304         $errormessage = $msg;\r
1305         $skin->parse('error');\r
1306         exit;\r
1307 }\r
1308 \r
1309 function getConfig() {\r
1310     global $CONF;\r
1311 \r
1312     $query = 'SELECT * FROM ' . sql_table('config');\r
1313     $res = sql_query($query);\r
1314 \r
1315     while ($obj = sql_fetch_object($res) ) {\r
1316         $CONF[$obj->name] = $obj->value;\r
1317     }\r
1318 }\r
1319 \r
1320 // some checks for names of blogs, categories, templates, members, ...\r
1321 function isValidShortName($name) {\r
1322 \r
1323         # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
1324         # original eregi: eregi('^[a-z0-9]+$', $name)\r
1325 \r
1326         return preg_match('#^[a-z0-9]+$#i', $name);\r
1327 \r
1328 }\r
1329 \r
1330 function isValidDisplayName($name) {\r
1331 \r
1332         # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
1333         # original eregi: eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name)\r
1334 \r
1335         return preg_match('#^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$#i', $name);\r
1336 \r
1337 }\r
1338 \r
1339 function isValidCategoryName($name) {\r
1340     return 1;\r
1341 }\r
1342 \r
1343 function isValidTemplateName($name) {\r
1344 \r
1345         # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
1346         # original eregi: eregi('^[a-z0-9/]+$', $name)\r
1347         // added - and _ to valid characters as of 4.00\r
1348 \r
1349         return preg_match('#^[a-z0-9/_\-]+$#i', $name);\r
1350 \r
1351 }\r
1352 \r
1353 function isValidSkinName($name) {\r
1354 \r
1355         # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
1356         # original eregi: eregi('^[a-z0-9/]+$', $name);\r
1357         // added - and _ to valid characters as of 4.00\r
1358 \r
1359         return preg_match('#^[a-z0-9/_\-]+$#i', $name);\r
1360 \r
1361 }\r
1362 \r
1363 // add and remove linebreaks\r
1364 function addBreaks($var) {\r
1365     return nl2br($var);\r
1366 }\r
1367 \r
1368 function removeBreaks($var) {\r
1369     return preg_replace("/<br \/>([\r\n])/", "$1", $var);\r
1370 }\r
1371 \r
1372 /**\r
1373   * functions for use in index.php\r
1374   */\r
1375 function selectBlog($shortname) {\r
1376     global $blogid, $archivelist;\r
1377     $blogid = getBlogIDFromName($shortname);\r
1378 \r
1379     // also force archivelist variable, if it is set\r
1380     if ($archivelist) {\r
1381         $archivelist = $blogid;\r
1382     }\r
1383 }\r
1384 \r
1385 function selectSkin($skinname) {\r
1386     global $skinid;\r
1387     $skinid = SKIN::getIdFromName($skinname);\r
1388 }\r
1389 \r
1390 /**\r
1391  * Can take either a category ID or a category name (be aware that\r
1392  * multiple categories can have the same name)\r
1393  */\r
1394 function selectCategory($cat) {\r
1395     global $catid;\r
1396     if (is_numeric($cat) ) {\r
1397         $catid = intval($cat);\r
1398     } else {\r
1399         $catid = getCatIDFromName($cat);\r
1400     }\r
1401 }\r
1402 \r
1403 function selectItem($id) {\r
1404     global $itemid;\r
1405     $itemid = intval($id);\r
1406 }\r
1407 \r
1408 function parseFile($filename, $includeMode = 'normal', $includePrefix = '')\r
1409 {\r
1410         global $skinid;\r
1411 \r
1412         if ( !$skinid || !existsID($skinid) )\r
1413         {\r
1414                 $skin = new Skin($CONF['BaseSkin']);\r
1415         }\r
1416         else\r
1417         {\r
1418                 $skin = new Skin($skinid);\r
1419     }\r
1420 \r
1421         $oldIncludeMode = Parser::getProperty('IncludeMode');\r
1422         $oldIncludePrefix = Parser::getProperty('IncludePrefix');\r
1423 \r
1424         $skin->parse('fileparse', $filename);\r
1425 \r
1426         Parser::setProperty('IncludeMode', $oldIncludeMode);\r
1427         Parser::setProperty('IncludePrefix', $oldIncludePrefix);\r
1428 \r
1429         return;\r
1430 }\r
1431 \r
1432 /**\r
1433   * Outputs a debug message\r
1434   */\r
1435 function debug($msg) {\r
1436     echo '<p><b>' . $msg . "</b></p>\n";\r
1437 }\r
1438 \r
1439 // shortcut\r
1440 function addToLog($level, $msg) {\r
1441     ActionLog::add($level, $msg);\r
1442 }\r
1443 \r
1444 // shows a link to help file\r
1445 function help($id) {\r
1446     echo helpHtml($id);\r
1447 }\r
1448 \r
1449 function helpHtml($id) {\r
1450     global $CONF;\r
1451     return helplink($id) . '<img src="' . $CONF['AdminURL'] . 'documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" title="' . _HELP_TT . '" /></a>';\r
1452 }\r
1453 \r
1454 function helplink($id) {\r
1455     global $CONF;\r
1456     return '<a href="' . $CONF['AdminURL'] . 'documentation/help.html#'. $id . '" onclick="if (event &amp;&amp; event.preventDefault) event.preventDefault(); return help(this.href);">';\r
1457 }\r
1458 \r
1459 /**\r
1460   * Includes a PHP file. This method can be called while parsing templates and skins\r
1461   */\r
1462 function includephp($filename) {\r
1463     // make predefined variables global, so most simple scripts can be used here\r
1464 \r
1465     // apache (names taken from PHP doc)\r
1466     global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;\r
1467     global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;\r
1468     global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;\r
1469     global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;\r
1470     global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;\r
1471     global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;\r
1472     global $REQUEST_URI;\r
1473 \r
1474     // php (taken from PHP doc)\r
1475     global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;\r
1476     global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;\r
1477 \r
1478     // other\r
1479     global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;\r
1480 \r
1481     if (@file_exists($filename) ) {\r
1482         include($filename);\r
1483     }\r
1484 }\r
1485 \r
1486 /**\r
1487  * Checks if a certain plugin exists\r
1488  * @param string $plug\r
1489  * @return bool\r
1490  **/\r
1491 function checkPlugin($plug) {\r
1492 \r
1493         global $DIR_PLUGINS;\r
1494 \r
1495         # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0\r
1496         # original ereg_replace: ereg_replace( '[\\|/]', '', $plug) . '.php')\r
1497         # important note that '\' must be matched with '\\\\' in preg* expressions\r
1498 \r
1499         return file_exists($DIR_PLUGINS . preg_replace('#[\\\\|/]#', '', $plug) . '.php');\r
1500 \r
1501 }\r
1502 \r
1503 /**\r
1504  * alterQueryStr()\r
1505  * \r
1506  * @param       string  $querystr       querystring to alter (e.g. foo=1&bar=2&x=y)\r
1507  * @param       string  $param  name of parameter to change (e.g. 'foo')\r
1508  * @param       string  $value  New value for that parameter (e.g. 3)\r
1509  * @result      string  altered query string (for the examples above: foo=3&bar=2&x=y)\r
1510  */\r
1511 function alterQueryStr($querystr, $param, $value)\r
1512 {\r
1513         $vars = preg_split('#&#', $querystr);\r
1514         $set = FALSE;\r
1515         \r
1516         for ( $i = 0; $i < count($vars); $i++ )\r
1517         {\r
1518                 $v = preg_split('#=#', $vars[$i]);\r
1519                 \r
1520                 if ( $v[0] == $param )\r
1521                 {\r
1522                         $v[1] = $value;\r
1523                         $vars[$i] = implode('=', $v);\r
1524                         $set = true;\r
1525                         break;\r
1526                 }\r
1527         }\r
1528         if ( !$set )\r
1529         {\r
1530                 $vars[] = "{$param}={$value}";\r
1531         }\r
1532         return ltrim(implode('&', $vars), '&');\r
1533 }\r
1534 \r
1535 // passes one variable as hidden input field (multiple fields for arrays)\r
1536 // @see passRequestVars in varsx.x.x.php\r
1537 function passVar($key, $value) {\r
1538     // array ?\r
1539     if (is_array($value) ) {\r
1540         for ($i = 0; $i < sizeof($value); $i++) {\r
1541             passVar($key . '[' . $i . ']', $value[$i]);\r
1542         }\r
1543 \r
1544         return;\r
1545     }\r
1546 \r
1547     // other values: do stripslashes if needed\r
1548     ?><input type="hidden" name="<?php echo Entity::hsc($key)?>" value="<?php echo Entity::hsc(undoMagic($value) )?>" /><?php\r
1549 }\r
1550 \r
1551 function checkVars($aVars) {\r
1552     global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;\r
1553 \r
1554     foreach ($aVars as $varName) {\r
1555 \r
1556         if (phpversion() >= '4.1.0') {\r
1557 \r
1558             if (   isset($_GET[$varName])\r
1559                 || isset($_POST[$varName])\r
1560                 || isset($_COOKIE[$varName])\r
1561                 || isset($_ENV[$varName])\r
1562                 || isset($_SESSION[$varName])\r
1563                 || isset($_FILES[$varName])\r
1564             ) {\r
1565                 die('Sorry. An error occurred.');\r
1566             }\r
1567 \r
1568         } else {\r
1569 \r
1570             if (   isset($HTTP_GET_VARS[$varName])\r
1571                 || isset($HTTP_POST_VARS[$varName])\r
1572                 || isset($HTTP_COOKIE_VARS[$varName])\r
1573                 || isset($HTTP_ENV_VARS[$varName])\r
1574                 || isset($HTTP_SESSION_VARS[$varName])\r
1575                 || isset($HTTP_POST_FILES[$varName])\r
1576             ) {\r
1577                 die('Sorry. An error occurred.');\r
1578             }\r
1579 \r
1580         }\r
1581     }\r
1582 }\r
1583 \r
1584 \r
1585 /**\r
1586  * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.\r
1587  * to avoid XSS\r
1588  */\r
1589 function sanitizeParams()\r
1590 {\r
1591     global $HTTP_SERVER_VARS;\r
1592 \r
1593     $array = array();\r
1594     $str = '';\r
1595     $frontParam = '';\r
1596 \r
1597     // REQUEST_URI of $HTTP_SERVER_VARS\r
1598     $str =& $HTTP_SERVER_VARS["REQUEST_URI"];\r
1599     serverStringToArray($str, $array, $frontParam);\r
1600     sanitizeArray($array);\r
1601     arrayToServerString($array, $frontParam, $str);\r
1602 \r
1603     // QUERY_STRING of $HTTP_SERVER_VARS\r
1604     $str =& $HTTP_SERVER_VARS["QUERY_STRING"];\r
1605     serverStringToArray($str, $array, $frontParam);\r
1606     sanitizeArray($array);\r
1607     arrayToServerString($array, $frontParam, $str);\r
1608 \r
1609     if (phpversion() >= '4.1.0') {\r
1610         // REQUEST_URI of $_SERVER\r
1611         $str =& $_SERVER["REQUEST_URI"];\r
1612         serverStringToArray($str, $array, $frontParam);\r
1613         sanitizeArray($array);\r
1614         arrayToServerString($array, $frontParam, $str);\r
1615 \r
1616         // QUERY_STRING of $_SERVER\r
1617         $str =& $_SERVER["QUERY_STRING"];\r
1618         serverStringToArray($str, $array, $frontParam);\r
1619         sanitizeArray($array);\r
1620         arrayToServerString($array, $frontParam, $str);\r
1621     }\r
1622 \r
1623     // $_GET\r
1624     convArrayForSanitizing($_GET, $array);\r
1625     sanitizeArray($array);\r
1626     revertArrayForSanitizing($array, $_GET);\r
1627 \r
1628     // $_REQUEST (only GET param)\r
1629     convArrayForSanitizing($_REQUEST, $array);\r
1630     sanitizeArray($array);\r
1631     revertArrayForSanitizing($array, $_REQUEST);\r
1632 }\r
1633 \r
1634 /**\r
1635  * ticketForPlugin()\r
1636  * \r
1637  * Check ticket when not checked in plugin's admin page\r
1638  * to avoid CSRF.\r
1639  * Also avoid the access to plugin/index.php by guest user.\r
1640  */\r
1641 function ticketForPlugin()\r
1642 {\r
1643         global $CONF, $DIR_PLUGINS, $member, $ticketforplugin;\r
1644         \r
1645         /* initialize */\r
1646         $ticketforplugin = array();\r
1647         $ticketforplugin['ticket'] = FALSE;\r
1648         \r
1649         /* $_SERVER['PATH_TRANSLATED']\r
1650          * http://www.php.net/manual/en/reserved.variables.server.php\r
1651          * Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly\r
1652          * under the Apache 2 SAPI in contrast to the situation in Apache 1,\r
1653          * where it's set to the same value as the SCRIPT_FILENAME server variable\r
1654          * when it's not populated by Apache.\r
1655          * This change was made to comply with the CGI specification\r
1656          * that PATH_TRANSLATED should only exist if PATH_INFO is defined.\r
1657          * Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO. \r
1658          */\r
1659         \r
1660         /* Check if using plugin's php file. */\r
1661         $p_translated = serverVar('SCRIPT_FILENAME');\r
1662         \r
1663         if (!file_exists($p_translated) )\r
1664         {\r
1665                 header("HTTP/1.0 404 Not Found");\r
1666                 exit('');\r
1667         }\r
1668         \r
1669         $p_translated = str_replace('\\', '/', $p_translated);\r
1670         $d_plugins = str_replace('\\', '/', $DIR_PLUGINS);\r
1671         \r
1672         // This isn't plugin php file.\r
1673         if ( i18n::strpos($p_translated, $d_plugins) !== 0 )\r
1674         {\r
1675                 return;\r
1676         }\r
1677 \r
1678         // Solve the plugin php file or admin directory\r
1679         $phppath = i18n::substr($p_translated, i18n::strlen($d_plugins) );\r
1680         // Remove the first "/" if exists.\r
1681         $phppath = preg_replace('#^/#', '', $phppath);\r
1682         // Remove the first "NP_" and the last ".php" if exists.\r
1683         $path = preg_replace('#^NP_(.*)\.php$#', '$1', $phppath);\r
1684         // Remove the "/" and beyond.\r
1685         $path = preg_replace('#^([^/]*)/(.*)$#', '$1', $path);\r
1686         \r
1687         // Solve the plugin name.\r
1688         $plugins = array();\r
1689         $query = 'SELECT pfile FROM '.sql_table('plugin');\r
1690         $res = sql_query($query);\r
1691         \r
1692         while($row = sql_fetch_row($res) )\r
1693         {\r
1694                 $name = i18n::substr($row[0], 3);\r
1695                 $plugins[strtolower($name)] = $name;\r
1696         }\r
1697         \r
1698         sql_free_result($res);\r
1699         \r
1700         if (array_key_exists($path, $plugins))\r
1701         {\r
1702                 $plugin_name = $plugins[$path];\r
1703         }\r
1704         else if (in_array($path, $plugins))\r
1705         {\r
1706                 $plugin_name = $path;\r
1707         }\r
1708         else\r
1709         {\r
1710                 header("HTTP/1.0 404 Not Found");\r
1711                 exit('');\r
1712         }\r
1713         \r
1714         /* Return if not index.php */\r
1715         if ( ($phppath != strtolower($plugin_name) . '/') && ($phppath != strtolower($plugin_name) . '/index.php') )\r
1716         {\r
1717                 return;\r
1718         }\r
1719         \r
1720         /* Exit if not logged in. */\r
1721         if ( !$member->isLoggedIn() )\r
1722         {\r
1723                 exit('You aren\'t logged in.');\r
1724         }\r
1725         \r
1726         global $manager, $DIR_LIBS, $DIR_LOCALES, $HTTP_GET_VARS, $HTTP_POST_VARS;\r
1727         \r
1728         /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */\r
1729         if (!($p_translated = serverVar('PATH_TRANSLATED') ) )\r
1730         {\r
1731                 $p_translated = serverVar('SCRIPT_FILENAME');\r
1732         }\r
1733         \r
1734         if ($file = @file($p_translated) )\r
1735         {\r
1736                 $prevline = '';\r
1737                 \r
1738                 foreach($file as $line)\r
1739                 {\r
1740                         if (preg_match('/[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]/i', $prevline . $line) )\r
1741                         {\r
1742                                 return;\r
1743                         }\r
1744                         \r
1745                         $prevline = $line;\r
1746                 }\r
1747         }\r
1748         \r
1749         /* Show a form if not valid ticket */\r
1750         if ( ( i18n::strpos(serverVar('REQUEST_URI'), '?') !== FALSE || serverVar('QUERY_STRING')\r
1751          || strtoupper(serverVar('REQUEST_METHOD') ) == 'POST')\r
1752          && (!$manager->checkTicket() ) )\r
1753         {\r
1754                 $oPluginAdmin = new PluginAdmin($plugin_name);\r
1755                 $oPluginAdmin->start();\r
1756                 echo '<p>' . _ERROR_BADTICKET . "</p>\n";\r
1757                 \r
1758                 /* Show the form to confirm action */\r
1759                 // PHP 4.0.x support\r
1760                 $get = (isset($_GET) ) ? $_GET : $HTTP_GET_VARS;\r
1761                 $post = (isset($_POST) ) ? $_POST : $HTTP_POST_VARS;\r
1762                 \r
1763                 // Resolve URI and QUERY_STRING\r
1764                 if ($uri = serverVar('REQUEST_URI') )\r
1765                 {\r
1766                         list($uri, $qstring) = preg_split('#\?#', $uri);\r
1767                 }\r
1768                 else\r
1769                 {\r
1770                         if ( !($uri = serverVar('PHP_SELF') ) )\r
1771                         {\r
1772                                 $uri = serverVar('SCRIPT_NAME');\r
1773                         }\r
1774                         $qstring = serverVar('QUERY_STRING');\r
1775                 }\r
1776                 if ($qstring)\r
1777                 {\r
1778                         $qstring = '?' . $qstring;\r
1779                 }\r
1780                 \r
1781                 echo '<p>' . _SETTINGS_UPDATE . ' : ' . _QMENU_PLUGINS . ' <span style="color:red;">' . Entity::hsc($plugin_name) . "</span> ?</p>\n";\r
1782                 \r
1783                 switch(strtoupper(serverVar('REQUEST_METHOD') ) )\r
1784                 {\r
1785                         case 'POST':\r
1786                                 echo '<form method="POST" action="'.Entity::hsc($uri.$qstring).'">';\r
1787                                 $manager->addTicketHidden();\r
1788                                 _addInputTags($post);\r
1789                                 break;\r
1790                         \r
1791                         case 'GET':\r
1792                                 echo '<form method="GET" action="'.Entity::hsc($uri).'">';\r
1793                                 $manager->addTicketHidden();\r
1794                                 _addInputTags($get);\r
1795                         \r
1796                         default:\r
1797                                 break;\r
1798                 }\r
1799                 \r
1800                 echo '<input type="submit" value="' . _YES . '" />&nbsp;&nbsp;&nbsp;&nbsp;';\r
1801                 echo '<input type="button" value="' . _NO . '" onclick="history.back(); return false;" />';\r
1802                 echo "</form>\n";\r
1803                 \r
1804                 $oPluginAdmin->end();\r
1805                 exit;\r
1806         }\r
1807         \r
1808         /* Create new ticket */\r
1809         $ticket=$manager->addTicketToUrl('');\r
1810         $ticketforplugin['ticket'] = preg_split($ticket, i18n::strpos($ticket, 'ticket=') + 7);\r
1811         return;\r
1812 }\r
1813 \r
1814 function _addInputTags(&$keys,$prefix=''){\r
1815     foreach($keys as $key=>$value){\r
1816         if ($prefix) $key=$prefix.'['.$key.']';\r
1817         if (is_array($value)) _addInputTags($value,$key);\r
1818         else {\r
1819             if (get_magic_quotes_gpc()) $value=stripslashes($value);\r
1820             if ($key=='ticket') continue;\r
1821             echo '<input type="hidden" name="'.Entity::hsc($key).\r
1822                 '" value="'.Entity::hsc($value).'" />'."\n";\r
1823         }\r
1824     }\r
1825 }\r
1826 \r
1827 /**\r
1828  * serverStringToArray()\r
1829  * Convert the server string such as $_SERVER['REQUEST_URI']\r
1830  * to arry like arry['blogid']=1 and array['page']=2 etc.\r
1831  * \r
1832  * @param       string  $str            string\r
1833  * @param       string  $array          \r
1834  * @param       string  $frontParam     \r
1835  */\r
1836 function serverStringToArray($str, &$array, &$frontParam)\r
1837 {\r
1838         // init param\r
1839         $array = array();\r
1840         $frontParam = "";\r
1841         \r
1842         // split front param, e.g. /index.php, and others, e.g. blogid=1&page=2\r
1843         if ( i18n::strpos($str, "?") > 0 )\r
1844         {\r
1845                 list($frontParam, $args) = preg_split("#\?#", $str, 2);\r
1846         }\r
1847         else\r
1848         {\r
1849                 $args = $str;\r
1850                 $frontParam = "";\r
1851         }\r
1852         \r
1853         // If there is no args like blogid=1&page=2, return\r
1854         if ( i18n::strpos($str, "=") == FALSE && !i18n::strlen($frontParam) )\r
1855         {\r
1856                 $frontParam = $str;\r
1857                 return;\r
1858         }\r
1859         \r
1860         $array = preg_split("#&#", $args);\r
1861         return;\r
1862 }\r
1863 \r
1864 /**\r
1865  * Convert array like array['blogid'] to server string\r
1866  * such as $_SERVER['REQUEST_URI']\r
1867  */\r
1868 function arrayToServerString($array, $frontParam, &$str)\r
1869 {\r
1870         if ( i18n::strpos($str, "?") !== FALSE )\r
1871         {\r
1872                 $str = $frontParam . "?";\r
1873         }\r
1874         else\r
1875         {\r
1876                 $str = $frontParam;\r
1877         }\r
1878         if ( count($array) )\r
1879         {\r
1880                 $str .= implode("&", $array);\r
1881         }\r
1882         return;\r
1883 }\r
1884 \r
1885 /**\r
1886  * sanitizeArray()\r
1887  * Sanitize array parameters.\r
1888  * This function checks both key and value.\r
1889  * - check key if it inclues " (double quote),  remove from array\r
1890  * - check value if it includes \ (escape sequece), remove remaining string\r
1891  * \r
1892  * @param       array   &$array \r
1893  * @return      void\r
1894  */\r
1895 function sanitizeArray(&$array)\r
1896 {\r
1897         $excludeListForSanitization = array('query');\r
1898         \r
1899         foreach ( $array as $k => $v )\r
1900         {\r
1901                 // split to key and value\r
1902                 list($key, $val) = preg_split("#=#", $v, 2);\r
1903                 if ( !isset($val) )\r
1904                 {\r
1905                         continue;\r
1906                 }\r
1907                 \r
1908                 // when magic quotes is on, need to use stripslashes,\r
1909                 // and then addslashes\r
1910                 if ( get_magic_quotes_gpc() )\r
1911                 {\r
1912                         $val = stripslashes($val);\r
1913                 }\r
1914                 // note that we must use addslashes here because this function is called before the db connection is made\r
1915                 // and sql_real_escape_string needs a db connection\r
1916                 $val = addslashes($val);\r
1917                 \r
1918                 // if $key is included in exclude list, skip this param\r
1919                 if ( !in_array($key, $excludeListForSanitization) )\r
1920                 {\r
1921                         // check value\r
1922                         if ( i18n::strpos($val, '\\') )\r
1923                         {\r
1924                                 list($val, $tmp) = preg_split('#\\\\#', $val);\r
1925                         }\r
1926                         \r
1927                         // remove control code etc.\r
1928                         $val = strtr($val, "\0\r\n<>'\"", "       ");\r
1929                         \r
1930                         // check key\r
1931                         if ( preg_match('#\"#', $key) )\r
1932                         {\r
1933                                 unset($array[$k]);\r
1934                                 continue;\r
1935                         }\r
1936                         \r
1937                         // set sanitized info\r
1938                         $array[$k] = sprintf("%s=%s", $key, $val);\r
1939                 }\r
1940         }\r
1941         return;\r
1942 }\r
1943 \r
1944 /**\r
1945  * Convert array for sanitizeArray function\r
1946  */\r
1947 function convArrayForSanitizing($src, &$array)\r
1948 {\r
1949     $array = array();\r
1950     foreach ($src as $key => $val) {\r
1951         if (key_exists($key, $_GET)) {\r
1952             array_push($array, sprintf("%s=%s", $key, $val));\r
1953         }\r
1954     }\r
1955 }\r
1956 \r
1957 /**\r
1958  * Revert array after sanitizeArray function\r
1959  */\r
1960 function revertArrayForSanitizing($array, &$dst)\r
1961 {\r
1962     foreach ($array as $v) {\r
1963         list($key, $val) = preg_split("/=/", $v, 2);\r
1964         $dst[$key] = $val;\r
1965     }\r
1966 }\r
1967 \r
1968 /**\r
1969  * Stops processing the request and redirects to the given URL.\r
1970  * - no actual contents should have been sent to the output yet\r
1971  * - the URL will be stripped of illegal or dangerous characters\r
1972  */\r
1973 function redirect($url) {\r
1974     $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%*]|i', '', $url);\r
1975     header('Location: ' . $url);\r
1976     exit;\r
1977 }\r
1978 \r
1979 /**\r
1980  * getBookmarklet()\r
1981  * Returns the Javascript code for a bookmarklet that works on most modern browsers\r
1982  * \r
1983  * @param       integer $blogid ID for weblog\r
1984  * @return      script to call Bookmarklet\r
1985  */\r
1986 function getBookmarklet($blogid, $width=600,  $height=500)\r
1987 {\r
1988         global $CONF;\r
1989         \r
1990         $script = "Q='';"\r
1991                 . "x=document;"\r
1992                 . "y=window;"\r
1993                 . "if ( x.selection )"\r
1994                 . "{"\r
1995                 . " Q=x.selection.createRange().text;"\r
1996                 . "}"\r
1997                 . "else if ( y.getSelection )"\r
1998                 . "{"\r
1999                 . " Q=y.getSelection();"\r
2000                 . "}"\r
2001                 . "else if ( x.getSelection )"\r
2002                 . "{"\r
2003                 . " Q=x.getSelection();"\r
2004                 . "}"\r
2005                 . "wingm = window.open('{$CONF['AdminURL']}bookmarklet.php?blogid={$blogid}"\r
2006                 . " &logtext=' + encodeURIComponent(Q) +"\r
2007                 . " '&loglink=' + encodeURIComponent(x.location.href) +"\r
2008                 . " '&loglinktitle=' + encodeURIComponent(x.title),"\r
2009                 . " 'nucleusbm',"\r
2010                 . " 'scrollbars=yes,width={$width},height={$height},left=10,top=10,status=yes,resizable=yes');"\r
2011                 . "wingm.focus();";\r
2012         \r
2013         return $script;\r
2014 }\r
2015 // END: functions from the end of file ADMIN.php\r
2016 \r
2017 /**\r
2018  * Returns a variable or null if not set\r
2019  *\r
2020  * @param mixed Variable\r
2021  * @return mixed Variable\r
2022  */\r
2023 function ifset(&$var) {\r
2024     if (isset($var)) {\r
2025         return $var;\r
2026     }\r
2027 \r
2028     return null;\r
2029 }\r
2030 \r
2031 /**\r
2032  * Returns number of subscriber to an event\r
2033  *\r
2034  * @param event\r
2035  * @return number of subscriber(s)\r
2036  */\r
2037 function numberOfEventSubscriber($event) {\r
2038     $query = 'SELECT COUNT(*) as count FROM ' . sql_table('plugin_event') . ' WHERE event=\'' . $event . '\'';\r
2039     $res = sql_query($query);\r
2040     $obj = sql_fetch_object($res);\r
2041     return $obj->count;\r
2042 }\r
2043 \r
2044 /**\r
2045  * sets $special global variable for use in index.php before selector()\r
2046  *\r
2047  * @param String id\r
2048  * @return nothing\r
2049  */\r
2050 function selectSpecialSkinType($id) {\r
2051     global $special;\r
2052     $special = strtolower($id);\r
2053 }\r
2054 \r
2055 /**\r
2056  * cleans filename of uploaded file for writing to file system\r
2057  *\r
2058  * @param String str\r
2059  * @return String cleaned filename ready for use\r
2060  */\r
2061 function cleanFileName($str) {\r
2062         $str = strtolower($str);\r
2063         $ext_point = i18n::strrpos($str,".");\r
2064         if ($ext_point===false) return false;\r
2065         $ext = i18n::substr($str,$ext_point,i18n::strlen($str));\r
2066         $str = i18n::substr($str,0,$ext_point);\r
2067 \r
2068         return preg_replace("/[^a-z0-9-]/","_",$str).$ext;\r
2069 }\r
2070 \r
2071 /**\r
2072  * Centralisation of the functions to send mail\r
2073  * Deprecated since 4.0:\r
2074  * Please use functions in NOTIFICATION class instead\r
2075  */\r
2076 function getMailFooter()\r
2077 {\r
2078         NOTIFICATION::get_mail_footer();\r
2079 }\r
2080 function isValidMailAddress($address)\r
2081 {\r
2082         return NOTIFICATION::address_validation($address);\r
2083 }\r
2084 /**\r
2085  * Centralisation of the functions that deals XML entities\r
2086  * Deprecated since 4.0:\r
2087  * Please use Entity::FunctionName(...) instead\r
2088  */\r
2089 function highlight($text, $expression, $highlight)\r
2090 {\r
2091         return Entity::highlight($text, $expression, $highlight);\r
2092 }\r
2093 function shorten($string, $maxlength, $suffix)\r
2094 {\r
2095         return Entity::shorten($string, $maxlength, $suffix);\r
2096 }\r
2097 function stringStripTags ($string)\r
2098 {\r
2099         return Entity::strip_tags($string);\r
2100 }\r
2101 function toAscii($string)\r
2102 {\r
2103         return Entity::anchor_footnoting($string);\r
2104 }\r
2105 function stringToAttribute ($string)\r
2106 {\r
2107         return Entity::hsc($string);\r
2108 }\r
2109 function stringToXML ($string)\r
2110 {\r
2111         return Entity::hen($string);\r
2112 }\r
2113 function encode_desc($data)\r
2114 {\r
2115         return Entity::hen($data);\r
2116 }\r
2117 /**\r
2118  * Centralisation of the functions that deals with locales\r
2119  * This functions is based on the old way to deal with languages\r
2120  * Deprecated since 4.0:\r
2121  */\r
2122 /* NOTE: use i18n::get_current_locale() directly instead of this */\r
2123 function getLanguageName()\r
2124 {\r
2125         if( ($language = i18n::convert_locale_to_old_language_file_name(i18n::get_current_locale())) === FALSE )\r
2126         {\r
2127                 $language ='english';\r
2128         }\r
2129         return $language;\r
2130 }\r
2131 /* NOTE: this is completely deprecated because generating much warnings */\r
2132 function selectLanguage($language)\r
2133 {\r
2134         global $DIR_LANG;\r
2135         include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');\r
2136         return;\r
2137 }\r
2138 \r
2139 /* NOTE: use i18n::get_available_locales() directly instead of this */\r
2140 function checkLanguage($lang)\r
2141 {\r
2142         return ( preg_match('#^(.+)_(.+)_(.+)$#', $lang)\r
2143           || i18n::convert_old_language_file_name_to_locale($lang) );\r
2144 }\r
2145 /* NOTE: use i18n::formatted_datetime() directly instead of this */\r
2146 function formatDate($format, $timestamp, $default_format, &$blog)\r
2147 {\r
2148         $offset = date('Z', $timestamp);\r
2149         if ( $blog )\r
2150         {\r
2151                 $offset += $blog->getTimeOffset() * 3600;\r
2152         }\r
2153         return i18n::formatted_datetime($format, $timestamp, $offset, $default_format);\r
2154 }\r
2155 /* NOTE: use i18n::formatted_datetime() directly instead of this */\r
2156 function mysqldate($timestamp)\r
2157 {\r
2158         return '"' . i18n::formatted_datetime('mysql', $timestamp) . '"';\r
2159  }\r
2160 /**\r
2161  * Centralisation of the functions that generate links\r
2162  * Deprecated since 4.0:\r
2163  * Please use Link::FunctionName(...) instead\r
2164  */\r
2165 function createItemLink($itemid, $extra = '')\r
2166 {\r
2167         return Link::create_item_link($itemid, $extra);\r
2168 }\r
2169 function createMemberLink($memberid, $extra = '')\r
2170 {\r
2171         return Link::create_member_link($memberid, $extra);\r
2172 }\r
2173 function createCategoryLink($catid, $extra = '')\r
2174 {\r
2175         return Link::create_category_link($catid, $extra);\r
2176 }\r
2177 function createArchiveListLink($blogid = '', $extra = '')\r
2178 {\r
2179         return Link::create_archivelist_link($blogid, $extra);\r
2180 }\r
2181 function createArchiveLink($blogid, $archive, $extra = '')\r
2182 {\r
2183         return Link::create_archive_link($blogid, $archive, $extra);\r
2184 }\r
2185 function createBlogidLink($blogid, $params = '')\r
2186 {\r
2187         return Link::create_blogid_link($blogid, $params = '');\r
2188 }\r
2189 function createLink($type, $params)\r
2190 {\r
2191         return Link::create_link($type, $params);\r
2192 }\r
2193 function createBlogLink($url, $params)\r
2194 {\r
2195         return Link::create_blog_link($url, $params);\r
2196 }\r