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) )
46 $DIR_LOCALES = $DIR_NUCLEUS . 'locales/';
47 $DIR_LANG = $DIR_LOCALES;
51 * load and initialize i18n class
53 if (!class_exists('i18n', FALSE))
55 include($DIR_LIBS . 'i18n.php');
57 if ( !i18n::init('UTF-8', $DIR_LOCALES) )
59 exit('Fail to initialize i18n class.');
62 * FIXME: This is for compatibility since 4.0, should be obsoleted at future release.
64 define('_CHARSET', i18n::get_current_charset());
67 * Indicates when Nucleus should display startup errors. Set to 1 if you want
68 * the error enabled (default), false otherwise
71 * Displays an error when visiting a public Nucleus page and headers have
72 * been sent out to early. This usually indicates an error in either a
73 * configuration file or a translation file, and could cause Nucleus to
76 * Displays an error only when visiting the admin area, and when one or
77 * more of the installation files (install.php, install.sql, upgrades/
78 * directory) are still on the server.
80 if ( !array_key_exists('alertOnHeadersSent', $CONF) || $CONF['alertOnHeadersSent'] !== 0 )
82 $CONF['alertOnHeadersSent'] = 1;
84 $CONF['alertOnSecurityRisk'] = 1;
86 * NOTE: this should be removed when releasing 4.0
87 $CONF['ItemURL'] = $CONF['Self'];
88 $CONF['ArchiveURL'] = $CONF['Self'];
89 $CONF['ArchiveListURL'] = $CONF['Self'];
90 $CONF['MemberURL'] = $CONF['Self'];
91 $CONF['SearchURL'] = $CONF['Self'];
92 $CONF['BlogURL'] = $CONF['Self'];
93 $CONF['CategoryURL'] = $CONF['Self'];
97 * NOTE: this should be removed when releasing 4.0
98 * switch URLMode back to normal when $CONF['Self'] ends in .php
99 * this avoids urls like index.php/item/13/index.php/item/15
100 if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {
101 $CONF['URLMode'] = 'normal';
105 * Set these to 1 to allow viewing of future items or draft items
106 * Should really never do this, but can be useful for some plugins that might need to
107 * Could cause some other issues if you use future posts otr drafts
110 $CONF['allowDrafts'] = 0;
111 $CONF['allowFuture'] = 0;
113 if ( getNucleusPatchLevel() > 0 )
115 $nucleus['version'] .= '/' . getNucleusPatchLevel();
119 if ( !isset($CONF['installscript']) )
121 $CONF['installscript'] = 0;
124 /* we will use postVar, getVar, ... methods instead of $_GET, $_POST ...*/
125 if ( $CONF['installscript'] != 1 )
127 /* vars were already included in install.php */
128 include_once($DIR_LIBS . 'vars4.1.0.php');
131 /* sanitize option */
132 $bLoggingSanitizedResult=0;
133 $bSanitizeAndContinue=0;
135 $orgRequestURI = serverVar('REQUEST_URI');
138 /* get all variables that can come from the request and put them in the global scope */
139 $blogid = requestVar('blogid');
140 $itemid = intRequestVar('itemid');
141 $catid = intRequestVar('catid');
142 $skinid = requestVar('skinid');
143 $memberid = requestVar('memberid');
144 $archivelist = requestVar('archivelist');
145 $imagepopup = requestVar('imagepopup');
146 $archive = requestVar('archive');
147 $query = requestVar('query');
148 $highlight = requestVar('highlight');
149 $amount = requestVar('amount');
150 $action = requestVar('action');
151 $nextaction = requestVar('nextaction');
152 $maxresults = requestVar('maxresults');
153 $startpos = intRequestVar('startpos');
156 $special = requestVar('special');
157 $virtualpath = ((getVar('virtualpath') != null) ? getVar('virtualpath') : serverVar('PATH_INFO'));
159 if ( !headers_sent() )
161 header('Generator: Nucleus CMS ' . $nucleus['version']);
164 /* include core classes that are needed for login & plugin handling */
165 include_once($DIR_LIBS . 'mysql.php');
166 /* added for 3.5 sql_* wrapper */
167 global $MYSQL_HANDLER;
168 if ( !isset($MYSQL_HANDLER) )
170 $MYSQL_HANDLER = array('mysql','');
172 if ( $MYSQL_HANDLER[0] == '' )
174 $MYSQL_HANDLER[0] = 'mysql';
176 include_once($DIR_LIBS . 'sql/'.$MYSQL_HANDLER[0].'.php');
177 /* end new for 3.5 sql_* wrapper */
178 include($DIR_LIBS . 'MEMBER.php');
179 include($DIR_LIBS . 'ACTIONLOG.php');
180 include($DIR_LIBS . 'MANAGER.php');
181 include($DIR_LIBS . 'PLUGIN.php');
183 $manager =& MANAGER::instance();
186 * make sure there's no unnecessary escaping:
187 * set_magic_quotes_runtime(0);
189 if ( version_compare(PHP_VERSION, '5.3.0', '<') )
191 ini_set('magic_quotes_runtime', '0');
195 if ( !array_key_exists('UsingAdminArea', $CONF) )
197 $CONF['UsingAdminArea'] = 0;
200 /* only needed when updating logs */
201 if ( $CONF['UsingAdminArea'] )
203 /* XML-RPC client classes */
204 include($DIR_LIBS . 'xmlrpc.inc.php');
205 include_once($DIR_LIBS . 'ADMIN.php');
208 /* connect to database */
212 /* logs sanitized result if need */
213 if ( $orgRequestURI!==serverVar('REQUEST_URI') )
215 $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";
216 $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');
217 if ( $bLoggingSanitizedResult )
219 addToLog(WARNING, $msg);
221 if ( !$bSanitizeAndContinue )
227 /* makes sure database connection gets closed on script termination */
228 register_shutdown_function('sql_disconnect');
234 * Nucleus CMS 4.0 uses 'locale' instead of 'language' to decide which translation file used
235 * Here simply convert old name to new name without checking translation file existance
236 * FIXME: This is for compatibility, should be obsoleted near future.
238 if ( !array_key_exists('Locale', $CONF) )
240 $CONF['Locale'] =& $CONF['Language'];
243 if ( !preg_match('#^(.+)_(.+)_(.+)$#', $CONF['Locale'])
244 && ($CONF['Locale'] = i18n::convert_old_language_file_name_to_locale($CONF['Language'])) === FALSE )
246 $CONF['Locale'] = '';
248 $locale = $CONF['Locale'];
250 /* Properly set $CONF['Self'] and others if it's not set...
251 * usually when we are access from admin menu
253 if ( !array_key_exists('Self', $CONF) )
255 $CONF['Self'] = $CONF['IndexURL'];
257 if ( $CONF['Self'][i18n::strlen($CONF['Self']) -1] == "/" )
259 $CONF['Self'] = i18n::substr($CONF['Self'], 0, i18n::strlen($CONF['Self']) -1);
263 $CONF['ItemURL'] = $CONF['Self'];
264 $CONF['ArchiveURL'] = $CONF['Self'];
265 $CONF['ArchiveListURL'] = $CONF['Self'];
266 $CONF['MemberURL'] = $CONF['Self'];
267 $CONF['SearchURL'] = $CONF['Self'];
268 $CONF['BlogURL'] = $CONF['Self'];
269 $CONF['CategoryURL'] = $CONF['Self'];
272 *switch URLMode back to normal when $CONF['Self'] ends in .php
273 * this avoids urls like index.php/item/13/index.php/item/15
275 if ( !array_key_exists('URLMode', $CONF)
276 || (($CONF['URLMode'] == 'pathinfo')
277 && (i18n::substr($CONF['Self'], i18n::strlen($CONF['Self']) - 4) == '.php')) )
279 $CONF['URLMode'] = 'normal';
282 /* automatically use simpler toolbar for mozilla */
283 if ( ($CONF['DisableJsTools'] == 0)
284 && strstr(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0')
285 && strstr(serverVar('HTTP_USER_AGENT'), 'Gecko') )
287 $CONF['DisableJsTools'] = 2;
290 /* login if cookies set*/
291 $member = new MEMBER();
293 /* secure cookie key settings (either 'none', 0, 8, 16, 24, or 32) */
294 if ( !array_key_exists('secureCookieKey', $CONF) )
296 $CONF['secureCookieKey'] = 24;
298 switch( $CONF['secureCookieKey'] )
301 $CONF['secureCookieKeyIP'] = preg_replace('/\.[0-9]+\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
304 $CONF['secureCookieKeyIP'] = preg_replace('/\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
307 $CONF['secureCookieKeyIP'] = preg_replace('/\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
310 $CONF['secureCookieKeyIP'] = serverVar('REMOTE_ADDR');
313 $CONF['secureCookieKeyIP'] = '';
317 * login/logout when required or renew cookies
318 * and decide locale on this session before plugin event generates
320 if ( $action == 'login' )
322 /* Form Authentication */
323 $login = postVar('login');
324 $pw = postVar('password');
325 /* shared computer or not */
326 $shared = intPostVar('shared');
327 /* avoid md5 collision by using a long key */
328 $pw=i18n::substr($pw,0,40);
330 if ( $member->login($login, $pw) )
332 $member->newCookieKey();
333 $member->setCookies($shared);
335 if ( $CONF['secureCookieKey'] !== 'none' )
337 /* secure cookie key */
338 $member->setCookieKey(md5($member->getCookieKey().$CONF['secureCookieKeyIP']));
342 /* allows direct access to parts of the admin area after logging in */
345 $action = $nextaction;
348 /* NOTE: include translation file and set locale */
349 $locale = include_translation($locale, $member);
350 i18n::set_current_locale($locale);
352 $manager->notify('LoginSuccess', array('member' => &$member, 'username' => $login) );
354 ACTIONLOG::add(INFO, "Login successful for $login (sharedpc=$shared)");
358 /* errormessage for [%errordiv%] */
359 $trimlogin = trim($login);
360 if ( empty($trimlogin) )
362 $errormessage = "Please enter a username.";
366 $errormessage = 'Login failed for ' . $login;
369 /* NOTE: include translation file and set locale */
370 $locale = include_translation($locale);
371 i18n::set_current_locale($locale);
373 $manager->notify('LoginFailed', array('username' => $login) );
374 ACTIONLOG::add(INFO, $errormessage);
379 * TODO: this should be removed when releasing 4.0
380 Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details
381 elseif ( serverVar('PHP_AUTH_USER') && serverVar('PHP_AUTH_PW') )
383 // HTTP Authentication
384 $login = serverVar('PHP_AUTH_USER');
385 $pw = serverVar('PHP_AUTH_PW');
387 if ( $member->login($login, $pw) )
389 $manager->notify('LoginSuccess',array('member' => &$member));
390 ACTIONLOG::add(INFO, "HTTP authentication successful for $login");
394 $manager->notify('LoginFailed',array('username' => $login));
395 ACTIONLOG::add(INFO, 'HTTP authentication failed for ' . $login);
397 //Since bad credentials, generate an apropriate error page
398 header("WWW-Authenticate: Basic realm=\"Nucleus CMS {$nucleus['version']}\"");
399 header('HTTP/1.0 401 Unauthorized');
400 echo 'Invalid username or password';
406 elseif ( ($action == 'logout')
408 && cookieVar($CONF['CookiePrefix'] . 'user') )
410 /* remove cookies on logout */
411 setcookie($CONF['CookiePrefix'] . 'user', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
412 setcookie($CONF['CookiePrefix'] . 'loginkey', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
414 /* NOTE: include translation file and set locale */
415 $locale = include_translation($locale);
416 i18n::set_current_locale($locale);
418 $manager->notify('Logout', array('username' => cookieVar($CONF['CookiePrefix'] . 'user') ) );
420 elseif ( cookieVar($CONF['CookiePrefix'] . 'user') )
422 /* Cookie Authentication */
423 $ck=cookieVar($CONF['CookiePrefix'] . 'loginkey');
426 * avoid md5 collision by using a long key
428 $ck = i18n::substr($ck,0,32);
429 if ( $CONF['secureCookieKey']!=='none' )
431 $ck = md5($ck.$CONF['secureCookieKeyIP']);
433 $res = $member->cookielogin(cookieVar($CONF['CookiePrefix'] . 'user'), $ck );
436 /* renew cookies when not on a shared computer */
438 && (cookieVar($CONF['CookiePrefix'] . 'sharedpc') != 1)
439 && (!headers_sent() ) )
441 $member->setCookieKey(cookieVar($CONF['CookiePrefix'] . 'loginkey'));
442 $member->setCookies();
445 /* NOTE: include translation file and set locale */
446 $locale = include_translation($locale, $member);
447 i18n::set_current_locale($locale);
451 /* NOTE: include translation file and set locale */
452 $locale = include_translation($locale);
453 i18n::set_current_locale($locale);
456 /* login completed */
457 $manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );
460 * Release ticket for plugin
464 /* first, let's see if the site is disabled or not. always allow admin area access. */
465 if ( $CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea'] )
467 redirect($CONF['DisableSiteURL']);
471 /* load other classes */
472 include($DIR_LIBS . 'PARSER.php');
473 include($DIR_LIBS . 'SKIN.php');
474 include($DIR_LIBS . 'TEMPLATE.php');
475 include($DIR_LIBS . 'BLOG.php');
476 include($DIR_LIBS . 'BODYACTIONS.php');
477 include($DIR_LIBS . 'COMMENTS.php');
478 include($DIR_LIBS . 'COMMENT.php');
479 /* include($DIR_LIBS . 'ITEM.php'); */
480 include($DIR_LIBS . 'NOTIFICATION.php');
481 include($DIR_LIBS . 'BAN.php');
482 include($DIR_LIBS . 'PAGEFACTORY.php');
483 include($DIR_LIBS . 'SEARCH.php');
484 include($DIR_LIBS . 'ENTITY.php');
485 include($DIR_LIBS . 'Link.php');
487 /* set lastVisit cookie (if allowed) */
488 if ( !headers_sent() )
490 if ( $CONF['LastVisit'] )
492 setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
496 setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
501 Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details
503 // To remove after v2.5 is released and translation files have been updated.
504 // Including this makes sure that translation files for v2.5beta can still be used for v2.5final
505 // without having weird _SETTINGS_EXTAUTH string showing up in the admin area.
506 if (!defined('_MEMBERS_BYPASS'))
508 define('_SETTINGS_EXTAUTH', 'Enable External Authentication');
509 define('_WARNING_EXTAUTH', 'Warning: Enable only if needed.');
510 define('_MEMBERS_BYPASS', 'Use External Authentication');
514 /* make sure the archivetype skinvar keeps working when _ARCHIVETYPE_XXX not defined */
515 if ( !defined('_ARCHIVETYPE_MONTH') )
517 define('_ARCHIVETYPE_DAY', 'day');
518 define('_ARCHIVETYPE_MONTH', 'month');
519 define('_ARCHIVETYPE_YEAR', 'year');
522 /* decode path_info */
523 if ( $CONF['URLMode'] == 'pathinfo' )
525 /* initialize keywords if this hasn't been done before */
526 if ( !isset($CONF['ItemKey']) || $CONF['ItemKey'] == '' )
528 $CONF['ItemKey'] = 'item';
531 if ( !isset($CONF['ArchiveKey']) || $CONF['ArchiveKey'] == '' )
533 $CONF['ArchiveKey'] = 'archive';
536 if ( !isset($CONF['ArchivesKey']) || $CONF['ArchivesKey'] == '' )
538 $CONF['ArchivesKey'] = 'archives';
541 if ( !isset($CONF['MemberKey']) || $CONF['MemberKey'] == '' )
543 $CONF['MemberKey'] = 'member';
546 if ( !isset($CONF['BlogKey']) || $CONF['BlogKey'] == '' )
548 $CONF['BlogKey'] = 'blog';
551 if ( !isset($CONF['CategoryKey']) || $CONF['CategoryKey'] == '' )
553 $CONF['CategoryKey'] = 'category';
556 if ( !isset($CONF['SpecialskinKey']) || $CONF['SpecialskinKey'] == '' )
558 $CONF['SpecialskinKey'] = 'special';
565 /* e.g. item, blog, ... */
566 'type' => basename(serverVar('SCRIPT_NAME') ),
567 'info' => $virtualpath,
568 'complete' => &$parsed
574 /* default implementation */
575 $data = i18n::explode("/", $virtualpath );
576 for ( $i = 0; $i < sizeof($data); $i++ )
580 /* item/1 (blogid) */
581 case $CONF['ItemKey']:
584 if ( $i < sizeof($data) )
586 $itemid = intval($data[$i]);
590 /* archives/1 (blogid) */
591 case $CONF['ArchivesKey']:
593 if ( $i < sizeof($data) )
595 $archivelist = intval($data[$i]);
599 /* two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid) */
600 case $CONF['ArchiveKey']:
601 if ( (($i + 1) < sizeof($data) ) && (!strstr($data[$i + 1], '-') ) )
603 $blogid = intval($data[++$i]);
606 if ( $i < sizeof($data) )
608 $archive = $data[$i];
615 case $CONF['BlogKey']:
617 if ( $i < sizeof($data) )
619 $blogid = intval($data[$i]);
623 /* category/1 (catid) */
624 case $CONF['CategoryKey']:
627 if ( $i < sizeof($data) )
629 $catid = intval($data[$i]);
633 case $CONF['MemberKey']:
635 if ( $i < sizeof($data) )
637 $memberid = intval($data[$i]);
641 case $CONF['SpecialskinKey']:
643 if ( $i < sizeof($data) )
645 $special = $data[$i];
646 $_REQUEST['special'] = $special;
657 * PostParseURL is a place to cleanup any of the path-related global variables before the selector function is run.
658 * It has 2 values in the data in case the original virtualpath is needed, but most the use will be in tweaking
659 * global variables to clean up (scrub out catid or add catid) or to set someother global variable based on
660 * the values of something like catid or itemid
666 /* e.g. item, blog, ... */
667 'type' => basename(serverVar('SCRIPT_NAME') ),
668 'info' => $virtualpath
673 * NOTE: Here is the end of initialization
677 * This function includes or requires the specified library file
678 * @param string $file
679 * @param bool $once use the _once() version
680 * @param bool $require use require() instead of include()
682 function include_libs($file, $once = TRUE, $require = TRUE)
686 // begin if: $DIR_LIBS isn't a directory
687 if ( !is_dir($DIR_LIBS) )
692 $lib_path = $DIR_LIBS . $file;
695 if ( $once && $require )
697 require_once($lib_path);
699 else if ( $once && !$require )
701 include_once($lib_path);
716 * This function includes or requires the specified plugin file
717 * @param string $file
718 * @param bool $once use the _once() version
719 * @param bool $require use require() instead of include()
721 function include_plugins($file, $once = TRUE, $require = TRUE)
725 // begin if: $DIR_LIBS isn't a directory
726 if ( !is_dir($DIR_PLUGINS) )
731 $plugin_path = $DIR_PLUGINS . $file;
734 if ( $once && $require )
736 require_once($plugin_path);
738 else if ( $once && !$require )
740 include_once($plugin_path);
744 require($plugin_path);
748 include($plugin_path);
753 * This function decide which locale is used and include translation
754 * @param string $locale locale name referring to 'language tags' defined in RFC 5646
755 * @param mixed $member member object
757 function include_translation($locale, $member = FALSE)
762 * 1. user's locale is used if set
763 * 2. system default is used if it is not empty
764 * 3. else 'en_Latn_US.ISO-8859-1.php' is included
765 * because this translation file is expected to include only 7bit ASCII characters
766 * which common in whole character coding scheme
768 if ( $member && $member->getLocale() )
770 $locale = $member->getLocale();
772 $translation_file = $DIR_LOCALES . $locale . '.' . i18n::get_current_charset() . '.php';
773 if ( !file_exists($translation_file) )
775 $locale = 'en_Latn_US';
776 $translation_file = $DIR_LOCALES . 'en_Latn_US.ISO-8859-1.php';
778 include($translation_file);
783 * This function returns the integer value of $_POST for the variable $name
784 * @param string $name field to get the integer value of
787 function intPostVar($name)
789 return intval(postVar($name));
794 * This function returns the integer value of $_GET for the variable $name
795 * @param string $name field to get the integer value of
798 function intGetVar($name)
800 return intval(getVar($name));
805 * This function returns the integer value of $_REQUEST for the variable $name. Also checks $_GET and $_POST if not found in $_REQUEST
806 * @param string $name field to get the integer value of
809 function intRequestVar($name)
811 return intval(requestVar($name));
816 * This function returns the integer value of $_COOKIE for the variable $name
817 * @param string $name field to get the integer value of
820 function intCookieVar($name)
822 return intval(cookieVar($name));
827 * This function returns the current Nucleus version (100 = 1.00, 101 = 1.01, etc...)
830 function getNucleusVersion()
837 * TODO: Better description of this function.
839 * Power users can install patches in between nucleus releases. These patches
840 * usually add new functionality in the plugin API and allow those to
841 * be tested without having to install CVS.
845 function getNucleusPatchLevel()
852 * This function returns the latest Nucleus version available for download from nucleuscms.org or FALSE if unable to attain data
853 * Format will be major.minor/patachlevel e.g. 3.41 or 3.41/02
854 * @return string|bool
856 function getLatestVersion()
858 // begin if: cURL is not available in this PHP installation
859 if ( !function_exists('curl_init') )
866 curl_setopt ($curl, CURLOPT_URL, 'http://nucleuscms.org/version_check.php');
867 curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
868 curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
869 $return = curl_exec($curl);
876 * This function returns a Nucleus table name with the appropriate prefix
877 * @param string $name
880 function sql_table($name)
882 global $MYSQL_PREFIX;
884 // begin if: no MySQL prefix
885 if ( empty($MYSQL_PREFIX) )
887 return 'nucleus_' . $name;
889 // else: use MySQL prefix
892 return $MYSQL_PREFIX . 'nucleus_' . $name;
899 * TODO: This function should be changed to send_content_type() per the Coding Guidelines. Ensure this change is compatible with rest of core.
901 * This function sends the Content-Type header if headers have not already been sent
902 * It also determines if the browser can accept application/xhtml+xml and sends it only to those that can.
903 * @param string $content_type
904 * @param string $page_type
905 * @param string $charset Deprecated. This has no meaning.
907 function sendContentType($content_type, $page_type = '', $charset = _CHARSET)
909 global $manager, $CONF;
911 if ( !headers_sent() )
913 // if content type is application/xhtml+xml, only send it to browsers
914 // that can handle it (IE6 cannot). Otherwise, send text/html
916 // v2.5: For admin area pages, keep sending text/html (unless it's a debug version)
917 // application/xhtml+xml still causes too much problems with the javascript implementations
919 // v3.3: ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,
920 // application/xhtml+xml seems to be working, so we're going to use it if we can.
922 if ( ($content_type == 'application/xhtml+xml')
923 && (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') ) )
925 $content_type = 'text/html';
929 'PreSendContentType',
931 'contentType' => &$content_type,
932 'charset' => i18n::get_current_charset(),
933 'pageType' => $page_type
937 // strip strange characters
938 $content_type = preg_replace('|[^a-z0-9-+./]|i', '', $content_type);
939 header('Content-Type: ' . $content_type . '; charset=' . i18n::get_current_charset());
946 * This function parses a query into an array of expressions that can be passed on to the highlight method
947 * @param string $query
949 function parseHighlight($query)
951 // TODO: add more intelligent splitting logic
954 $query = preg_replace('/\'|"/', '', $query);
961 $aHighlight = i18n::explode(' ', $query);
963 for ( $i = 0; $i < count($aHighlight); $i++ )
965 $aHighlight[$i] = trim($aHighlight[$i]);
967 if ( i18n::strlen($aHighlight[$i]) < 3 )
969 unset($aHighlight[$i]);
973 if ( count($aHighlight) == 1 )
975 return $aHighlight[0];
985 * This function gets the blog ID from the blog name
986 * @param string $name
989 function getBlogIDFromName($name)
991 return quickQuery('SELECT `bnumber` AS `result` FROM `' . sql_table('blog') . '` WHERE `bshortname` = "' . sql_real_escape_string($name) . '"');
996 * This function gets the blog name from the blog ID
1000 function getBlogNameFromID($id)
1002 return quickQuery('SELECT `bname` AS `result` FROM `' . sql_table('blog') . '` WHERE `bnumber` = ' . intval($id));
1007 * This function gets the blog ID from the item ID
1008 * @param int $item_id
1011 function getBlogIDFromItemID($item_id)
1013 return quickQuery('SELECT `iblog` AS `result` FROM `' . sql_table('item') . '` WHERE `inumber` = ' . intval($item_id));
1018 * This function gets the blog ID from the comment ID
1019 * @param int $comment_id
1022 function getBlogIDFromCommentID($comment_id)
1024 return quickQuery('SELECT `cblog` AS `result` FROM `' . sql_table('comment') . '` WHERE `cnumber` = ' . intval($comment_id));
1029 * This function gets the blog ID from the category ID
1030 * @param int $category_id
1033 function getBlogIDFromCatID($category_id)
1035 return quickQuery('SELECT `cblog` AS `result` FROM `' . sql_table('category') . '` WHERE `catid` = ' . intval($category_id));
1040 * This function gets the category ID from the category name
1044 function getCatIDFromName($name)
1046 return quickQuery('SELECT `catid` AS `result` FROM `' . sql_table('category') . '` WHERE `cname` = "' . sql_real_escape_string($name) . '"');
1051 * This function performs a quick SQL query
1052 * @param string $query
1055 function quickQuery($query)
1057 $res = sql_query($query);
1058 $obj = sql_fetch_object($res);
1059 return $obj->result;
1062 function getPluginNameFromPid($pid) {
1063 $res = sql_query('SELECT pfile FROM ' . sql_table('plugin') . ' WHERE pid=' . intval($pid) );
1064 $obj = sql_fetch_object($res);
1066 // return isset($obj->pfile) ? $obj->pfile : false;
1069 function selector() {
1070 global $itemid, $blogid, $memberid, $query, $amount, $archivelist, $maxresults;
1071 global $archive, $skinid, $blog, $memberinfo, $CONF, $member;
1072 global $imagepopup, $catid, $special;
1075 $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');
1076 $action = requestVar('action');
1078 if ( in_array($action, $actionNames) )
1080 global $DIR_LIBS, $errormessage;
1081 include_once($DIR_LIBS . 'ACTION.php');
1083 $errorInfo = $a->doAction($action);
1087 $errormessage = $errorInfo['message'];
1091 // show error when headers already sent out
1092 if ( headers_sent() && $CONF['alertOnHeadersSent'] )
1094 // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)
1095 if ( function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') )
1097 headers_sent($hsFile, $hsLine);
1098 $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';
1106 '<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>',
1107 'Page headers already sent'
1112 // make is so ?archivelist without blogname or blogid shows the archivelist
1113 // for the default weblog
1114 if ( serverVar('QUERY_STRING') == 'archivelist' )
1116 $archivelist = $CONF['DefaultBlog'];
1119 // now decide which type of skin we need
1122 // itemid given -> only show that item
1125 if ( !$manager->existsItem($itemid,intval($CONF['allowFuture']),intval($CONF['allowDrafts'])) )
1127 doError(_ERROR_NOSUCHITEM);
1130 global $itemidprev, $itemidnext, $catid, $itemtitlenext, $itemtitleprev;
1132 // 1. get timestamp, blogid and catid for item
1133 $query = 'SELECT itime, iblog, icat FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid);
1134 $res = sql_query($query);
1135 $obj = sql_fetch_object($res);
1137 // if a different blog id has been set through the request or selectBlog(),
1140 if ( $blogid && (intval($blogid) != $obj->iblog) )
1142 doError(_ERROR_NOSUCHITEM);
1145 // if a category has been selected which doesn't match the item, ignore the
1147 if ( ($catid != 0) && ($catid != $obj->icat) )
1152 $blogid = $obj->iblog;
1153 $timestamp = strtotime($obj->itime);
1155 $b =& $manager->getBlog($blogid);
1157 if ( $b->isValidCategory($catid) )
1159 $catextra = ' and icat=' . $catid;
1166 // get previous itemid and title
1167 $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';
1168 $res = sql_query($query);
1170 $obj = sql_fetch_object($res);
1174 $itemidprev = $obj->inumber;
1175 $itemtitleprev = $obj->ititle;
1178 // get next itemid and title
1179 $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';
1180 $res = sql_query($query);
1182 $obj = sql_fetch_object($res);
1186 $itemidnext = $obj->inumber;
1187 $itemtitlenext = $obj->ititle;
1195 // get next and prev month links ...
1196 global $archivenext, $archiveprev, $archivetype, $archivenextexists, $archiveprevexists;
1198 // sql queries for the timestamp of the first and the last published item
1199 $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 ORDER BY itime ASC";
1200 $first_timestamp=quickQuery ($query);
1201 $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 ORDER BY itime DESC";
1202 $last_timestamp=quickQuery ($query);
1204 sscanf($archive, '%d-%d-%d', $y, $m, $d);
1208 $archivetype = _ARCHIVETYPE_DAY;
1209 $t = mktime(0, 0, 0, $m, $d, $y);
1210 // one day has 24 * 60 * 60 = 86400 seconds
1211 $archiveprev = i18n::strftime('%Y-%m-%d', $t - 86400 );
1212 // check for published items
1213 if ( $t > $first_timestamp )
1215 $archiveprevexists = true;
1219 $archiveprevexists = false;
1224 $archivenext = i18n::strftime('%Y-%m-%d', $t);
1225 if ( $t < $last_timestamp )
1227 $archivenextexists = true;
1231 $archivenextexists = false;
1236 $archivetype = _ARCHIVETYPE_YEAR;
1237 $t = mktime(0, 0, 0, 12, 31, $y - 1);
1238 // one day before is in the previous year
1239 $archiveprev = i18n::strftime('%Y', $t);
1240 if ( $t > $first_timestamp )
1242 $archiveprevexists = true;
1246 $archiveprevexists = false;
1249 // timestamp for the next year
1250 $t = mktime(0, 0, 0, 1, 1, $y + 1);
1251 $archivenext = i18n::strftime('%Y', $t);
1252 if ( $t < $last_timestamp )
1254 $archivenextexists = true;
1258 $archivenextexists = false;
1263 $archivetype = _ARCHIVETYPE_MONTH;
1264 $t = mktime(0, 0, 0, $m, 1, $y);
1265 // one day before is in the previous month
1266 $archiveprev = i18n::strftime('%Y-%m', $t - 86400);
1267 if ( $t > $first_timestamp )
1269 $archiveprevexists = true;
1273 $archiveprevexists = false;
1276 // timestamp for the next month
1277 $t = mktime(0, 0, 0, $m+1, 1, $y);
1278 $archivenext = i18n::strftime('%Y-%m', $t);
1279 if ( $t < $last_timestamp )
1281 $archivenextexists = true;
1285 $archivenextexists = false;
1289 elseif ($archivelist)
1291 $type = 'archivelist';
1293 if ( is_numeric($archivelist) )
1295 $blogid = intVal($archivelist);
1299 $blogid = getBlogIDFromName($archivelist);
1304 doError(_ERROR_NOSUCHBLOG);
1311 $query = stripslashes($query);
1313 if ( is_numeric($blogid) )
1315 $blogid = intVal($blogid);
1319 $blogid = getBlogIDFromName($blogid);
1324 doError(_ERROR_NOSUCHBLOG);
1327 elseif ( $memberid )
1331 if ( !MEMBER::existsID($memberid) )
1333 doError(_ERROR_NOSUCHMEMBER);
1335 $memberinfo = $manager->getMember($memberid);
1337 elseif ( $imagepopup )
1339 // media object (images etc.)
1340 $type = 'imagepopup';
1342 // TODO: check if media-object exists
1343 // TODO: set some vars?
1347 // show regular index page
1352 // any type of skin with catid
1353 if ( $catid && !$blogid )
1355 $blogid = getBlogIDFromCatID($catid);
1358 // decide which blog should be displayed
1361 $blogid = $CONF['DefaultBlog'];
1364 $b =& $manager->getBlog($blogid);
1365 $blog = $b; // references can't be placed in global variables?
1367 if ( !$blog->isValid )
1369 doError(_ERROR_NOSUCHBLOG);
1372 // set catid if necessary
1375 // check if the category is valid
1376 if ( !$blog->isValidCategory($catid) )
1378 doError(_ERROR_NOSUCHCATEGORY);
1382 $blog->setSelectedCategory($catid);
1386 // decide which skin should be used
1387 if ( $skinid != '' && ($skinid == 0) )
1389 selectSkin($skinid);
1394 $skinid = $blog->getDefaultSkin();
1397 //$special = requestVar('special'); //get at top of file as global
1398 if ( !empty($special) && isValidShortName($special) )
1400 $type = strtolower($special);
1403 $skin = new SKIN($skinid);
1405 if ( !$skin->isValid )
1407 doError(_ERROR_NOSUCHSKIN);
1410 // set global skinpart variable so can determine quickly what is being parsed from any plugin or phpinclude
1415 $skin->parse($type);
1417 // check to see we should throw JustPosted event
1418 $blog->checkJustPosted();
1423 * Show error skin with given message. An optional skin-object to use can be given
1425 function doError($msg, $skin = '') {
1426 global $errormessage, $CONF, $skinid, $blogid, $manager;
1430 if (SKIN::existsID($skinid) ) {
1431 $skin = new SKIN($skinid);
1432 } elseif ($manager->existsBlogID($blogid) ) {
1433 $blog =& $manager->getBlog($blogid);
1434 $skin = new SKIN($blog->getDefaultSkin() );
1435 } elseif ($CONF['DefaultBlog']) {
1436 $blog =& $manager->getBlog($CONF['DefaultBlog']);
1437 $skin = new SKIN($blog->getDefaultSkin() );
1439 // this statement should actually never be executed
1440 $skin = new SKIN($CONF['BaseSkin']);
1445 $skinid = $skin->id;
1446 $errormessage = $msg;
1447 $skin->parse('error');
1451 function getConfig() {
1454 $query = 'SELECT * FROM ' . sql_table('config');
1455 $res = sql_query($query);
1457 while ($obj = sql_fetch_object($res) ) {
1458 $CONF[$obj->name] = $obj->value;
1462 // some checks for names of blogs, categories, templates, members, ...
1463 function isValidShortName($name) {
1465 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1466 # original eregi: eregi('^[a-z0-9]+$', $name)
1468 return preg_match('#^[a-z0-9]+$#i', $name);
1472 function isValidDisplayName($name) {
1474 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1475 # original eregi: eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name)
1477 return preg_match('#^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$#i', $name);
1481 function isValidCategoryName($name) {
1485 function isValidTemplateName($name) {
1487 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1488 # original eregi: eregi('^[a-z0-9/]+$', $name)
1489 // added - and _ to valid characters as of 4.00
1491 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
1495 function isValidSkinName($name) {
1497 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1498 # original eregi: eregi('^[a-z0-9/]+$', $name);
1499 // added - and _ to valid characters as of 4.00
1501 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
1505 // add and remove linebreaks
1506 function addBreaks($var) {
1510 function removeBreaks($var) {
1511 return preg_replace("/<br \/>([\r\n])/", "$1", $var);
1515 * Converts a unix timestamp to a mysql DATETIME format, and places
1518 function mysqldate($timestamp) {
1519 return '"' . date('Y-m-d H:i:s', $timestamp) . '"';
1523 * functions for use in index.php
1525 function selectBlog($shortname) {
1526 global $blogid, $archivelist;
1527 $blogid = getBlogIDFromName($shortname);
1529 // also force archivelist variable, if it is set
1531 $archivelist = $blogid;
1535 function selectSkin($skinname) {
1537 $skinid = SKIN::getIdFromName($skinname);
1541 * Can take either a category ID or a category name (be aware that
1542 * multiple categories can have the same name)
1544 function selectCategory($cat) {
1546 if (is_numeric($cat) ) {
1547 $catid = intval($cat);
1549 $catid = getCatIDFromName($cat);
1553 function selectItem($id) {
1555 $itemid = intval($id);
1558 // force the use of a translation file (warning: can cause warnings)
1559 function selectLanguage($language) {
1563 # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
1564 # original ereg_replace: preg_replace( '@\\|/@', '', $language) . '.php')
1565 # important note that '\' must be matched with '\\\\' in preg* expressions
1567 include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');
1571 function parseFile($filename, $includeMode = 'normal', $includePrefix = '') {
1572 $handler = new ACTIONS('fileparser');
1573 $parser = new PARSER(SKIN::getAllowedActionsForType('fileparser'), $handler);
1574 $handler->parser =& $parser;
1576 // set IncludeMode properties of parser
1577 PARSER::setProperty('IncludeMode', $includeMode);
1578 PARSER::setProperty('IncludePrefix', $includePrefix);
1580 if (!file_exists($filename) ) {
1581 doError('A file is missing');
1584 $fsize = filesize($filename);
1591 $fd = fopen ($filename, 'r');
1592 $contents = fread ($fd, $fsize);
1595 // parse file contents
1596 $parser->parse($contents);
1600 * Outputs a debug message
1602 function debug($msg) {
1603 echo '<p><b>' . $msg . "</b></p>\n";
1607 function addToLog($level, $msg) {
1608 ACTIONLOG::add($level, $msg);
1611 // shows a link to help file
1612 function help($id) {
1616 function helpHtml($id) {
1618 return helplink($id) . '<img src="' . $CONF['AdminURL'] . 'documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" title="' . _HELP_TT . '" /></a>';
1621 function helplink($id) {
1623 return '<a href="' . $CONF['AdminURL'] . 'documentation/help.html#'. $id . '" onclick="if (event && event.preventDefault) event.preventDefault(); return help(this.href);">';
1627 * Includes a PHP file. This method can be called while parsing templates and skins
1629 function includephp($filename) {
1630 // make predefined variables global, so most simple scripts can be used here
1632 // apache (names taken from PHP doc)
1633 global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;
1634 global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;
1635 global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;
1636 global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;
1637 global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;
1638 global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;
1639 global $REQUEST_URI;
1641 // php (taken from PHP doc)
1642 global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;
1643 global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;
1646 global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;
1648 if (@file_exists($filename) ) {
1654 * Checks if a certain plugin exists
1655 * @param string $plug
1658 function checkPlugin($plug) {
1660 global $DIR_PLUGINS;
1662 # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
1663 # original ereg_replace: ereg_replace( '[\\|/]', '', $plug) . '.php')
1664 # important note that '\' must be matched with '\\\\' in preg* expressions
1666 return file_exists($DIR_PLUGINS . preg_replace('#[\\\\|/]#', '', $plug) . '.php');
1672 * querystring to alter (e.g. foo=1&bar=2&x=y)
1674 * name of parameter to change (e.g. 'foo')
1676 * New value for that parameter (e.g. 3)
1678 * altered query string (for the examples above: foo=3&bar=2&x=y)
1680 function alterQueryStr($querystr, $param, $value) {
1681 $vars = i18n::explode('&', $querystr);
1684 for ($i = 0; $i < count($vars); $i++) {
1685 $v = i18n::explode('=', $vars[$i]);
1687 if ($v[0] == $param) {
1689 $vars[$i] = implode('=', $v);
1696 $vars[] = $param . '=' . $value;
1699 return ltrim(implode('&', $vars), '&');
1702 // passes one variable as hidden input field (multiple fields for arrays)
1703 // @see passRequestVars in varsx.x.x.php
1704 function passVar($key, $value) {
1706 if (is_array($value) ) {
1707 for ($i = 0; $i < sizeof($value); $i++) {
1708 passVar($key . '[' . $i . ']', $value[$i]);
1714 // other values: do stripslashes if needed
1715 ?><input type="hidden" name="<?php echo ENTITY::hsc($key)?>" value="<?php echo ENTITY::hsc(undoMagic($value) )?>" /><?php
1718 function checkVars($aVars) {
1719 global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;
1721 foreach ($aVars as $varName) {
1723 if (phpversion() >= '4.1.0') {
1725 if ( isset($_GET[$varName])
1726 || isset($_POST[$varName])
1727 || isset($_COOKIE[$varName])
1728 || isset($_ENV[$varName])
1729 || isset($_SESSION[$varName])
1730 || isset($_FILES[$varName])
1732 die('Sorry. An error occurred.');
1737 if ( isset($HTTP_GET_VARS[$varName])
1738 || isset($HTTP_POST_VARS[$varName])
1739 || isset($HTTP_COOKIE_VARS[$varName])
1740 || isset($HTTP_ENV_VARS[$varName])
1741 || isset($HTTP_SESSION_VARS[$varName])
1742 || isset($HTTP_POST_FILES[$varName])
1744 die('Sorry. An error occurred.');
1753 * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.
1756 function sanitizeParams()
1758 global $HTTP_SERVER_VARS;
1764 // REQUEST_URI of $HTTP_SERVER_VARS
1765 $str =& $HTTP_SERVER_VARS["REQUEST_URI"];
1766 serverStringToArray($str, $array, $frontParam);
1767 sanitizeArray($array);
1768 arrayToServerString($array, $frontParam, $str);
1770 // QUERY_STRING of $HTTP_SERVER_VARS
1771 $str =& $HTTP_SERVER_VARS["QUERY_STRING"];
1772 serverStringToArray($str, $array, $frontParam);
1773 sanitizeArray($array);
1774 arrayToServerString($array, $frontParam, $str);
1776 if (phpversion() >= '4.1.0') {
1777 // REQUEST_URI of $_SERVER
1778 $str =& $_SERVER["REQUEST_URI"];
1779 serverStringToArray($str, $array, $frontParam);
1780 sanitizeArray($array);
1781 arrayToServerString($array, $frontParam, $str);
1783 // QUERY_STRING of $_SERVER
1784 $str =& $_SERVER["QUERY_STRING"];
1785 serverStringToArray($str, $array, $frontParam);
1786 sanitizeArray($array);
1787 arrayToServerString($array, $frontParam, $str);
1791 convArrayForSanitizing($_GET, $array);
1792 sanitizeArray($array);
1793 revertArrayForSanitizing($array, $_GET);
1795 // $_REQUEST (only GET param)
1796 convArrayForSanitizing($_REQUEST, $array);
1797 sanitizeArray($array);
1798 revertArrayForSanitizing($array, $_REQUEST);
1802 * Check ticket when not checked in plugin's admin page
1804 * Also avoid the access to plugin/index.php by guest user.
1806 function ticketForPlugin()
1808 global $CONF, $DIR_PLUGINS, $member, $ticketforplugin;
1811 $ticketforplugin = array();
1812 $ticketforplugin['ticket'] = FALSE;
1814 /* $_SERVER['PATH_TRANSLATED']
1815 * http://www.php.net/manual/en/reserved.variables.server.php
1816 * Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly
1817 * under the Apache 2 SAPI in contrast to the situation in Apache 1,
1818 * where it's set to the same value as the SCRIPT_FILENAME server variable
1819 * when it's not populated by Apache.
1820 * This change was made to comply with the CGI specification
1821 * that PATH_TRANSLATED should only exist if PATH_INFO is defined.
1822 * Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.
1825 /* Check if using plugin's php file. */
1826 $p_translated = serverVar('SCRIPT_FILENAME');
1828 if (!file_exists($p_translated) )
1830 header("HTTP/1.0 404 Not Found");
1834 $p_translated = str_replace('\\', '/', $p_translated);
1835 $d_plugins = str_replace('\\', '/', $DIR_PLUGINS);
1837 // This isn't plugin php file.
1838 if ( i18n::strpos($p_translated, $d_plugins) !== 0 )
1843 // Solve the plugin php file or admin directory
1844 $phppath = i18n::substr($p_translated, i18n::strlen($d_plugins) );
1845 // Remove the first "/" if exists.
1846 $phppath = preg_replace('#^/#', '', $phppath);
1847 // Remove the first "NP_" and the last ".php" if exists.
1848 $path = preg_replace('#^NP_(.*)\.php$#', '$1', $phppath);
1849 // Remove the "/" and beyond.
1850 $path = preg_replace('#^([^/]*)/(.*)$#', '$1', $path);
1852 // Solve the plugin name.
1854 $query = 'SELECT `pfile` FROM '.sql_table('plugin');
1855 $res = sql_query($query);
1857 while($row = sql_fetch_row($res) )
1859 $name = i18n::substr($row[0], 3);
1860 $plugins[strtolower($name)] = $name;
1863 sql_free_result($res);
1865 if (array_key_exists($path, $plugins))
1867 $plugin_name = $plugins[$path];
1869 else if (in_array($path, $plugins))
1871 $plugin_name = $path;
1875 header("HTTP/1.0 404 Not Found");
1879 /* Return if not index.php */
1880 if ( ($phppath != strtolower($plugin_name) . '/') && ($phppath != strtolower($plugin_name) . '/index.php') )
1885 /* Exit if not logged in. */
1886 if ( !$member->isLoggedIn() )
1888 exit('You aren\'t logged in.');
1891 global $manager, $DIR_LIBS, $DIR_LOCALE, $HTTP_GET_VARS, $HTTP_POST_VARS;
1893 /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */
1894 if (!($p_translated = serverVar('PATH_TRANSLATED') ) )
1896 $p_translated = serverVar('SCRIPT_FILENAME');
1899 if ($file = @file($p_translated) )
1903 foreach($file as $line)
1905 if (preg_match('/[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]/i', $prevline . $line) )
1914 /* Show a form if not valid ticket */
1915 if ( ( strstr(serverVar('REQUEST_URI'), '?') || serverVar('QUERY_STRING')
1916 || strtoupper(serverVar('REQUEST_METHOD') ) == 'POST')
1917 && (!$manager->checkTicket() ) )
1919 $oPluginAdmin = new PluginAdmin($plugin_name);
1920 $oPluginAdmin->start();
1921 echo '<p>' . _ERROR_BADTICKET . "</p>\n";
1923 /* Show the form to confirm action */
1924 // PHP 4.0.x support
1925 $get = (isset($_GET) ) ? $_GET : $HTTP_GET_VARS;
1926 $post = (isset($_POST) ) ? $_POST : $HTTP_POST_VARS;
1928 // Resolve URI and QUERY_STRING
1929 if ($uri = serverVar('REQUEST_URI') )
1931 list($uri, $qstring) = i18n::explode('?', $uri);
1935 if ( !($uri = serverVar('PHP_SELF') ) )
1937 $uri = serverVar('SCRIPT_NAME');
1939 $qstring = serverVar('QUERY_STRING');
1943 $qstring = '?' . $qstring;
1946 echo '<p>' . _SETTINGS_UPDATE . ' : ' . _QMENU_PLUGINS . ' <span style="color:red;">' . ENTITY::hsc($plugin_name) . "</span> ?</p>\n";
1948 switch(strtoupper(serverVar('REQUEST_METHOD') ) )
1951 echo '<form method="POST" action="'.ENTITY::hsc($uri.$qstring).'">';
1952 $manager->addTicketHidden();
1953 _addInputTags($post);
1957 echo '<form method="GET" action="'.ENTITY::hsc($uri).'">';
1958 $manager->addTicketHidden();
1959 _addInputTags($get);
1965 echo '<input type="submit" value="' . _YES . '" /> ';
1966 echo '<input type="button" value="' . _NO . '" onclick="history.back(); return false;" />';
1969 $oPluginAdmin->end();
1973 /* Create new ticket */
1974 $ticket=$manager->addTicketToUrl('');
1975 $ticketforplugin['ticket']=i18n::substr($ticket,i18n::strpos($ticket,'ticket=')+7);
1978 function _addInputTags(&$keys,$prefix=''){
1979 foreach($keys as $key=>$value){
1980 if ($prefix) $key=$prefix.'['.$key.']';
1981 if (is_array($value)) _addInputTags($value,$key);
1983 if (get_magic_quotes_gpc()) $value=stripslashes($value);
1984 if ($key=='ticket') continue;
1985 echo '<input type="hidden" name="'.ENTITY::hsc($key).
1986 '" value="'.ENTITY::hsc($value).'" />'."\n";
1992 * Convert the server string such as $_SERVER['REQUEST_URI']
1993 * to arry like arry['blogid']=1 and array['page']=2 etc.
1995 function serverStringToArray($str, &$array, &$frontParam)
2001 // split front param, e.g. /index.php, and others, e.g. blogid=1&page=2
2002 if (strstr($str, "?")){
2003 list($frontParam, $args) = preg_split("/\?/", $str, 2);
2010 // If there is no args like blogid=1&page=2, return
2011 if (!strstr($str, "=") && !i18n::strlen($frontParam)) {
2016 $array = i18n::explode("&", $args);
2020 * Convert array like array['blogid'] to server string
2021 * such as $_SERVER['REQUEST_URI']
2023 function arrayToServerString($array, $frontParam, &$str)
2025 if (strstr($str, "?")) {
2026 $str = $frontParam . "?";
2030 if (count($array)) {
2031 $str .= implode("&", $array);
2036 * Sanitize array parameters.
2037 * This function checks both key and value.
2038 * - check key if it inclues " (double quote), remove from array
2039 * - check value if it includes \ (escape sequece), remove remaining string
2041 function sanitizeArray(&$array)
2043 $excludeListForSanitization = array('query');
2044 // $excludeListForSanitization = array();
2046 foreach ($array as $k => $v) {
2048 // split to key and value
2049 list($key, $val) = preg_split("/=/", $v, 2);
2054 // when magic quotes is on, need to use stripslashes,
2055 // and then addslashes
2056 if (get_magic_quotes_gpc()) {
2057 $val = stripslashes($val);
2059 // note that we must use addslashes here because this function is called before the db connection is made
2060 // and sql_real_escape_string needs a db connection
2061 $val = addslashes($val);
2063 // if $key is included in exclude list, skip this param
2064 if (!in_array($key, $excludeListForSanitization)) {
2067 if (i18n::strpos($val, '\\')) {
2068 list($val, $tmp) = i18n::explode('\\', $val);
2071 // remove control code etc.
2072 $val = strtr($val, "\0\r\n<>'\"", " ");
2075 if (preg_match('/\"/i', $key)) {
2080 // set sanitized info
2081 $array[$k] = sprintf("%s=%s", $key, $val);
2087 * Convert array for sanitizeArray function
2089 function convArrayForSanitizing($src, &$array)
2092 foreach ($src as $key => $val) {
2093 if (key_exists($key, $_GET)) {
2094 array_push($array, sprintf("%s=%s", $key, $val));
2100 * Revert array after sanitizeArray function
2102 function revertArrayForSanitizing($array, &$dst)
2104 foreach ($array as $v) {
2105 list($key, $val) = preg_split("/=/", $v, 2);
2111 * Stops processing the request and redirects to the given URL.
2112 * - no actual contents should have been sent to the output yet
2113 * - the URL will be stripped of illegal or dangerous characters
2115 function redirect($url) {
2116 $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%*]|i', '', $url);
2117 header('Location: ' . $url);
2123 * replace html entities for plugin description, but available for the other strings
2124 * NOTE: we can use ENTITY::hen() or ENTITY::hsc() alternatively and this is deprecated.
2125 * @param string $data target string
2128 function encode_desc($data)
2130 return ENTITY::hen($data);
2134 * Returns the Javascript code for a bookmarklet that works on most modern browsers
2137 function getBookmarklet($blogid) {
2141 $document = 'document';
2142 $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('";
2143 $bookmarkletline .= $CONF['AdminURL'] . "bookmarklet.php?blogid=$blogid";
2144 $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();";
2146 return $bookmarkletline;
2148 // END: functions from the end of file ADMIN.php
2151 * Returns a variable or null if not set
2153 * @param mixed Variable
2154 * @return mixed Variable
2156 function ifset(&$var) {
2165 * Returns number of subscriber to an event
2168 * @return number of subscriber(s)
2170 function numberOfEventSubscriber($event) {
2171 $query = 'SELECT COUNT(*) as count FROM ' . sql_table('plugin_event') . ' WHERE event=\'' . $event . '\'';
2172 $res = sql_query($query);
2173 $obj = sql_fetch_object($res);
2178 * sets $special global variable for use in index.php before selector()
2183 function selectSpecialSkinType($id) {
2185 $special = strtolower($id);
2189 * cleans filename of uploaded file for writing to file system
2192 * @return String cleaned filename ready for use
2194 function cleanFileName($str) {
2195 $str = strtolower($str);
2196 $ext_point = i18n::strrpos($str,".");
2197 if ($ext_point===false) return false;
2198 $ext = i18n::substr($str,$ext_point,i18n::strlen($str));
2199 $str = i18n::substr($str,0,$ext_point);
2201 return preg_replace("/[^a-z0-9-]/","_",$str).$ext;
2205 * Centralisation of the functions to send mail
2206 * Deprecated since 4.0:
2207 * Please use functions in NOTIFICATION class instead
2209 function getMailFooter()
2211 NOTIFICATION::get_mail_footer();
2213 function isValidMailAddress($address)
2215 return NOTIFICATION::address_validation($address);
2218 * Centralisation of the functions that deals XML entities
2219 * Deprecated since 4.0:
2220 * Please use ENTITY::FunctionName(...) instead
2222 function highlight($text, $expression, $highlight)
2224 return ENTITY::highlight($text, $expression, $highlight);
2226 function shorten($string, $maxlength, $suffix)
2228 return ENTITY::shorten($string, $maxlength, $suffix);
2230 function stringStripTags ($string)
2232 return ENTITY::strip_tags($string);
2234 function toAscii($string)
2236 return ENTITY::anchor_footnoting($string);
2238 function stringToAttribute ($string)
2240 return ENTITY::hsc($string);
2242 function stringToXML ($string)
2244 return ENTITY::hen($string);
2248 * Centralisation of the functions that deals with locales
2249 * This functions is based on the old way to deal with languages
2250 * Deprecated since 4.0:
2252 /* NOTE: use i18n::get_current_locale() directly instead of this */
2253 function getLanguageName()
2255 if( ($language = i18n::convert_locale_to_old_language_file_name(i18n::get_current_locale())) === FALSE )
2257 $language ='english';
2262 /* NOTE: use i18n::get_available_locales() directly instead of this */
2263 function checkLanguage($lang)
2265 return ( preg_match('#^(.+)_(.+)_(.+)$#', $lang)
2266 || i18n::convert_old_language_file_name_to_locale($lang) );
2268 /* NOTE: use i18n::formatted_datetime() directly instead of this */
2269 function formatDate($format, $timestamp, $default_format, &$blog)
2271 $offset = date('Z', $timestamp);
2274 $offset += $blog->getTimeOffset() * 3600;
2276 return i18n::formatted_datetime($format, $timestamp, $default_format, $offset);
2280 * Centralisation of the functions that generate links
2281 * Deprecated since 4.0:
2282 * Please use Link::FunctionName(...) instead
2284 function createItemLink($itemid, $extra = '')
2286 return Link::create_item_link($itemid, $extra);
2289 function createMemberLink($memberid, $extra = '')
2291 return Link::create_member_link($memberid, $extra);
2294 function createCategoryLink($catid, $extra = '')
2296 return Link::create_category_link($catid, $extra);
2299 function createArchiveListLink($blogid = '', $extra = '')
2301 return Link::create_archivelist_link($blogid, $extra);
2304 function createArchiveLink($blogid, $archive, $extra = '')
2306 return Link::create_archive_link($blogid, $archive, $extra);
2309 function createBlogidLink($blogid, $params = '')
2311 return Link::create_blogid_link($blogid, $params = '');
2314 function createLink($type, $params)
2316 return Link::create_link($type, $params);
2319 function createBlogLink($url, $params)
2321 return Link::create_blog_link($url, $params);