OSDN Git Service

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