OSDN Git Service

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