4 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
\r
5 * Copyright (C) 2002-2009 The Nucleus Group
\r
7 * This program is free software; you can redistribute it and/or
\r
8 * modify it under the terms of the GNU General Public License
\r
9 * as published by the Free Software Foundation; either version 2
\r
10 * of the License, or (at your option) any later version.
\r
11 * (see nucleus/documentation/index.html#license for more info)
\r
14 * @license http://nucleuscms.org/license.txt GNU General Public License
\r
15 * @copyright Copyright (C) 2002-2009 The Nucleus Group
\r
16 * @version $Id: globalfunctions.php 1834 2012-05-09 15:10:58Z sakamocchi $
\r
19 /* needed if we include globalfunctions from install.php */
\r
20 global $nucleus, $CONF, $DIR_LIBS, $DIR_LOCALES, $manager, $member;
\r
22 $nucleus['version'] = 'v4.00 SVN';
\r
23 $nucleus['codename'] = '';
\r
26 * make sure there's no unnecessary escaping:
\r
27 * set_magic_quotes_runtime(0);
\r
29 if ( version_compare(PHP_VERSION, '5.3.0', '<') )
\r
31 ini_set('magic_quotes_runtime', '0');
\r
34 /* check and die if someone is trying to override internal globals (when register_globals turn on) */
\r
35 checkVars(array('nucleus', 'CONF', 'DIR_LIBS', 'MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE', 'DIR_LOCALES', 'DIR_PLUGINS', 'HTTP_GET_VARS', 'HTTP_POST_VARS', 'HTTP_COOKIE_VARS', 'HTTP_ENV_VARS', 'HTTP_SESSION_VARS', 'HTTP_POST_FILES', 'HTTP_SERVER_VARS', 'GLOBALS', 'argv', 'argc', '_GET', '_POST', '_COOKIE', '_ENV', '_SESSION', '_SERVER', '_FILES'));
\r
37 if ( !isset($CONF) )
\r
43 if ( array_key_exists('debug', $CONF) && $CONF['debug'] )
\r
45 /* report all errors! */
\r
46 error_reporting(E_ALL);
\r
50 ini_set('display_errors','0');
\r
51 error_reporting(E_ERROR | E_WARNING | E_PARSE);
\r
55 * alertOnHeadersSent
\r
56 * Displays an error when visiting a public Nucleus page and headers have
\r
57 * been sent out to early. This usually indicates an error in either a
\r
58 * configuration file or a translation file, and could cause Nucleus to
\r
61 if ( !array_key_exists('alertOnHeadersSent', $CONF) )
\r
63 $CONF['alertOnHeadersSent'] = 1;
\r
67 * alertOnSecurityRisk
\r
68 * Displays an error only when visiting the admin area, and when one or
\r
69 * more of the installation files (install.php, install.sql, upgrades/
\r
70 * directory) are still on the server.
\r
72 if ( !array_key_exists('alertOnSecurityRisk', $CONF) )
\r
74 $CONF['alertOnSecurityRisk'] = 1;
\r
78 * Set these to 1 to allow viewing of future items or draft items
\r
79 * Should really never do this, but can be useful for some plugins that might need to
\r
80 * Could cause some other issues if you use future posts otr drafts
\r
83 $CONF['allowDrafts'] = 0;
\r
84 $CONF['allowFuture'] = 0;
\r
86 if ( getNucleusPatchLevel() > 0 )
\r
88 $nucleus['version'] .= '/' . getNucleusPatchLevel();
\r
92 if ( !array_key_exists('installscript', $CONF) || empty($CONF['installscript']) )
\r
94 $CONF['installscript'] = 0;
\r
96 if ( !array_key_exists('UsingAdminArea', $CONF) )
\r
98 $CONF['UsingAdminArea'] = 0;
\r
101 if ( !headers_sent() )
\r
103 header('Generator: Nucleus CMS ' . $nucleus['version']);
\r
107 /* TODO: This is for compatibility since 4.0, should be obsoleted at future release. */
\r
108 if ( !isset($DIR_LOCALES) )
\r
110 $DIR_LOCALES = $DIR_NUCLEUS . 'locales/';
\r
113 if ( !isset($DIR_LANG) )
\r
115 $DIR_LANG = $DIR_LOCALES;
\r
118 /* load and initialize i18n class */
\r
119 if (!class_exists('i18n', FALSE))
\r
121 include($DIR_LIBS . 'i18n.php');
\r
123 if ( !i18n::init('UTF-8', $DIR_LOCALES) )
\r
125 exit('Fail to initialize i18n class.');
\r
128 /* TODO: This is just for compatibility since 4.0, should be obsoleted at future release. */
\r
129 define('_CHARSET', i18n::get_current_charset());
\r
133 * NOTE: Since 4.0 release, Entity class becomes to be important class
\r
134 * with some wrapper functions for htmlspechalchars/htmlentity PHP's built-in function
\r
136 include($DIR_LIBS . 'ENTITY.php');
\r
138 /* we will use postVar, getVar, ... methods instead of $_GET, $_POST ... */
\r
139 if ( $CONF['installscript'] != 1 )
\r
141 /* vars were already included in install.php */
\r
142 include_once($DIR_LIBS . 'vars4.1.0.php');
\r
144 /* added for 4.0 DB::* wrapper and compatibility sql_* */
\r
145 include_once($DIR_LIBS . 'sql/sql.php');
\r
148 /* include core classes that are needed for login & plugin handling */
\r
149 include($DIR_LIBS . 'MEMBER.php');
\r
150 include($DIR_LIBS . 'ACTIONLOG.php');
\r
151 include($DIR_LIBS . 'MANAGER.php');
\r
152 include($DIR_LIBS . 'PLUGIN.php');
\r
154 $manager =& MANAGER::instance();
\r
156 /* only needed when updating logs */
\r
157 if ( $CONF['UsingAdminArea'] )
\r
159 /* XML-RPC client classes */
\r
160 include($DIR_LIBS . 'xmlrpc.inc.php');
\r
161 include($DIR_LIBS . 'ADMIN.php');
\r
165 /* connect to database */
\r
166 global $MYSQL_HANDLER;
\r
167 if ( !isset($MYSQL_HANDLER) )
\r
169 $MYSQL_HANDLER = array('mysql','');
\r
171 if ( $MYSQL_HANDLER[0] == '' )
\r
173 $MYSQL_HANDLER[0] = 'mysql';
\r
175 DB::setConnectionInfo($MYSQL_HANDLER[1], $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE);
\r
178 /* force locale or charset */
\r
180 $charset = i18n::get_current_charset();
\r
183 'locale' => &$locale,
\r
184 'charset' => &$charset
\r
186 $manager->notify('ForceLocale', $data);
\r
188 if ( $data['locale'] !== '' )
\r
190 i18n::set_forced_locale($data['locale']);
\r
192 if ( $data['charset'] !== '' )
\r
194 i18n::set_forced_charset($data['charset']);
\r
200 /* convert forced charset to current charset */
\r
201 if ( i18n::get_forced_charset() != i18n::get_current_charset() )
\r
203 $_POST = i18n::convert_array($_POST, i18n::get_forced_charset());
\r
204 $_GET = i18n::convert_array($_GET, i18n::get_forced_charset());
\r
205 $_REQUEST = i18n::convert_array($_REQUEST, i18n::get_forced_charset());
\r
206 $_COOKIE = i18n::convert_array($_COOKIE, i18n::get_forced_charset());
\r
207 $_FILES = i18n::convert_array($_FILES, i18n::get_forced_charset());
\r
209 if ( session_id() !== '' )
\r
211 $_SESSION = i18n::convert_array($_SESSION, i18n::get_forced_charset());
\r
216 /* sanitize option */
\r
217 $bLoggingSanitizedResult = 0;
\r
218 $bSanitizeAndContinue = 0;
\r
219 $orgRequestURI = serverVar('REQUEST_URI');
\r
222 /* logs sanitized result if need */
\r
223 if ( $orgRequestURI !== serverVar('REQUEST_URI') )
\r
225 $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";
\r
226 $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');
\r
227 if ( $bLoggingSanitizedResult )
\r
229 addToLog(WARNING, $msg);
\r
231 if ( !$bSanitizeAndContinue )
\r
237 /* get all variables that can come from the request and put them in the global scope */
\r
238 $blogid = requestVar('blogid');
\r
239 $itemid = intRequestVar('itemid');
\r
240 $catid = intRequestVar('catid');
\r
241 $skinid = requestVar('skinid');
\r
242 $memberid = requestVar('memberid');
\r
243 $archivelist = requestVar('archivelist');
\r
244 $imagepopup = requestVar('imagepopup');
\r
245 $archive = requestVar('archive');
\r
246 $query = requestVar('query');
\r
247 $highlight = requestVar('highlight');
\r
248 $amount = requestVar('amount');
\r
249 $action = requestVar('action');
\r
250 $nextaction = requestVar('nextaction');
\r
251 $maxresults = requestVar('maxresults');
\r
252 $startpos = intRequestVar('startpos');
\r
253 $errormessage = '';
\r
255 $special = requestVar('special');
\r
256 $virtualpath = ((getVar('virtualpath') != NULL) ? getVar('virtualpath') : serverVar('PATH_INFO'));
\r
263 /* Properly set $CONF['Self'] and others if it's not set...
\r
264 * usually when we are access from admin menu
\r
266 if ( !array_key_exists('Self', $CONF) )
\r
268 $CONF['Self'] = $CONF['IndexURL'];
\r
269 /* strip trailing */
\r
270 if ( $CONF['Self'][i18n::strlen($CONF['Self']) -1] == "/" )
\r
272 $CONF['Self'] = i18n::substr($CONF['Self'], 0, i18n::strlen($CONF['Self']) -1);
\r
276 $CONF['ItemURL'] = $CONF['Self'];
\r
277 $CONF['ArchiveURL'] = $CONF['Self'];
\r
278 $CONF['ArchiveListURL'] = $CONF['Self'];
\r
279 $CONF['MemberURL'] = $CONF['Self'];
\r
280 $CONF['SearchURL'] = $CONF['Self'];
\r
281 $CONF['BlogURL'] = $CONF['Self'];
\r
282 $CONF['CategoryURL'] = $CONF['Self'];
\r
285 *switch URLMode back to normal when $CONF['Self'] ends in .php
\r
286 * this avoids urls like index.php/item/13/index.php/item/15
\r
288 if ( !array_key_exists('URLMode', $CONF)
\r
289 || (($CONF['URLMode'] == 'pathinfo')
\r
290 && (i18n::substr($CONF['Self'], i18n::strlen($CONF['Self']) - 4) == '.php')) )
\r
292 $CONF['URLMode'] = 'normal';
\r
295 /* automatically use simpler toolbar for mozilla */
\r
296 if ( ($CONF['DisableJsTools'] == 0)
\r
297 && i18n::strpos(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0') !== FALSE
\r
298 && i18n::strpos(serverVar('HTTP_USER_AGENT'), 'Gecko') !== FALSE )
\r
300 $CONF['DisableJsTools'] = 2;
\r
303 $member = new Member();
\r
305 if ( $action == 'login' )
\r
307 $login = postVar('login');
\r
308 $password = postVar('password');
\r
309 $shared = intPostVar('shared');
\r
310 $member->login($login, $password, $shared);
\r
312 elseif ( ($action == 'logout') )
\r
318 $member->cookielogin();
\r
322 /* TODO: This is for backward compatibility, should be obsoleted near future. */
\r
323 if ( !preg_match('#^(.+)_(.+)_(.+)$#', $CONF['Locale'])
\r
324 && ($CONF['Locale'] = i18n::convert_old_language_file_name_to_locale($CONF['Locale'])) === FALSE )
\r
326 $CONF['Locale'] = 'en_Latn_US';
\r
328 if ( !array_key_exists('Language', $CONF) )
\r
330 $CONF['Language'] = i18n::convert_locale_to_old_language_file_name($CONF['Locale']);
\r
332 $locale = $CONF['Locale'];
\r
335 /* NOTE: include translation file and set locale */
\r
336 if ( $member->isLoggedIn() )
\r
338 if ( $member->getLocale() )
\r
340 $locale = $member->getLocale();
\r
345 if ( i18n::get_forced_locale() !== '' )
\r
347 $locale = i18n::get_forced_locale();
\r
350 include_translation($locale);
\r
351 i18n::set_current_locale($locale);
\r
354 /* login completed */
\r
355 $manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );
\r
358 if ( $member->isLoggedIn() && $nextaction )
\r
360 $action = $nextaction;
\r
363 /* first, let's see if the site is disabled or not. always allow admin area access. */
\r
364 if ( $CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea'] )
\r
366 redirect($CONF['DisableSiteURL']);
\r
370 /* load other classes */
\r
371 include($DIR_LIBS . 'PARSER.php');
\r
372 include($DIR_LIBS . 'SKIN.php');
\r
373 include($DIR_LIBS . 'TEMPLATE.php');
\r
374 include($DIR_LIBS . 'BLOG.php');
\r
375 include($DIR_LIBS . 'BODYACTIONS.php');
\r
376 include($DIR_LIBS . 'COMMENTS.php');
\r
377 include($DIR_LIBS . 'COMMENT.php');
\r
378 include($DIR_LIBS . 'NOTIFICATION.php');
\r
379 include($DIR_LIBS . 'BAN.php');
\r
380 include($DIR_LIBS . 'SEARCH.php');
\r
381 include($DIR_LIBS . 'LINK.php');
\r
383 /* set lastVisit cookie (if allowed) */
\r
384 if ( !headers_sent() )
\r
386 if ( $CONF['LastVisit'] )
\r
388 setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
\r
392 setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
\r
396 if ( !defined('_ARCHIVETYPE_MONTH') )
\r
398 define('_ARCHIVETYPE_DAY', 'day');
\r
399 define('_ARCHIVETYPE_MONTH', 'month');
\r
400 define('_ARCHIVETYPE_YEAR', 'year');
\r
403 /* decode path_info */
\r
404 if ( $CONF['URLMode'] == 'pathinfo' )
\r
406 /* initialize keywords if this hasn't been done before */
\r
407 if ( !isset($CONF['ItemKey']) || $CONF['ItemKey'] == '' )
\r
409 $CONF['ItemKey'] = 'item';
\r
412 if ( !isset($CONF['ArchiveKey']) || $CONF['ArchiveKey'] == '' )
\r
414 $CONF['ArchiveKey'] = 'archive';
\r
417 if ( !isset($CONF['ArchivesKey']) || $CONF['ArchivesKey'] == '' )
\r
419 $CONF['ArchivesKey'] = 'archives';
\r
422 if ( !isset($CONF['MemberKey']) || $CONF['MemberKey'] == '' )
\r
424 $CONF['MemberKey'] = 'member';
\r
427 if ( !isset($CONF['BlogKey']) || $CONF['BlogKey'] == '' )
\r
429 $CONF['BlogKey'] = 'blog';
\r
432 if ( !isset($CONF['CategoryKey']) || $CONF['CategoryKey'] == '' )
\r
434 $CONF['CategoryKey'] = 'category';
\r
437 if ( !isset($CONF['SpecialskinKey']) || $CONF['SpecialskinKey'] == '' )
\r
439 $CONF['SpecialskinKey'] = 'special';
\r
446 /* e.g. item, blog, ... */
\r
447 'type' => basename(serverVar('SCRIPT_NAME') ),
\r
448 'info' => $virtualpath,
\r
449 'complete' => &$parsed
\r
455 /* default implementation */
\r
456 $data = preg_split("#/#", $virtualpath );
\r
457 for ( $i = 0; $i < sizeof($data); $i++ )
\r
459 switch ( $data[$i] )
\r
461 /* item/1 (blogid) */
\r
462 case $CONF['ItemKey']:
\r
465 if ( $i < sizeof($data) )
\r
467 $itemid = intval($data[$i]);
\r
471 /* archives/1 (blogid) */
\r
472 case $CONF['ArchivesKey']:
\r
474 if ( $i < sizeof($data) )
\r
476 $archivelist = intval($data[$i]);
\r
480 /* two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid) */
\r
481 case $CONF['ArchiveKey']:
\r
482 if ( (($i + 1) < sizeof($data) ) && (i18n::strpos($data[$i + 1], '-') === FALSE ) )
\r
484 $blogid = (integer) $data[++$i];
\r
487 if ( $i < sizeof($data) )
\r
489 $archive = $data[$i];
\r
496 case $CONF['BlogKey']:
\r
498 if ( $i < sizeof($data) )
\r
500 $blogid = intval($data[$i]);
\r
504 /* category/1 (catid) */
\r
505 case $CONF['CategoryKey']:
\r
508 if ( $i < sizeof($data) )
\r
510 $catid = intval($data[$i]);
\r
514 case $CONF['MemberKey']:
\r
516 if ( $i < sizeof($data) )
\r
518 $memberid = intval($data[$i]);
\r
522 case $CONF['SpecialskinKey']:
\r
524 if ( $i < sizeof($data) )
\r
526 $special = $data[$i];
\r
527 $_REQUEST['special'] = $special;
\r
539 * PostParseURL is a place to cleanup any of the path-related global variables before the selector function is run.
\r
540 * It has 2 values in the data in case the original virtualpath is needed, but most the use will be in tweaking
\r
541 * global variables to clean up (scrub out catid or add catid) or to set someother global variable based on
\r
542 * the values of something like catid or itemid
\r
546 'type' => basename(serverVar('SCRIPT_NAME')),
\r
547 'info' => $virtualpath
\r
549 $manager->notify('PostParseURL', $data);
\r
552 * NOTE: Here is the end of initialization
\r
557 * This function includes or requires the specified library file
\r
559 * @param string $file
\r
560 * @param boolean $once use the _once() version
\r
561 * @param boolean $require use require() instead of include()
\r
564 function include_libs($file, $once = TRUE, $require = TRUE)
\r
568 // $DIR_LIBS isn't a directory
\r
569 if ( !is_dir($DIR_LIBS) )
\r
574 $lib_path = $DIR_LIBS . $file;
\r
576 if ( $once && $require )
\r
578 require_once($lib_path);
\r
580 else if ( $once && !$require )
\r
582 include_once($lib_path);
\r
584 else if ( $require )
\r
586 require($lib_path);
\r
590 include($lib_path);
\r
596 * include_plugins()
\r
597 * This function includes or requires the specified plugin file
\r
599 * @param string $file
\r
600 * @param boolean $once use the _once() version
\r
601 * @param boolean $require use require() instead of include()
\r
604 function include_plugins($file, $once = TRUE, $require = TRUE)
\r
606 global $DIR_PLUGINS;
\r
608 // begin if: $DIR_LIBS isn't a directory
\r
609 if ( !is_dir($DIR_PLUGINS) )
\r
614 $plugin_path = $DIR_PLUGINS . $file;
\r
617 if ( $once && $require )
\r
619 require_once($plugin_path);
\r
621 else if ( $once && !$require )
\r
623 include_once($plugin_path);
\r
625 elseif ( $require )
\r
627 require($plugin_path);
\r
631 include($plugin_path);
\r
637 * include_translation()
\r
638 * This function decide which locale is used and include translation
\r
640 * @param string &$locale locale name referring to 'language tags' defined in RFC 5646
\r
643 function include_translation(&$locale)
\r
645 global $DIR_LOCALES;
\r
647 $translation_file = $DIR_LOCALES . $locale . '.' . i18n::get_current_charset() . '.php';
\r
648 if ( !file_exists($translation_file) )
\r
650 $locale = 'en_Latn_US';
\r
651 $translation_file = $DIR_LOCALES . 'en_Latn_US.ISO-8859-1.php';
\r
653 include($translation_file);
\r
659 * This function returns the integer value of $_POST for the variable $name
\r
661 * @param string $name field to get the integer value of
\r
664 function intPostVar($name)
\r
666 return (integer) postVar($name);
\r
672 * This function returns the integer value of $_GET for the variable $name
\r
674 * @param string $name field to get the integer value of
\r
677 function intGetVar($name)
\r
679 return (integer) getVar($name);
\r
685 * This function returns the integer value of $_REQUEST for the variable $name. Also checks $_GET and $_POST if not found in $_REQUEST
\r
687 * @param string $name field to get the integer value of
\r
690 function intRequestVar($name)
\r
692 return (integer) requestVar($name);
\r
698 * This function returns the integer value of $_COOKIE for the variable $name
\r
700 * @param string $name field to get the integer value of
\r
703 function intCookieVar($name)
\r
705 return (integer) cookieVar($name);
\r
709 * getNucleusVersion()
\r
710 * This function returns the current Nucleus version (100 = 1.00, 101 = 1.01, etc...)
\r
715 function getNucleusVersion()
\r
721 * getNucleusPatchLevel()
\r
722 * TODO: Better description of this function.
\r
724 * Power users can install patches in between nucleus releases. These patches
\r
725 * usually add new functionality in the plugin API and allow those to
\r
726 * be tested without having to install CVS.
\r
731 function getNucleusPatchLevel()
\r
737 * getLatestVersion()
\r
738 * This function returns the latest Nucleus version available for download from nucleuscms.org or FALSE if unable to attain data
\r
739 * Format will be major.minor/patachlevel e.g. 3.41 or 3.41/02
\r
744 function getLatestVersion()
\r
746 // begin if: cURL is not available in this PHP installation
\r
747 if ( !function_exists('curl_init') )
\r
752 $curl = curl_init();
\r
755 curl_setopt ($curl, CURLOPT_URL, 'http://nucleuscms.org/version_check.php');
\r
756 curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
\r
757 curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
\r
759 $return = curl_exec($curl);
\r
768 * This function returns a Nucleus table name with the appropriate prefix
\r
769 * @param string $name
\r
772 function sql_table($name)
\r
774 global $MYSQL_PREFIX;
\r
776 // begin if: no MySQL prefix
\r
777 if ( empty($MYSQL_PREFIX) )
\r
779 return 'nucleus_' . $name;
\r
781 // else: use MySQL prefix
\r
784 return $MYSQL_PREFIX . 'nucleus_' . $name;
\r
790 * sendContentType()
\r
791 * This function sends the Content-Type header if headers have not already been sent
\r
792 * It also determines if the browser can accept application/xhtml+xml and sends it only to those that can.
\r
794 * if content type is application/xhtml+xml, only send it to browsers
\r
795 * that can handle it (IE6 cannot). Otherwise, send text/html
\r
798 * For admin area pages, keep sending text/html (unless it's a debug version)
\r
799 * application/xhtml+xml still causes too much problems with the javascript implementations
\r
802 * ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,
\r
803 * application/xhtml+xml seems to be working, so we're going to use it if we can.
\r
805 * @param string $content_type MIME media type registered to IANA, http://www.iana.org/assignments/media-types/index.html
\r
806 * @param string $page_type
\r
807 * @param string $charset Deprecated. This has no meaning.
\r
811 function sendContentType($content_type, $page_type = '', $charset = '')
\r
813 global $manager, $CONF;
\r
815 if ( headers_sent() )
\r
820 /* NOTE: MIME Media Type */
\r
821 if ( ($content_type == 'application/xhtml+xml')
\r
822 && (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') ) )
\r
824 $content_type = 'text/html';
\r
827 /* NOTE: generate event */
\r
829 'pageType' => $page_type,
\r
830 'contentType' => &$content_type
\r
832 $manager->notify('PreSendContentType', $data);
\r
834 /* NOTE: confirm MIME Media Type */
\r
835 $content_type = preg_replace('#[^a-zA-Z0-9-+./]#', '', $content_type);
\r
837 /* NOTE: confirm character set */
\r
838 $charset = i18n::get_current_charset();
\r
839 if ( i18n::get_forced_charset() !== '' )
\r
841 $charset = i18n::get_forced_charset();
\r
844 /* NOTE: send HTTP 1.1 header */
\r
845 header("Content-Type: {$content_type}; charset={$charset}");
\r
847 /* NOTE: set handler for translating character set */
\r
848 if ( $charset != i18n::get_current_charset() )
\r
850 ob_start(array('i18n', 'convert_handler'));
\r
858 * This function parses a query into an array of expressions that can be passed on to the highlight method
\r
859 * @param string $query
\r
862 function parseHighlight($query)
\r
864 // TODO: add more intelligent splitting logic
\r
866 // get rid of quotes
\r
867 $query = preg_replace('/\'|"/', '', $query);
\r
874 $aHighlight = preg_split('# #', $query);
\r
876 for ( $i = 0; $i < count($aHighlight); $i++ )
\r
878 $aHighlight[$i] = trim($aHighlight[$i]);
\r
880 if ( i18n::strlen($aHighlight[$i]) < 3 )
\r
882 unset($aHighlight[$i]);
\r
886 if ( count($aHighlight) == 1 )
\r
888 return $aHighlight[0];
\r
892 return $aHighlight;
\r
903 function getConfig()
\r
907 $query = sprintf('SELECT * FROM %s', sql_table('config'));
\r
908 $res = DB::getResult($query);
\r
910 foreach ( $res as $row )
\r
912 $CONF[$row['name']] = $row['value'];
\r
918 * This function gets the blog ID from the blog name
\r
919 * @param string $name
\r
922 function getBlogIDFromName($name)
\r
924 $query = sprintf('SELECT bnumber AS result FROM %s WHERE bshortname=%s', sql_table('blog'), DB::quoteValue($name));
\r
925 return DB::getValue($query);
\r
929 * This function gets the blog name from the blog ID
\r
933 function getBlogNameFromID($id)
\r
935 $query = sprintf('SELECT bname AS result FROM %s WHERE bnumber=%d', sql_table('blog'), intval($id));
\r
936 return DB::getValue($query);
\r
940 * This function gets the blog ID from the item ID
\r
941 * @param int $item_id
\r
944 function getBlogIDFromItemID($item_id)
\r
946 $query = sprintf('SELECT iblog AS result FROM %s WHERE inumber=%d', sql_table('item'), intval($item_id));
\r
947 return DB::getValue($query);
\r
951 * This function gets the blog ID from the comment ID
\r
952 * @param int $comment_id
\r
955 function getBlogIDFromCommentID($comment_id)
\r
957 $query = sprintf('SELECT cblog AS result FROM %s WHERE cnumber=%d', sql_table('comment'), intval($comment_id));
\r
958 return DB::getValue($query);
\r
962 * This function gets the blog ID from the category ID
\r
963 * @param int $category_id
\r
966 function getBlogIDFromCatID($category_id)
\r
968 $query = sprintf('SELECT cblog AS result FROM %s WHERE catid=%d', sql_table('category'), intval($category_id));
\r
969 return DB::getValue($query);
\r
973 * This function gets the category ID from the category name
\r
977 function getCatIDFromName($name)
\r
979 $query = sprintf('SELECT catid AS result FROM %s WHERE cname=%s', sql_table('category'), DB::quoteValue($name));
\r
980 return DB::getValue($query);
\r
985 * functions to be used in index.php to select something
\r
987 function selectBlog($shortname)
\r
989 global $blogid, $archivelist;
\r
990 $blogid = getBlogIDFromName($shortname);
\r
992 // also force archivelist variable, if it is set
\r
993 if ( $archivelist )
\r
995 $archivelist = $blogid;
\r
999 function selectSkin($skinname)
\r
1002 $skinid = SKIN::getIdFromName($skinname);
\r
1005 function selectCategory($cat)
\r
1008 if ( is_numeric($cat) )
\r
1010 $catid = (integer) $cat;
\r
1014 $catid = getCatIDFromName($cat);
\r
1018 function selectItem($id)
\r
1021 $itemid = (integer) $id;
\r
1024 function selectSpecialSkinType($id)
\r
1027 $special = strtolower($id);
\r
1030 function selector()
\r
1032 global $archive, $archivelist, $archivenext, $archivenextexists, $archiveprev, $archiveprevexists, $archivetype;
\r
1033 global $blog, $blogid;
\r
1035 global $itemid, $itemidnext, $itemidprev, $itemtitlenext, $itemtitleprev;
\r
1036 global $CONF, $DIR_LIBS, $amount, $errormessage, $imagepopup;
\r
1037 global $manager, $maxresults, $query;
\r
1038 global $member, $memberid, $memberinfo;
\r
1039 global $skinid, $skinpart, $special;
\r
1041 $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');
\r
1042 $action = requestVar('action');
\r
1044 if ( in_array($action, $actionNames) )
\r
1046 include_once($DIR_LIBS . 'ACTION.php');
\r
1047 $a = new Action();
\r
1048 $errorInfo = $a->doAction($action);
\r
1052 $errormessage = $errorInfo['message'];
\r
1056 // show error when headers already sent out
\r
1057 if ( headers_sent() && $CONF['alertOnHeadersSent'] )
\r
1059 // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)
\r
1060 if ( function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') )
\r
1062 headers_sent($hsFile, $hsLine);
\r
1063 $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';
\r
1071 "<p>The page headers have already been sent out{$extraInfo}. This could cause Nucleus not to work in the expected way.</p>"
\r
1072 . "<p>Usually, this is caused by spaces or newlines at the end of the <code>config.php</code> file, "
\r
1073 . "at the end of the translation file or at the end of a plugin file.</p>"
\r
1074 . "<p>Please check this and try again.</p>"
\r
1075 . "<p>If you don't want to see this error message again, without solving the problem, "
\r
1076 . "set <code>{$CONF['alertOnHeadersSent']}</code> in <code>globalfunctions.php</code> to <code>0</code></p>"
\r
1077 . "Page headers already sent"
\r
1082 // make is so ?archivelist without blogname or blogid shows the archivelist
\r
1083 // for the default weblog
\r
1084 if ( serverVar('QUERY_STRING') == 'archivelist' )
\r
1086 $archivelist = $CONF['DefaultBlog'];
\r
1089 // now decide which type of skin we need
\r
1092 // itemid given -> only show that item
\r
1095 if ( !$manager->existsItem($itemid,intval($CONF['allowFuture']),intval($CONF['allowDrafts'])) )
\r
1097 doError(_ERROR_NOSUCHITEM);
\r
1100 // 1. get timestamp, blogid and catid for item
\r
1101 $query = 'SELECT itime, iblog, icat FROM %s WHERE inumber=%d';
\r
1102 $query = sprintf($query, sql_table('item'), intval($itemid));
\r
1103 $row = DB::getRow($query);
\r
1105 // if a different blog id has been set through the request or selectBlog(),
\r
1108 if ( $blogid && (intval($blogid) != $row['iblog']) )
\r
1110 doError(_ERROR_NOSUCHITEM);
\r
1113 // if a category has been selected which doesn't match the item, ignore the
\r
1115 if ( ($catid != 0) && ($catid != $row['icat']) )
\r
1120 $blogid = $row['iblog'];
\r
1121 $timestamp = strtotime($row['itime']);
\r
1123 $b =& $manager->getBlog($blogid);
\r
1125 if ( !$b->isValidCategory($catid) )
\r
1127 $query = "SELECT inumber, ititle FROM %s WHERE itime<%s AND idraft=0 AND iblog=%d ORDER BY itime DESC LIMIT 1";
\r
1128 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), intval($blogid));
\r
1132 $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
1133 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), intval($blogid), intval($catid));
\r
1135 $row = DB::getRow($query);
\r
1139 $itemidprev = $row['inumber'];
\r
1140 $itemtitleprev = $row['ititle'];
\r
1143 // get next itemid and title
\r
1144 if ( !$b->isValidCategory($catid) )
\r
1146 $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
1147 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), DB::formatDateTime($b->getCorrectTime()), intval($blogid));
\r
1151 $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
1152 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), DB::formatDateTime($b->getCorrectTime()), intval($blogid), intval($catid));
\r
1154 $row = DB::getRow($query);
\r
1158 $itemidnext = $row['inumber'];
\r
1159 $itemtitlenext = $row['ititle'];
\r
1162 elseif ( $archive )
\r
1165 $type = 'archive';
\r
1167 // sql queries for the timestamp of the first and the last published item
\r
1168 $query = sprintf('SELECT UNIX_TIMESTAMP(itime) as result FROM %s WHERE idraft=0 ORDER BY itime ASC', sql_table('item'));
\r
1169 $first_timestamp = DB::getValue($query);
\r
1170 $query = sprintf('SELECT UNIX_TIMESTAMP(itime) as result FROM %s WHERE idraft=0 ORDER BY itime DESC', sql_table('item'));
\r
1171 $last_timestamp = DB::getValue($query);
\r
1173 sscanf($archive, '%d-%d-%d', $y, $m, $d);
\r
1177 $archivetype = _ARCHIVETYPE_DAY;
\r
1178 $t = mktime(0, 0, 0, $m, $d, $y);
\r
1179 // one day has 24 * 60 * 60 = 86400 seconds
\r
1180 $archiveprev = i18n::formatted_datetime('%Y-%m-%d', $t - 86400 );
\r
1181 // check for published items
\r
1182 if ( $t > $first_timestamp )
\r
1184 $archiveprevexists = true;
\r
1188 $archiveprevexists = false;
\r
1193 $archivenext = i18n::formatted_datetime('%Y-%m-%d', $t);
\r
1194 if ( $t < $last_timestamp )
\r
1196 $archivenextexists = true;
\r
1200 $archivenextexists = false;
\r
1203 elseif ( $m == 0 )
\r
1205 $archivetype = _ARCHIVETYPE_YEAR;
\r
1206 $t = mktime(0, 0, 0, 12, 31, $y - 1);
\r
1207 // one day before is in the previous year
\r
1208 $archiveprev = i18n::formatted_datetime('%Y', $t);
\r
1209 if ( $t > $first_timestamp )
\r
1211 $archiveprevexists = true;
\r
1215 $archiveprevexists = false;
\r
1218 // timestamp for the next year
\r
1219 $t = mktime(0, 0, 0, 1, 1, $y + 1);
\r
1220 $archivenext = i18n::formatted_datetime('%Y', $t);
\r
1221 if ( $t < $last_timestamp )
\r
1223 $archivenextexists = true;
\r
1227 $archivenextexists = false;
\r
1232 $archivetype = _ARCHIVETYPE_MONTH;
\r
1233 $t = mktime(0, 0, 0, $m, 1, $y);
\r
1234 // one day before is in the previous month
\r
1235 $archiveprev = i18n::formatted_datetime('%Y-%m', $t - 86400);
\r
1236 if ( $t > $first_timestamp )
\r
1238 $archiveprevexists = true;
\r
1242 $archiveprevexists = false;
\r
1245 // timestamp for the next month
\r
1246 $t = mktime(0, 0, 0, $m+1, 1, $y);
\r
1247 $archivenext = i18n::formatted_datetime('%Y-%m', $t);
\r
1248 if ( $t < $last_timestamp )
\r
1250 $archivenextexists = true;
\r
1254 $archivenextexists = false;
\r
1258 elseif ( $archivelist )
\r
1260 $type = 'archivelist';
\r
1262 if ( is_numeric($archivelist) )
\r
1264 $blogid = intVal($archivelist);
\r
1268 $blogid = getBlogIDFromName($archivelist);
\r
1273 doError(_ERROR_NOSUCHBLOG);
\r
1280 $query = stripslashes($query);
\r
1282 if ( is_numeric($blogid) )
\r
1284 $blogid = intVal($blogid);
\r
1288 $blogid = getBlogIDFromName($blogid);
\r
1293 doError(_ERROR_NOSUCHBLOG);
\r
1296 elseif ( $memberid )
\r
1300 if ( !Member::existsID($memberid) )
\r
1302 doError(_ERROR_NOSUCHMEMBER);
\r
1304 $memberinfo = $manager->getMember($memberid);
\r
1306 elseif ( $imagepopup )
\r
1308 // media object (images etc.)
\r
1309 $type = 'imagepopup';
\r
1311 // TODO: check if media-object exists
\r
1312 // TODO: set some vars?
\r
1316 // show regular index page
\r
1321 // any type of skin with catid
\r
1322 if ( $catid && !$blogid )
\r
1324 $blogid = getBlogIDFromCatID($catid);
\r
1327 // decide which blog should be displayed
\r
1330 $blogid = $CONF['DefaultBlog'];
\r
1333 $b =& $manager->getBlog($blogid);
\r
1334 $blog = $b; // references can't be placed in global variables?
\r
1336 if ( !$blog->isValid )
\r
1338 doError(_ERROR_NOSUCHBLOG);
\r
1341 // set catid if necessary
\r
1344 // check if the category is valid
\r
1345 if ( !$blog->isValidCategory($catid) )
\r
1347 doError(_ERROR_NOSUCHCATEGORY);
\r
1351 $blog->setSelectedCategory($catid);
\r
1357 $skinid = $blog->getDefaultSkin();
\r
1360 //$special = requestVar('special'); //get at top of file as global
\r
1361 if ( !empty($special) && isValidShortName($special) )
\r
1363 $type = strtolower($special);
\r
1366 $skin = new SKIN($skinid);
\r
1368 if ( !$skin->isValid() )
\r
1370 doError(_ERROR_NOSUCHSKIN);
\r
1373 // set global skinpart variable so can determine quickly what is being parsed from any plugin or phpinclude
\r
1374 $skinpart = $type;
\r
1377 $skin->parse($type);
\r
1379 // check to see we should throw JustPosted event
\r
1380 $blog->checkJustPosted();
\r
1386 * Show error skin with given message. An optional skin-object to use can be given
\r
1388 * @param string $msg
\r
1389 * @param string $skin
\r
1392 function doError($msg, $skin = '')
\r
1394 global $errormessage, $CONF, $skinid, $blogid, $manager;
\r
1396 if ( $skin == '' )
\r
1398 if ( Skin::existsID($skinid) )
\r
1402 elseif ( $manager->existsBlogID($blogid) )
\r
1404 $blog =& $manager->getBlog($blogid);
\r
1405 $id = $blog->getDefaultSkin();
\r
1407 elseif ($CONF['DefaultBlog'] )
\r
1409 $blog =& $manager->getBlog($CONF['DefaultBlog']);
\r
1410 $id = $blog->getDefaultSkin();
\r
1414 // this statement should actually never be executed
\r
1415 $id = $CONF['BaseSkin'];
\r
1417 $skin = new Skin($id);
\r
1420 $skinid = $skin->getID();
\r
1421 $errormessage = $msg;
\r
1422 $skin->parse('error');
\r
1427 * Errors before the database connection has been made
\r
1429 * @param string $msg message to notify
\r
1430 * @param string $title page title
\r
1433 function startUpError($msg, $title)
\r
1435 header('Content-Type: text/xml; charset=' . i18n::get_current_charset());
\r
1436 echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
\r
1438 echo "<title>{$title}</title></head>\n";
\r
1440 echo "<h1>{$title}</h1>\n";
\r
1447 function isValidShortName($name)
\r
1449 return preg_match('#^[a-z0-9]+$#i', $name);
\r
1451 function isValidDisplayName($name)
\r
1453 return preg_match('#^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$#i', $name);
\r
1455 function isValidCategoryName($name)
\r
1459 function isValidTemplateName($name)
\r
1461 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
\r
1463 function isValidSkinName($name)
\r
1465 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
\r
1468 // add and remove linebreaks
\r
1469 function addBreaks($var)
\r
1471 return nl2br($var);
\r
1473 function removeBreaks($var)
\r
1475 return preg_replace("/<br \/>([\r\n])/", "$1", $var);
\r
1481 * @param string $filename
\r
1482 * @param string $includeMode
\r
1483 * @param string $includePrefix
\r
1486 function parseFile($filename, $includeMode = 'normal', $includePrefix = '')
\r
1490 if ( !$skinid || !existsID($skinid) )
\r
1492 $skin = new Skin($CONF['BaseSkin']);
\r
1496 $skin = new Skin($skinid);
\r
1499 $oldIncludeMode = Parser::getProperty('IncludeMode');
\r
1500 $oldIncludePrefix = Parser::getProperty('IncludePrefix');
\r
1502 $skin->parse('fileparse', $filename);
\r
1504 Parser::setProperty('IncludeMode', $oldIncludeMode);
\r
1505 Parser::setProperty('IncludePrefix', $oldIncludePrefix);
\r
1512 * Outputs a debug message
\r
1514 * @param string $msg
\r
1517 function debug($msg)
\r
1519 echo '<p><b>' . $msg . "</b></p>\n";
\r
1523 // shows a link to help file
\r
1524 function help($id)
\r
1526 echo helpHtml($id);
\r
1529 function helpHtml($id)
\r
1532 return helplink($id) . '<img src="' . $CONF['AdminURL'] . 'documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" title="' . _HELP_TT . '" /></a>';
\r
1534 function helplink($id)
\r
1537 return '<a href="' . $CONF['AdminURL'] . 'documentation/help.html#'. $id . '" onclick="if (event && event.preventDefault) event.preventDefault(); return help(this.href);">';
\r
1542 * Includes a PHP file. This method can be called while parsing templates and skins
\r
1544 * @param string $filename name of file to parse
\r
1547 function includephp($filename)
\r
1549 // make predefined variables global, so most simple scripts can be used here
\r
1551 // apache (names taken from PHP doc)
\r
1552 global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;
\r
1553 global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;
\r
1554 global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;
\r
1555 global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;
\r
1556 global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;
\r
1557 global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;
\r
1558 global $REQUEST_URI;
\r
1560 // php (taken from PHP doc)
\r
1561 global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;
\r
1562 global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;
\r
1565 global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;
\r
1567 if ( @file_exists($filename) )
\r
1569 include($filename);
\r
1575 * Checks if a certain plugin exists
\r
1576 * @param string $plug name of plugin
\r
1577 * @return boolean exists or not
\r
1579 function checkPlugin($name)
\r
1581 global $DIR_PLUGINS;
\r
1582 return file_exists($DIR_PLUGINS . preg_replace('#[\\\\|/]#', '', $name) . '.php');
\r
1588 * @param string $querystr querystring to alter (e.g. foo=1&bar=2&x=y)
\r
1589 * @param string $param name of parameter to change (e.g. 'foo')
\r
1590 * @param string $value New value for that parameter (e.g. 3)
\r
1591 * @return string altered query string (for the examples above: foo=3&bar=2&x=y)
\r
1593 function alterQueryStr($querystr, $param, $value)
\r
1595 $vars = preg_split('#&#', $querystr);
\r
1598 for ( $i = 0; $i < count($vars); $i++ )
\r
1600 $v = preg_split('#=#', $vars[$i]);
\r
1602 if ( $v[0] == $param )
\r
1605 $vars[$i] = implode('=', $v);
\r
1612 $vars[] = "{$param}={$value}";
\r
1614 return ltrim(implode('&', $vars), '&');
\r
1619 * passes one variable as hidden input field (multiple fields for arrays)
\r
1620 * @see passRequestVars in varsx.x.x.php
\r
1622 * @param string $key
\r
1623 * @param string $value
\r
1626 function passVar($key, $value)
\r
1629 if ( is_array($value) )
\r
1631 for ( $i = 0; $i < sizeof($value); $i++ )
\r
1633 passVar($key . '[' . $i . ']', $value[$i]);
\r
1638 // other values: do stripslashes if needed
\r
1639 echo '<input type="hidden" name="' . Entity::hsc($key) . '" value="' . Entity::hsc(undoMagic($value)) . '" />' . "\n";
\r
1646 * @param string $variables
\r
1649 function checkVars($variables)
\r
1651 foreach ( $variables as $variable )
\r
1653 if ( array_key_exists($variable, $_GET)
\r
1654 || array_key_exists($variable, $_POST)
\r
1655 || array_key_exists($variable, $_COOKIE)
\r
1656 || array_key_exists($variable, $_ENV)
\r
1657 || (session_id() !== '' && array_key_exists($variable, $_SESSION))
\r
1658 || array_key_exists($variable, $_FILES) )
\r
1660 die('Sorry. An error occurred.');
\r
1667 * sanitizeParams()
\r
1668 * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.
\r
1674 function sanitizeParams()
\r
1680 // REQUEST_URI of $_SERVER
\r
1681 $str =& $_SERVER["REQUEST_URI"];
\r
1682 serverStringToArray($str, $array, $frontParam);
\r
1683 sanitizeArray($array);
\r
1684 arrayToServerString($array, $frontParam, $str);
\r
1686 // QUERY_STRING of $_SERVER
\r
1687 $str =& $_SERVER["QUERY_STRING"];
\r
1688 serverStringToArray($str, $array, $frontParam);
\r
1689 sanitizeArray($array);
\r
1690 arrayToServerString($array, $frontParam, $str);
\r
1693 convArrayForSanitizing($_GET, $array);
\r
1694 sanitizeArray($array);
\r
1695 revertArrayForSanitizing($array, $_GET);
\r
1697 // $_REQUEST (only GET param)
\r
1698 convArrayForSanitizing($_REQUEST, $array);
\r
1699 sanitizeArray($array);
\r
1700 revertArrayForSanitizing($array, $_REQUEST);
\r
1705 function _addInputTags(&$keys,$prefix='')
\r
1707 foreach ( $keys as $key=>$value )
\r
1711 $key=$prefix.'['.$key.']';
\r
1713 if ( is_array($value) )
\r
1715 _addInputTags($value,$key);
\r
1719 if ( get_magic_quotes_gpc() )
\r
1720 {$value=stripslashes($value);
\r
1722 if ( $key == 'ticket' )
\r
1726 echo '<input type="hidden" name="'.Entity::hsc($key).
\r
1727 '" value="'.Entity::hsc($value).'" />'."\n";
\r
1734 * serverStringToArray()
\r
1735 * Convert the server string such as $_SERVER['REQUEST_URI']
\r
1736 * to arry like arry['blogid']=1 and array['page']=2 etc.
\r
1738 * @param string $uri string
\r
1739 * @param string &$query_elements elements of query according to application/x-www-form-urlencoded
\r
1740 * @param string &$hier_part hierarchical part includes path
\r
1743 * RFC 3986: Uniform Resource Identifiers (URI): Generic Syntax
\r
1744 * 3. Syntax Components
\r
1745 * http://www.ietf.org/rfc/rfc3986.txt
\r
1747 * Hypertext Markup Language - 2.0
\r
1748 * 8.2.1. The form-urlencoded Media Type
\r
1749 * http://tools.ietf.org/html/rfc1866#section-8.2.1
\r
1751 * $_SERVER > Language Reference > Predefined Variables > PHP Manual
\r
1752 * http://www.php.net/manual/en/reserved.variables.server.php
\r
1754 function serverStringToArray($uri, &$query_elements, &$hier_part)
\r
1757 $query_elements = array();
\r
1760 // split hierarchical part, e.g. /index.php, query and fragment, e.g. blogid=1&page=2#section1
\r
1761 if ( i18n::strpos($uri, "?") > 0 )
\r
1763 list($hier_part, $query_and_fragment) = preg_split("#\?#", $uri, 2);
\r
1767 $query_and_fragment = $uri;
\r
1771 // If there is no query like blogid=1&page=2, return
\r
1772 if ( i18n::strpos($uri, "=") == FALSE && !i18n::strlen($hier_part) )
\r
1774 $hier_part = $uri;
\r
1778 $query_elements = preg_split("#&#", $query_and_fragment);
\r
1783 * arrayToServerString()
\r
1784 * Convert array like array['blogid'] to server string
\r
1785 * such as $_SERVER['REQUEST_URI']
\r
1787 * @param array $query_elements elements of query according to application/x-www-form-urlencoded
\r
1788 * @param string $hier_part hier-part defined in RFC3986
\r
1789 * @param string &$uri return value
\r
1793 * RFC 3986: Uniform Resource Identifiers (URI): Generic Syntax
\r
1794 * 3. Syntax Components
\r
1795 * http://www.ietf.org/rfc/rfc3986.txt
\r
1797 * Hypertext Markup Language - 2.0
\r
1798 * 8.2.1. The form-urlencoded Media Type
\r
1799 * http://tools.ietf.org/html/rfc1866#section-8.2.1
\r
1801 * $_SERVER > Language Reference > Predefined Variables > PHP Manual
\r
1802 * http://www.php.net/manual/en/reserved.variables.server.php
\r
1804 function arrayToServerString($query_elements, $hier_part, &$uri)
\r
1806 if ( i18n::strpos($uri, "?") !== FALSE )
\r
1808 $uri = $hier_part . "?";
\r
1812 $uri = $hier_part;
\r
1814 if ( count($query_elements) > 0 )
\r
1816 $uri .= implode("&", $query_elements);
\r
1823 * Sanitize array parameters.
\r
1824 * This function checks both key and value.
\r
1825 * - check key if it inclues " (double quote), remove from array
\r
1826 * - check value if it includes \ (escape sequece), remove remaining string
\r
1828 * @param array &$array elements of query according to application/x-www-form-urlencoded
\r
1831 function sanitizeArray(&$array)
\r
1833 $excludeListForSanitization = array('query');
\r
1835 foreach ( $array as $k => $v )
\r
1837 // split to key and value
\r
1838 list($key, $val) = preg_split("#=#", $v, 2);
\r
1839 if ( !isset($val) )
\r
1844 // when magic quotes is on, need to use stripslashes,
\r
1845 // and then addslashes
\r
1846 if ( get_magic_quotes_gpc() )
\r
1848 $val = stripslashes($val);
\r
1851 // note that we must use addslashes here because this function is called before the db connection is made
\r
1852 // and sql_real_escape_string needs a db connection
\r
1853 $val = addslashes($val);
\r
1855 // if $key is included in exclude list, skip this param
\r
1856 if ( !in_array($key, $excludeListForSanitization) )
\r
1859 if ( i18n::strpos($val, '\\') > 0 )
\r
1861 list($val, $tmp) = preg_split('#\\\\#', $val);
\r
1864 // remove control code etc.
\r
1865 $val = strtr($val, "\0\r\n<>'\"", " ");
\r
1868 if ( preg_match('#\"#', $key) > 0 )
\r
1870 unset($array[$k]);
\r
1874 // set sanitized info
\r
1875 $array[$k] = sprintf("%s=%s", $key, $val);
\r
1882 * convArrayForSanitizing()
\r
1883 * Convert array for sanitizeArray function
\r
1885 * @param string $src array to be sanitized
\r
1886 * @param array &$array array to be temporarily stored
\r
1889 function convArrayForSanitizing($src, &$array)
\r
1892 foreach ( $src as $key => $val )
\r
1894 if ( !key_exists($key, $_GET) )
\r
1898 $array[] = sprintf("%s=%s", $key, $val);
\r
1905 * revertArrayForSanitizing()
\r
1906 * Revert array after sanitizeArray function
\r
1908 * @param array $array element of query according to application/x-www-form-urlencoded
\r
1909 * @param array &$dst combination of key and value
\r
1912 function revertArrayForSanitizing($array, &$dst)
\r
1914 foreach ( $array as $v )
\r
1916 list($key, $val) = preg_split("#=#", $v, 2);
\r
1917 $dst[$key] = $val;
\r
1925 * Stops processing the request and redirects to the given URL.
\r
1926 * - no actual contents should have been sent to the output yet
\r
1927 * - the URL will be stripped of illegal or dangerous characters
\r
1929 * @param string $uri
\r
1932 function redirect($url)
\r
1934 $url = preg_replace('#[^a-z0-9-~+_.?\#=&;,/:@%*]#i', '', $url);
\r
1935 header('Location: ' . $url);
\r
1940 * getBookmarklet()
\r
1941 * Returns the Javascript code for a bookmarklet that works on most modern browsers
\r
1943 * @param integer $blogid ID for weblog
\r
1944 * @return script to call Bookmarklet
\r
1946 function getBookmarklet($blogid, $width=600, $height=500)
\r
1953 . "if ( x.selection )"
\r
1955 . " Q=x.selection.createRange().text;"
\r
1957 . "else if ( y.getSelection )"
\r
1959 . " Q=y.getSelection();"
\r
1961 . "else if ( x.getSelection )"
\r
1963 . " Q=x.getSelection();"
\r
1965 . "wingm = window.open('{$CONF['AdminURL']}bookmarklet.php?blogid={$blogid}"
\r
1966 . " &logtext=' + encodeURIComponent(Q) +"
\r
1967 . " '&loglink=' + encodeURIComponent(x.location.href) +"
\r
1968 . " '&loglinktitle=' + encodeURIComponent(x.title),"
\r
1970 . " 'scrollbars=yes,width={$width},height={$height},left=10,top=10,status=yes,resizable=yes');"
\r
1971 . "wingm.focus();";
\r
1978 * cleans filename of uploaded file for writing to file system
\r
1980 * @param string $str
\r
1981 * @return string $cleaned filename ready for use
\r
1983 function cleanFileName($str)
\r
1985 $str = strtolower($str);
\r
1986 $ext_point = i18n::strrpos($str,".");
\r
1987 if ( $ext_point === FALSE )
\r
1991 $ext = i18n::substr($str,$ext_point,i18n::strlen($str));
\r
1992 $str = i18n::substr($str,0,$ext_point);
\r
1994 return preg_replace("#[^a-z0-9-]#", "_", $str) . $ext;
\r
1998 * use Notification class instead of this
\r
1999 * Deprecated since 4.0:
\r
2001 function getMailFooter()
\r
2003 NOTIFICATION::get_mail_footer();
\r
2005 function isValidMailAddress($address)
\r
2007 return NOTIFICATION::address_validation($address);
\r
2010 * use Entity class instead of this
\r
2011 * Deprecated since 4.0:
\r
2013 function highlight($text, $expression, $highlight)
\r
2015 return Entity::highlight($text, $expression, $highlight);
\r
2017 function shorten($string, $maxlength, $suffix)
\r
2019 return Entity::shorten($string, $maxlength, $suffix);
\r
2021 function stringStripTags ($string)
\r
2023 return Entity::strip_tags($string);
\r
2025 function toAscii($string)
\r
2027 return Entity::anchor_footnoting($string);
\r
2029 function stringToAttribute ($string)
\r
2031 return Entity::hsc($string);
\r
2033 function stringToXML ($string)
\r
2035 return Entity::hen($string);
\r
2037 function encode_desc($data)
\r
2039 return Entity::hen($data);
\r
2042 * Centralisation of the functions that deals with locales
\r
2043 * This functions is based on the old way to deal with languages
\r
2044 * Deprecated since 4.0:
\r
2046 function getLanguageName()
\r
2048 if( ($language = i18n::convert_locale_to_old_language_file_name(i18n::get_current_locale())) === FALSE )
\r
2050 $language ='english';
\r
2054 function selectLanguage($language)
\r
2057 include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');
\r
2061 * use i18n class instead of these
\r
2062 * Deprecated since 4.0
\r
2064 function checkLanguage($lang)
\r
2066 return ( preg_match('#^(.+)_(.+)_(.+)$#', $lang)
\r
2067 || i18n::convert_old_language_file_name_to_locale($lang) );
\r
2069 function formatDate($format, $timestamp, $default_format, &$blog)
\r
2071 $offset = date('Z', $timestamp);
\r
2074 $offset += $blog->getTimeOffset() * 3600;
\r
2076 return i18n::formatted_datetime($format, $timestamp, $offset, $default_format);
\r
2080 * use DB class instead of these
\r
2081 * Deprecated since 4.0
\r
2083 function quickQuery($query)
\r
2085 $row = DB::getRow($query);
\r
2086 return $row['result'];
\r
2088 function mysqldate($timestamp)
\r
2090 return DB::formatDateTime($timestamp);
\r
2093 * Centralisation of the functions that generate links
\r
2094 * Deprecated since 4.0:
\r
2095 * Please use Link::FunctionName(...) instead
\r
2097 function createItemLink($itemid, $extra = '')
\r
2099 return Link::create_item_link($itemid, $extra);
\r
2101 function createMemberLink($memberid, $extra = '')
\r
2103 return Link::create_member_link($memberid, $extra);
\r
2105 function createCategoryLink($catid, $extra = '')
\r
2107 return Link::create_category_link($catid, $extra);
\r
2109 function createArchiveListLink($blogid = '', $extra = '')
\r
2111 return Link::create_archivelist_link($blogid, $extra);
\r
2113 function createArchiveLink($blogid, $archive, $extra = '')
\r
2115 return Link::create_archive_link($blogid, $archive, $extra);
\r
2117 function createBlogidLink($blogid, $params = '')
\r
2119 return Link::create_blogid_link($blogid, $params = '');
\r
2121 function createLink($type, $params)
\r
2123 return Link::create_link($type, $params);
\r
2125 function createBlogLink($url, $params)
\r
2127 return Link::create_blog_link($url, $params);
\r
2130 * use ActionLog class instead of this
\r
2131 * Deprecated since 4.0
\r
2133 function addToLog($level, $msg)
\r
2135 ActionLog::add($level, $msg);
\r
2138 * use PHP's implement
\r
2139 * Deprecated since 4.0
\r
2141 function ifset(&$var)
\r
2143 if ( isset($var) )
\r
2151 * use Manager::getPluginNameFromPid() instead of this
\r
2152 * Deprecated since 4.0
\r
2154 function getPluginNameFromPid($pid)
\r
2157 return $manager->getPluginNameFromPid($pid);
\r
2160 * use Manager::numberOfEventSubscribers() instead of this
\r
2161 * Deprecated since 4.0
\r
2163 function numberOfEventSubscribers($event)
\r
2166 return $manager->getNumberOfSubscribers($event);
\r
2170 * PluginAdmin has already the alternative implement
\r
2171 * Deprecated since 4.0
\r
2173 function ticketForPlugin()
\r
2175 global $CONF, $DIR_LIBS, $DIR_LOCALES, $DIR_PLUGINS, $manager, $member, $ticketforplugin;
\r
2178 $ticketforplugin = array();
\r
2179 $ticketforplugin['ticket'] = FALSE;
\r
2181 /* Check if using plugin's php file. */
\r
2182 $p_translated = serverVar('SCRIPT_FILENAME');
\r
2184 if (!file_exists($p_translated) )
\r
2186 header("HTTP/1.0 404 Not Found");
\r
2190 // check whether this is plugin or not
\r
2191 $p_translated = str_replace('\\', '/', $p_translated);
\r
2192 $d_plugins = str_replace('\\', '/', $DIR_PLUGINS);
\r
2193 if ( i18n::strpos($p_translated, $d_plugins) !== 0 )
\r
2198 // Solve the plugin php file or admin directory
\r
2199 $phppath = i18n::substr($p_translated, i18n::strlen($d_plugins) );
\r
2200 // Remove the first "/" if exists.
\r
2201 $phppath = preg_replace('#^/#', '', $phppath);
\r
2202 // Remove the first "NP_" and the last ".php" if exists.
\r
2203 $path = preg_replace('#^NP_(.*)\.php$#', '$1', $phppath);
\r
2204 // Remove the "/" and beyond.
\r
2205 $path = preg_replace('#^([^/]*)/(.*)$#', '$1', $path);
\r
2207 // Solve the plugin name.
\r
2208 $plugins = array();
\r
2209 $query = sprintf('SELECT pfile FROM %s;', sql_table('plugin'));
\r
2210 $res = DB::getResult($query);
\r
2212 foreach ( $res as $row )
\r
2214 $name = i18n::substr($row['pfile'], 3);
\r
2215 $plugins[strtolower($name)] = $name;
\r
2218 $res->closeCursor();
\r
2220 if ( !array_key_exists($path, $plugins) )
\r
2222 header("HTTP/1.0 404 Not Found");
\r
2227 $plugin_name = $plugins[$path];
\r
2230 /* Return if not index.php */
\r
2231 if ( ($phppath != strtolower($plugin_name) . '/')
\r
2232 && ($phppath != strtolower($plugin_name) . '/index.php') )
\r
2237 /* Exit if not logged in. */
\r
2238 if ( !$member->isLoggedIn() )
\r
2240 exit('You aren\'t logged in.');
\r
2243 /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */
\r
2244 if ( $file = @file($p_translated) )
\r
2248 foreach($file as $line)
\r
2250 if (preg_match('#[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]#i', $prevline . $line) )
\r
2255 $prevline = $line;
\r
2259 /* Show a form if not valid ticket */
\r
2260 if ( (i18n::strpos(serverVar('REQUEST_URI'), '?') !== FALSE
\r
2261 || serverVar('QUERY_STRING')
\r
2262 || strtoupper(serverVar('REQUEST_METHOD') ) == 'POST')
\r
2263 && !$manager->checkTicket() )
\r
2265 $oPluginAdmin = new PluginAdmin($plugin_name);
\r
2266 $oPluginAdmin->start();
\r
2268 echo '<p>' . _ERROR_BADTICKET . "</p>\n";
\r
2270 // Resolve URI and QUERY_STRING
\r
2271 if ($uri = serverVar('REQUEST_URI') )
\r
2273 list($uri, $qstring) = preg_split('#\?#', $uri);
\r
2277 if ( !($uri = serverVar('PHP_SELF') ) )
\r
2279 $uri = serverVar('SCRIPT_NAME');
\r
2281 $qstring = serverVar('QUERY_STRING');
\r
2285 $qstring = '?' . $qstring;
\r
2288 echo '<p>' . _SETTINGS_UPDATE . ' : ' . _QMENU_PLUGINS . ' <span style="color:red;">' . Entity::hsc($plugin_name) . "</span> ?</p>\n";
\r
2290 switch(strtoupper(serverVar('REQUEST_METHOD') ) )
\r
2293 echo '<form method="POST" action="'.Entity::hsc($uri.$qstring).'">';
\r
2294 $manager->addTicketHidden();
\r
2295 _addInputTags($_POST);
\r
2299 echo '<form method="GET" action="'.Entity::hsc($uri).'">';
\r
2300 $manager->addTicketHidden();
\r
2301 _addInputTags($_GET);
\r
2307 echo '<input type="submit" value="' . _YES . '" /> ';
\r
2308 echo '<input type="button" value="' . _NO . '" onclick="history.back(); return false;" />';
\r
2311 $oPluginAdmin->end();
\r
2315 /* Create new ticket */
\r
2316 $ticket=$manager->addTicketToUrl('');
\r
2317 $ticketforplugin['ticket'] = preg_split($ticket, i18n::strpos($ticket, 'ticket=') + 7);
\r