OSDN Git Service

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