5 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
\r
6 * Copyright (C) 2002-2009 The Nucleus Group
\r
8 * This program is free software; you can redistribute it and/or
\r
9 * modify it under the terms of the GNU General Public License
\r
10 * as published by the Free Software Foundation; either version 2
\r
11 * of the License, or (at your option) any later version.
\r
12 * (see nucleus/documentation/index.html#license for more info)
\r
15 * @license http://nucleuscms.org/license.txt GNU General Public License
\r
16 * @copyright Copyright (C) 2002-2009 The Nucleus Group
\r
17 * @version $Id: globalfunctions.php 1856 2012-05-18 09:30:16Z sakamocchi $
20 /* needed if we include globalfunctions from install.php */
\r
21 global $nucleus, $CONF, $DIR_LIBS, $DIR_LOCALES, $manager, $member, $MYSQL_HANDLER, $StartTime;
23 /* just for benchmark tag */
24 $StartTime = microtime(TRUE);
26 $nucleus['version'] = 'v4.00 SVN';
\r
27 $nucleus['codename'] = '';
\r
30 * make sure there's no unnecessary escaping:
\r
31 * set_magic_quotes_runtime(0);
\r
33 if ( version_compare(PHP_VERSION, '5.3.0', '<') )
\r
35 ini_set('magic_quotes_runtime', '0');
\r
38 /* check and die if someone is trying to override internal globals (when register_globals turn on) */
\r
39 checkVars(array('nucleus', 'CONF', 'DIR_LIBS',
40 'MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE',
41 'DIR_LOCALES', 'DIR_PLUGINS',
42 'HTTP_GET_VARS', 'HTTP_POST_VARS', 'HTTP_COOKIE_VARS', 'HTTP_ENV_VARS',
43 'HTTP_SESSION_VARS', 'HTTP_POST_FILES', 'HTTP_SERVER_VARS',
44 'GLOBALS', 'argv', 'argc', '_GET', '_POST', '_COOKIE', '_ENV', '_SESSION', '_SERVER', '_FILES'));
46 if ( !isset($CONF) )
\r
52 if ( array_key_exists('debug', $CONF) && $CONF['debug'] )
\r
54 /* report all errors! */
\r
55 error_reporting(E_ALL);
\r
59 ini_set('display_errors','0');
\r
60 error_reporting(E_ERROR | E_WARNING | E_PARSE);
\r
64 * alertOnHeadersSent
\r
65 * Displays an error when visiting a public Nucleus page and headers have
\r
66 * been sent out to early. This usually indicates an error in either a
\r
67 * configuration file or a translation file, and could cause Nucleus to
\r
70 if ( !array_key_exists('alertOnHeadersSent', $CONF) )
\r
72 $CONF['alertOnHeadersSent'] = 1;
\r
76 * alertOnSecurityRisk
\r
77 * Displays an error only when visiting the admin area, and when one or
\r
78 * more of the installation files (install.php, install.sql, upgrades/
\r
79 * directory) are still on the server.
\r
81 if ( !array_key_exists('alertOnSecurityRisk', $CONF) )
\r
83 $CONF['alertOnSecurityRisk'] = 1;
\r
87 * Set these to 1 to allow viewing of future items or draft items
\r
88 * Should really never do this, but can be useful for some plugins that might need to
\r
89 * Could cause some other issues if you use future posts otr drafts
\r
92 $CONF['allowDrafts'] = 0;
\r
93 $CONF['allowFuture'] = 0;
\r
95 if ( getNucleusPatchLevel() > 0 )
\r
97 $nucleus['version'] .= '/' . getNucleusPatchLevel();
\r
100 /* Avoid notices */
\r
101 if ( !array_key_exists('installscript', $CONF) || empty($CONF['installscript']) )
\r
103 $CONF['installscript'] = 0;
\r
105 if ( !array_key_exists('UsingAdminArea', $CONF) )
\r
107 $CONF['UsingAdminArea'] = 0;
\r
110 if ( !headers_sent() )
\r
112 header('Generator: Nucleus CMS ' . $nucleus['version']);
\r
116 /* TODO: This is for compatibility since 4.0, should be obsoleted at future release. */
\r
117 if ( !isset($DIR_LOCALES) )
\r
119 $DIR_LOCALES = $DIR_NUCLEUS . 'locales/';
\r
122 if ( !isset($DIR_LANG) )
\r
124 $DIR_LANG = $DIR_LOCALES;
\r
127 /* load and initialize i18n class */
\r
128 if (!class_exists('i18n', FALSE))
\r
130 include($DIR_LIBS . 'i18n.php');
\r
132 if ( !i18n::init('UTF-8', $DIR_LOCALES) )
\r
134 exit('Fail to initialize i18n class.');
\r
137 /* TODO: This is just for compatibility since 4.0, should be obsoleted at future release. */
\r
138 define('_CHARSET', i18n::get_current_charset());
\r
142 * NOTE: Since 4.0 release, Entity class becomes to be important class
\r
143 * with some wrapper functions for htmlspechalchars/htmlentity PHP's built-in function
\r
145 include($DIR_LIBS . 'ENTITY.php');
\r
147 /* we will use postVar, getVar, ... methods instead of $_GET, $_POST ... */
\r
148 if ( $CONF['installscript'] != 1 )
\r
150 /* vars were already included in install.php */
\r
151 include_once($DIR_LIBS . 'vars4.1.0.php');
\r
153 /* added for 4.0 DB::* wrapper and compatibility sql_* */
\r
154 include_once($DIR_LIBS . 'sql/sql.php');
\r
157 /* include core classes that are needed for login & plugin handling */
\r
158 include($DIR_LIBS . 'MEMBER.php');
\r
159 include($DIR_LIBS . 'ACTIONLOG.php');
\r
160 include($DIR_LIBS . 'MANAGER.php');
\r
161 include($DIR_LIBS . 'PLUGIN.php');
\r
163 $manager =& MANAGER::instance();
\r
165 /* only needed when updating logs */
\r
166 if ( $CONF['UsingAdminArea'] )
\r
168 /* XML-RPC client classes */
\r
169 include($DIR_LIBS . 'xmlrpc.inc.php');
\r
170 include($DIR_LIBS . 'ADMIN.php');
\r
174 /* connect to database */
\r
175 if ( !isset($MYSQL_HANDLER) )
\r
177 $MYSQL_HANDLER = array('mysql','');
\r
179 if ( $MYSQL_HANDLER[0] == '' )
\r
181 $MYSQL_HANDLER[0] = 'mysql';
\r
183 DB::setConnectionInfo($MYSQL_HANDLER[1], $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE);
\r
186 /* force locale or charset */
\r
188 $charset = i18n::get_current_charset();
\r
191 'locale' => &$locale,
\r
192 'charset' => &$charset
\r
194 $manager->notify('ForceLocale', $data);
\r
196 if ( $data['locale'] !== '' )
\r
198 i18n::set_forced_locale($data['locale']);
\r
200 if ( $data['charset'] !== '' )
\r
202 i18n::set_forced_charset($data['charset']);
\r
208 /* convert forced charset to current charset */
\r
209 if ( i18n::get_forced_charset() != i18n::get_current_charset() )
\r
211 $_POST = i18n::convert_array($_POST, i18n::get_forced_charset());
\r
212 $_GET = i18n::convert_array($_GET, i18n::get_forced_charset());
\r
213 $_REQUEST = i18n::convert_array($_REQUEST, i18n::get_forced_charset());
\r
214 $_COOKIE = i18n::convert_array($_COOKIE, i18n::get_forced_charset());
\r
215 $_FILES = i18n::convert_array($_FILES, i18n::get_forced_charset());
\r
217 if ( session_id() !== '' )
\r
219 $_SESSION = i18n::convert_array($_SESSION, i18n::get_forced_charset());
\r
224 /* sanitize option */
\r
225 $bLoggingSanitizedResult = 0;
\r
226 $bSanitizeAndContinue = 0;
\r
227 $orgRequestURI = serverVar('REQUEST_URI');
\r
230 /* logs sanitized result if need */
\r
231 if ( $orgRequestURI !== serverVar('REQUEST_URI') )
\r
233 $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";
\r
234 $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');
\r
235 if ( $bLoggingSanitizedResult )
\r
237 addToLog(WARNING, $msg);
\r
239 if ( !$bSanitizeAndContinue )
\r
245 /* get all variables that can come from the request and put them in the global scope */
\r
246 $blogid = requestVar('blogid');
\r
247 $itemid = intRequestVar('itemid');
\r
248 $catid = intRequestVar('catid');
\r
249 $skinid = requestVar('skinid');
\r
250 $memberid = requestVar('memberid');
\r
251 $archivelist = requestVar('archivelist');
\r
252 $imagepopup = requestVar('imagepopup');
\r
253 $archive = requestVar('archive');
\r
254 $query = requestVar('query');
\r
255 $highlight = requestVar('highlight');
\r
256 $amount = requestVar('amount');
\r
257 $action = requestVar('action');
\r
258 $nextaction = requestVar('nextaction');
\r
259 $maxresults = requestVar('maxresults');
\r
260 $startpos = intRequestVar('startpos');
\r
261 $errormessage = '';
\r
263 $special = requestVar('special');
\r
270 /* Properly set $CONF['Self'] and others if it's not set...
\r
271 * usually when we are access from admin menu
\r
273 if ( !array_key_exists('Self', $CONF) )
\r
275 $CONF['Self'] = $CONF['IndexURL'];
\r
276 /* strip trailing */
\r
277 if ( $CONF['Self'][i18n::strlen($CONF['Self']) -1] == "/" )
\r
279 $CONF['Self'] = i18n::substr($CONF['Self'], 0, i18n::strlen($CONF['Self']) -1);
\r
283 $CONF['ItemURL'] = $CONF['Self'];
\r
284 $CONF['ArchiveURL'] = $CONF['Self'];
\r
285 $CONF['ArchiveListURL'] = $CONF['Self'];
\r
286 $CONF['MemberURL'] = $CONF['Self'];
\r
287 $CONF['SearchURL'] = $CONF['Self'];
\r
288 $CONF['BlogURL'] = $CONF['Self'];
\r
289 $CONF['CategoryURL'] = $CONF['Self'];
\r
291 /* automatically use simpler toolbar for mozilla */
\r
292 if ( ($CONF['DisableJsTools'] == 0)
\r
293 && i18n::strpos(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0') !== FALSE
\r
294 && i18n::strpos(serverVar('HTTP_USER_AGENT'), 'Gecko') !== FALSE )
\r
296 $CONF['DisableJsTools'] = 2;
\r
299 /* login processing */
300 $member = new Member();
\r
302 if ( $action == 'login' )
\r
304 $login = postVar('login');
\r
305 $password = postVar('password');
\r
306 $shared = intPostVar('shared');
\r
307 $member->login($login, $password, $shared);
\r
309 elseif ( ($action == 'logout') )
\r
315 $member->cookielogin();
\r
319 /* TODO: This is for backward compatibility, should be obsoleted near future. */
\r
320 if ( !preg_match('#^(.+)_(.+)_(.+)$#', $CONF['Locale'])
\r
321 && ($CONF['Locale'] = i18n::convert_old_language_file_name_to_locale($CONF['Locale'])) === FALSE )
\r
323 $CONF['Locale'] = 'en_Latn_US';
\r
325 if ( !array_key_exists('Language', $CONF) )
\r
327 $CONF['Language'] = i18n::convert_locale_to_old_language_file_name($CONF['Locale']);
\r
329 $locale = $CONF['Locale'];
\r
332 /* NOTE: include translation file and set locale */
\r
333 if ( $member->isLoggedIn() )
\r
335 if ( $member->getLocale() )
\r
337 $locale = $member->getLocale();
\r
342 if ( i18n::get_forced_locale() !== '' )
\r
344 $locale = i18n::get_forced_locale();
\r
347 include_translation($locale);
\r
348 i18n::set_current_locale($locale);
\r
351 /* login completed */
\r
352 $manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );
\r
355 if ( $member->isLoggedIn() && $nextaction )
\r
357 $action = $nextaction;
\r
360 /* first, let's see if the site is disabled or not. always allow admin area access. */
\r
361 if ( $CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea'] )
\r
363 redirect($CONF['DisableSiteURL']);
\r
367 /* load other classes */
\r
368 include($DIR_LIBS . 'PARSER.php');
\r
369 include($DIR_LIBS . 'SKIN.php');
\r
370 include($DIR_LIBS . 'TEMPLATE.php');
\r
371 include($DIR_LIBS . 'BLOG.php');
\r
372 include($DIR_LIBS . 'BODYACTIONS.php');
\r
373 include($DIR_LIBS . 'COMMENTS.php');
\r
374 include($DIR_LIBS . 'COMMENT.php');
\r
375 include($DIR_LIBS . 'NOTIFICATION.php');
\r
376 include($DIR_LIBS . 'BAN.php');
\r
377 include($DIR_LIBS . 'PAGEFACTORY.php');
\r
378 include($DIR_LIBS . 'SEARCH.php');
\r
379 include($DIR_LIBS . 'LINK.php');
\r
381 /* set lastVisit cookie (if allowed) */
\r
382 if ( !headers_sent() )
\r
384 if ( $CONF['LastVisit'] )
\r
386 setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
\r
390 setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
\r
394 if ( !defined('_ARCHIVETYPE_MONTH') )
\r
396 define('_ARCHIVETYPE_DAY', 'day');
\r
397 define('_ARCHIVETYPE_MONTH', 'month');
\r
398 define('_ARCHIVETYPE_YEAR', 'year');
\r
401 /* for path resolving */
402 $virtualpath = getVar('virtualpath');
403 if ( getVar('virtualpath') == '' )
405 $virtualpath = serverVar('PATH_INFO');
409 * switch URLMode back to normal when $CONF['Self'] ends in .php
410 * this avoids urls like index.php/item/13/index.php/item/15
412 if ( !array_key_exists('URLMode', $CONF) || ($CONF['URLMode'] != 'pathinfo') )
414 $CONF['URLMode'] = 'normal';
418 if ( i18n::substr($CONF['Self'], i18n::strlen($CONF['Self']) - 4) != '.php' )
420 decodePathInfo($virtualpath);
425 * PostParseURL is a place to cleanup any of the path-related global variables before the selector function is run.
\r
426 * It has 2 values in the data in case the original virtualpath is needed, but most the use will be in tweaking
\r
427 * global variables to clean up (scrub out catid or add catid) or to set someother global variable based on
\r
428 * the values of something like catid or itemid
\r
432 'type' => basename(serverVar('SCRIPT_NAME')),
\r
433 'info' => $virtualpath
\r
435 $manager->notify('PostParseURL', $data);
\r
438 * NOTE: Here is the end of initialization
\r
443 * This function includes or requires the specified library file
\r
445 * @param string $file
\r
446 * @param boolean $once use the _once() version
\r
447 * @param boolean $require use require() instead of include()
\r
450 function include_libs($file, $once = TRUE, $require = TRUE)
\r
454 // $DIR_LIBS isn't a directory
\r
455 if ( !is_dir($DIR_LIBS) )
\r
460 $lib_path = $DIR_LIBS . $file;
\r
462 if ( $once && $require )
\r
464 require_once($lib_path);
\r
466 else if ( $once && !$require )
\r
468 include_once($lib_path);
\r
470 else if ( $require )
\r
472 require($lib_path);
\r
476 include($lib_path);
\r
482 * include_plugins()
\r
483 * This function includes or requires the specified plugin file
\r
485 * @param string $file
\r
486 * @param boolean $once use the _once() version
\r
487 * @param boolean $require use require() instead of include()
\r
490 function include_plugins($file, $once = TRUE, $require = TRUE)
\r
492 global $DIR_PLUGINS;
\r
494 // begin if: $DIR_LIBS isn't a directory
\r
495 if ( !is_dir($DIR_PLUGINS) )
\r
500 $plugin_path = $DIR_PLUGINS . $file;
\r
503 if ( $once && $require )
\r
505 require_once($plugin_path);
\r
507 else if ( $once && !$require )
\r
509 include_once($plugin_path);
\r
511 elseif ( $require )
\r
513 require($plugin_path);
\r
517 include($plugin_path);
\r
523 * include_translation()
\r
524 * This function decide which locale is used and include translation
\r
526 * @param string &$locale locale name referring to 'language tags' defined in RFC 5646
\r
529 function include_translation(&$locale)
\r
531 global $DIR_LOCALES;
\r
533 $translation_file = $DIR_LOCALES . $locale . '.' . i18n::get_current_charset() . '.php';
\r
534 if ( !file_exists($translation_file) )
\r
536 $locale = 'en_Latn_US';
\r
537 $translation_file = $DIR_LOCALES . 'en_Latn_US.ISO-8859-1.php';
\r
539 include($translation_file);
\r
545 * This function returns the integer value of $_POST for the variable $name
\r
547 * @param string $name field to get the integer value of
\r
550 function intPostVar($name)
\r
552 return (integer) postVar($name);
\r
558 * This function returns the integer value of $_GET for the variable $name
\r
560 * @param string $name field to get the integer value of
\r
563 function intGetVar($name)
\r
565 return (integer) getVar($name);
\r
571 * This function returns the integer value of $_REQUEST for the variable $name. Also checks $_GET and $_POST if not found in $_REQUEST
\r
573 * @param string $name field to get the integer value of
\r
576 function intRequestVar($name)
\r
578 return (integer) requestVar($name);
\r
584 * This function returns the integer value of $_COOKIE for the variable $name
\r
586 * @param string $name field to get the integer value of
\r
589 function intCookieVar($name)
\r
591 return (integer) cookieVar($name);
\r
595 * getNucleusVersion()
\r
596 * This function returns the current Nucleus version (100 = 1.00, 101 = 1.01, etc...)
\r
601 function getNucleusVersion()
\r
607 * getNucleusPatchLevel()
\r
608 * TODO: Better description of this function.
\r
610 * Power users can install patches in between nucleus releases. These patches
\r
611 * usually add new functionality in the plugin API and allow those to
\r
612 * be tested without having to install CVS.
\r
617 function getNucleusPatchLevel()
\r
623 * getLatestVersion()
\r
624 * This function returns the latest Nucleus version available for download from nucleuscms.org or FALSE if unable to attain data
\r
625 * Format will be major.minor/patachlevel e.g. 3.41 or 3.41/02
\r
630 function getLatestVersion()
\r
632 // begin if: cURL is not available in this PHP installation
\r
633 if ( !function_exists('curl_init') )
\r
638 $curl = curl_init();
\r
641 curl_setopt ($curl, CURLOPT_URL, 'http://nucleuscms.org/version_check.php');
\r
642 curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
\r
643 curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
\r
645 $return = curl_exec($curl);
\r
654 * This function returns a Nucleus table name with the appropriate prefix
\r
655 * @param string $name
\r
658 function sql_table($name)
\r
660 global $MYSQL_PREFIX;
\r
662 // begin if: no MySQL prefix
\r
663 if ( empty($MYSQL_PREFIX) )
\r
665 return 'nucleus_' . $name;
\r
667 // else: use MySQL prefix
\r
670 return $MYSQL_PREFIX . 'nucleus_' . $name;
\r
676 * sendContentType()
\r
677 * This function sends the Content-Type header if headers have not already been sent
\r
678 * It also determines if the browser can accept application/xhtml+xml and sends it only to those that can.
\r
680 * if content type is application/xhtml+xml, only send it to browsers
\r
681 * that can handle it (IE6 cannot). Otherwise, send text/html
\r
684 * For admin area pages, keep sending text/html (unless it's a debug version)
\r
685 * application/xhtml+xml still causes too much problems with the javascript implementations
\r
688 * ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,
\r
689 * application/xhtml+xml seems to be working, so we're going to use it if we can.
\r
691 * @param string $content_type MIME media type registered to IANA, http://www.iana.org/assignments/media-types/index.html
\r
692 * @param string $page_type
\r
693 * @param string $charset Deprecated. This has no meaning.
\r
697 function sendContentType($content_type, $page_type = '', $charset = '')
\r
699 global $manager, $CONF;
\r
701 if ( headers_sent() )
\r
706 /* NOTE: MIME Media Type */
\r
707 if ( ($content_type == 'application/xhtml+xml')
\r
708 && (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') ) )
\r
710 $content_type = 'text/html';
\r
713 /* NOTE: generate event */
\r
715 'pageType' => $page_type,
\r
716 'contentType' => &$content_type
\r
718 $manager->notify('PreSendContentType', $data);
\r
720 /* NOTE: confirm MIME Media Type */
\r
721 $content_type = preg_replace('#[^a-zA-Z0-9-+./]#', '', $content_type);
\r
723 /* NOTE: confirm character set */
\r
724 $charset = i18n::get_current_charset();
\r
725 if ( i18n::get_forced_charset() !== '' )
\r
727 $charset = i18n::get_forced_charset();
\r
730 /* NOTE: send HTTP 1.1 header */
\r
731 header("Content-Type: {$content_type}; charset={$charset}");
\r
733 /* NOTE: set handler for translating character set */
\r
734 if ( $charset != i18n::get_current_charset() )
\r
736 ob_start(array('i18n', 'convert_handler'));
\r
744 * This function parses a query into an array of expressions that can be passed on to the highlight method
\r
745 * @param string $query
\r
748 function parseHighlight($query)
\r
750 // TODO: add more intelligent splitting logic
\r
752 // get rid of quotes
\r
753 $query = preg_replace('/\'|"/', '', $query);
\r
760 $aHighlight = preg_split('# #', $query);
\r
762 for ( $i = 0; $i < count($aHighlight); $i++ )
\r
764 $aHighlight[$i] = trim($aHighlight[$i]);
\r
766 if ( i18n::strlen($aHighlight[$i]) < 3 )
\r
768 unset($aHighlight[$i]);
\r
772 if ( count($aHighlight) == 1 )
\r
774 return $aHighlight[0];
\r
778 return $aHighlight;
\r
789 function getConfig()
\r
793 $query = sprintf('SELECT * FROM %s', sql_table('config'));
\r
794 $res = DB::getResult($query);
\r
796 foreach ( $res as $row )
\r
798 $CONF[$row['name']] = $row['value'];
\r
804 * This function gets the blog ID from the blog name
\r
805 * @param string $name
\r
808 function getBlogIDFromName($name)
\r
810 $query = sprintf('SELECT bnumber AS result FROM %s WHERE bshortname=%s', sql_table('blog'), DB::quoteValue($name));
\r
811 return DB::getValue($query);
\r
815 * This function gets the blog name from the blog ID
\r
819 function getBlogNameFromID($id)
\r
821 $query = sprintf('SELECT bname AS result FROM %s WHERE bnumber=%d', sql_table('blog'), intval($id));
\r
822 return DB::getValue($query);
\r
826 * This function gets the blog ID from the item ID
\r
827 * @param int $item_id
\r
830 function getBlogIDFromItemID($item_id)
\r
832 $query = sprintf('SELECT iblog AS result FROM %s WHERE inumber=%d', sql_table('item'), intval($item_id));
\r
833 return DB::getValue($query);
\r
837 * This function gets the blog ID from the comment ID
\r
838 * @param int $comment_id
\r
841 function getBlogIDFromCommentID($comment_id)
\r
843 $query = sprintf('SELECT cblog AS result FROM %s WHERE cnumber=%d', sql_table('comment'), intval($comment_id));
\r
844 return DB::getValue($query);
\r
848 * This function gets the blog ID from the category ID
\r
849 * @param int $category_id
\r
852 function getBlogIDFromCatID($category_id)
\r
854 $query = sprintf('SELECT cblog AS result FROM %s WHERE catid=%d', sql_table('category'), intval($category_id));
\r
855 return DB::getValue($query);
\r
859 * This function gets the category ID from the category name
\r
863 function getCatIDFromName($name)
\r
865 $query = sprintf('SELECT catid AS result FROM %s WHERE cname=%s', sql_table('category'), DB::quoteValue($name));
\r
866 return DB::getValue($query);
\r
871 * functions to be used in index.php to select something
\r
873 function selectBlog($shortname)
\r
875 global $blogid, $archivelist;
\r
876 $blogid = getBlogIDFromName($shortname);
\r
878 // also force archivelist variable, if it is set
\r
879 if ( $archivelist )
\r
881 $archivelist = $blogid;
\r
885 function selectSkin($skinname)
\r
888 $skinid = SKIN::getIdFromName($skinname);
\r
891 function selectCategory($cat)
\r
894 if ( is_numeric($cat) )
\r
896 $catid = (integer) $cat;
\r
900 $catid = getCatIDFromName($cat);
\r
904 function selectItem($id)
\r
907 $itemid = (integer) $id;
\r
910 function selectSpecialSkinType($id)
\r
913 $special = strtolower($id);
\r
916 function selector()
\r
918 global $archive, $archivelist, $archivenext, $archivenextexists, $archiveprev, $archiveprevexists, $archivetype;
\r
919 global $blog, $blogid;
\r
921 global $itemid, $itemidnext, $itemidprev, $itemtitlenext, $itemtitleprev;
\r
922 global $CONF, $DIR_LIBS, $amount, $errormessage, $imagepopup;
\r
923 global $manager, $maxresults, $query;
\r
924 global $member, $memberid, $memberinfo;
\r
925 global $skinid, $skinpart, $special;
\r
927 $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');
\r
928 $action = requestVar('action');
\r
930 if ( in_array($action, $actionNames) )
\r
932 include_once($DIR_LIBS . 'ACTION.php');
\r
934 $errorInfo = $a->doAction($action);
\r
938 $errormessage = $errorInfo['message'];
\r
942 // show error when headers already sent out
\r
943 if ( headers_sent() && $CONF['alertOnHeadersSent'] )
\r
945 // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)
\r
946 if ( function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') )
\r
948 headers_sent($hsFile, $hsLine);
\r
949 $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';
\r
957 "<p>The page headers have already been sent out{$extraInfo}. This could cause Nucleus not to work in the expected way.</p>"
\r
958 . "<p>Usually, this is caused by spaces or newlines at the end of the <code>config.php</code> file, "
\r
959 . "at the end of the translation file or at the end of a plugin file.</p>"
\r
960 . "<p>Please check this and try again.</p>"
\r
961 . "<p>If you don't want to see this error message again, without solving the problem, "
\r
962 . "set <code>{$CONF['alertOnHeadersSent']}</code> in <code>globalfunctions.php</code> to <code>0</code></p>"
\r
963 . "Page headers already sent"
\r
968 // make is so ?archivelist without blogname or blogid shows the archivelist
\r
969 // for the default weblog
\r
970 if ( serverVar('QUERY_STRING') == 'archivelist' )
\r
972 $archivelist = $CONF['DefaultBlog'];
\r
975 // now decide which type of skin we need
\r
978 // itemid given -> only show that item
\r
981 if ( !$manager->existsItem($itemid,intval($CONF['allowFuture']),intval($CONF['allowDrafts'])) )
\r
983 doError(_ERROR_NOSUCHITEM);
\r
986 // 1. get timestamp, blogid and catid for item
\r
987 $query = 'SELECT itime, iblog, icat FROM %s WHERE inumber=%d';
\r
988 $query = sprintf($query, sql_table('item'), intval($itemid));
\r
989 $row = DB::getRow($query);
\r
991 // if a different blog id has been set through the request or selectBlog(),
\r
994 if ( $blogid && (intval($blogid) != $row['iblog']) )
\r
996 doError(_ERROR_NOSUCHITEM);
\r
999 // if a category has been selected which doesn't match the item, ignore the
\r
1001 if ( ($catid != 0) && ($catid != $row['icat']) )
\r
1006 $blogid = $row['iblog'];
\r
1007 $timestamp = strtotime($row['itime']);
\r
1009 $b =& $manager->getBlog($blogid);
\r
1011 if ( !$b->isValidCategory($catid) )
\r
1013 $query = "SELECT inumber, ititle FROM %s WHERE itime<%s AND idraft=0 AND iblog=%d ORDER BY itime DESC LIMIT 1";
\r
1014 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), intval($blogid));
\r
1018 $query = "SELECT inumber, ititle FROM %s WHERE itime<%s AND idraft=0 AND iblog=%d AND icat=%d ORDER BY itime DESC LIMIT 1";
\r
1019 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), intval($blogid), intval($catid));
\r
1021 $row = DB::getRow($query);
\r
1025 $itemidprev = $row['inumber'];
\r
1026 $itemtitleprev = $row['ititle'];
\r
1029 // get next itemid and title
\r
1030 if ( !$b->isValidCategory($catid) )
\r
1032 $query = "SELECT inumber, ititle FROM %s WHERE itime>%s AND itime<=%s AND idraft=0 AND iblog=%d ORDER BY itime ASC LIMIT 1";
\r
1033 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), DB::formatDateTime($b->getCorrectTime()), intval($blogid));
\r
1037 $query = "SELECT inumber, ititle FROM %s WHERE itime>%s AND itime<=%s AND idraft=0 AND iblog=%d AND icat=%d ORDER BY itime ASC LIMIT 1";
\r
1038 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), DB::formatDateTime($b->getCorrectTime()), intval($blogid), intval($catid));
\r
1040 $row = DB::getRow($query);
\r
1044 $itemidnext = $row['inumber'];
\r
1045 $itemtitlenext = $row['ititle'];
\r
1048 elseif ( $archive )
\r
1051 $type = 'archive';
\r
1053 // sql queries for the timestamp of the first and the last published item
\r
1054 $query = sprintf('SELECT UNIX_TIMESTAMP(itime) as result FROM %s WHERE idraft=0 ORDER BY itime ASC', sql_table('item'));
\r
1055 $first_timestamp = DB::getValue($query);
\r
1056 $query = sprintf('SELECT UNIX_TIMESTAMP(itime) as result FROM %s WHERE idraft=0 ORDER BY itime DESC', sql_table('item'));
\r
1057 $last_timestamp = DB::getValue($query);
\r
1059 sscanf($archive, '%d-%d-%d', $y, $m, $d);
\r
1063 $archivetype = _ARCHIVETYPE_DAY;
\r
1064 $t = mktime(0, 0, 0, $m, $d, $y);
\r
1065 // one day has 24 * 60 * 60 = 86400 seconds
\r
1066 $archiveprev = i18n::formatted_datetime('%Y-%m-%d', $t - 86400 );
\r
1067 // check for published items
\r
1068 if ( $t > $first_timestamp )
\r
1070 $archiveprevexists = true;
\r
1074 $archiveprevexists = false;
\r
1079 $archivenext = i18n::formatted_datetime('%Y-%m-%d', $t);
\r
1080 if ( $t < $last_timestamp )
\r
1082 $archivenextexists = true;
\r
1086 $archivenextexists = false;
\r
1089 elseif ( $m == 0 )
\r
1091 $archivetype = _ARCHIVETYPE_YEAR;
\r
1092 $t = mktime(0, 0, 0, 12, 31, $y - 1);
\r
1093 // one day before is in the previous year
\r
1094 $archiveprev = i18n::formatted_datetime('%Y', $t);
\r
1095 if ( $t > $first_timestamp )
\r
1097 $archiveprevexists = true;
\r
1101 $archiveprevexists = false;
\r
1104 // timestamp for the next year
\r
1105 $t = mktime(0, 0, 0, 1, 1, $y + 1);
\r
1106 $archivenext = i18n::formatted_datetime('%Y', $t);
\r
1107 if ( $t < $last_timestamp )
\r
1109 $archivenextexists = true;
\r
1113 $archivenextexists = false;
\r
1118 $archivetype = _ARCHIVETYPE_MONTH;
\r
1119 $t = mktime(0, 0, 0, $m, 1, $y);
\r
1120 // one day before is in the previous month
\r
1121 $archiveprev = i18n::formatted_datetime('%Y-%m', $t - 86400);
\r
1122 if ( $t > $first_timestamp )
\r
1124 $archiveprevexists = true;
\r
1128 $archiveprevexists = false;
\r
1131 // timestamp for the next month
\r
1132 $t = mktime(0, 0, 0, $m+1, 1, $y);
\r
1133 $archivenext = i18n::formatted_datetime('%Y-%m', $t);
\r
1134 if ( $t < $last_timestamp )
\r
1136 $archivenextexists = true;
\r
1140 $archivenextexists = false;
\r
1144 elseif ( $archivelist )
\r
1146 $type = 'archivelist';
\r
1148 if ( is_numeric($archivelist) )
\r
1150 $blogid = intVal($archivelist);
\r
1154 $blogid = getBlogIDFromName($archivelist);
\r
1159 doError(_ERROR_NOSUCHBLOG);
\r
1166 $query = stripslashes($query);
\r
1168 if ( is_numeric($blogid) )
\r
1170 $blogid = intVal($blogid);
\r
1174 $blogid = getBlogIDFromName($blogid);
\r
1179 doError(_ERROR_NOSUCHBLOG);
\r
1182 elseif ( $memberid )
\r
1186 if ( !Member::existsID($memberid) )
\r
1188 doError(_ERROR_NOSUCHMEMBER);
\r
1190 $memberinfo = $manager->getMember($memberid);
\r
1192 elseif ( $imagepopup )
\r
1194 // media object (images etc.)
\r
1195 $type = 'imagepopup';
\r
1197 // TODO: check if media-object exists
\r
1198 // TODO: set some vars?
\r
1202 // show regular index page
\r
1207 // any type of skin with catid
\r
1208 if ( $catid && !$blogid )
\r
1210 $blogid = getBlogIDFromCatID($catid);
\r
1213 // decide which blog should be displayed
\r
1216 $blogid = $CONF['DefaultBlog'];
\r
1219 $b =& $manager->getBlog($blogid);
\r
1220 $blog = $b; // references can't be placed in global variables?
\r
1222 if ( !$blog->isValid )
\r
1224 doError(_ERROR_NOSUCHBLOG);
\r
1227 // set catid if necessary
\r
1230 // check if the category is valid
\r
1231 if ( !$blog->isValidCategory($catid) )
\r
1233 doError(_ERROR_NOSUCHCATEGORY);
\r
1237 $blog->setSelectedCategory($catid);
\r
1243 $skinid = $blog->getDefaultSkin();
\r
1246 if ( !empty($special) && isValidShortName($special) )
\r
1248 $type = strtolower($special);
\r
1251 $skin = new SKIN($skinid);
\r
1253 if ( !$skin->isValid() )
\r
1255 doError(_ERROR_NOSUCHSKIN);
\r
1258 // set global skinpart variable so can determine quickly what is being parsed from any plugin or phpinclude
\r
1259 $skinpart = $type;
\r
1262 $skin->parse($type);
\r
1264 // check to see we should throw JustPosted event
\r
1265 $blog->checkJustPosted();
\r
1271 * Show error skin with given message. An optional skin-object to use can be given
\r
1273 * @param string $msg
\r
1274 * @param string $skin
\r
1277 function doError($msg, $skin = '')
\r
1279 global $errormessage, $CONF, $skinid, $blogid, $manager;
\r
1281 if ( $skin == '' )
\r
1283 if ( Skin::existsID($skinid) )
\r
1287 elseif ( $manager->existsBlogID($blogid) )
\r
1289 $blog =& $manager->getBlog($blogid);
\r
1290 $id = $blog->getDefaultSkin();
\r
1292 elseif ($CONF['DefaultBlog'] )
\r
1294 $blog =& $manager->getBlog($CONF['DefaultBlog']);
\r
1295 $id = $blog->getDefaultSkin();
\r
1299 // this statement should actually never be executed
\r
1300 $id = $CONF['BaseSkin'];
\r
1302 $skin = new Skin($id);
\r
1305 $errormessage = $msg;
\r
1306 $skin->parse('error');
\r
1311 * Errors before the database connection has been made
\r
1313 * @param string $msg message to notify
\r
1314 * @param string $title page title
\r
1317 function startUpError($msg, $title)
\r
1319 header('Content-Type: text/xml; charset=' . i18n::get_current_charset());
\r
1320 echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
\r
1322 echo "<title>{$title}</title></head>\n";
\r
1324 echo "<h1>{$title}</h1>\n";
\r
1331 function isValidShortName($name)
\r
1333 return preg_match('#^[a-z0-9]+$#i', $name);
\r
1335 function isValidDisplayName($name)
\r
1337 return preg_match('#^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$#i', $name);
\r
1339 function isValidCategoryName($name)
\r
1343 function isValidTemplateName($name)
\r
1345 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
\r
1347 function isValidSkinName($name)
\r
1349 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
\r
1352 // add and remove linebreaks
\r
1353 function addBreaks($var)
\r
1355 return nl2br($var);
\r
1357 function removeBreaks($var)
\r
1359 return preg_replace("/<br \/>([\r\n])/", "$1", $var);
\r
1365 * @param string $filename
\r
1366 * @param string $includeMode
\r
1367 * @param string $includePrefix
\r
1370 function parseFile($filename, $includeMode = 'normal', $includePrefix = '')
\r
1374 if ( !$skinid || !existsID($skinid) )
\r
1376 $skin = new Skin($CONF['BaseSkin']);
\r
1380 $skin = new Skin($skinid);
\r
1383 $oldIncludeMode = Parser::getProperty('IncludeMode');
\r
1384 $oldIncludePrefix = Parser::getProperty('IncludePrefix');
\r
1386 $skin->parse('fileparse', $filename);
\r
1388 Parser::setProperty('IncludeMode', $oldIncludeMode);
\r
1389 Parser::setProperty('IncludePrefix', $oldIncludePrefix);
\r
1396 * Outputs a debug message
\r
1398 * @param string $msg
\r
1401 function debug($msg)
\r
1403 echo '<p><b>' . $msg . "</b></p>\n";
\r
1407 // shows a link to help file
\r
1408 function help($id)
\r
1410 echo helpHtml($id);
\r
1413 function helpHtml($id)
\r
1416 return helplink($id) . '<img src="' . $CONF['AdminURL'] . 'documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" title="' . _HELP_TT . '" /></a>';
\r
1418 function helplink($id)
\r
1421 return '<a href="' . $CONF['AdminURL'] . 'documentation/help.html#'. $id . '" onclick="if (event && event.preventDefault) event.preventDefault(); return help(this.href);">';
\r
1426 * Includes a PHP file. This method can be called while parsing templates and skins
\r
1428 * @param string $filename name of file to parse
\r
1431 function includephp($filename)
\r
1433 // make predefined variables global, so most simple scripts can be used here
\r
1435 // apache (names taken from PHP doc)
\r
1436 global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;
\r
1437 global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;
\r
1438 global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;
\r
1439 global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;
\r
1440 global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;
\r
1441 global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;
\r
1442 global $REQUEST_URI;
\r
1444 // php (taken from PHP doc)
\r
1445 global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;
\r
1446 global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;
\r
1449 global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;
\r
1451 if ( @file_exists($filename) )
\r
1453 include($filename);
\r
1459 * Checks if a certain plugin exists
\r
1460 * @param string $plug name of plugin
\r
1461 * @return boolean exists or not
\r
1463 function checkPlugin($name)
\r
1465 global $DIR_PLUGINS;
\r
1466 return file_exists($DIR_PLUGINS . preg_replace('#[\\\\|/]#', '', $name) . '.php');
\r
1472 * @param string $querystr querystring to alter (e.g. foo=1&bar=2&x=y)
\r
1473 * @param string $param name of parameter to change (e.g. 'foo')
\r
1474 * @param string $value New value for that parameter (e.g. 3)
\r
1475 * @return string altered query string (for the examples above: foo=3&bar=2&x=y)
\r
1477 function alterQueryStr($querystr, $param, $value)
\r
1479 $vars = preg_split('#&#', $querystr);
\r
1482 for ( $i = 0; $i < count($vars); $i++ )
\r
1484 $v = preg_split('#=#', $vars[$i]);
\r
1486 if ( $v[0] == $param )
\r
1489 $vars[$i] = implode('=', $v);
\r
1496 $vars[] = "{$param}={$value}";
\r
1498 return ltrim(implode('&', $vars), '&');
\r
1503 * passes one variable as hidden input field (multiple fields for arrays)
\r
1504 * @see passRequestVars in varsx.x.x.php
\r
1506 * @param string $key
\r
1507 * @param string $value
\r
1510 function passVar($key, $value)
\r
1513 if ( is_array($value) )
\r
1515 for ( $i = 0; $i < sizeof($value); $i++ )
\r
1517 passVar($key . '[' . $i . ']', $value[$i]);
\r
1522 // other values: do stripslashes if needed
\r
1523 echo '<input type="hidden" name="' . Entity::hsc($key) . '" value="' . Entity::hsc(undoMagic($value)) . '" />' . "\n";
\r
1530 * @param string $variables
\r
1533 function checkVars($variables)
\r
1535 foreach ( $variables as $variable )
\r
1537 if ( array_key_exists($variable, $_GET)
\r
1538 || array_key_exists($variable, $_POST)
\r
1539 || array_key_exists($variable, $_COOKIE)
\r
1540 || array_key_exists($variable, $_ENV)
\r
1541 || (session_id() !== '' && array_key_exists($variable, $_SESSION))
\r
1542 || array_key_exists($variable, $_FILES) )
\r
1544 die('Sorry. An error occurred.');
\r
1551 * sanitizeParams()
\r
1552 * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.
\r
1558 function sanitizeParams()
\r
1564 // REQUEST_URI of $_SERVER
\r
1565 $str =& $_SERVER["REQUEST_URI"];
\r
1566 serverStringToArray($str, $array, $frontParam);
\r
1567 sanitizeArray($array);
\r
1568 arrayToServerString($array, $frontParam, $str);
\r
1570 // QUERY_STRING of $_SERVER
\r
1571 $str =& $_SERVER["QUERY_STRING"];
\r
1572 serverStringToArray($str, $array, $frontParam);
\r
1573 sanitizeArray($array);
\r
1574 arrayToServerString($array, $frontParam, $str);
\r
1577 convArrayForSanitizing($_GET, $array);
\r
1578 sanitizeArray($array);
\r
1579 revertArrayForSanitizing($array, $_GET);
\r
1581 // $_REQUEST (only GET param)
\r
1582 convArrayForSanitizing($_REQUEST, $array);
\r
1583 sanitizeArray($array);
\r
1584 revertArrayForSanitizing($array, $_REQUEST);
\r
1589 function _addInputTags(&$keys,$prefix='')
\r
1591 foreach ( $keys as $key=>$value )
\r
1595 $key=$prefix.'['.$key.']';
\r
1597 if ( is_array($value) )
\r
1599 _addInputTags($value,$key);
\r
1603 if ( get_magic_quotes_gpc() )
\r
1604 {$value=stripslashes($value);
\r
1606 if ( $key == 'ticket' )
\r
1610 echo '<input type="hidden" name="'.Entity::hsc($key).
\r
1611 '" value="'.Entity::hsc($value).'" />'."\n";
\r
1618 * serverStringToArray()
\r
1619 * Convert the server string such as $_SERVER['REQUEST_URI']
\r
1620 * to arry like arry['blogid']=1 and array['page']=2 etc.
\r
1622 * @param string $uri string
\r
1623 * @param string &$query_elements elements of query according to application/x-www-form-urlencoded
\r
1624 * @param string &$hier_part hierarchical part includes path
\r
1627 * RFC 3986: Uniform Resource Identifiers (URI): Generic Syntax
\r
1628 * 3. Syntax Components
\r
1629 * http://www.ietf.org/rfc/rfc3986.txt
\r
1631 * Hypertext Markup Language - 2.0
\r
1632 * 8.2.1. The form-urlencoded Media Type
\r
1633 * http://tools.ietf.org/html/rfc1866#section-8.2.1
\r
1635 * $_SERVER > Language Reference > Predefined Variables > PHP Manual
\r
1636 * http://www.php.net/manual/en/reserved.variables.server.php
\r
1638 function serverStringToArray($uri, &$query_elements, &$hier_part)
\r
1641 $query_elements = array();
\r
1644 // split hierarchical part, e.g. /index.php, query and fragment, e.g. blogid=1&page=2#section1
\r
1645 if ( i18n::strpos($uri, "?") > 0 )
\r
1647 list($hier_part, $query_and_fragment) = preg_split("#\?#", $uri, 2);
\r
1651 $query_and_fragment = $uri;
\r
1655 // If there is no query like blogid=1&page=2, return
\r
1656 if ( i18n::strpos($uri, "=") == FALSE && !i18n::strlen($hier_part) )
\r
1658 $hier_part = $uri;
\r
1662 $query_elements = preg_split("#&#", $query_and_fragment);
\r
1667 * arrayToServerString()
\r
1668 * Convert array like array['blogid'] to server string
\r
1669 * such as $_SERVER['REQUEST_URI']
\r
1671 * @param array $query_elements elements of query according to application/x-www-form-urlencoded
\r
1672 * @param string $hier_part hier-part defined in RFC3986
\r
1673 * @param string &$uri return value
\r
1677 * RFC 3986: Uniform Resource Identifiers (URI): Generic Syntax
\r
1678 * 3. Syntax Components
\r
1679 * http://www.ietf.org/rfc/rfc3986.txt
\r
1681 * Hypertext Markup Language - 2.0
\r
1682 * 8.2.1. The form-urlencoded Media Type
\r
1683 * http://tools.ietf.org/html/rfc1866#section-8.2.1
\r
1685 * $_SERVER > Language Reference > Predefined Variables > PHP Manual
\r
1686 * http://www.php.net/manual/en/reserved.variables.server.php
\r
1688 function arrayToServerString($query_elements, $hier_part, &$uri)
\r
1690 if ( i18n::strpos($uri, "?") !== FALSE )
\r
1692 $uri = $hier_part . "?";
\r
1696 $uri = $hier_part;
\r
1698 if ( count($query_elements) > 0 )
\r
1700 $uri .= implode("&", $query_elements);
\r
1707 * Sanitize array parameters.
\r
1708 * This function checks both key and value.
\r
1709 * - check key if it inclues " (double quote), remove from array
\r
1710 * - check value if it includes \ (escape sequece), remove remaining string
\r
1712 * @param array &$array elements of query according to application/x-www-form-urlencoded
\r
1715 function sanitizeArray(&$array)
\r
1717 $excludeListForSanitization = array('query');
\r
1719 foreach ( $array as $k => $v )
\r
1721 // split to key and value
\r
1722 list($key, $val) = preg_split("#=#", $v, 2);
\r
1723 if ( !isset($val) )
\r
1728 // when magic quotes is on, need to use stripslashes,
\r
1729 // and then addslashes
\r
1730 if ( get_magic_quotes_gpc() )
\r
1732 $val = stripslashes($val);
\r
1735 // note that we must use addslashes here because this function is called before the db connection is made
\r
1736 // and sql_real_escape_string needs a db connection
\r
1737 $val = addslashes($val);
\r
1739 // if $key is included in exclude list, skip this param
\r
1740 if ( !in_array($key, $excludeListForSanitization) )
\r
1743 if ( i18n::strpos($val, '\\') > 0 )
\r
1745 list($val, $tmp) = preg_split('#\\\\#', $val);
\r
1748 // remove control code etc.
\r
1749 $val = strtr($val, "\0\r\n<>'\"", " ");
\r
1752 if ( preg_match('#\"#', $key) > 0 )
\r
1754 unset($array[$k]);
\r
1758 // set sanitized info
\r
1759 $array[$k] = sprintf("%s=%s", $key, $val);
\r
1766 * convArrayForSanitizing()
\r
1767 * Convert array for sanitizeArray function
\r
1769 * @param string $src array to be sanitized
\r
1770 * @param array &$array array to be temporarily stored
\r
1773 function convArrayForSanitizing($src, &$array)
\r
1776 foreach ( $src as $key => $val )
\r
1778 if ( !key_exists($key, $_GET) )
\r
1782 $array[] = sprintf("%s=%s", $key, $val);
\r
1789 * revertArrayForSanitizing()
\r
1790 * Revert array after sanitizeArray function
\r
1792 * @param array $array element of query according to application/x-www-form-urlencoded
\r
1793 * @param array &$dst combination of key and value
\r
1796 function revertArrayForSanitizing($array, &$dst)
\r
1798 foreach ( $array as $v )
\r
1800 list($key, $val) = preg_split("#=#", $v, 2);
\r
1801 $dst[$key] = $val;
\r
1812 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
1813 * Copyright (C) 2002-2009 The Nucleus Group
1815 * This program is free software; you can redistribute it and/or
1816 * modify it under the terms of the GNU General Public License
1817 * as published by the Free Software Foundation; either version 2
1818 * of the License, or (at your option) any later version.
1819 * (see nucleus/documentation/index.html#license for more info)
1822 * @license http://nucleuscms.org/license.txt GNU General Public License
1823 * @copyright Copyright (C) 2002-2009 The Nucleus Group
1824 * @version $Id: globalfunctions.php 1886 2012-06-17 08:27:27Z sakamocchi $
1827 /* needed if we include globalfunctions from install.php */
1828 global $nucleus, $CONF, $DIR_LIBS, $DIR_LOCALES, $manager, $member, $MYSQL_HANDLER, $StartTime;
1830 /* just for benchmark tag */
1831 $StartTime = microtime(TRUE);
1833 $nucleus['version'] = 'v4.00 SVN';
1834 $nucleus['codename'] = '';
1837 * make sure there's no unnecessary escaping:
1838 * set_magic_quotes_runtime(0);
1840 if ( version_compare(PHP_VERSION, '5.3.0', '<') )
1842 ini_set('magic_quotes_runtime', '0');
1845 /* check and die if someone is trying to override internal globals (when register_globals turn on) */
1846 checkVars(array('nucleus', 'CONF', 'DIR_LIBS',
1847 'MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE',
1848 'DIR_LOCALES', 'DIR_PLUGINS',
1849 'HTTP_GET_VARS', 'HTTP_POST_VARS', 'HTTP_COOKIE_VARS', 'HTTP_ENV_VARS',
1850 'HTTP_SESSION_VARS', 'HTTP_POST_FILES', 'HTTP_SERVER_VARS',
1851 'GLOBALS', 'argv', 'argc', '_GET', '_POST', '_COOKIE', '_ENV', '_SESSION', '_SERVER', '_FILES'));
1853 if ( !isset($CONF) )
1859 if ( array_key_exists('debug', $CONF) && $CONF['debug'] )
1861 /* report all errors! */
1862 error_reporting(E_ALL | E_STRICT);
1866 ini_set('display_errors','0');
1867 error_reporting(E_ERROR | E_WARNING | E_PARSE);
1871 * alertOnHeadersSent
1872 * Displays an error when visiting a public Nucleus page and headers have
1873 * been sent out to early. This usually indicates an error in either a
1874 * configuration file or a translation file, and could cause Nucleus to
1877 if ( !array_key_exists('alertOnHeadersSent', $CONF) )
1879 $CONF['alertOnHeadersSent'] = 1;
1882 * alertOnSecurityRisk
1883 * Displays an error only when visiting the admin area, and when one or
1884 * more of the installation files (install.php, install.sql, upgrades/
1885 * directory) are still on the server.
1887 if ( !array_key_exists('alertOnSecurityRisk', $CONF) )
1889 $CONF['alertOnSecurityRisk'] = 1;
1892 * Set these to 1 to allow viewing of future items or draft items
1893 * Should really never do this, but can be useful for some plugins that might need to
1894 * Could cause some other issues if you use future posts otr drafts
1897 $CONF['allowDrafts'] = 0;
1898 $CONF['allowFuture'] = 0;
1900 if ( getNucleusPatchLevel() > 0 )
1902 $nucleus['version'] .= '/' . getNucleusPatchLevel();
1906 if ( !array_key_exists('installscript', $CONF) || empty($CONF['installscript']) )
1908 $CONF['installscript'] = 0;
1910 if ( !array_key_exists('UsingAdminArea', $CONF) )
1912 $CONF['UsingAdminArea'] = 0;
1915 if ( !headers_sent() )
1917 header('Generator: Nucleus CMS ' . $nucleus['version']);
1921 /* TODO: This is for compatibility since 4.0, should be obsoleted at future release. */
1922 if ( !isset($DIR_LOCALES) )
1924 $DIR_LOCALES = $DIR_NUCLEUS . 'locales/';
1927 if ( !isset($DIR_LANG) )
1929 $DIR_LANG = $DIR_LOCALES;
1932 /* load and initialize i18n class */
1933 if (!class_exists('i18n', FALSE))
1935 include($DIR_LIBS . 'i18n.php');
1937 if ( !i18n::init('UTF-8', $DIR_LOCALES) )
1939 exit('Fail to initialize i18n class.');
1942 /* TODO: This is just for compatibility since 4.0, should be obsoleted at future release. */
1943 define('_CHARSET', i18n::get_current_charset());
1947 * NOTE: Since 4.0 release, Entity class becomes to be important class
1948 * with some wrapper functions for htmlspechalchars/htmlentity PHP's built-in function
1950 include($DIR_LIBS . 'ENTITY.php');
1952 /* we will use postVar, getVar, ... methods instead of $_GET, $_POST ... */
1953 if ( $CONF['installscript'] != 1 )
1955 /* vars were already included in install.php */
1956 include_once($DIR_LIBS . 'vars4.1.0.php');
1958 /* added for 4.0 DB::* wrapper and compatibility sql_* */
1959 include_once($DIR_LIBS . 'sql/sql.php');
1962 /* include core classes that are needed for login & plugin handling */
1963 include($DIR_LIBS . 'MEMBER.php');
1964 include($DIR_LIBS . 'ACTIONLOG.php');
1965 include($DIR_LIBS . 'MANAGER.php');
1966 include($DIR_LIBS . 'PLUGIN.php');
1968 $manager =& MANAGER::instance();
1970 /* only needed when updating logs */
1971 if ( $CONF['UsingAdminArea'] )
1973 /* XML-RPC client classes */
1974 include($DIR_LIBS . 'xmlrpc.inc.php');
1975 include($DIR_LIBS . 'ADMIN.php');
1979 /* connect to database */
1980 if ( !isset($MYSQL_HANDLER) )
1982 $MYSQL_HANDLER = array('mysql','');
1984 if ( $MYSQL_HANDLER[0] == '' )
1986 $MYSQL_HANDLER[0] = 'mysql';
1988 DB::setConnectionInfo($MYSQL_HANDLER[1], $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE);
1991 /* force locale or charset */
1993 $charset = i18n::get_current_charset();
1996 'locale' => &$locale,
1997 'charset' => &$charset
1999 $manager->notify('ForceLocale', $data);
2001 if ( $data['locale'] !== '' )
2003 i18n::set_forced_locale($data['locale']);
2005 if ( $data['charset'] !== '' )
2007 i18n::set_forced_charset($data['charset']);
2013 /* convert forced charset to current charset */
2014 if ( i18n::get_forced_charset() != i18n::get_current_charset() )
2016 $_POST = i18n::convert_array($_POST, i18n::get_forced_charset());
2017 $_GET = i18n::convert_array($_GET, i18n::get_forced_charset());
2018 $_REQUEST = i18n::convert_array($_REQUEST, i18n::get_forced_charset());
2019 $_COOKIE = i18n::convert_array($_COOKIE, i18n::get_forced_charset());
2020 $_FILES = i18n::convert_array($_FILES, i18n::get_forced_charset());
2022 if ( session_id() !== '' )
2024 $_SESSION = i18n::convert_array($_SESSION, i18n::get_forced_charset());
2029 /* sanitize option */
2030 $bLoggingSanitizedResult = 0;
2031 $bSanitizeAndContinue = 0;
2032 $orgRequestURI = serverVar('REQUEST_URI');
2035 /* logs sanitized result if need */
2036 if ( $orgRequestURI !== serverVar('REQUEST_URI') )
2038 $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";
2039 $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');
2040 if ( $bLoggingSanitizedResult )
2042 addToLog(WARNING, $msg);
2044 if ( !$bSanitizeAndContinue )
2050 /* get all variables that can come from the request and put them in the global scope */
2051 $blogid = requestVar('blogid');
2052 $itemid = intRequestVar('itemid');
2053 $catid = intRequestVar('catid');
2054 $skinid = requestVar('skinid');
2055 $memberid = requestVar('memberid');
2056 $archivelist = requestVar('archivelist');
2057 $imagepopup = requestVar('imagepopup');
2058 $archive = requestVar('archive');
2059 $query = requestVar('query');
2060 $highlight = requestVar('highlight');
2061 $amount = requestVar('amount');
2062 $action = requestVar('action');
2063 $nextaction = requestVar('nextaction');
2064 $maxresults = requestVar('maxresults');
2065 $startpos = intRequestVar('startpos');
2068 $special = requestVar('special');
2075 /* Properly set $CONF['Self'] and others if it's not set...
2076 * usually when we are access from admin menu
2078 if ( !array_key_exists('Self', $CONF) )
2080 $CONF['Self'] = $CONF['IndexURL'];
2081 /* strip trailing */
2082 if ( $CONF['Self'][i18n::strlen($CONF['Self']) -1] == "/" )
2084 $CONF['Self'] = i18n::substr($CONF['Self'], 0, i18n::strlen($CONF['Self']) -1);
2088 $CONF['ItemURL'] = $CONF['Self'];
2089 $CONF['ArchiveURL'] = $CONF['Self'];
2090 $CONF['ArchiveListURL'] = $CONF['Self'];
2091 $CONF['MemberURL'] = $CONF['Self'];
2092 $CONF['SearchURL'] = $CONF['Self'];
2093 $CONF['BlogURL'] = $CONF['Self'];
2094 $CONF['CategoryURL'] = $CONF['Self'];
2096 /* automatically use simpler toolbar for mozilla */
2097 if ( ($CONF['DisableJsTools'] == 0)
2098 && i18n::strpos(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0') !== FALSE
2099 && i18n::strpos(serverVar('HTTP_USER_AGENT'), 'Gecko') !== FALSE )
2101 $CONF['DisableJsTools'] = 2;
2104 /* login processing */
2105 $member = new Member();
2106 if ( $action == 'login' )
2108 $login = postVar('login');
2109 $password = postVar('password');
2110 $shared = intPostVar('shared');
2111 $member->login($login, $password, $shared);
2113 elseif ( ($action == 'logout') )
2119 $member->cookielogin();
2122 /* TODO: This is for backward compatibility, should be obsoleted near future. */
2123 if ( !preg_match('#^(.+)_(.+)_(.+)$#', $CONF['Locale'])
2124 && ($CONF['Locale'] = i18n::convert_old_language_file_name_to_locale($CONF['Locale'])) === FALSE )
2126 $CONF['Locale'] = 'en_Latn_US';
2128 if ( !array_key_exists('Language', $CONF) )
2130 $CONF['Language'] = i18n::convert_locale_to_old_language_file_name($CONF['Locale']);
2132 $locale = $CONF['Locale'];
2135 /* NOTE: include translation file and set locale */
2136 if ( $member->isLoggedIn() )
2138 if ( $member->getLocale() )
2140 $locale = $member->getLocale();
2145 if ( i18n::get_forced_locale() !== '' )
2147 $locale = i18n::get_forced_locale();
2150 include_translation($locale);
2151 i18n::set_current_locale($locale);
2154 /* login completed */
2155 $data = array('loggedIn' => $member->isLoggedIn());
2156 $manager->notify('PostAuthentication', $data);
2159 if ( $member->isLoggedIn() && $nextaction )
2161 $action = $nextaction;
2164 /* first, let's see if the site is disabled or not. always allow admin area access. */
2165 if ( $CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea'] )
2167 redirect($CONF['DisableSiteURL']);
2171 /* load other classes */
2172 include($DIR_LIBS . 'PARSER.php');
2173 include($DIR_LIBS . 'SKIN.php');
2174 include($DIR_LIBS . 'TEMPLATE.php');
2175 include($DIR_LIBS . 'BLOG.php');
2176 include($DIR_LIBS . 'BODYACTIONS.php');
2177 include($DIR_LIBS . 'COMMENTS.php');
2178 include($DIR_LIBS . 'COMMENT.php');
2179 include($DIR_LIBS . 'NOTIFICATION.php');
2180 include($DIR_LIBS . 'BAN.php');
2181 include($DIR_LIBS . 'SEARCH.php');
2182 include($DIR_LIBS . 'LINK.php');
2184 /* set lastVisit cookie (if allowed) */
2185 if ( !headers_sent() )
2187 if ( $CONF['LastVisit'] )
2189 setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
2193 setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
2197 /* for path resolving */
2198 $virtualpath = getVar('virtualpath');
2199 if ( getVar('virtualpath') == '' )
2201 $virtualpath = serverVar('PATH_INFO');
2205 * switch URLMode back to normal when $CONF['Self'] ends in .php
2206 * this avoids urls like index.php/item/13/index.php/item/15
2208 if ( !array_key_exists('URLMode', $CONF) || ($CONF['URLMode'] != 'pathinfo') )
2210 $CONF['URLMode'] = 'normal';
2214 if ( i18n::substr($CONF['Self'], i18n::strlen($CONF['Self']) - 4) != '.php' )
2216 decodePathInfo($virtualpath);
2221 * PostParseURL is a place to cleanup any of the path-related global variables before the selector function is run.
2222 * It has 2 values in the data in case the original virtualpath is needed, but most the use will be in tweaking
2223 * global variables to clean up (scrub out catid or add catid) or to set someother global variable based on
2224 * the values of something like catid or itemid
2228 'type' => basename(serverVar('SCRIPT_NAME')),
2229 'info' => $virtualpath
2231 $manager->notify('PostParseURL', $data);
2234 * NOTE: Here is the end of initialization
2239 * This function includes or requires the specified library file
2241 * @param string $file
2242 * @param boolean $once use the _once() version
2243 * @param boolean $require use require() instead of include()
2246 function include_libs($file, $once = TRUE, $require = TRUE)
2250 // $DIR_LIBS isn't a directory
2251 if ( !is_dir($DIR_LIBS) )
2256 $lib_path = $DIR_LIBS . $file;
2258 if ( $once && $require )
2260 require_once($lib_path);
2262 else if ( $once && !$require )
2264 include_once($lib_path);
2266 else if ( $require )
2279 * This function includes or requires the specified plugin file
2281 * @param string $file
2282 * @param boolean $once use the _once() version
2283 * @param boolean $require use require() instead of include()
2286 function include_plugins($file, $once = TRUE, $require = TRUE)
2288 global $DIR_PLUGINS;
2290 // begin if: $DIR_LIBS isn't a directory
2291 if ( !is_dir($DIR_PLUGINS) )
2296 $plugin_path = $DIR_PLUGINS . $file;
2299 if ( $once && $require )
2301 require_once($plugin_path);
2303 else if ( $once && !$require )
2305 include_once($plugin_path);
2309 require($plugin_path);
2313 include($plugin_path);
2319 * include_translation()
2320 * This function decide which locale is used and include translation
2322 * @param string &$locale locale name referring to 'language tags' defined in RFC 5646
2325 function include_translation(&$locale)
2327 global $DIR_LOCALES;
2329 $translation_file = $DIR_LOCALES . $locale . '.' . i18n::get_current_charset() . '.php';
2330 if ( !file_exists($translation_file) )
2332 $locale = 'en_Latn_US';
2333 $translation_file = $DIR_LOCALES . 'en_Latn_US.ISO-8859-1.php';
2335 include($translation_file);
2339 * PHP is written by C and utilize C library, whose APIs are defined in POSIX.
2341 * setlocale() is one of APIs of C library.
2342 * but the argument value for setlocale() depends on each implements
2344 * The latest POSIX standard:
2345 * The Open Group Base Specifications Issue 7
2346 * IEEE Std 1003.1™-2008
2347 * http://pubs.opengroup.org/onlinepubs/9699919799/mindex.html
2349 * Microsoft's operating system uses their own implementation
2351 * http://msdn.microsoft.com/en-us/library/39cwe7zf%28v=vs.110%29.aspx
2352 * Country/Region Strings
2353 * http://msdn.microsoft.com/en-us/library/cdax410z%28v=vs.110%29.aspx
2355 * Linux and Unix (in this meaning, Apple's OS X derives from UNIX) uses ISO standard.
2356 * two characters language tag (ISO 639-1)
2357 * two characters region and country lag (ISO 3166-1 alpha-1)
2360 if ( PHP_OS == "WIN32" || PHP_OS == "WINNT" )
2362 /* LOCALE_IN_WINDOWS is defined in each translation files */
2363 setlocale(LC_ALL, _LOCALE_IN_WINDOWS);
2367 setlocale(LC_ALL, preg_replace('#(.+)_(.+)_(.+)#', '$1-$3', $locale));
2374 * This function returns the integer value of $_POST for the variable $name
2376 * @param string $name field to get the integer value of
2379 function intPostVar($name)
2381 return (integer) postVar($name);
2387 * This function returns the integer value of $_GET for the variable $name
2389 * @param string $name field to get the integer value of
2392 function intGetVar($name)
2394 return (integer) getVar($name);
2400 * This function returns the integer value of $_REQUEST for the variable $name. Also checks $_GET and $_POST if not found in $_REQUEST
2402 * @param string $name field to get the integer value of
2405 function intRequestVar($name)
2407 return (integer) requestVar($name);
2413 * This function returns the integer value of $_COOKIE for the variable $name
2415 * @param string $name field to get the integer value of
2418 function intCookieVar($name)
2420 return (integer) cookieVar($name);
2424 * getNucleusVersion()
2425 * This function returns the current Nucleus version (100 = 1.00, 101 = 1.01, etc...)
2430 function getNucleusVersion()
2436 * getNucleusPatchLevel()
2437 * TODO: Better description of this function.
2439 * Power users can install patches in between nucleus releases. These patches
2440 * usually add new functionality in the plugin API and allow those to
2441 * be tested without having to install CVS.
2446 function getNucleusPatchLevel()
2452 * getLatestVersion()
2453 * This function returns the latest Nucleus version available for download from nucleuscms.org or FALSE if unable to attain data
2454 * Format will be major.minor/patachlevel e.g. 3.41 or 3.41/02
2459 function getLatestVersion()
2461 // begin if: cURL is not available in this PHP installation
2462 if ( !function_exists('curl_init') )
2467 $curl = curl_init();
2470 curl_setopt ($curl, CURLOPT_URL, 'http://nucleuscms.org/version_check.php');
2471 curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
2472 curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
2474 $return = curl_exec($curl);
2483 * This function returns a Nucleus table name with the appropriate prefix
2484 * @param string $name
2487 function sql_table($name)
2489 global $MYSQL_PREFIX;
2491 // begin if: no MySQL prefix
2492 if ( empty($MYSQL_PREFIX) )
2494 return 'nucleus_' . $name;
2496 // else: use MySQL prefix
2499 return $MYSQL_PREFIX . 'nucleus_' . $name;
2506 * This function sends the Content-Type header if headers have not already been sent
2507 * It also determines if the browser can accept application/xhtml+xml and sends it only to those that can.
2509 * if content type is application/xhtml+xml, only send it to browsers
2510 * that can handle it (IE6 cannot). Otherwise, send text/html
2513 * For admin area pages, keep sending text/html (unless it's a debug version)
2514 * application/xhtml+xml still causes too much problems with the javascript implementations
2517 * ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,
2518 * application/xhtml+xml seems to be working, so we're going to use it if we can.
2520 * @param string $content_type MIME media type registered to IANA, http://www.iana.org/assignments/media-types/index.html
2521 * @param string $page_type
2522 * @param string $charset Deprecated. This has no meaning.
2526 function sendContentType($content_type, $page_type = '', $charset = '')
2528 global $manager, $CONF;
2530 if ( headers_sent() )
2535 /* NOTE: MIME Media Type */
2536 if ( ($content_type == 'application/xhtml+xml')
2537 && (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') ) )
2539 $content_type = 'text/html';
2542 /* NOTE: generate event */
2544 'pageType' => $page_type,
2545 'contentType' => &$content_type
2547 $manager->notify('PreSendContentType', $data);
2549 /* NOTE: confirm MIME Media Type */
2550 $content_type = preg_replace('#[^a-zA-Z0-9-+./]#', '', $content_type);
2552 /* NOTE: confirm character set */
2553 $charset = i18n::get_current_charset();
2554 if ( i18n::get_forced_charset() !== '' )
2556 $charset = i18n::get_forced_charset();
2559 /* NOTE: send HTTP 1.1 header */
2560 header("Content-Type: {$content_type}; charset={$charset}");
2562 /* NOTE: set handler for translating character set */
2563 if ( $charset != i18n::get_current_charset() )
2565 ob_start(array('i18n', 'convert_handler'));
2573 * This function parses a query into an array of expressions that can be passed on to the highlight method
2574 * @param string $query
2577 function parseHighlight($query)
2579 // TODO: add more intelligent splitting logic
2581 // get rid of quotes
2582 $query = preg_replace('/\'|"/', '', $query);
2589 $aHighlight = preg_split('# #', $query);
2591 for ( $i = 0; $i < count($aHighlight); $i++ )
2593 $aHighlight[$i] = trim($aHighlight[$i]);
2595 if ( i18n::strlen($aHighlight[$i]) < 3 )
2597 unset($aHighlight[$i]);
2601 if ( count($aHighlight) == 1 )
2603 return $aHighlight[0];
2618 function getConfig()
2622 $query = sprintf('SELECT * FROM %s', sql_table('config'));
2623 $res = DB::getResult($query);
2625 foreach ( $res as $row )
2627 $CONF[$row['name']] = $row['value'];
2633 * This function gets the blog ID from the blog name
2634 * @param string $name
2637 function getBlogIDFromName($name)
2639 $query = sprintf('SELECT bnumber AS result FROM %s WHERE bshortname=%s', sql_table('blog'), DB::quoteValue($name));
2640 return DB::getValue($query);
2644 * This function gets the blog name from the blog ID
2648 function getBlogNameFromID($id)
2650 $query = sprintf('SELECT bname AS result FROM %s WHERE bnumber=%d', sql_table('blog'), intval($id));
2651 return DB::getValue($query);
2655 * This function gets the blog ID from the item ID
2656 * @param int $item_id
2659 function getBlogIDFromItemID($item_id)
2661 $query = sprintf('SELECT iblog AS result FROM %s WHERE inumber=%d', sql_table('item'), intval($item_id));
2662 return DB::getValue($query);
2666 * This function gets the blog ID from the comment ID
2667 * @param int $comment_id
2670 function getBlogIDFromCommentID($comment_id)
2672 $query = sprintf('SELECT cblog AS result FROM %s WHERE cnumber=%d', sql_table('comment'), intval($comment_id));
2673 return DB::getValue($query);
2677 * This function gets the blog ID from the category ID
2678 * @param int $category_id
2681 function getBlogIDFromCatID($category_id)
2683 $query = sprintf('SELECT cblog AS result FROM %s WHERE catid=%d', sql_table('category'), intval($category_id));
2684 return DB::getValue($query);
2688 * This function gets the category ID from the category name
2692 function getCatIDFromName($name)
2694 $query = sprintf('SELECT catid AS result FROM %s WHERE cname=%s', sql_table('category'), DB::quoteValue($name));
2695 return DB::getValue($query);
2700 * functions to be used in index.php to select something
2702 function selectBlog($shortname)
2704 global $blogid, $archivelist;
2705 $blogid = getBlogIDFromName($shortname);
2707 // also force archivelist variable, if it is set
2710 $archivelist = $blogid;
2714 function selectSkin($skinname)
2717 $skinid = SKIN::getIdFromName($skinname);
2720 function selectCategory($cat)
2723 if ( is_numeric($cat) )
2725 $catid = (integer) $cat;
2729 $catid = getCatIDFromName($cat);
2733 function selectItem($id)
2736 $itemid = (integer) $id;
2739 function selectSpecialSkinType($id)
2742 $special = strtolower($id);
2747 global $archive, $archivelist, $archivenext, $archivenextexists, $archiveprev, $archiveprevexists, $archivetype;
2748 global $blog, $blogid;
2750 global $itemid, $itemidnext, $itemidprev, $itemtitlenext, $itemtitleprev;
2751 global $CONF, $DIR_LIBS, $amount, $errormessage, $imagepopup;
2752 global $manager, $maxresults, $query;
2753 global $member, $memberid, $memberinfo;
2754 global $skinid, $skinpart, $special;
2756 $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');
2757 $action = requestVar('action');
2759 if ( in_array($action, $actionNames) )
2761 include_once($DIR_LIBS . 'ACTION.php');
2763 $errorInfo = $a->doAction($action);
2767 $errormessage = $errorInfo['message'];
2771 // show error when headers already sent out
2772 if ( headers_sent() && $CONF['alertOnHeadersSent'] )
2774 // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)
2775 if ( function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') )
2777 headers_sent($hsFile, $hsLine);
2778 $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';
2786 "<p>The page headers have already been sent out{$extraInfo}. This could cause Nucleus not to work in the expected way.</p>"
2787 . "<p>Usually, this is caused by spaces or newlines at the end of the <code>config.php</code> file, "
2788 . "at the end of the translation file or at the end of a plugin file.</p>"
2789 . "<p>Please check this and try again.</p>"
2790 . "<p>If you don't want to see this error message again, without solving the problem, "
2791 . "set <code>{$CONF['alertOnHeadersSent']}</code> in <code>globalfunctions.php</code> to <code>0</code></p>"
2792 . "Page headers already sent"
2797 // make is so ?archivelist without blogname or blogid shows the archivelist
2798 // for the default weblog
2799 if ( serverVar('QUERY_STRING') == 'archivelist' )
2801 $archivelist = $CONF['DefaultBlog'];
2804 // now decide which type of skin we need
2807 // itemid given -> only show that item
2810 if ( !$manager->existsItem($itemid,intval($CONF['allowFuture']),intval($CONF['allowDrafts'])) )
2812 doError(_ERROR_NOSUCHITEM);
2816 // 1. get timestamp, blogid and catid for item
2817 $query = 'SELECT itime, iblog, icat FROM %s WHERE inumber=%d';
2818 $query = sprintf($query, sql_table('item'), intval($itemid));
2819 $row = DB::getRow($query);
2821 // if a different blog id has been set through the request or selectBlog(),
2824 if ( $blogid && (intval($blogid) != $row['iblog']) )
2826 doError(_ERROR_NOSUCHITEM);
2830 // if a category has been selected which doesn't match the item, ignore the
2832 if ( ($catid != 0) && ($catid != $row['icat']) )
2837 $blogid = $row['iblog'];
2838 $timestamp = strtotime($row['itime']);
2840 $b =& $manager->getBlog($blogid);
2842 if ( !$b->isValidCategory($catid) )
2844 $query = "SELECT inumber, ititle FROM %s WHERE itime<%s AND idraft=0 AND iblog=%d ORDER BY itime DESC LIMIT 1";
2845 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), intval($blogid));
2849 $query = "SELECT inumber, ititle FROM %s WHERE itime<%s AND idraft=0 AND iblog=%d AND icat=%d ORDER BY itime DESC LIMIT 1";
2850 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), intval($blogid), intval($catid));
2852 $row = DB::getRow($query);
2856 $itemidprev = $row['inumber'];
2857 $itemtitleprev = $row['ititle'];
2860 // get next itemid and title
2861 if ( !$b->isValidCategory($catid) )
2863 $query = "SELECT inumber, ititle FROM %s WHERE itime>%s AND itime<=%s AND idraft=0 AND iblog=%d ORDER BY itime ASC LIMIT 1";
2864 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), DB::formatDateTime($b->getCorrectTime()), intval($blogid));
2868 $query = "SELECT inumber, ititle FROM %s WHERE itime>%s AND itime<=%s AND idraft=0 AND iblog=%d AND icat=%d ORDER BY itime ASC LIMIT 1";
2869 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), DB::formatDateTime($b->getCorrectTime()), intval($blogid), intval($catid));
2871 $row = DB::getRow($query);
2875 $itemidnext = $row['inumber'];
2876 $itemtitlenext = $row['ititle'];
2884 // sql queries for the timestamp of the first and the last published item
2885 $query = sprintf('SELECT UNIX_TIMESTAMP(itime) as result FROM %s WHERE idraft=0 ORDER BY itime ASC', sql_table('item'));
2886 $first_timestamp = DB::getValue($query);
2887 $query = sprintf('SELECT UNIX_TIMESTAMP(itime) as result FROM %s WHERE idraft=0 ORDER BY itime DESC', sql_table('item'));
2888 $last_timestamp = DB::getValue($query);
2890 sscanf($archive, '%d-%d-%d', $y, $m, $d);
2894 $archivetype = _LABEL_DAY_UNIT;
2895 $t = mktime(0, 0, 0, $m, $d, $y);
2896 // one day has 24 * 60 * 60 = 86400 seconds
2897 $archiveprev = i18n::formatted_datetime('%Y-%m-%d', $t - 86400 );
2898 // check for published items
2899 if ( $t > $first_timestamp )
2901 $archiveprevexists = true;
2905 $archiveprevexists = false;
2910 $archivenext = i18n::formatted_datetime('%Y-%m-%d', $t);
2911 if ( $t < $last_timestamp )
2913 $archivenextexists = true;
2917 $archivenextexists = false;
2922 $archivetype = _LABEL_YEAR_UNIT;
2923 $t = mktime(0, 0, 0, 12, 31, $y - 1);
2924 // one day before is in the previous year
2925 $archiveprev = i18n::formatted_datetime('%Y', $t);
2926 if ( $t > $first_timestamp )
2928 $archiveprevexists = true;
2932 $archiveprevexists = false;
2935 // timestamp for the next year
2936 $t = mktime(0, 0, 0, 1, 1, $y + 1);
2937 $archivenext = i18n::formatted_datetime('%Y', $t);
2938 if ( $t < $last_timestamp )
2940 $archivenextexists = true;
2944 $archivenextexists = false;
2949 $archivetype = _LABEL_MONTH_UNIT;
2950 $t = mktime(0, 0, 0, $m, 1, $y);
2951 // one day before is in the previous month
2952 $archiveprev = i18n::formatted_datetime('%Y-%m', $t - 86400);
2953 if ( $t > $first_timestamp )
2955 $archiveprevexists = true;
2959 $archiveprevexists = false;
2962 // timestamp for the next month
2963 $t = mktime(0, 0, 0, $m+1, 1, $y);
2964 $archivenext = i18n::formatted_datetime('%Y-%m', $t);
2965 if ( $t < $last_timestamp )
2967 $archivenextexists = true;
2971 $archivenextexists = false;
2975 elseif ( $archivelist )
2977 $type = 'archivelist';
2979 if ( is_numeric($archivelist) )
2981 $blogid = intVal($archivelist);
2985 $blogid = getBlogIDFromName($archivelist);
2990 doError(_ERROR_NOSUCHBLOG);
2998 $query = stripslashes($query);
3000 if ( is_numeric($blogid) )
3002 $blogid = intVal($blogid);
3006 $blogid = getBlogIDFromName($blogid);
3011 doError(_ERROR_NOSUCHBLOG);
3015 elseif ( $memberid )
3019 if ( !Member::existsID($memberid) )
3021 doError(_ERROR_NOSUCHMEMBER);
3024 $memberinfo = $manager->getMember($memberid);
3026 elseif ( $imagepopup )
3028 // media object (images etc.)
3029 $type = 'imagepopup';
3031 // TODO: check if media-object exists
3032 // TODO: set some vars?
3036 // show regular index page
3041 // any type of skin with catid
3042 if ( $catid && !$blogid )
3044 $blogid = getBlogIDFromCatID($catid);
3047 // decide which blog should be displayed
3050 $blogid = $CONF['DefaultBlog'];
3053 $b =& $manager->getBlog($blogid);
3054 $blog = $b; // references can't be placed in global variables?
3056 if ( !$blog->isValid )
3058 doError(_ERROR_NOSUCHBLOG);
3062 // set catid if necessary
3065 // check if the category is valid
3066 if ( !$blog->isValidCategory($catid) )
3068 doError(_ERROR_NOSUCHCATEGORY);
3073 $blog->setSelectedCategory($catid);
3079 $skinid = $blog->getDefaultSkin();
3082 if ( !empty($special) && isValidShortName($special) )
3084 $type = strtolower($special);
3087 $skin =& $manager->getSkin($skinid);
3089 if ( !$skin->isValid() )
3091 doError(_ERROR_NOSUCHSKIN);
3095 // set global skinpart variable so can determine quickly what is being parsed from any plugin or phpinclude
3099 $skin->parse($type);
3101 // check to see we should throw JustPosted event
3102 $blog->checkJustPosted();
3108 * Show error skin with given message. An optional skin-object to use can be given
3110 * @param string $msg
3111 * @param string $skin
3114 function doError($msg, $skin = '')
3116 global $errormessage, $CONF, $skinid, $blogid, $manager;
3120 if ( Skin::existsID($skinid) )
3124 elseif ( $manager->existsBlogID($blogid) )
3126 $blog =& $manager->getBlog($blogid);
3127 $id = $blog->getDefaultSkin();
3129 elseif ($CONF['DefaultBlog'] )
3131 $blog =& $manager->getBlog($CONF['DefaultBlog']);
3132 $id = $blog->getDefaultSkin();
3136 // this statement should actually never be executed
3137 $id = $CONF['BaseSkin'];
3139 $skin =& $manager->getSkin($id);
3142 $errormessage = $msg;
3143 $skin->parse('error');
3148 * Errors before the database connection has been made
3150 * @param string $msg message to notify
3151 * @param string $title page title
3154 function startUpError($msg, $title)
3156 header('Content-Type: text/xml; charset=' . i18n::get_current_charset());
3157 echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
3159 echo "<title>{$title}</title></head>\n";
3161 echo "<h1>{$title}</h1>\n";
3168 function isValidShortName($name)
3170 return preg_match('#^[a-z0-9]+$#i', $name);
3172 function isValidDisplayName($name)
3174 return preg_match('#^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$#i', $name);
3176 function isValidCategoryName($name)
3180 function isValidTemplateName($name)
3182 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
3184 function isValidSkinName($name)
3186 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
3189 // add and remove linebreaks
3190 function addBreaks($var)
3194 function removeBreaks($var)
3196 return preg_replace("/<br \/>([\r\n])/", "$1", $var);
3202 * @param string $filename
3203 * @param string $includeMode
3204 * @param string $includePrefix
3207 function parseFile($filename, $includeMode = 'normal', $includePrefix = '')
3209 global $manager, $skinid;
3211 if ( !$skinid || !existsID($skinid) )
3213 $skin =& $manager->getSkin($CONF['BaseSkin']);
3217 $skin =& $manager->getSkin($skinid);
3220 $oldIncludeMode = Parser::getProperty('IncludeMode');
3221 $oldIncludePrefix = Parser::getProperty('IncludePrefix');
3223 $skin->parse('fileparse', $filename);
3225 Parser::setProperty('IncludeMode', $oldIncludeMode);
3226 Parser::setProperty('IncludePrefix', $oldIncludePrefix);
3233 * Outputs a debug message
3235 * @param string $msg
3238 function debug($msg)
3240 echo '<p><b>' . $msg . "</b></p>\n";
3244 // shows a link to help file
3250 function helpHtml($id)
3253 return helplink($id) . '<img src="' . $CONF['AdminURL'] . 'documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" title="' . _HELP_TT . '" /></a>';
3255 function helplink($id)
3258 return '<a href="' . $CONF['AdminURL'] . 'documentation/help.html#'. $id . '" onclick="if (event && event.preventDefault) event.preventDefault(); return help(this.href);">';
3263 * Includes a PHP file. This method can be called while parsing templates and skins
3265 * @param string $filename name of file to parse
3268 function includephp($filename)
3270 // make predefined variables global, so most simple scripts can be used here
3272 // apache (names taken from PHP doc)
3273 global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;
3274 global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;
3275 global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;
3276 global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;
3277 global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;
3278 global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;
3279 global $REQUEST_URI;
3281 // php (taken from PHP doc)
3282 global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;
3283 global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;
3286 global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;
3288 if ( @file_exists($filename) )
3296 * Checks if a certain plugin exists
3297 * @param string $plug name of plugin
3298 * @return boolean exists or not
3300 function checkPlugin($name)
3302 global $DIR_PLUGINS;
3303 return file_exists($DIR_PLUGINS . preg_replace('#[\\\\|/]#', '', $name) . '.php');
3309 * @param string $querystr querystring to alter (e.g. foo=1&bar=2&x=y)
3310 * @param string $param name of parameter to change (e.g. 'foo')
3311 * @param string $value New value for that parameter (e.g. 3)
3312 * @return string altered query string (for the examples above: foo=3&bar=2&x=y)
3314 function alterQueryStr($querystr, $param, $value)
3316 $vars = preg_split('#&#', $querystr);
3319 for ( $i = 0; $i < count($vars); $i++ )
3321 $v = preg_split('#=#', $vars[$i]);
3323 if ( $v[0] == $param )
3326 $vars[$i] = implode('=', $v);
3333 $vars[] = "{$param}={$value}";
3335 return ltrim(implode('&', $vars), '&');
3340 * passes one variable as hidden input field (multiple fields for arrays)
3341 * @see passRequestVars in varsx.x.x.php
3343 * @param string $key
3344 * @param string $value
3347 function passVar($key, $value)
3350 if ( is_array($value) )
3352 for ( $i = 0; $i < sizeof($value); $i++ )
3354 passVar($key . '[' . $i . ']', $value[$i]);
3359 // other values: do stripslashes if needed
3360 echo '<input type="hidden" name="' . Entity::hsc($key) . '" value="' . Entity::hsc(undoMagic($value)) . '" />' . "\n";
3367 * @param string $variables
3370 function checkVars($variables)
3372 foreach ( $variables as $variable )
3374 if ( array_key_exists($variable, $_GET)
3375 || array_key_exists($variable, $_POST)
3376 || array_key_exists($variable, $_COOKIE)
3377 || array_key_exists($variable, $_ENV)
3378 || (session_id() !== '' && array_key_exists($variable, $_SESSION))
3379 || array_key_exists($variable, $_FILES) )
3381 die('Sorry. An error occurred.');
3389 * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.
3395 function sanitizeParams()
3401 // REQUEST_URI of $_SERVER
3402 $str =& $_SERVER["REQUEST_URI"];
3403 serverStringToArray($str, $array, $frontParam);
3404 sanitizeArray($array);
3405 arrayToServerString($array, $frontParam, $str);
3407 // QUERY_STRING of $_SERVER
3408 $str =& $_SERVER["QUERY_STRING"];
3409 serverStringToArray($str, $array, $frontParam);
3410 sanitizeArray($array);
3411 arrayToServerString($array, $frontParam, $str);
3414 convArrayForSanitizing($_GET, $array);
3415 sanitizeArray($array);
3416 revertArrayForSanitizing($array, $_GET);
3418 // $_REQUEST (only GET param)
3419 convArrayForSanitizing($_REQUEST, $array);
3420 sanitizeArray($array);
3421 revertArrayForSanitizing($array, $_REQUEST);
3426 function _addInputTags(&$keys,$prefix='')
3428 foreach ( $keys as $key=>$value )
3432 $key=$prefix.'['.$key.']';
3434 if ( is_array($value) )
3436 _addInputTags($value,$key);
3440 if ( get_magic_quotes_gpc() )
3441 {$value=stripslashes($value);
3443 if ( $key == 'ticket' )
3447 echo '<input type="hidden" name="'.Entity::hsc($key).
3448 '" value="'.Entity::hsc($value).'" />'."\n";
3455 * serverStringToArray()
3456 * Convert the server string such as $_SERVER['REQUEST_URI']
3457 * to arry like arry['blogid']=1 and array['page']=2 etc.
3459 * @param string $uri string
3460 * @param string &$query_elements elements of query according to application/x-www-form-urlencoded
3461 * @param string &$hier_part hierarchical part includes path
3464 * RFC 3986: Uniform Resource Identifiers (URI): Generic Syntax
3465 * 3. Syntax Components
3466 * http://www.ietf.org/rfc/rfc3986.txt
3468 * Hypertext Markup Language - 2.0
3469 * 8.2.1. The form-urlencoded Media Type
3470 * http://tools.ietf.org/html/rfc1866#section-8.2.1
3472 * $_SERVER > Language Reference > Predefined Variables > PHP Manual
3473 * http://www.php.net/manual/en/reserved.variables.server.php
3475 function serverStringToArray($uri, &$query_elements, &$hier_part)
3478 $query_elements = array();
3481 // split hierarchical part, e.g. /index.php, query and fragment, e.g. blogid=1&page=2#section1
3482 if ( i18n::strpos($uri, "?") > 0 )
3484 list($hier_part, $query_and_fragment) = preg_split("#\?#", $uri, 2);
3488 $query_and_fragment = $uri;
3492 // If there is no query like blogid=1&page=2, return
3493 if ( i18n::strpos($uri, "=") == FALSE && !i18n::strlen($hier_part) )
3499 $query_elements = preg_split("#&#", $query_and_fragment);
3504 * arrayToServerString()
3505 * Convert array like array['blogid'] to server string
3506 * such as $_SERVER['REQUEST_URI']
3508 * @param array $query_elements elements of query according to application/x-www-form-urlencoded
3509 * @param string $hier_part hier-part defined in RFC3986
3510 * @param string &$uri return value
3514 * RFC 3986: Uniform Resource Identifiers (URI): Generic Syntax
3515 * 3. Syntax Components
3516 * http://www.ietf.org/rfc/rfc3986.txt
3518 * Hypertext Markup Language - 2.0
3519 * 8.2.1. The form-urlencoded Media Type
3520 * http://tools.ietf.org/html/rfc1866#section-8.2.1
3522 * $_SERVER > Language Reference > Predefined Variables > PHP Manual
3523 * http://www.php.net/manual/en/reserved.variables.server.php
3525 function arrayToServerString($query_elements, $hier_part, &$uri)
3527 if ( i18n::strpos($uri, "?") !== FALSE )
3529 $uri = $hier_part . "?";
3535 if ( count($query_elements) > 0 )
3537 $uri .= implode("&", $query_elements);
3544 * Sanitize array parameters.
3545 * This function checks both key and value.
3546 * - check key if it inclues " (double quote), remove from array
3547 * - check value if it includes \ (escape sequece), remove remaining string
3549 * @param array &$array elements of query according to application/x-www-form-urlencoded
3552 function sanitizeArray(&$array)
3554 $excludeListForSanitization = array('query');
3556 foreach ( $array as $k => $v )
3558 // split to key and value
3559 list($key, $val) = preg_split("#=#", $v, 2);
3565 // when magic quotes is on, need to use stripslashes,
3566 // and then addslashes
3567 if ( get_magic_quotes_gpc() )
3569 $val = stripslashes($val);
3572 // note that we must use addslashes here because this function is called before the db connection is made
3573 // and sql_real_escape_string needs a db connection
3574 $val = addslashes($val);
3576 // if $key is included in exclude list, skip this param
3577 if ( !in_array($key, $excludeListForSanitization) )
3580 if ( i18n::strpos($val, '\\') > 0 )
3582 list($val, $tmp) = preg_split('#\\\\#', $val);
3585 // remove control code etc.
3586 $val = strtr($val, "\0\r\n<>'\"", " ");
3589 if ( preg_match('#\"#', $key) > 0 )
3595 // set sanitized info
3596 $array[$k] = sprintf("%s=%s", $key, $val);
3603 * convArrayForSanitizing()
3604 * Convert array for sanitizeArray function
3606 * @param string $src array to be sanitized
3607 * @param array &$array array to be temporarily stored
3610 function convArrayForSanitizing($src, &$array)
3613 foreach ( $src as $key => $val )
3615 if ( !key_exists($key, $_GET) )
3619 $array[] = sprintf("%s=%s", $key, $val);
3626 * revertArrayForSanitizing()
3627 * Revert array after sanitizeArray function
3629 * @param array $array element of query according to application/x-www-form-urlencoded
3630 * @param array &$dst combination of key and value
3633 function revertArrayForSanitizing($array, &$dst)
3635 foreach ( $array as $v )
3637 list($key, $val) = preg_split("#=#", $v, 2);
3645 >>>>>>> skinnable-master
3648 * @param string $virtualpath
3651 function decodePathInfo($virtualpath)
3653 global $CONF, $manager, $archive, $blog, $catid, $memberid, $special;
3655 /* initialize keywords if this hasn't been done before */
3656 if ( !isset($CONF['ItemKey']) || empty($CONF['ItemKey']) )
3658 $CONF['ItemKey'] = 'item';
3661 if ( !isset($CONF['ArchiveKey']) || empty($CONF['ArchiveKey']) )
3663 $CONF['ArchiveKey'] = 'archive';
3666 if ( !isset($CONF['ArchivesKey']) || empty($CONF['ArchivesKey']) )
3668 $CONF['ArchivesKey'] = 'archives';
3671 if ( !isset($CONF['MemberKey']) || empty($CONF['MemberKey']) )
3673 $CONF['MemberKey'] = 'member';
3676 if ( !isset($CONF['BlogKey']) || empty($CONF['BlogKey']) )
3678 $CONF['BlogKey'] = 'blog';
3681 if ( !isset($CONF['CategoryKey']) || empty($CONF['CategoryKey']) )
3683 $CONF['CategoryKey'] = 'category';
3686 if ( !isset($CONF['SpecialskinKey']) || empty($CONF['SpecialskinKey']) )
3688 $CONF['SpecialskinKey'] = 'special';
3693 'type' => basename(serverVar('SCRIPT_NAME') ),
3694 'info' => $virtualpath,
3695 'complete' => &$parsed
3697 $manager->notify('ParseURL', $data);
3699 /* already parsed by the other subsystem */
3704 /* default implementation */
3705 $data = preg_split("#/#", $virtualpath);
3706 for ( $i = 0; $i < sizeof($data); $i++ )
3708 switch ( $data[$i] )
3710 /* item/1 (blogid) */
3711 case $CONF['ItemKey']:
3714 if ( $i < sizeof($data) )
3716 $itemid = (integer) $data[$i];
3720 /* archives/1 (blogid) */
3721 case $CONF['ArchivesKey']:
3723 if ( $i < sizeof($data) )
3725 $archivelist = (integer) $data[$i];
3729 /* two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid) */
3730 case $CONF['ArchiveKey']:
3731 if ( (($i + 1) < sizeof($data) ) && (i18n::strpos($data[$i + 1], '-') === FALSE ) )
3733 $blogid = (integer) $data[++$i];
3736 if ( $i < sizeof($data) )
3738 $archive = $data[$i];
3745 case $CONF['BlogKey']:
3747 if ( $i < sizeof($data) )
3749 $blogid = intval($data[$i]);
3753 /* category/1 (catid) */
3754 case $CONF['CategoryKey']:
3757 if ( $i < sizeof($data) )
3759 $catid = intval($data[$i]);
3763 case $CONF['MemberKey']:
3765 if ( $i < sizeof($data) )
3767 $memberid = intval($data[$i]);
3771 case $CONF['SpecialskinKey']:
3773 if ( $i < sizeof($data) )
3775 $special = $data[$i];
3792 * Stops processing the request and redirects to the given URL.
\r
3793 * - no actual contents should have been sent to the output yet
\r
3794 * - the URL will be stripped of illegal or dangerous characters
\r
3796 * @param string $uri
\r
3799 function redirect($url)
\r
3801 $url = preg_replace('#[^a-z0-9-~+_.?\#=&;,/:@%*]#i', '', $url);
\r
3802 header('Location: ' . $url);
\r
3807 * getBookmarklet()
\r
3808 * Returns the Javascript code for a bookmarklet that works on most modern browsers
\r
3810 * @param integer $blogid ID for weblog
\r
3811 * @return script to call Bookmarklet
\r
3813 function getBookmarklet($blogid, $width=600, $height=500)
\r
3820 . "if ( x.selection )"
\r
3822 . " Q=x.selection.createRange().text;"
\r
3824 . "else if ( y.getSelection )"
\r
3826 . " Q=y.getSelection();"
\r
3828 . "else if ( x.getSelection )"
\r
3830 . " Q=x.getSelection();"
\r
3832 . "wingm = window.open('{$CONF['AdminURL']}bookmarklet.php?blogid={$blogid}"
\r
3833 . " &logtext=' + encodeURIComponent(Q) +"
\r
3834 . " '&loglink=' + encodeURIComponent(x.location.href) +"
\r
3835 . " '&loglinktitle=' + encodeURIComponent(x.title),"
\r
3837 . " 'scrollbars=yes,width={$width},height={$height},left=10,top=10,status=yes,resizable=yes');"
\r
3838 . "wingm.focus();";
\r
3845 * cleans filename of uploaded file for writing to file system
\r
3847 * @param string $str
\r
3848 * @return string $cleaned filename ready for use
\r
3850 function cleanFileName($str)
\r
3852 $str = strtolower($str);
\r
3853 $ext_point = i18n::strrpos($str,".");
\r
3854 if ( $ext_point === FALSE )
\r
3858 $ext = i18n::substr($str,$ext_point,i18n::strlen($str));
\r
3859 $str = i18n::substr($str,0,$ext_point);
\r
3861 return preg_replace("#[^a-z0-9-]#", "_", $str) . $ext;
\r
3865 * use Notification class instead of this
\r
3866 * Deprecated since 4.0:
\r
3868 function getMailFooter()
\r
3870 NOTIFICATION::get_mail_footer();
\r
3872 function isValidMailAddress($address)
\r
3874 return NOTIFICATION::address_validation($address);
\r
3877 * use Entity class instead of this
\r
3878 * Deprecated since 4.0:
\r
3880 function highlight($text, $expression, $highlight)
\r
3882 return Entity::highlight($text, $expression, $highlight);
\r
3884 function shorten($string, $maxlength, $suffix)
\r
3886 return Entity::shorten($string, $maxlength, $suffix);
\r
3888 function stringStripTags ($string)
\r
3890 return Entity::strip_tags($string);
\r
3892 function toAscii($string)
\r
3894 return Entity::anchor_footnoting($string);
\r
3896 function stringToAttribute ($string)
\r
3898 return Entity::hsc($string);
\r
3900 function stringToXML ($string)
\r
3902 return Entity::hen($string);
\r
3904 function encode_desc($data)
\r
3906 return Entity::hen($data);
\r
3909 * Centralisation of the functions that deals with locales
\r
3910 * This functions is based on the old way to deal with languages
\r
3911 * Deprecated since 4.0:
\r
3913 function getLanguageName()
\r
3915 if( ($language = i18n::convert_locale_to_old_language_file_name(i18n::get_current_locale())) === FALSE )
\r
3917 $language ='english';
\r
3921 function selectLanguage($language)
\r
3924 include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');
\r
3928 * use i18n class instead of these
\r
3929 * Deprecated since 4.0
\r
3931 function checkLanguage($lang)
\r
3933 return ( preg_match('#^(.+)_(.+)_(.+)$#', $lang)
\r
3934 || i18n::convert_old_language_file_name_to_locale($lang) );
\r
3936 function formatDate($format, $timestamp, $default_format, &$blog)
\r
3938 $offset = date('Z', $timestamp);
\r
3941 $offset += $blog->getTimeOffset() * 3600;
\r
3943 return i18n::formatted_datetime($format, $timestamp, $offset, $default_format);
\r
3947 * use DB class instead of these
\r
3948 * Deprecated since 4.0
\r
3950 function quickQuery($query)
\r
3952 $row = DB::getRow($query);
\r
3953 return $row['result'];
\r
3955 function mysqldate($timestamp)
\r
3957 return DB::formatDateTime($timestamp);
\r
3960 * Centralisation of the functions that generate links
\r
3961 * Deprecated since 4.0:
\r
3962 * Please use Link::FunctionName(...) instead
\r
3964 function createItemLink($itemid, $extra = '')
\r
3966 return Link::create_item_link($itemid, $extra);
\r
3968 function createMemberLink($memberid, $extra = '')
\r
3970 return Link::create_member_link($memberid, $extra);
\r
3972 function createCategoryLink($catid, $extra = '')
\r
3974 return Link::create_category_link($catid, $extra);
\r
3976 function createArchiveListLink($blogid = '', $extra = '')
\r
3978 return Link::create_archivelist_link($blogid, $extra);
\r
3980 function createArchiveLink($blogid, $archive, $extra = '')
\r
3982 return Link::create_archive_link($blogid, $archive, $extra);
\r
3984 function createBlogidLink($blogid, $params = '')
\r
3986 return Link::create_blogid_link($blogid, $params = '');
\r
3988 function createLink($type, $params)
\r
3990 return Link::create_link($type, $params);
\r
3992 function createBlogLink($url, $params)
\r
3994 return Link::create_blog_link($url, $params);
\r
3997 * use ActionLog class instead of this
\r
3998 * Deprecated since 4.0
\r
4000 function addToLog($level, $msg)
\r
4002 ActionLog::add($level, $msg);
\r
4005 * use PHP's implement
\r
4006 * Deprecated since 4.0
\r
4008 function ifset(&$var)
\r
4010 if ( isset($var) )
\r
4018 * use Manager::getPluginNameFromPid() instead of this
\r
4019 * Deprecated since 4.0
\r
4021 function getPluginNameFromPid($pid)
\r
4024 return $manager->getPluginNameFromPid($pid);
\r
4027 * use Manager::numberOfEventSubscribers() instead of this
\r
4028 * Deprecated since 4.0
\r
4030 function numberOfEventSubscribers($event)
\r
4033 return $manager->getNumberOfSubscribers($event);
\r
4037 * PluginAdmin has already the alternative implement
\r
4038 * Deprecated since 4.0
\r
4040 function ticketForPlugin()
\r
4042 global $CONF, $DIR_LIBS, $DIR_LOCALES, $DIR_PLUGINS, $manager, $member, $ticketforplugin;
\r
4045 $ticketforplugin = array();
\r
4046 $ticketforplugin['ticket'] = FALSE;
\r
4048 /* Check if using plugin's php file. */
\r
4049 $p_translated = serverVar('SCRIPT_FILENAME');
\r
4051 if (!file_exists($p_translated) )
\r
4053 header("HTTP/1.0 404 Not Found");
\r
4057 // check whether this is plugin or not
\r
4058 $p_translated = str_replace('\\', '/', $p_translated);
\r
4059 $d_plugins = str_replace('\\', '/', $DIR_PLUGINS);
\r
4060 if ( i18n::strpos($p_translated, $d_plugins) !== 0 )
\r
4065 // Solve the plugin php file or admin directory
\r
4066 $phppath = i18n::substr($p_translated, i18n::strlen($d_plugins) );
\r
4067 // Remove the first "/" if exists.
\r
4068 $phppath = preg_replace('#^/#', '', $phppath);
\r
4069 // Remove the first "NP_" and the last ".php" if exists.
\r
4070 $path = preg_replace('#^NP_(.*)\.php$#', '$1', $phppath);
\r
4071 // Remove the "/" and beyond.
\r
4072 $path = preg_replace('#^([^/]*)/(.*)$#', '$1', $path);
\r
4074 // Solve the plugin name.
\r
4075 $plugins = array();
\r
4076 $query = sprintf('SELECT pfile FROM %s;', sql_table('plugin'));
\r
4077 $res = DB::getResult($query);
\r
4079 foreach ( $res as $row )
\r
4081 $name = i18n::substr($row['pfile'], 3);
\r
4082 $plugins[strtolower($name)] = $name;
\r
4085 $res->closeCursor();
\r
4087 if ( !array_key_exists($path, $plugins) )
\r
4089 header("HTTP/1.0 404 Not Found");
\r
4094 $plugin_name = $plugins[$path];
\r
4097 /* Return if not index.php */
\r
4098 if ( ($phppath != strtolower($plugin_name) . '/')
\r
4099 && ($phppath != strtolower($plugin_name) . '/index.php') )
\r
4104 /* Exit if not logged in. */
\r
4105 if ( !$member->isLoggedIn() )
\r
4107 exit('You aren\'t logged in.');
\r
4110 /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */
\r
4111 if ( $file = @file($p_translated) )
\r
4115 foreach($file as $line)
\r
4117 if (preg_match('#[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]#i', $prevline . $line) )
\r
4122 $prevline = $line;
\r
4126 /* Show a form if not valid ticket */
\r
4127 if ( (i18n::strpos(serverVar('REQUEST_URI'), '?') !== FALSE
\r
4128 || serverVar('QUERY_STRING')
\r
4129 || strtoupper(serverVar('REQUEST_METHOD') ) == 'POST')
\r
4130 && !$manager->checkTicket() )
\r
4132 $oPluginAdmin = new PluginAdmin($plugin_name);
\r
4133 $oPluginAdmin->start();
\r
4135 echo '<p>' . _ERROR_BADTICKET . "</p>\n";
\r
4137 // Resolve URI and QUERY_STRING
\r
4138 if ($uri = serverVar('REQUEST_URI') )
\r
4140 list($uri, $qstring) = preg_split('#\?#', $uri);
\r
4144 if ( !($uri = serverVar('PHP_SELF') ) )
\r
4146 $uri = serverVar('SCRIPT_NAME');
\r
4148 $qstring = serverVar('QUERY_STRING');
\r
4152 $qstring = '?' . $qstring;
\r
4155 echo '<p>' . _SETTINGS_UPDATE . ' : ' . _QMENU_PLUGINS . ' <span style="color:red;">' . Entity::hsc($plugin_name) . "</span> ?</p>\n";
\r
4157 switch(strtoupper(serverVar('REQUEST_METHOD') ) )
\r
4160 echo '<form method="POST" action="'.Entity::hsc($uri.$qstring).'">';
\r
4161 $manager->addTicketHidden();
\r
4162 _addInputTags($_POST);
\r
4166 echo '<form method="GET" action="'.Entity::hsc($uri).'">';
\r
4167 $manager->addTicketHidden();
\r
4168 _addInputTags($_GET);
\r
4174 echo '<input type="submit" value="' . _YES . '" /> ';
\r
4175 echo '<input type="button" value="' . _NO . '" onclick="history.back(); return false;" />';
\r
4178 $oPluginAdmin->end();
\r
4182 /* Create new ticket */
\r
4183 $ticket=$manager->addTicketToUrl('');
\r
4184 $ticketforplugin['ticket'] = preg_split($ticket, i18n::strpos($ticket, 'ticket=') + 7);
\r
4189 * Stops processing the request and redirects to the given URL.
4190 * - no actual contents should have been sent to the output yet
4191 * - the URL will be stripped of illegal or dangerous characters
4193 * @param string $uri
4196 function redirect($url)
4198 $url = preg_replace('#[^a-z0-9-~+_.?\#=&;,/:@%*]#i', '', $url);
4199 header('Location: ' . $url);
4205 * Returns the Javascript code for a bookmarklet that works on most modern browsers
4207 * @param integer $blogid ID for weblog
4208 * @return script to call Bookmarklet
4210 function getBookmarklet($blogid, $width=600, $height=500)
4217 . "if ( x.selection )"
4219 . " Q=x.selection.createRange().text;"
4221 . "else if ( y.getSelection )"
4223 . " Q=y.getSelection();"
4225 . "else if ( x.getSelection )"
4227 . " Q=x.getSelection();"
4229 . "wingm = window.open('{$CONF['AdminURL']}bookmarklet.php?blogid={$blogid}"
4230 . " &logtext=' + encodeURIComponent(Q) +"
4231 . " '&loglink=' + encodeURIComponent(x.location.href) +"
4232 . " '&loglinktitle=' + encodeURIComponent(x.title),"
4234 . " 'scrollbars=yes,width={$width},height={$height},left=10,top=10,status=yes,resizable=yes');"
4242 * cleans filename of uploaded file for writing to file system
4244 * @param string $str
4245 * @return string $cleaned filename ready for use
4247 function cleanFileName($str)
4249 $str = strtolower($str);
4250 $ext_point = i18n::strrpos($str,".");
4251 if ( $ext_point === FALSE )
4255 $ext = i18n::substr($str,$ext_point,i18n::strlen($str));
4256 $str = i18n::substr($str,0,$ext_point);
4258 return preg_replace("#[^a-z0-9-]#", "_", $str) . $ext;
4262 * use Notification class instead of this
4263 * Deprecated since 4.0:
4265 function getMailFooter()
4267 NOTIFICATION::get_mail_footer();
4269 function isValidMailAddress($address)
4271 return NOTIFICATION::address_validation($address);
4274 * use Entity class instead of this
4275 * Deprecated since 4.0:
4277 function highlight($text, $expression, $highlight)
4279 return Entity::highlight($text, $expression, $highlight);
4281 function shorten($string, $maxlength, $suffix)
4283 return Entity::shorten($string, $maxlength, $suffix);
4285 function stringStripTags ($string)
4287 return Entity::strip_tags($string);
4289 function toAscii($string)
4291 return Entity::anchor_footnoting($string);
4293 function stringToAttribute ($string)
4295 return Entity::hsc($string);
4297 function stringToXML ($string)
4299 return Entity::hen($string);
4301 function encode_desc($data)
4303 return Entity::hen($data);
4306 * Centralisation of the functions that deals with locales
4307 * This functions is based on the old way to deal with languages
4308 * Deprecated since 4.0:
4310 function getLanguageName()
4312 if( ($language = i18n::convert_locale_to_old_language_file_name(i18n::get_current_locale())) === FALSE )
4314 $language ='english';
4318 function selectLanguage($language)
4321 include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');
4325 * use i18n class instead of these
4326 * Deprecated since 4.0
4328 function checkLanguage($lang)
4330 return ( preg_match('#^(.+)_(.+)_(.+)$#', $lang)
4331 || i18n::convert_old_language_file_name_to_locale($lang) );
4333 function formatDate($format, $timestamp, $default_format, &$blog)
4335 $offset = date('Z', $timestamp);
4338 $offset += $blog->getTimeOffset() * 3600;
4340 return i18n::formatted_datetime($format, $timestamp, $offset, $default_format);
4344 * use DB class instead of these
4345 * Deprecated since 4.0
4347 function quickQuery($query)
4349 $row = DB::getRow($query);
4350 return $row['result'];
4352 function mysqldate($timestamp)
4354 return DB::formatDateTime($timestamp);
4357 * Centralisation of the functions that generate links
4358 * Deprecated since 4.0:
4359 * Please use Link::FunctionName(...) instead
4361 function createItemLink($itemid, $extra = '')
4363 return Link::create_item_link($itemid, $extra);
4365 function createMemberLink($memberid, $extra = '')
4367 return Link::create_member_link($memberid, $extra);
4369 function createCategoryLink($catid, $extra = '')
4371 return Link::create_category_link($catid, $extra);
4373 function createArchiveListLink($blogid = '', $extra = '')
4375 return Link::create_archivelist_link($blogid, $extra);
4377 function createArchiveLink($blogid, $archive, $extra = '')
4379 return Link::create_archive_link($blogid, $archive, $extra);
4381 function createBlogidLink($blogid, $params = '')
4383 return Link::create_blogid_link($blogid, $params = '');
4385 function createLink($type, $params)
4387 return Link::create_link($type, $params);
4389 function createBlogLink($url, $params)
4391 return Link::create_blog_link($url, $params);
4394 * use ActionLog class instead of this
4395 * Deprecated since 4.0
4397 function addToLog($level, $msg)
4399 ActionLog::add($level, $msg);
4402 * use PHP's implement
4403 * Deprecated since 4.0
4405 function ifset(&$var)
4415 * use Manager::getPluginNameFromPid() instead of this
4416 * Deprecated since 4.0
4418 function getPluginNameFromPid($pid)
4421 return $manager->getPluginNameFromPid($pid);
4424 * use Manager::numberOfEventSubscribers() instead of this
4425 * Deprecated since 4.0
4427 function numberOfEventSubscribers($event)
4430 return $manager->getNumberOfSubscribers($event);
4434 * PluginAdmin has already the alternative implement
4435 * Deprecated since 4.0
4437 function ticketForPlugin()
4439 global $CONF, $DIR_LIBS, $DIR_LOCALES, $DIR_PLUGINS, $manager, $member, $ticketforplugin;
4442 $ticketforplugin = array();
4443 $ticketforplugin['ticket'] = FALSE;
4445 /* Check if using plugin's php file. */
4446 $p_translated = serverVar('SCRIPT_FILENAME');
4448 if (!file_exists($p_translated) )
4450 header("HTTP/1.0 404 Not Found");
4454 // check whether this is plugin or not
4455 $p_translated = str_replace('\\', '/', $p_translated);
4456 $d_plugins = str_replace('\\', '/', $DIR_PLUGINS);
4457 if ( i18n::strpos($p_translated, $d_plugins) !== 0 )
4462 // Solve the plugin php file or admin directory
4463 $phppath = i18n::substr($p_translated, i18n::strlen($d_plugins) );
4464 // Remove the first "/" if exists.
4465 $phppath = preg_replace('#^/#', '', $phppath);
4466 // Remove the first "NP_" and the last ".php" if exists.
4467 $path = preg_replace('#^NP_(.*)\.php$#', '$1', $phppath);
4468 // Remove the "/" and beyond.
4469 $path = preg_replace('#^([^/]*)/(.*)$#', '$1', $path);
4471 // Solve the plugin name.
4473 $query = sprintf('SELECT pfile FROM %s;', sql_table('plugin'));
4474 $res = DB::getResult($query);
4476 foreach ( $res as $row )
4478 $name = i18n::substr($row['pfile'], 3);
4479 $plugins[strtolower($name)] = $name;
4482 $res->closeCursor();
4484 if ( !array_key_exists($path, $plugins) )
4486 header("HTTP/1.0 404 Not Found");
4491 $plugin_name = $plugins[$path];
4494 /* Return if not index.php */
4495 if ( ($phppath != strtolower($plugin_name) . '/')
4496 && ($phppath != strtolower($plugin_name) . '/index.php') )
4501 /* Exit if not logged in. */
4502 if ( !$member->isLoggedIn() )
4504 exit('You aren\'t logged in.');
4507 /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */
4508 if ( $file = @file($p_translated) )
4512 foreach($file as $line)
4514 if (preg_match('#[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]#i', $prevline . $line) )
4523 /* Show a form if not valid ticket */
4524 if ( (i18n::strpos(serverVar('REQUEST_URI'), '?') !== FALSE
4525 || serverVar('QUERY_STRING')
4526 || strtoupper(serverVar('REQUEST_METHOD') ) == 'POST')
4527 && !$manager->checkTicket() )
4529 $oPluginAdmin = new PluginAdmin($plugin_name);
4530 $oPluginAdmin->start();
4532 echo '<p>' . _ERROR_BADTICKET . "</p>\n";
4534 // Resolve URI and QUERY_STRING
4535 if ($uri = serverVar('REQUEST_URI') )
4537 list($uri, $qstring) = preg_split('#\?#', $uri);
4541 if ( !($uri = serverVar('PHP_SELF') ) )
4543 $uri = serverVar('SCRIPT_NAME');
4545 $qstring = serverVar('QUERY_STRING');
4549 $qstring = '?' . $qstring;
4552 echo '<p>' . _SETTINGS_UPDATE . ' : ' . _QMENU_PLUGINS . ' <span style="color:red;">' . Entity::hsc($plugin_name) . "</span> ?</p>\n";
4554 switch(strtoupper(serverVar('REQUEST_METHOD') ) )
4557 echo '<form method="POST" action="'.Entity::hsc($uri.$qstring).'">';
4558 $manager->addTicketHidden();
4559 _addInputTags($_POST);
4563 echo '<form method="GET" action="'.Entity::hsc($uri).'">';
4564 $manager->addTicketHidden();
4565 _addInputTags($_GET);
4571 echo '<input type="submit" value="' . _YES . '" /> ';
4572 echo '<input type="button" value="' . _NO . '" onclick="history.back(); return false;" />';
4575 $oPluginAdmin->end();
4579 /* Create new ticket */
4580 $ticket=$manager->addTicketToUrl('');
4581 $ticketforplugin['ticket'] = preg_split($ticket, i18n::strpos($ticket, 'ticket=') + 7);
4584 >>>>>>> skinnable-master