4 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
5 * Copyright (C) 2002-2009 The Nucleus Group
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 * (see nucleus/documentation/index.html#license for more info)
14 * @license http://nucleuscms.org/license.txt GNU General Public License
15 * @copyright Copyright (C) 2002-2009 The Nucleus Group
16 * @version $Id: globalfunctions.php 1639 2012-01-29 08:10:11Z sakamocchi $
19 /* needed if we include globalfunctions from install.php */
20 global $nucleus, $CONF, $DIR_LIBS, $DIR_LOCALE, $manager, $member;
22 $nucleus['version'] = 'v4.00 SVN';
23 $nucleus['codename'] = '';
25 /* check and die if someone is trying to override internal globals (when register_globals turn on) */
26 checkVars(array('nucleus', 'CONF', 'DIR_LIBS', 'MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE', '$DIR_LOCALE', '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'));
31 /* report all errors! */
32 error_reporting(E_ALL);
36 ini_set('display_errors','0');
37 error_reporting(E_ERROR | E_WARNING | E_PARSE);
41 * FIXME: This is for compatibility since 4.0, should be obsoleted at future release.
43 if ( !isset($DIR_LOCALES) )
45 $DIR_LOCALES = $DIR_NUCLEUS . 'locales/';
48 if ( !isset($DIR_LANG) )
50 $DIR_LANG = $DIR_LOCALES;
54 * load and initialize i18n class
56 if (!class_exists('i18n', FALSE))
58 include($DIR_LIBS . 'i18n.php');
60 if ( !i18n::init('UTF-8', $DIR_LOCALES) )
62 exit('Fail to initialize i18n class.');
65 * FIXME: This is for compatibility since 4.0, should be obsoleted at future release.
67 define('_CHARSET', i18n::get_current_charset());
70 * Indicates when Nucleus should display startup errors. Set to 1 if you want
71 * the error enabled (default), false otherwise
74 * Displays an error when visiting a public Nucleus page and headers have
75 * been sent out to early. This usually indicates an error in either a
76 * configuration file or a translation file, and could cause Nucleus to
79 * Displays an error only when visiting the admin area, and when one or
80 * more of the installation files (install.php, install.sql, upgrades/
81 * directory) are still on the server.
83 if ( !array_key_exists('alertOnHeadersSent', $CONF) || $CONF['alertOnHeadersSent'] !== 0 )
85 $CONF['alertOnHeadersSent'] = 1;
87 $CONF['alertOnSecurityRisk'] = 1;
89 * NOTE: this should be removed when releasing 4.0
90 $CONF['ItemURL'] = $CONF['Self'];
91 $CONF['ArchiveURL'] = $CONF['Self'];
92 $CONF['ArchiveListURL'] = $CONF['Self'];
93 $CONF['MemberURL'] = $CONF['Self'];
94 $CONF['SearchURL'] = $CONF['Self'];
95 $CONF['BlogURL'] = $CONF['Self'];
96 $CONF['CategoryURL'] = $CONF['Self'];
100 * NOTE: this should be removed when releasing 4.0
101 * switch URLMode back to normal when $CONF['Self'] ends in .php
102 * this avoids urls like index.php/item/13/index.php/item/15
103 if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {
104 $CONF['URLMode'] = 'normal';
108 * Set these to 1 to allow viewing of future items or draft items
109 * Should really never do this, but can be useful for some plugins that might need to
110 * Could cause some other issues if you use future posts otr drafts
113 $CONF['allowDrafts'] = 0;
114 $CONF['allowFuture'] = 0;
116 if ( getNucleusPatchLevel() > 0 )
118 $nucleus['version'] .= '/' . getNucleusPatchLevel();
122 if ( !isset($CONF['installscript']) )
124 $CONF['installscript'] = 0;
127 /* we will use postVar, getVar, ... methods instead of $_GET, $_POST ...*/
128 if ( $CONF['installscript'] != 1 )
130 /* vars were already included in install.php */
131 include_once($DIR_LIBS . 'vars4.1.0.php');
134 /* sanitize option */
135 $bLoggingSanitizedResult=0;
136 $bSanitizeAndContinue=0;
138 $orgRequestURI = serverVar('REQUEST_URI');
141 /* get all variables that can come from the request and put them in the global scope */
142 $blogid = requestVar('blogid');
143 $itemid = intRequestVar('itemid');
144 $catid = intRequestVar('catid');
145 $skinid = requestVar('skinid');
146 $memberid = requestVar('memberid');
147 $archivelist = requestVar('archivelist');
148 $imagepopup = requestVar('imagepopup');
149 $archive = requestVar('archive');
150 $query = requestVar('query');
151 $highlight = requestVar('highlight');
152 $amount = requestVar('amount');
153 $action = requestVar('action');
154 $nextaction = requestVar('nextaction');
155 $maxresults = requestVar('maxresults');
156 $startpos = intRequestVar('startpos');
159 $special = requestVar('special');
160 $virtualpath = ((getVar('virtualpath') != null) ? getVar('virtualpath') : serverVar('PATH_INFO'));
162 if ( !headers_sent() )
164 header('Generator: Nucleus CMS ' . $nucleus['version']);
167 /* include core classes that are needed for login & plugin handling */
168 include_once($DIR_LIBS . 'mysql.php');
169 /* added for 3.5 sql_* wrapper */
170 global $MYSQL_HANDLER;
171 if ( !isset($MYSQL_HANDLER) )
173 $MYSQL_HANDLER = array('mysql','');
175 if ( $MYSQL_HANDLER[0] == '' )
177 $MYSQL_HANDLER[0] = 'mysql';
179 include_once($DIR_LIBS . 'sql/'.$MYSQL_HANDLER[0].'.php');
180 /* end new for 3.5 sql_* wrapper */
181 include($DIR_LIBS . 'MEMBER.php');
182 include($DIR_LIBS . 'ACTIONLOG.php');
183 include($DIR_LIBS . 'MANAGER.php');
184 include($DIR_LIBS . 'PLUGIN.php');
186 $manager =& MANAGER::instance();
189 * make sure there's no unnecessary escaping:
190 * set_magic_quotes_runtime(0);
192 if ( version_compare(PHP_VERSION, '5.3.0', '<') )
194 ini_set('magic_quotes_runtime', '0');
198 if ( !array_key_exists('UsingAdminArea', $CONF) )
200 $CONF['UsingAdminArea'] = 0;
203 /* only needed when updating logs */
204 if ( $CONF['UsingAdminArea'] )
206 /* XML-RPC client classes */
207 include($DIR_LIBS . 'xmlrpc.inc.php');
208 include_once($DIR_LIBS . 'ADMIN.php');
211 /* connect to database */
215 /* logs sanitized result if need */
216 if ( $orgRequestURI!==serverVar('REQUEST_URI') )
218 $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";
219 $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');
220 if ( $bLoggingSanitizedResult )
222 addToLog(WARNING, $msg);
224 if ( !$bSanitizeAndContinue )
230 /* makes sure database connection gets closed on script termination */
231 register_shutdown_function('sql_disconnect');
237 * Nucleus CMS 4.0 uses 'locale' instead of 'language' to decide which translation file used
238 * Here simply convert old name to new name without checking translation file existance
239 * FIXME: This is for compatibility, should be obsoleted near future.
241 if ( !array_key_exists('Locale', $CONF) )
243 $CONF['Locale'] =& $CONF['Language'];
246 if ( !preg_match('#^(.+)_(.+)_(.+)$#', $CONF['Locale'])
247 && ($CONF['Locale'] = i18n::convert_old_language_file_name_to_locale($CONF['Language'])) === FALSE )
249 $CONF['Locale'] = '';
251 $locale = $CONF['Locale'];
253 /* Properly set $CONF['Self'] and others if it's not set...
254 * usually when we are access from admin menu
256 if ( !array_key_exists('Self', $CONF) )
258 $CONF['Self'] = $CONF['IndexURL'];
260 if ( $CONF['Self'][i18n::strlen($CONF['Self']) -1] == "/" )
262 $CONF['Self'] = i18n::substr($CONF['Self'], 0, i18n::strlen($CONF['Self']) -1);
266 $CONF['ItemURL'] = $CONF['Self'];
267 $CONF['ArchiveURL'] = $CONF['Self'];
268 $CONF['ArchiveListURL'] = $CONF['Self'];
269 $CONF['MemberURL'] = $CONF['Self'];
270 $CONF['SearchURL'] = $CONF['Self'];
271 $CONF['BlogURL'] = $CONF['Self'];
272 $CONF['CategoryURL'] = $CONF['Self'];
275 *switch URLMode back to normal when $CONF['Self'] ends in .php
276 * this avoids urls like index.php/item/13/index.php/item/15
278 if ( !array_key_exists('URLMode', $CONF)
279 || (($CONF['URLMode'] == 'pathinfo')
280 && (i18n::substr($CONF['Self'], i18n::strlen($CONF['Self']) - 4) == '.php')) )
282 $CONF['URLMode'] = 'normal';
285 /* automatically use simpler toolbar for mozilla */
286 if ( ($CONF['DisableJsTools'] == 0)
287 && strstr(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0')
288 && strstr(serverVar('HTTP_USER_AGENT'), 'Gecko') )
290 $CONF['DisableJsTools'] = 2;
293 /* login if cookies set*/
294 $member = new MEMBER();
296 /* secure cookie key settings (either 'none', 0, 8, 16, 24, or 32) */
297 if ( !array_key_exists('secureCookieKey', $CONF) )
299 $CONF['secureCookieKey'] = 24;
301 switch( $CONF['secureCookieKey'] )
304 $CONF['secureCookieKeyIP'] = preg_replace('/\.[0-9]+\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
307 $CONF['secureCookieKeyIP'] = preg_replace('/\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
310 $CONF['secureCookieKeyIP'] = preg_replace('/\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
313 $CONF['secureCookieKeyIP'] = serverVar('REMOTE_ADDR');
316 $CONF['secureCookieKeyIP'] = '';
320 * login/logout when required or renew cookies
321 * and decide locale on this session before plugin event generates
323 if ( $action == 'login' )
325 /* Form Authentication */
326 $login = postVar('login');
327 $pw = postVar('password');
328 /* shared computer or not */
329 $shared = intPostVar('shared');
330 /* avoid md5 collision by using a long key */
331 $pw=i18n::substr($pw,0,40);
333 if ( $member->login($login, $pw) )
335 $member->newCookieKey();
336 $member->setCookies($shared);
338 if ( $CONF['secureCookieKey'] !== 'none' )
340 /* secure cookie key */
341 $member->setCookieKey(md5($member->getCookieKey().$CONF['secureCookieKeyIP']));
345 /* allows direct access to parts of the admin area after logging in */
348 $action = $nextaction;
351 /* NOTE: include translation file and set locale */
352 $locale = include_translation($locale, $member);
353 i18n::set_current_locale($locale);
355 $manager->notify('LoginSuccess', array('member' => &$member, 'username' => $login) );
357 ACTIONLOG::add(INFO, "Login successful for $login (sharedpc=$shared)");
361 /* errormessage for [%errordiv%] */
362 $trimlogin = trim($login);
363 if ( empty($trimlogin) )
365 $errormessage = "Please enter a username.";
369 $errormessage = 'Login failed for ' . $login;
372 /* NOTE: include translation file and set locale */
373 $locale = include_translation($locale);
374 i18n::set_current_locale($locale);
376 $manager->notify('LoginFailed', array('username' => $login) );
377 ACTIONLOG::add(INFO, $errormessage);
382 * TODO: this should be removed when releasing 4.0
383 Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details
384 elseif ( serverVar('PHP_AUTH_USER') && serverVar('PHP_AUTH_PW') )
386 // HTTP Authentication
387 $login = serverVar('PHP_AUTH_USER');
388 $pw = serverVar('PHP_AUTH_PW');
390 if ( $member->login($login, $pw) )
392 $manager->notify('LoginSuccess',array('member' => &$member));
393 ACTIONLOG::add(INFO, "HTTP authentication successful for $login");
397 $manager->notify('LoginFailed',array('username' => $login));
398 ACTIONLOG::add(INFO, 'HTTP authentication failed for ' . $login);
400 //Since bad credentials, generate an apropriate error page
401 header("WWW-Authenticate: Basic realm=\"Nucleus CMS {$nucleus['version']}\"");
402 header('HTTP/1.0 401 Unauthorized');
403 echo 'Invalid username or password';
409 elseif ( ($action == 'logout')
411 && cookieVar($CONF['CookiePrefix'] . 'user') )
413 /* remove cookies on logout */
414 setcookie($CONF['CookiePrefix'] . 'user', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
415 setcookie($CONF['CookiePrefix'] . 'loginkey', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
417 /* NOTE: include translation file and set locale */
418 $locale = include_translation($locale);
419 i18n::set_current_locale($locale);
421 $manager->notify('Logout', array('username' => cookieVar($CONF['CookiePrefix'] . 'user') ) );
423 elseif ( cookieVar($CONF['CookiePrefix'] . 'user') )
425 /* Cookie Authentication */
426 $ck=cookieVar($CONF['CookiePrefix'] . 'loginkey');
429 * avoid md5 collision by using a long key
431 $ck = i18n::substr($ck,0,32);
432 if ( $CONF['secureCookieKey']!=='none' )
434 $ck = md5($ck.$CONF['secureCookieKeyIP']);
436 $res = $member->cookielogin(cookieVar($CONF['CookiePrefix'] . 'user'), $ck );
439 /* renew cookies when not on a shared computer */
441 && (cookieVar($CONF['CookiePrefix'] . 'sharedpc') != 1)
442 && (!headers_sent() ) )
444 $member->setCookieKey(cookieVar($CONF['CookiePrefix'] . 'loginkey'));
445 $member->setCookies();
448 /* NOTE: include translation file and set locale */
449 $locale = include_translation($locale, $member);
450 i18n::set_current_locale($locale);
454 /* NOTE: include translation file and set locale */
455 $locale = include_translation($locale);
456 i18n::set_current_locale($locale);
459 /* login completed */
460 $manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );
463 * Release ticket for plugin
467 /* first, let's see if the site is disabled or not. always allow admin area access. */
468 if ( $CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea'] )
470 redirect($CONF['DisableSiteURL']);
474 /* load other classes */
475 include($DIR_LIBS . 'PARSER.php');
476 include($DIR_LIBS . 'SKIN.php');
477 include($DIR_LIBS . 'TEMPLATE.php');
478 include($DIR_LIBS . 'BLOG.php');
479 include($DIR_LIBS . 'BODYACTIONS.php');
480 include($DIR_LIBS . 'COMMENTS.php');
481 include($DIR_LIBS . 'COMMENT.php');
482 /* include($DIR_LIBS . 'ITEM.php'); */
483 include($DIR_LIBS . 'NOTIFICATION.php');
484 include($DIR_LIBS . 'BAN.php');
485 include($DIR_LIBS . 'PAGEFACTORY.php');
486 include($DIR_LIBS . 'SEARCH.php');
487 include($DIR_LIBS . 'ENTITY.php');
488 include($DIR_LIBS . 'LINK.php');
490 /* set lastVisit cookie (if allowed) */
491 if ( !headers_sent() )
493 if ( $CONF['LastVisit'] )
495 setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
499 setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
504 Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details
506 // To remove after v2.5 is released and translation files have been updated.
507 // Including this makes sure that translation files for v2.5beta can still be used for v2.5final
508 // without having weird _SETTINGS_EXTAUTH string showing up in the admin area.
509 if (!defined('_MEMBERS_BYPASS'))
511 define('_SETTINGS_EXTAUTH', 'Enable External Authentication');
512 define('_WARNING_EXTAUTH', 'Warning: Enable only if needed.');
513 define('_MEMBERS_BYPASS', 'Use External Authentication');
517 /* make sure the archivetype skinvar keeps working when _ARCHIVETYPE_XXX not defined */
518 if ( !defined('_ARCHIVETYPE_MONTH') )
520 define('_ARCHIVETYPE_DAY', 'day');
521 define('_ARCHIVETYPE_MONTH', 'month');
522 define('_ARCHIVETYPE_YEAR', 'year');
525 /* decode path_info */
526 if ( $CONF['URLMode'] == 'pathinfo' )
528 /* initialize keywords if this hasn't been done before */
529 if ( !isset($CONF['ItemKey']) || $CONF['ItemKey'] == '' )
531 $CONF['ItemKey'] = 'item';
534 if ( !isset($CONF['ArchiveKey']) || $CONF['ArchiveKey'] == '' )
536 $CONF['ArchiveKey'] = 'archive';
539 if ( !isset($CONF['ArchivesKey']) || $CONF['ArchivesKey'] == '' )
541 $CONF['ArchivesKey'] = 'archives';
544 if ( !isset($CONF['MemberKey']) || $CONF['MemberKey'] == '' )
546 $CONF['MemberKey'] = 'member';
549 if ( !isset($CONF['BlogKey']) || $CONF['BlogKey'] == '' )
551 $CONF['BlogKey'] = 'blog';
554 if ( !isset($CONF['CategoryKey']) || $CONF['CategoryKey'] == '' )
556 $CONF['CategoryKey'] = 'category';
559 if ( !isset($CONF['SpecialskinKey']) || $CONF['SpecialskinKey'] == '' )
561 $CONF['SpecialskinKey'] = 'special';
568 /* e.g. item, blog, ... */
569 'type' => basename(serverVar('SCRIPT_NAME') ),
570 'info' => $virtualpath,
571 'complete' => &$parsed
577 /* default implementation */
578 $data = i18n::explode("/", $virtualpath );
579 for ( $i = 0; $i < sizeof($data); $i++ )
583 /* item/1 (blogid) */
584 case $CONF['ItemKey']:
587 if ( $i < sizeof($data) )
589 $itemid = intval($data[$i]);
593 /* archives/1 (blogid) */
594 case $CONF['ArchivesKey']:
596 if ( $i < sizeof($data) )
598 $archivelist = intval($data[$i]);
602 /* two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid) */
603 case $CONF['ArchiveKey']:
604 if ( (($i + 1) < sizeof($data) ) && (!strstr($data[$i + 1], '-') ) )
606 $blogid = intval($data[++$i]);
609 if ( $i < sizeof($data) )
611 $archive = $data[$i];
618 case $CONF['BlogKey']:
620 if ( $i < sizeof($data) )
622 $blogid = intval($data[$i]);
626 /* category/1 (catid) */
627 case $CONF['CategoryKey']:
630 if ( $i < sizeof($data) )
632 $catid = intval($data[$i]);
636 case $CONF['MemberKey']:
638 if ( $i < sizeof($data) )
640 $memberid = intval($data[$i]);
644 case $CONF['SpecialskinKey']:
646 if ( $i < sizeof($data) )
648 $special = $data[$i];
649 $_REQUEST['special'] = $special;
660 * PostParseURL is a place to cleanup any of the path-related global variables before the selector function is run.
661 * It has 2 values in the data in case the original virtualpath is needed, but most the use will be in tweaking
662 * global variables to clean up (scrub out catid or add catid) or to set someother global variable based on
663 * the values of something like catid or itemid
669 /* e.g. item, blog, ... */
670 'type' => basename(serverVar('SCRIPT_NAME') ),
671 'info' => $virtualpath
676 * NOTE: Here is the end of initialization
680 * This function includes or requires the specified library file
681 * @param string $file
682 * @param bool $once use the _once() version
683 * @param bool $require use require() instead of include()
685 function include_libs($file, $once = TRUE, $require = TRUE)
689 // begin if: $DIR_LIBS isn't a directory
690 if ( !is_dir($DIR_LIBS) )
695 $lib_path = $DIR_LIBS . $file;
698 if ( $once && $require )
700 require_once($lib_path);
702 else if ( $once && !$require )
704 include_once($lib_path);
719 * This function includes or requires the specified plugin file
720 * @param string $file
721 * @param bool $once use the _once() version
722 * @param bool $require use require() instead of include()
724 function include_plugins($file, $once = TRUE, $require = TRUE)
728 // begin if: $DIR_LIBS isn't a directory
729 if ( !is_dir($DIR_PLUGINS) )
734 $plugin_path = $DIR_PLUGINS . $file;
737 if ( $once && $require )
739 require_once($plugin_path);
741 else if ( $once && !$require )
743 include_once($plugin_path);
747 require($plugin_path);
751 include($plugin_path);
756 * This function decide which locale is used and include translation
757 * @param string $locale locale name referring to 'language tags' defined in RFC 5646
758 * @param mixed $member member object
760 function include_translation($locale, $member = FALSE)
765 * 1. user's locale is used if set
766 * 2. system default is used if it is not empty
767 * 3. else 'en_Latn_US.ISO-8859-1.php' is included
768 * because this translation file is expected to include only 7bit ASCII characters
769 * which common in whole character coding scheme
771 if ( $member && $member->getLocale() )
773 $locale = $member->getLocale();
775 $translation_file = $DIR_LOCALES . $locale . '.' . i18n::get_current_charset() . '.php';
776 if ( !file_exists($translation_file) )
778 $locale = 'en_Latn_US';
779 $translation_file = $DIR_LOCALES . 'en_Latn_US.ISO-8859-1.php';
781 include($translation_file);
786 * This function returns the integer value of $_POST for the variable $name
787 * @param string $name field to get the integer value of
790 function intPostVar($name)
792 return intval(postVar($name));
797 * This function returns the integer value of $_GET for the variable $name
798 * @param string $name field to get the integer value of
801 function intGetVar($name)
803 return intval(getVar($name));
808 * This function returns the integer value of $_REQUEST for the variable $name. Also checks $_GET and $_POST if not found in $_REQUEST
809 * @param string $name field to get the integer value of
812 function intRequestVar($name)
814 return intval(requestVar($name));
819 * This function returns the integer value of $_COOKIE for the variable $name
820 * @param string $name field to get the integer value of
823 function intCookieVar($name)
825 return intval(cookieVar($name));
830 * This function returns the current Nucleus version (100 = 1.00, 101 = 1.01, etc...)
833 function getNucleusVersion()
840 * TODO: Better description of this function.
842 * Power users can install patches in between nucleus releases. These patches
843 * usually add new functionality in the plugin API and allow those to
844 * be tested without having to install CVS.
848 function getNucleusPatchLevel()
855 * This function returns the latest Nucleus version available for download from nucleuscms.org or FALSE if unable to attain data
856 * Format will be major.minor/patachlevel e.g. 3.41 or 3.41/02
857 * @return string|bool
859 function getLatestVersion()
861 // begin if: cURL is not available in this PHP installation
862 if ( !function_exists('curl_init') )
869 curl_setopt ($curl, CURLOPT_URL, 'http://nucleuscms.org/version_check.php');
870 curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
871 curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
872 $return = curl_exec($curl);
879 * This function returns a Nucleus table name with the appropriate prefix
880 * @param string $name
883 function sql_table($name)
885 global $MYSQL_PREFIX;
887 // begin if: no MySQL prefix
888 if ( empty($MYSQL_PREFIX) )
890 return 'nucleus_' . $name;
892 // else: use MySQL prefix
895 return $MYSQL_PREFIX . 'nucleus_' . $name;
902 * TODO: This function should be changed to send_content_type() per the Coding Guidelines. Ensure this change is compatible with rest of core.
904 * This function sends the Content-Type header if headers have not already been sent
905 * It also determines if the browser can accept application/xhtml+xml and sends it only to those that can.
906 * @param string $content_type
907 * @param string $page_type
908 * @param string $charset Deprecated. This has no meaning.
910 function sendContentType($content_type, $page_type = '', $charset = _CHARSET)
912 global $manager, $CONF;
914 if ( !headers_sent() )
916 // if content type is application/xhtml+xml, only send it to browsers
917 // that can handle it (IE6 cannot). Otherwise, send text/html
919 // v2.5: For admin area pages, keep sending text/html (unless it's a debug version)
920 // application/xhtml+xml still causes too much problems with the javascript implementations
922 // v3.3: ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,
923 // application/xhtml+xml seems to be working, so we're going to use it if we can.
925 if ( ($content_type == 'application/xhtml+xml')
926 && (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') ) )
928 $content_type = 'text/html';
932 'PreSendContentType',
934 'contentType' => &$content_type,
935 'charset' => i18n::get_current_charset(),
936 'pageType' => $page_type
940 // strip strange characters
941 $content_type = preg_replace('|[^a-z0-9-+./]|i', '', $content_type);
942 header('Content-Type: ' . $content_type . '; charset=' . i18n::get_current_charset());
949 * This function parses a query into an array of expressions that can be passed on to the highlight method
950 * @param string $query
952 function parseHighlight($query)
954 // TODO: add more intelligent splitting logic
957 $query = preg_replace('/\'|"/', '', $query);
964 $aHighlight = i18n::explode(' ', $query);
966 for ( $i = 0; $i < count($aHighlight); $i++ )
968 $aHighlight[$i] = trim($aHighlight[$i]);
970 if ( i18n::strlen($aHighlight[$i]) < 3 )
972 unset($aHighlight[$i]);
976 if ( count($aHighlight) == 1 )
978 return $aHighlight[0];
988 * This function gets the blog ID from the blog name
989 * @param string $name
992 function getBlogIDFromName($name)
994 return quickQuery('SELECT `bnumber` AS `result` FROM `' . sql_table('blog') . '` WHERE `bshortname` = "' . sql_real_escape_string($name) . '"');
999 * This function gets the blog name from the blog ID
1003 function getBlogNameFromID($id)
1005 return quickQuery('SELECT `bname` AS `result` FROM `' . sql_table('blog') . '` WHERE `bnumber` = ' . intval($id));
1010 * This function gets the blog ID from the item ID
1011 * @param int $item_id
1014 function getBlogIDFromItemID($item_id)
1016 return quickQuery('SELECT `iblog` AS `result` FROM `' . sql_table('item') . '` WHERE `inumber` = ' . intval($item_id));
1021 * This function gets the blog ID from the comment ID
1022 * @param int $comment_id
1025 function getBlogIDFromCommentID($comment_id)
1027 return quickQuery('SELECT `cblog` AS `result` FROM `' . sql_table('comment') . '` WHERE `cnumber` = ' . intval($comment_id));
1032 * This function gets the blog ID from the category ID
1033 * @param int $category_id
1036 function getBlogIDFromCatID($category_id)
1038 return quickQuery('SELECT `cblog` AS `result` FROM `' . sql_table('category') . '` WHERE `catid` = ' . intval($category_id));
1043 * This function gets the category ID from the category name
1047 function getCatIDFromName($name)
1049 return quickQuery('SELECT `catid` AS `result` FROM `' . sql_table('category') . '` WHERE `cname` = "' . sql_real_escape_string($name) . '"');
1054 * This function performs a quick SQL query
1055 * @param string $query
1058 function quickQuery($query)
1060 $res = sql_query($query);
1061 $obj = sql_fetch_object($res);
1062 return $obj->result;
1065 function getPluginNameFromPid($pid) {
1066 $res = sql_query('SELECT pfile FROM ' . sql_table('plugin') . ' WHERE pid=' . intval($pid) );
1067 $obj = sql_fetch_object($res);
1069 // return isset($obj->pfile) ? $obj->pfile : false;
1072 function selector() {
1073 global $itemid, $blogid, $memberid, $query, $amount, $archivelist, $maxresults;
1074 global $archive, $skinid, $blog, $memberinfo, $CONF, $member;
1075 global $imagepopup, $catid, $special;
1078 $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');
1079 $action = requestVar('action');
1081 if ( in_array($action, $actionNames) )
1083 global $DIR_LIBS, $errormessage;
1084 include_once($DIR_LIBS . 'ACTION.php');
1086 $errorInfo = $a->doAction($action);
1090 $errormessage = $errorInfo['message'];
1094 // show error when headers already sent out
1095 if ( headers_sent() && $CONF['alertOnHeadersSent'] )
1097 // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)
1098 if ( function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') )
1100 headers_sent($hsFile, $hsLine);
1101 $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';
1109 '<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>',
1110 'Page headers already sent'
1115 // make is so ?archivelist without blogname or blogid shows the archivelist
1116 // for the default weblog
1117 if ( serverVar('QUERY_STRING') == 'archivelist' )
1119 $archivelist = $CONF['DefaultBlog'];
1122 // now decide which type of skin we need
1125 // itemid given -> only show that item
1128 if ( !$manager->existsItem($itemid,intval($CONF['allowFuture']),intval($CONF['allowDrafts'])) )
1130 doError(_ERROR_NOSUCHITEM);
1133 global $itemidprev, $itemidnext, $catid, $itemtitlenext, $itemtitleprev;
1135 // 1. get timestamp, blogid and catid for item
1136 $query = 'SELECT itime, iblog, icat FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid);
1137 $res = sql_query($query);
1138 $obj = sql_fetch_object($res);
1140 // if a different blog id has been set through the request or selectBlog(),
1143 if ( $blogid && (intval($blogid) != $obj->iblog) )
1145 doError(_ERROR_NOSUCHITEM);
1148 // if a category has been selected which doesn't match the item, ignore the
1150 if ( ($catid != 0) && ($catid != $obj->icat) )
1155 $blogid = $obj->iblog;
1156 $timestamp = strtotime($obj->itime);
1158 $b =& $manager->getBlog($blogid);
1160 if ( $b->isValidCategory($catid) )
1162 $catextra = ' and icat=' . $catid;
1169 // get previous itemid and title
1170 $query = 'SELECT inumber, ititle FROM ' . sql_table('item') . ' WHERE itime<' . mysqldate($timestamp) . ' and idraft=0 and iblog=' . $blogid . $catextra . ' ORDER BY itime DESC LIMIT 1';
1171 $res = sql_query($query);
1173 $obj = sql_fetch_object($res);
1177 $itemidprev = $obj->inumber;
1178 $itemtitleprev = $obj->ititle;
1181 // get next itemid and title
1182 $query = 'SELECT inumber, ititle FROM ' . sql_table('item') . ' WHERE itime>' . mysqldate($timestamp) . ' and itime <= ' . mysqldate($b->getCorrectTime()) . ' and idraft=0 and iblog=' . $blogid . $catextra . ' ORDER BY itime ASC LIMIT 1';
1183 $res = sql_query($query);
1185 $obj = sql_fetch_object($res);
1189 $itemidnext = $obj->inumber;
1190 $itemtitlenext = $obj->ititle;
1198 // get next and prev month links ...
1199 global $archivenext, $archiveprev, $archivetype, $archivenextexists, $archiveprevexists;
1201 // sql queries for the timestamp of the first and the last published item
1202 $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 ORDER BY itime ASC";
1203 $first_timestamp=quickQuery ($query);
1204 $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 ORDER BY itime DESC";
1205 $last_timestamp=quickQuery ($query);
1207 sscanf($archive, '%d-%d-%d', $y, $m, $d);
1211 $archivetype = _ARCHIVETYPE_DAY;
1212 $t = mktime(0, 0, 0, $m, $d, $y);
1213 // one day has 24 * 60 * 60 = 86400 seconds
1214 $archiveprev = i18n::strftime('%Y-%m-%d', $t - 86400 );
1215 // check for published items
1216 if ( $t > $first_timestamp )
1218 $archiveprevexists = true;
1222 $archiveprevexists = false;
1227 $archivenext = i18n::strftime('%Y-%m-%d', $t);
1228 if ( $t < $last_timestamp )
1230 $archivenextexists = true;
1234 $archivenextexists = false;
1239 $archivetype = _ARCHIVETYPE_YEAR;
1240 $t = mktime(0, 0, 0, 12, 31, $y - 1);
1241 // one day before is in the previous year
1242 $archiveprev = i18n::strftime('%Y', $t);
1243 if ( $t > $first_timestamp )
1245 $archiveprevexists = true;
1249 $archiveprevexists = false;
1252 // timestamp for the next year
1253 $t = mktime(0, 0, 0, 1, 1, $y + 1);
1254 $archivenext = i18n::strftime('%Y', $t);
1255 if ( $t < $last_timestamp )
1257 $archivenextexists = true;
1261 $archivenextexists = false;
1266 $archivetype = _ARCHIVETYPE_MONTH;
1267 $t = mktime(0, 0, 0, $m, 1, $y);
1268 // one day before is in the previous month
1269 $archiveprev = i18n::strftime('%Y-%m', $t - 86400);
1270 if ( $t > $first_timestamp )
1272 $archiveprevexists = true;
1276 $archiveprevexists = false;
1279 // timestamp for the next month
1280 $t = mktime(0, 0, 0, $m+1, 1, $y);
1281 $archivenext = i18n::strftime('%Y-%m', $t);
1282 if ( $t < $last_timestamp )
1284 $archivenextexists = true;
1288 $archivenextexists = false;
1292 elseif ($archivelist)
1294 $type = 'archivelist';
1296 if ( is_numeric($archivelist) )
1298 $blogid = intVal($archivelist);
1302 $blogid = getBlogIDFromName($archivelist);
1307 doError(_ERROR_NOSUCHBLOG);
1314 $query = stripslashes($query);
1316 if ( is_numeric($blogid) )
1318 $blogid = intVal($blogid);
1322 $blogid = getBlogIDFromName($blogid);
1327 doError(_ERROR_NOSUCHBLOG);
1330 elseif ( $memberid )
1334 if ( !MEMBER::existsID($memberid) )
1336 doError(_ERROR_NOSUCHMEMBER);
1338 $memberinfo = $manager->getMember($memberid);
1340 elseif ( $imagepopup )
1342 // media object (images etc.)
1343 $type = 'imagepopup';
1345 // TODO: check if media-object exists
1346 // TODO: set some vars?
1350 // show regular index page
1355 // any type of skin with catid
1356 if ( $catid && !$blogid )
1358 $blogid = getBlogIDFromCatID($catid);
1361 // decide which blog should be displayed
1364 $blogid = $CONF['DefaultBlog'];
1367 $b =& $manager->getBlog($blogid);
1368 $blog = $b; // references can't be placed in global variables?
1370 if ( !$blog->isValid )
1372 doError(_ERROR_NOSUCHBLOG);
1375 // set catid if necessary
1378 // check if the category is valid
1379 if ( !$blog->isValidCategory($catid) )
1381 doError(_ERROR_NOSUCHCATEGORY);
1385 $blog->setSelectedCategory($catid);
1389 // decide which skin should be used
1390 if ( $skinid != '' && ($skinid == 0) )
1392 selectSkin($skinid);
1397 $skinid = $blog->getDefaultSkin();
1400 //$special = requestVar('special'); //get at top of file as global
1401 if ( !empty($special) && isValidShortName($special) )
1403 $type = strtolower($special);
1406 $skin = new SKIN($skinid);
1408 if ( !$skin->isValid )
1410 doError(_ERROR_NOSUCHSKIN);
1413 // set global skinpart variable so can determine quickly what is being parsed from any plugin or phpinclude
1418 $skin->parse($type);
1420 // check to see we should throw JustPosted event
1421 $blog->checkJustPosted();
1426 * Show error skin with given message. An optional skin-object to use can be given
1428 function doError($msg, $skin = '') {
1429 global $errormessage, $CONF, $skinid, $blogid, $manager;
1433 if (SKIN::existsID($skinid) ) {
1434 $skin = new SKIN($skinid);
1435 } elseif ($manager->existsBlogID($blogid) ) {
1436 $blog =& $manager->getBlog($blogid);
1437 $skin = new SKIN($blog->getDefaultSkin() );
1438 } elseif ($CONF['DefaultBlog']) {
1439 $blog =& $manager->getBlog($CONF['DefaultBlog']);
1440 $skin = new SKIN($blog->getDefaultSkin() );
1442 // this statement should actually never be executed
1443 $skin = new SKIN($CONF['BaseSkin']);
1448 $skinid = $skin->id;
1449 $errormessage = $msg;
1450 $skin->parse('error');
1454 function getConfig() {
1457 $query = 'SELECT * FROM ' . sql_table('config');
1458 $res = sql_query($query);
1460 while ($obj = sql_fetch_object($res) ) {
1461 $CONF[$obj->name] = $obj->value;
1465 // some checks for names of blogs, categories, templates, members, ...
1466 function isValidShortName($name) {
1468 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1469 # original eregi: eregi('^[a-z0-9]+$', $name)
1471 return preg_match('#^[a-z0-9]+$#i', $name);
1475 function isValidDisplayName($name) {
1477 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1478 # original eregi: eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name)
1480 return preg_match('#^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$#i', $name);
1484 function isValidCategoryName($name) {
1488 function isValidTemplateName($name) {
1490 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1491 # original eregi: eregi('^[a-z0-9/]+$', $name)
1492 // added - and _ to valid characters as of 4.00
1494 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
1498 function isValidSkinName($name) {
1500 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1501 # original eregi: eregi('^[a-z0-9/]+$', $name);
1502 // added - and _ to valid characters as of 4.00
1504 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
1508 // add and remove linebreaks
1509 function addBreaks($var) {
1513 function removeBreaks($var) {
1514 return preg_replace("/<br \/>([\r\n])/", "$1", $var);
1518 * Converts a unix timestamp to a mysql DATETIME format, and places
1521 function mysqldate($timestamp) {
1522 return '"' . date('Y-m-d H:i:s', $timestamp) . '"';
1526 * functions for use in index.php
1528 function selectBlog($shortname) {
1529 global $blogid, $archivelist;
1530 $blogid = getBlogIDFromName($shortname);
1532 // also force archivelist variable, if it is set
1534 $archivelist = $blogid;
1538 function selectSkin($skinname) {
1540 $skinid = SKIN::getIdFromName($skinname);
1544 * Can take either a category ID or a category name (be aware that
1545 * multiple categories can have the same name)
1547 function selectCategory($cat) {
1549 if (is_numeric($cat) ) {
1550 $catid = intval($cat);
1552 $catid = getCatIDFromName($cat);
1556 function selectItem($id) {
1558 $itemid = intval($id);
1561 // force the use of a translation file (warning: can cause warnings)
1562 function selectLanguage($language) {
1566 # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
1567 # original ereg_replace: preg_replace( '@\\|/@', '', $language) . '.php')
1568 # important note that '\' must be matched with '\\\\' in preg* expressions
1570 include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');
1574 function parseFile($filename, $includeMode = 'normal', $includePrefix = '') {
1575 $handler = new ACTIONS('fileparser');
1576 $parser = new PARSER(SKIN::getAllowedActionsForType('fileparser'), $handler);
1577 $handler->parser =& $parser;
1579 // set IncludeMode properties of parser
1580 PARSER::setProperty('IncludeMode', $includeMode);
1581 PARSER::setProperty('IncludePrefix', $includePrefix);
1583 if (!file_exists($filename) ) {
1584 doError('A file is missing');
1587 $fsize = filesize($filename);
1594 $fd = fopen ($filename, 'r');
1595 $contents = fread ($fd, $fsize);
1598 // parse file contents
1599 $parser->parse($contents);
1603 * Outputs a debug message
1605 function debug($msg) {
1606 echo '<p><b>' . $msg . "</b></p>\n";
1610 function addToLog($level, $msg) {
1611 ACTIONLOG::add($level, $msg);
1614 // shows a link to help file
1615 function help($id) {
1619 function helpHtml($id) {
1621 return helplink($id) . '<img src="' . $CONF['AdminURL'] . 'documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" title="' . _HELP_TT . '" /></a>';
1624 function helplink($id) {
1626 return '<a href="' . $CONF['AdminURL'] . 'documentation/help.html#'. $id . '" onclick="if (event && event.preventDefault) event.preventDefault(); return help(this.href);">';
1630 * Includes a PHP file. This method can be called while parsing templates and skins
1632 function includephp($filename) {
1633 // make predefined variables global, so most simple scripts can be used here
1635 // apache (names taken from PHP doc)
1636 global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;
1637 global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;
1638 global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;
1639 global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;
1640 global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;
1641 global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;
1642 global $REQUEST_URI;
1644 // php (taken from PHP doc)
1645 global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;
1646 global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;
1649 global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;
1651 if (@file_exists($filename) ) {
1657 * Checks if a certain plugin exists
1658 * @param string $plug
1661 function checkPlugin($plug) {
1663 global $DIR_PLUGINS;
1665 # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
1666 # original ereg_replace: ereg_replace( '[\\|/]', '', $plug) . '.php')
1667 # important note that '\' must be matched with '\\\\' in preg* expressions
1669 return file_exists($DIR_PLUGINS . preg_replace('#[\\\\|/]#', '', $plug) . '.php');
1675 * querystring to alter (e.g. foo=1&bar=2&x=y)
1677 * name of parameter to change (e.g. 'foo')
1679 * New value for that parameter (e.g. 3)
1681 * altered query string (for the examples above: foo=3&bar=2&x=y)
1683 function alterQueryStr($querystr, $param, $value) {
1684 $vars = i18n::explode('&', $querystr);
1687 for ($i = 0; $i < count($vars); $i++) {
1688 $v = i18n::explode('=', $vars[$i]);
1690 if ($v[0] == $param) {
1692 $vars[$i] = implode('=', $v);
1699 $vars[] = $param . '=' . $value;
1702 return ltrim(implode('&', $vars), '&');
1705 // passes one variable as hidden input field (multiple fields for arrays)
1706 // @see passRequestVars in varsx.x.x.php
1707 function passVar($key, $value) {
1709 if (is_array($value) ) {
1710 for ($i = 0; $i < sizeof($value); $i++) {
1711 passVar($key . '[' . $i . ']', $value[$i]);
1717 // other values: do stripslashes if needed
1718 ?><input type="hidden" name="<?php echo ENTITY::hsc($key)?>" value="<?php echo ENTITY::hsc(undoMagic($value) )?>" /><?php
1721 function checkVars($aVars) {
1722 global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;
1724 foreach ($aVars as $varName) {
1726 if (phpversion() >= '4.1.0') {
1728 if ( isset($_GET[$varName])
1729 || isset($_POST[$varName])
1730 || isset($_COOKIE[$varName])
1731 || isset($_ENV[$varName])
1732 || isset($_SESSION[$varName])
1733 || isset($_FILES[$varName])
1735 die('Sorry. An error occurred.');
1740 if ( isset($HTTP_GET_VARS[$varName])
1741 || isset($HTTP_POST_VARS[$varName])
1742 || isset($HTTP_COOKIE_VARS[$varName])
1743 || isset($HTTP_ENV_VARS[$varName])
1744 || isset($HTTP_SESSION_VARS[$varName])
1745 || isset($HTTP_POST_FILES[$varName])
1747 die('Sorry. An error occurred.');
1756 * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.
1759 function sanitizeParams()
1761 global $HTTP_SERVER_VARS;
1767 // REQUEST_URI of $HTTP_SERVER_VARS
1768 $str =& $HTTP_SERVER_VARS["REQUEST_URI"];
1769 serverStringToArray($str, $array, $frontParam);
1770 sanitizeArray($array);
1771 arrayToServerString($array, $frontParam, $str);
1773 // QUERY_STRING of $HTTP_SERVER_VARS
1774 $str =& $HTTP_SERVER_VARS["QUERY_STRING"];
1775 serverStringToArray($str, $array, $frontParam);
1776 sanitizeArray($array);
1777 arrayToServerString($array, $frontParam, $str);
1779 if (phpversion() >= '4.1.0') {
1780 // REQUEST_URI of $_SERVER
1781 $str =& $_SERVER["REQUEST_URI"];
1782 serverStringToArray($str, $array, $frontParam);
1783 sanitizeArray($array);
1784 arrayToServerString($array, $frontParam, $str);
1786 // QUERY_STRING of $_SERVER
1787 $str =& $_SERVER["QUERY_STRING"];
1788 serverStringToArray($str, $array, $frontParam);
1789 sanitizeArray($array);
1790 arrayToServerString($array, $frontParam, $str);
1794 convArrayForSanitizing($_GET, $array);
1795 sanitizeArray($array);
1796 revertArrayForSanitizing($array, $_GET);
1798 // $_REQUEST (only GET param)
1799 convArrayForSanitizing($_REQUEST, $array);
1800 sanitizeArray($array);
1801 revertArrayForSanitizing($array, $_REQUEST);
1805 * Check ticket when not checked in plugin's admin page
1807 * Also avoid the access to plugin/index.php by guest user.
1809 function ticketForPlugin()
1811 global $CONF, $DIR_PLUGINS, $member, $ticketforplugin;
1814 $ticketforplugin = array();
1815 $ticketforplugin['ticket'] = FALSE;
1817 /* $_SERVER['PATH_TRANSLATED']
1818 * http://www.php.net/manual/en/reserved.variables.server.php
1819 * Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly
1820 * under the Apache 2 SAPI in contrast to the situation in Apache 1,
1821 * where it's set to the same value as the SCRIPT_FILENAME server variable
1822 * when it's not populated by Apache.
1823 * This change was made to comply with the CGI specification
1824 * that PATH_TRANSLATED should only exist if PATH_INFO is defined.
1825 * Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.
1828 /* Check if using plugin's php file. */
1829 $p_translated = serverVar('SCRIPT_FILENAME');
1831 if (!file_exists($p_translated) )
1833 header("HTTP/1.0 404 Not Found");
1837 $p_translated = str_replace('\\', '/', $p_translated);
1838 $d_plugins = str_replace('\\', '/', $DIR_PLUGINS);
1840 // This isn't plugin php file.
1841 if ( i18n::strpos($p_translated, $d_plugins) !== 0 )
1846 // Solve the plugin php file or admin directory
1847 $phppath = i18n::substr($p_translated, i18n::strlen($d_plugins) );
1848 // Remove the first "/" if exists.
1849 $phppath = preg_replace('#^/#', '', $phppath);
1850 // Remove the first "NP_" and the last ".php" if exists.
1851 $path = preg_replace('#^NP_(.*)\.php$#', '$1', $phppath);
1852 // Remove the "/" and beyond.
1853 $path = preg_replace('#^([^/]*)/(.*)$#', '$1', $path);
1855 // Solve the plugin name.
1857 $query = 'SELECT `pfile` FROM '.sql_table('plugin');
1858 $res = sql_query($query);
1860 while($row = sql_fetch_row($res) )
1862 $name = i18n::substr($row[0], 3);
1863 $plugins[strtolower($name)] = $name;
1866 sql_free_result($res);
1868 if (array_key_exists($path, $plugins))
1870 $plugin_name = $plugins[$path];
1872 else if (in_array($path, $plugins))
1874 $plugin_name = $path;
1878 header("HTTP/1.0 404 Not Found");
1882 /* Return if not index.php */
1883 if ( ($phppath != strtolower($plugin_name) . '/') && ($phppath != strtolower($plugin_name) . '/index.php') )
1888 /* Exit if not logged in. */
1889 if ( !$member->isLoggedIn() )
1891 exit('You aren\'t logged in.');
1894 global $manager, $DIR_LIBS, $DIR_LOCALE, $HTTP_GET_VARS, $HTTP_POST_VARS;
1896 /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */
1897 if (!($p_translated = serverVar('PATH_TRANSLATED') ) )
1899 $p_translated = serverVar('SCRIPT_FILENAME');
1902 if ($file = @file($p_translated) )
1906 foreach($file as $line)
1908 if (preg_match('/[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]/i', $prevline . $line) )
1917 /* Show a form if not valid ticket */
1918 if ( ( strstr(serverVar('REQUEST_URI'), '?') || serverVar('QUERY_STRING')
1919 || strtoupper(serverVar('REQUEST_METHOD') ) == 'POST')
1920 && (!$manager->checkTicket() ) )
1922 $oPluginAdmin = new PluginAdmin($plugin_name);
1923 $oPluginAdmin->start();
1924 echo '<p>' . _ERROR_BADTICKET . "</p>\n";
1926 /* Show the form to confirm action */
1927 // PHP 4.0.x support
1928 $get = (isset($_GET) ) ? $_GET : $HTTP_GET_VARS;
1929 $post = (isset($_POST) ) ? $_POST : $HTTP_POST_VARS;
1931 // Resolve URI and QUERY_STRING
1932 if ($uri = serverVar('REQUEST_URI') )
1934 list($uri, $qstring) = i18n::explode('?', $uri);
1938 if ( !($uri = serverVar('PHP_SELF') ) )
1940 $uri = serverVar('SCRIPT_NAME');
1942 $qstring = serverVar('QUERY_STRING');
1946 $qstring = '?' . $qstring;
1949 echo '<p>' . _SETTINGS_UPDATE . ' : ' . _QMENU_PLUGINS . ' <span style="color:red;">' . ENTITY::hsc($plugin_name) . "</span> ?</p>\n";
1951 switch(strtoupper(serverVar('REQUEST_METHOD') ) )
1954 echo '<form method="POST" action="'.ENTITY::hsc($uri.$qstring).'">';
1955 $manager->addTicketHidden();
1956 _addInputTags($post);
1960 echo '<form method="GET" action="'.ENTITY::hsc($uri).'">';
1961 $manager->addTicketHidden();
1962 _addInputTags($get);
1968 echo '<input type="submit" value="' . _YES . '" /> ';
1969 echo '<input type="button" value="' . _NO . '" onclick="history.back(); return false;" />';
1972 $oPluginAdmin->end();
1976 /* Create new ticket */
1977 $ticket=$manager->addTicketToUrl('');
1978 $ticketforplugin['ticket']=i18n::substr($ticket,i18n::strpos($ticket,'ticket=')+7);
1981 function _addInputTags(&$keys,$prefix=''){
1982 foreach($keys as $key=>$value){
1983 if ($prefix) $key=$prefix.'['.$key.']';
1984 if (is_array($value)) _addInputTags($value,$key);
1986 if (get_magic_quotes_gpc()) $value=stripslashes($value);
1987 if ($key=='ticket') continue;
1988 echo '<input type="hidden" name="'.ENTITY::hsc($key).
1989 '" value="'.ENTITY::hsc($value).'" />'."\n";
1995 * Convert the server string such as $_SERVER['REQUEST_URI']
1996 * to arry like arry['blogid']=1 and array['page']=2 etc.
1998 function serverStringToArray($str, &$array, &$frontParam)
2004 // split front param, e.g. /index.php, and others, e.g. blogid=1&page=2
2005 if (strstr($str, "?")){
2006 list($frontParam, $args) = preg_split("/\?/", $str, 2);
2013 // If there is no args like blogid=1&page=2, return
2014 if (!strstr($str, "=") && !i18n::strlen($frontParam)) {
2019 $array = i18n::explode("&", $args);
2023 * Convert array like array['blogid'] to server string
2024 * such as $_SERVER['REQUEST_URI']
2026 function arrayToServerString($array, $frontParam, &$str)
2028 if (strstr($str, "?")) {
2029 $str = $frontParam . "?";
2033 if (count($array)) {
2034 $str .= implode("&", $array);
2039 * Sanitize array parameters.
2040 * This function checks both key and value.
2041 * - check key if it inclues " (double quote), remove from array
2042 * - check value if it includes \ (escape sequece), remove remaining string
2044 function sanitizeArray(&$array)
2046 $excludeListForSanitization = array('query');
2047 // $excludeListForSanitization = array();
2049 foreach ($array as $k => $v) {
2051 // split to key and value
2052 list($key, $val) = preg_split("/=/", $v, 2);
2057 // when magic quotes is on, need to use stripslashes,
2058 // and then addslashes
2059 if (get_magic_quotes_gpc()) {
2060 $val = stripslashes($val);
2062 // note that we must use addslashes here because this function is called before the db connection is made
2063 // and sql_real_escape_string needs a db connection
2064 $val = addslashes($val);
2066 // if $key is included in exclude list, skip this param
2067 if (!in_array($key, $excludeListForSanitization)) {
2070 if (i18n::strpos($val, '\\')) {
2071 list($val, $tmp) = i18n::explode('\\', $val);
2074 // remove control code etc.
2075 $val = strtr($val, "\0\r\n<>'\"", " ");
2078 if (preg_match('/\"/i', $key)) {
2083 // set sanitized info
2084 $array[$k] = sprintf("%s=%s", $key, $val);
2090 * Convert array for sanitizeArray function
2092 function convArrayForSanitizing($src, &$array)
2095 foreach ($src as $key => $val) {
2096 if (key_exists($key, $_GET)) {
2097 array_push($array, sprintf("%s=%s", $key, $val));
2103 * Revert array after sanitizeArray function
2105 function revertArrayForSanitizing($array, &$dst)
2107 foreach ($array as $v) {
2108 list($key, $val) = preg_split("/=/", $v, 2);
2114 * Stops processing the request and redirects to the given URL.
2115 * - no actual contents should have been sent to the output yet
2116 * - the URL will be stripped of illegal or dangerous characters
2118 function redirect($url) {
2119 $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%*]|i', '', $url);
2120 header('Location: ' . $url);
2125 * Returns the Javascript code for a bookmarklet that works on most modern browsers
2128 function getBookmarklet($blogid) {
2132 $document = 'document';
2133 $bookmarkletline = "javascript:Q='';x=".$document.";y=window;if(x.selection){Q=x.selection.createRange().text;}else if(y.getSelection){Q=y.getSelection();}else if(x.getSelection){Q=x.getSelection();}wingm=window.open('";
2134 $bookmarkletline .= $CONF['AdminURL'] . "bookmarklet.php?blogid=$blogid";
2135 $bookmarkletline .="&logtext='+escape(Q)+'&loglink='+escape(x.location.href)+'&loglinktitle='+escape(x.title),'nucleusbm','scrollbars=yes,width=600,height=550,left=10,top=10,status=yes,resizable=yes');wingm.focus();";
2137 return $bookmarkletline;
2139 // END: functions from the end of file ADMIN.php
2142 * Returns a variable or null if not set
2144 * @param mixed Variable
2145 * @return mixed Variable
2147 function ifset(&$var) {
2156 * Returns number of subscriber to an event
2159 * @return number of subscriber(s)
2161 function numberOfEventSubscriber($event) {
2162 $query = 'SELECT COUNT(*) as count FROM ' . sql_table('plugin_event') . ' WHERE event=\'' . $event . '\'';
2163 $res = sql_query($query);
2164 $obj = sql_fetch_object($res);
2169 * sets $special global variable for use in index.php before selector()
2174 function selectSpecialSkinType($id) {
2176 $special = strtolower($id);
2180 * cleans filename of uploaded file for writing to file system
2183 * @return String cleaned filename ready for use
2185 function cleanFileName($str) {
2186 $str = strtolower($str);
2187 $ext_point = i18n::strrpos($str,".");
2188 if ($ext_point===false) return false;
2189 $ext = i18n::substr($str,$ext_point,i18n::strlen($str));
2190 $str = i18n::substr($str,0,$ext_point);
2192 return preg_replace("/[^a-z0-9-]/","_",$str).$ext;
2196 * Centralisation of the functions to send mail
2197 * Deprecated since 4.0:
2198 * Please use functions in NOTIFICATION class instead
2200 function getMailFooter()
2202 NOTIFICATION::get_mail_footer();
2204 function isValidMailAddress($address)
2206 return NOTIFICATION::address_validation($address);
2209 * Centralisation of the functions that deals XML entities
2210 * Deprecated since 4.0:
2211 * Please use ENTITY::FunctionName(...) instead
2213 function highlight($text, $expression, $highlight)
2215 return ENTITY::highlight($text, $expression, $highlight);
2217 function shorten($string, $maxlength, $suffix)
2219 return ENTITY::shorten($string, $maxlength, $suffix);
2221 function stringStripTags ($string)
2223 return ENTITY::strip_tags($string);
2225 function toAscii($string)
2227 return ENTITY::anchor_footnoting($string);
2229 function stringToAttribute ($string)
2231 return ENTITY::hsc($string);
2233 function stringToXML ($string)
2235 return ENTITY::hen($string);
2237 function encode_desc($data)
2239 return ENTITY::hen($data);
2242 * Centralisation of the functions that deals with locales
2243 * This functions is based on the old way to deal with languages
2244 * Deprecated since 4.0:
2246 /* NOTE: use i18n::get_current_locale() directly instead of this */
2247 function getLanguageName()
2249 if( ($language = i18n::convert_locale_to_old_language_file_name(i18n::get_current_locale())) === FALSE )
2251 $language ='english';
2256 /* NOTE: use i18n::get_available_locales() directly instead of this */
2257 function checkLanguage($lang)
2259 return ( preg_match('#^(.+)_(.+)_(.+)$#', $lang)
2260 || i18n::convert_old_language_file_name_to_locale($lang) );
2262 /* NOTE: use i18n::formatted_datetime() directly instead of this */
2263 function formatDate($format, $timestamp, $default_format, &$blog)
2265 $offset = date('Z', $timestamp);
2268 $offset += $blog->getTimeOffset() * 3600;
2270 return i18n::formatted_datetime($format, $timestamp, $default_format, $offset);
2273 * Centralisation of the functions that generate links
2274 * Deprecated since 4.0:
2275 * Please use LINK::FunctionName(...) instead
2277 function createItemLink($itemid, $extra = '')
2279 return LINK::create_item_link($itemid, $extra);
2281 function createMemberLink($memberid, $extra = '')
2283 return LINK::create_member_link($memberid, $extra);
2285 function createCategoryLink($catid, $extra = '')
2287 return LINK::create_category_link($catid, $extra);
2289 function createArchiveListLink($blogid = '', $extra = '')
2291 return LINK::create_archivelist_link($blogid, $extra);
2293 function createArchiveLink($blogid, $archive, $extra = '')
2295 return LINK::create_archive_link($blogid, $archive, $extra);
2297 function createBlogidLink($blogid, $params = '')
2299 return LINK::create_blogid_link($blogid, $params = '');
2301 function createLink($type, $params)
2303 return LINK::create_link($type, $params);
2305 function createBlogLink($url, $params)
2307 return LINK::create_blog_link($url, $params);