OSDN Git Service

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