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 1825 2012-05-04 16:56:35Z 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
47 if ( array_key_exists('debug', $CONF) && $CONF['debug'] )
\r
49 /* report all errors! */
\r
50 error_reporting(E_ALL);
\r
54 ini_set('display_errors','0');
\r
55 error_reporting(E_ERROR | E_WARNING | E_PARSE);
\r
59 * alertOnHeadersSent
\r
60 * Displays an error when visiting a public Nucleus page and headers have
\r
61 * been sent out to early. This usually indicates an error in either a
\r
62 * configuration file or a translation file, and could cause Nucleus to
\r
65 if ( !array_key_exists('alertOnHeadersSent', $CONF) || $CONF['alertOnHeadersSent'] !== 0 )
\r
67 $CONF['alertOnHeadersSent'] = 1;
\r
70 * alertOnSecurityRisk
\r
71 * Displays an error only when visiting the admin area, and when one or
\r
72 * more of the installation files (install.php, install.sql, upgrades/
\r
73 * directory) are still on the server.
\r
75 $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
164 /* connect to database */
\r
165 global $MYSQL_HANDLER;
\r
166 if ( !isset($MYSQL_HANDLER) )
\r
168 $MYSQL_HANDLER = array('mysql','');
\r
170 if ( $MYSQL_HANDLER[0] == '' )
\r
172 $MYSQL_HANDLER[0] = 'mysql';
\r
174 DB::setConnectionInfo($MYSQL_HANDLER[1], $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE);
\r
176 /* force locale or charset */
\r
178 $charset = i18n::get_current_charset();
\r
181 'locale' => &$locale,
\r
182 'charset' => &$charset
\r
184 $manager->notify('ForceLocale', $data);
\r
186 if ( $data['locale'] !== '' )
\r
187 { i18n::set_forced_locale($data['locale']);
\r
189 if ( $data['charset'] !== '' )
\r
191 i18n::set_forced_charset($data['charset']);
\r
197 /* convert forced charset to current charset */
\r
198 if ( i18n::get_forced_charset() != i18n::get_current_charset() )
\r
200 $_POST = i18n::convert_array($_POST, i18n::get_forced_charset());
\r
201 $_GET = i18n::convert_array($_GET, i18n::get_forced_charset());
\r
202 $_REQUEST = i18n::convert_array($_REQUEST, i18n::get_forced_charset());
\r
203 $_COOKIE = i18n::convert_array($_COOKIE, i18n::get_forced_charset());
\r
204 $_FILES = i18n::convert_array($_FILES, i18n::get_forced_charset());
\r
206 if ( session_id() !== '' )
\r
208 $_SESSION = i18n::convert_array($_SESSION, i18n::get_forced_charset());
\r
213 /* sanitize option */
\r
214 $bLoggingSanitizedResult = 0;
\r
215 $bSanitizeAndContinue = 0;
\r
216 $orgRequestURI = serverVar('REQUEST_URI');
\r
219 /* logs sanitized result if need */
\r
220 if ( $orgRequestURI !== serverVar('REQUEST_URI') )
\r
222 $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";
\r
223 $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');
\r
224 if ( $bLoggingSanitizedResult )
\r
226 addToLog(WARNING, $msg);
\r
228 if ( !$bSanitizeAndContinue )
\r
234 /* makes sure database connection gets closed on script termination */
\r
235 register_shutdown_function('sql_disconnect');
\r
236 /* get all variables that can come from the request and put them in the global scope */
\r
237 $blogid = requestVar('blogid');
\r
238 $itemid = intRequestVar('itemid');
\r
239 $catid = intRequestVar('catid');
\r
240 $skinid = requestVar('skinid');
\r
241 $memberid = requestVar('memberid');
\r
242 $archivelist = requestVar('archivelist');
\r
243 $imagepopup = requestVar('imagepopup');
\r
244 $archive = requestVar('archive');
\r
245 $query = requestVar('query');
\r
246 $highlight = requestVar('highlight');
\r
247 $amount = requestVar('amount');
\r
248 $action = requestVar('action');
\r
249 $nextaction = requestVar('nextaction');
\r
250 $maxresults = requestVar('maxresults');
\r
251 $startpos = intRequestVar('startpos');
\r
252 $errormessage = '';
\r
254 $special = requestVar('special');
\r
255 $virtualpath = ((getVar('virtualpath') != NULL) ? getVar('virtualpath') : serverVar('PATH_INFO'));
\r
257 /* get all variables that can come from the request and put them in the global scope */
\r
258 $blogid = requestVar('blogid');
\r
259 $itemid = intRequestVar('itemid');
\r
260 $catid = intRequestVar('catid');
\r
261 $skinid = requestVar('skinid');
\r
262 $memberid = requestVar('memberid');
\r
263 $archivelist = requestVar('archivelist');
\r
264 $imagepopup = requestVar('imagepopup');
\r
265 $archive = requestVar('archive');
\r
266 $query = requestVar('query');
\r
267 $highlight = requestVar('highlight');
\r
268 $amount = requestVar('amount');
\r
269 $action = requestVar('action');
\r
270 $nextaction = requestVar('nextaction');
\r
271 $maxresults = requestVar('maxresults');
\r
272 $startpos = intRequestVar('startpos');
\r
273 $errormessage = '';
\r
275 $special = requestVar('special');
\r
276 $virtualpath = ((getVar('virtualpath') != NULL) ? getVar('virtualpath') : serverVar('PATH_INFO'));
\r
283 /* Properly set $CONF['Self'] and others if it's not set...
\r
284 * usually when we are access from admin menu
\r
286 if ( !array_key_exists('Self', $CONF) )
\r
288 $CONF['Self'] = $CONF['IndexURL'];
\r
289 /* strip trailing */
\r
290 if ( $CONF['Self'][i18n::strlen($CONF['Self']) -1] == "/" )
\r
292 $CONF['Self'] = i18n::substr($CONF['Self'], 0, i18n::strlen($CONF['Self']) -1);
\r
296 $CONF['ItemURL'] = $CONF['Self'];
\r
297 $CONF['ArchiveURL'] = $CONF['Self'];
\r
298 $CONF['ArchiveListURL'] = $CONF['Self'];
\r
299 $CONF['MemberURL'] = $CONF['Self'];
\r
300 $CONF['SearchURL'] = $CONF['Self'];
\r
301 $CONF['BlogURL'] = $CONF['Self'];
\r
302 $CONF['CategoryURL'] = $CONF['Self'];
\r
305 *switch URLMode back to normal when $CONF['Self'] ends in .php
\r
306 * this avoids urls like index.php/item/13/index.php/item/15
\r
308 if ( !array_key_exists('URLMode', $CONF)
\r
309 || (($CONF['URLMode'] == 'pathinfo')
\r
310 && (i18n::substr($CONF['Self'], i18n::strlen($CONF['Self']) - 4) == '.php')) )
\r
312 $CONF['URLMode'] = 'normal';
\r
315 /* automatically use simpler toolbar for mozilla */
\r
316 if ( ($CONF['DisableJsTools'] == 0)
\r
317 && i18n::strpos(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0') !== FALSE
\r
318 && i18n::strpos(serverVar('HTTP_USER_AGENT'), 'Gecko') !== FALSE )
\r
320 $CONF['DisableJsTools'] = 2;
\r
323 $member = new Member();
\r
325 if ( $action == 'login' )
\r
327 $login = postVar('login');
\r
328 $password = postVar('password');
\r
329 $shared = intPostVar('shared');
\r
330 $member->login($login, $password, $shared);
\r
332 elseif ( ($action == 'logout') )
\r
338 $member->cookielogin();
\r
342 /* TODO: This is for backward compatibility, should be obsoleted near future. */
\r
343 if ( !preg_match('#^(.+)_(.+)_(.+)$#', $CONF['Locale'])
\r
344 && ($CONF['Locale'] = i18n::convert_old_language_file_name_to_locale($CONF['Locale'])) === FALSE )
\r
346 $CONF['Locale'] = 'en_Latn_US';
\r
348 if ( !array_key_exists('Language', $CONF) )
\r
350 $CONF['Language'] = i18n::convert_locale_to_old_language_file_name($CONF['Locale']);
\r
352 $locale = $CONF['Locale'];
\r
355 /* NOTE: include translation file and set locale */
\r
356 if ( $member->isLoggedIn() )
\r
358 if ( $member->getLocale() )
\r
360 $locale = $member->getLocale();
\r
365 if ( i18n::get_forced_locale() !== '' )
\r
367 $locale = i18n::get_forced_locale();
\r
370 include_translation($locale);
\r
371 i18n::set_current_locale($locale);
\r
374 /* login completed */
\r
375 $manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );
\r
378 if ( $member->isLoggedIn() && $nextaction )
\r
380 $action = $nextaction;
\r
384 * Release ticket for plugin
\r
388 /* first, let's see if the site is disabled or not. always allow admin area access. */
\r
389 if ( $CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea'] )
\r
391 redirect($CONF['DisableSiteURL']);
\r
395 /* load other classes */
\r
396 include($DIR_LIBS . 'PARSER.php');
\r
397 include($DIR_LIBS . 'SKIN.php');
\r
398 include($DIR_LIBS . 'TEMPLATE.php');
\r
399 include($DIR_LIBS . 'BLOG.php');
\r
400 include($DIR_LIBS . 'BODYACTIONS.php');
\r
401 include($DIR_LIBS . 'COMMENTS.php');
\r
402 include($DIR_LIBS . 'COMMENT.php');
\r
403 include($DIR_LIBS . 'NOTIFICATION.php');
\r
404 include($DIR_LIBS . 'BAN.php');
\r
405 include($DIR_LIBS . 'PAGEFACTORY.php');
\r
406 include($DIR_LIBS . 'SEARCH.php');
\r
407 include($DIR_LIBS . 'LINK.php');
\r
409 /* set lastVisit cookie (if allowed) */
\r
410 if ( !headers_sent() )
\r
412 if ( $CONF['LastVisit'] )
\r
414 setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
\r
418 setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
\r
422 if ( !defined('_ARCHIVETYPE_MONTH') )
\r
424 define('_ARCHIVETYPE_DAY', 'day');
\r
425 define('_ARCHIVETYPE_MONTH', 'month');
\r
426 define('_ARCHIVETYPE_YEAR', 'year');
\r
429 /* decode path_info */
\r
430 if ( $CONF['URLMode'] == 'pathinfo' )
\r
432 /* initialize keywords if this hasn't been done before */
\r
433 if ( !isset($CONF['ItemKey']) || $CONF['ItemKey'] == '' )
\r
435 $CONF['ItemKey'] = 'item';
\r
438 if ( !isset($CONF['ArchiveKey']) || $CONF['ArchiveKey'] == '' )
\r
440 $CONF['ArchiveKey'] = 'archive';
\r
443 if ( !isset($CONF['ArchivesKey']) || $CONF['ArchivesKey'] == '' )
\r
445 $CONF['ArchivesKey'] = 'archives';
\r
448 if ( !isset($CONF['MemberKey']) || $CONF['MemberKey'] == '' )
\r
450 $CONF['MemberKey'] = 'member';
\r
453 if ( !isset($CONF['BlogKey']) || $CONF['BlogKey'] == '' )
\r
455 $CONF['BlogKey'] = 'blog';
\r
458 if ( !isset($CONF['CategoryKey']) || $CONF['CategoryKey'] == '' )
\r
460 $CONF['CategoryKey'] = 'category';
\r
463 if ( !isset($CONF['SpecialskinKey']) || $CONF['SpecialskinKey'] == '' )
\r
465 $CONF['SpecialskinKey'] = 'special';
\r
472 /* e.g. item, blog, ... */
\r
473 'type' => basename(serverVar('SCRIPT_NAME') ),
\r
474 'info' => $virtualpath,
\r
475 'complete' => &$parsed
\r
481 /* default implementation */
\r
482 $data = preg_split("#/#", $virtualpath );
\r
483 for ( $i = 0; $i < sizeof($data); $i++ )
\r
485 switch ( $data[$i] )
\r
487 /* item/1 (blogid) */
\r
488 case $CONF['ItemKey']:
\r
491 if ( $i < sizeof($data) )
\r
493 $itemid = intval($data[$i]);
\r
497 /* archives/1 (blogid) */
\r
498 case $CONF['ArchivesKey']:
\r
500 if ( $i < sizeof($data) )
\r
502 $archivelist = intval($data[$i]);
\r
506 /* two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid) */
\r
507 case $CONF['ArchiveKey']:
\r
508 if ( (($i + 1) < sizeof($data) ) && (i18n::strpos($data[$i + 1], '-') === FALSE ) )
\r
510 $blogid = (integer) $data[++$i];
\r
513 if ( $i < sizeof($data) )
\r
515 $archive = $data[$i];
\r
522 case $CONF['BlogKey']:
\r
524 if ( $i < sizeof($data) )
\r
526 $blogid = intval($data[$i]);
\r
530 /* category/1 (catid) */
\r
531 case $CONF['CategoryKey']:
\r
534 if ( $i < sizeof($data) )
\r
536 $catid = intval($data[$i]);
\r
540 case $CONF['MemberKey']:
\r
542 if ( $i < sizeof($data) )
\r
544 $memberid = intval($data[$i]);
\r
548 case $CONF['SpecialskinKey']:
\r
550 if ( $i < sizeof($data) )
\r
552 $special = $data[$i];
\r
553 $_REQUEST['special'] = $special;
\r
565 * PostParseURL is a place to cleanup any of the path-related global variables before the selector function is run.
\r
566 * It has 2 values in the data in case the original virtualpath is needed, but most the use will be in tweaking
\r
567 * global variables to clean up (scrub out catid or add catid) or to set someother global variable based on
\r
568 * the values of something like catid or itemid
\r
572 'type' => basename(serverVar('SCRIPT_NAME')),
\r
573 'info' => $virtualpath
\r
575 $manager->notify('PostParseURL', $data);
\r
578 * NOTE: Here is the end of initialization
\r
582 * Errors before the database connection has been made
\r
584 * @param string $msg message to notify
\r
585 * @param string $title page title
\r
588 function startUpError($msg, $title)
\r
590 header('Content-Type: text/xml; charset=' . i18n::get_current_charset());
\r
591 echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
\r
593 echo '<title>'. Entity::hsc($title) . "</title></head>\n";
\r
595 echo '<h1>' . Entity::hsc($title) . "</h1>\n";
\r
603 * This function includes or requires the specified library file
\r
604 * @param string $file
\r
605 * @param bool $once use the _once() version
\r
606 * @param bool $require use require() instead of include()
\r
608 function include_libs($file, $once = TRUE, $require = TRUE)
\r
612 // begin if: $DIR_LIBS isn't a directory
\r
613 if ( !is_dir($DIR_LIBS) )
\r
618 $lib_path = $DIR_LIBS . $file;
\r
621 if ( $once && $require )
\r
623 require_once($lib_path);
\r
625 else if ( $once && !$require )
\r
627 include_once($lib_path);
\r
629 else if ( $require )
\r
631 require($lib_path);
\r
635 include($lib_path);
\r
642 * This function includes or requires the specified plugin file
\r
643 * @param string $file
\r
644 * @param bool $once use the _once() version
\r
645 * @param bool $require use require() instead of include()
\r
647 function include_plugins($file, $once = TRUE, $require = TRUE)
\r
649 global $DIR_PLUGINS;
\r
651 // begin if: $DIR_LIBS isn't a directory
\r
652 if ( !is_dir($DIR_PLUGINS) )
\r
657 $plugin_path = $DIR_PLUGINS . $file;
\r
660 if ( $once && $require )
\r
662 require_once($plugin_path);
\r
664 else if ( $once && !$require )
\r
666 include_once($plugin_path);
\r
668 elseif ( $require )
\r
670 require($plugin_path);
\r
674 include($plugin_path);
\r
679 * This function decide which locale is used and include translation
\r
680 * @param string $locale locale name referring to 'language tags' defined in RFC 5646
\r
683 function include_translation(&$locale)
\r
685 global $DIR_LOCALES;
\r
687 $translation_file = $DIR_LOCALES . $locale . '.' . i18n::get_current_charset() . '.php';
\r
688 if ( !file_exists($translation_file) )
\r
690 $locale = 'en_Latn_US';
\r
691 $translation_file = $DIR_LOCALES . 'en_Latn_US.ISO-8859-1.php';
\r
693 include($translation_file);
\r
698 * This function returns the integer value of $_POST for the variable $name
\r
699 * @param string $name field to get the integer value of
\r
702 function intPostVar($name)
\r
704 return intval(postVar($name));
\r
709 * This function returns the integer value of $_GET for the variable $name
\r
710 * @param string $name field to get the integer value of
\r
713 function intGetVar($name)
\r
715 return intval(getVar($name));
\r
720 * This function returns the integer value of $_REQUEST for the variable $name. Also checks $_GET and $_POST if not found in $_REQUEST
\r
721 * @param string $name field to get the integer value of
\r
724 function intRequestVar($name)
\r
726 return intval(requestVar($name));
\r
731 * This function returns the integer value of $_COOKIE for the variable $name
\r
732 * @param string $name field to get the integer value of
\r
735 function intCookieVar($name)
\r
737 return intval(cookieVar($name));
\r
742 * This function returns the current Nucleus version (100 = 1.00, 101 = 1.01, etc...)
\r
745 function getNucleusVersion()
\r
752 * TODO: Better description of this function.
\r
754 * Power users can install patches in between nucleus releases. These patches
\r
755 * usually add new functionality in the plugin API and allow those to
\r
756 * be tested without having to install CVS.
\r
760 function getNucleusPatchLevel()
\r
767 * This function returns the latest Nucleus version available for download from nucleuscms.org or FALSE if unable to attain data
\r
768 * Format will be major.minor/patachlevel e.g. 3.41 or 3.41/02
\r
769 * @return string|bool
\r
771 function getLatestVersion()
\r
773 // begin if: cURL is not available in this PHP installation
\r
774 if ( !function_exists('curl_init') )
\r
779 $curl = curl_init();
\r
781 curl_setopt ($curl, CURLOPT_URL, 'http://nucleuscms.org/version_check.php');
\r
782 curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
\r
783 curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
\r
784 $return = curl_exec($curl);
\r
791 * This function returns a Nucleus table name with the appropriate prefix
\r
792 * @param string $name
\r
795 function sql_table($name)
\r
797 global $MYSQL_PREFIX;
\r
799 // begin if: no MySQL prefix
\r
800 if ( empty($MYSQL_PREFIX) )
\r
802 return 'nucleus_' . $name;
\r
804 // else: use MySQL prefix
\r
807 return $MYSQL_PREFIX . 'nucleus_' . $name;
\r
814 * sendContentType()
\r
815 * This function sends the Content-Type header if headers have not already been sent
\r
816 * It also determines if the browser can accept application/xhtml+xml and sends it only to those that can.
\r
818 * if content type is application/xhtml+xml, only send it to browsers
\r
819 * that can handle it (IE6 cannot). Otherwise, send text/html
\r
822 * For admin area pages, keep sending text/html (unless it's a debug version)
\r
823 * application/xhtml+xml still causes too much problems with the javascript implementations
\r
826 * ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,
\r
827 * application/xhtml+xml seems to be working, so we're going to use it if we can.
\r
829 * @param string $content_type MIME media type registered to IANA, http://www.iana.org/assignments/media-types/index.html
\r
830 * @param string $page_type
\r
831 * @param string $charset Deprecated. This has no meaning.
\r
835 function sendContentType($content_type, $page_type = '', $charset = '')
\r
837 global $manager, $CONF;
\r
839 if ( headers_sent() )
\r
844 /* NOTE: MIME Media Type */
\r
845 if ( ($content_type == 'application/xhtml+xml')
\r
846 && (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') ) )
\r
848 $content_type = 'text/html';
\r
851 /* NOTE: generate event */
\r
853 'pageType' => $page_type,
\r
854 'contentType' => &$content_type
\r
856 $manager->notify('PreSendContentType', $data);
\r
858 /* NOTE: confirm MIME Media Type */
\r
859 $content_type = preg_replace('#[^a-zA-Z0-9-+./]#', '', $content_type);
\r
861 /* NOTE: confirm character set */
\r
862 $charset = i18n::get_current_charset();
\r
863 if ( i18n::get_forced_charset() !== '' )
\r
865 $charset = i18n::get_forced_charset();
\r
868 /* NOTE: send HTTP 1.1 header */
\r
869 header("Content-Type: {$content_type}; charset={$charset}");
\r
871 /* NOTE: set handler for translating character set */
\r
872 if ( $charset != i18n::get_current_charset() )
\r
874 ob_start(array('i18n', 'convert_handler'));
\r
882 * This function parses a query into an array of expressions that can be passed on to the highlight method
\r
883 * @param string $query
\r
885 function parseHighlight($query)
\r
887 // TODO: add more intelligent splitting logic
\r
889 // get rid of quotes
\r
890 $query = preg_replace('/\'|"/', '', $query);
\r
897 $aHighlight = preg_split('# #', $query);
\r
899 for ( $i = 0; $i < count($aHighlight); $i++ )
\r
901 $aHighlight[$i] = trim($aHighlight[$i]);
\r
903 if ( i18n::strlen($aHighlight[$i]) < 3 )
\r
905 unset($aHighlight[$i]);
\r
909 if ( count($aHighlight) == 1 )
\r
911 return $aHighlight[0];
\r
915 return $aHighlight;
\r
921 * This function gets the blog ID from the blog name
\r
922 * @param string $name
\r
925 function getBlogIDFromName($name)
\r
927 $query = sprintf('SELECT bnumber AS result FROM %s WHERE bshortname=%s', sql_table('blog'), DB::quoteValue($name));
\r
928 return DB::getValue($query);
\r
933 * This function gets the blog name from the blog ID
\r
937 function getBlogNameFromID($id)
\r
939 $query = sprintf('SELECT bname AS result FROM %s WHERE bnumber=%d', sql_table('blog'), intval($id));
\r
940 return DB::getValue($query);
\r
945 * This function gets the blog ID from the item ID
\r
946 * @param int $item_id
\r
949 function getBlogIDFromItemID($item_id)
\r
951 $query = sprintf('SELECT iblog AS result FROM %s WHERE inumber=%d', sql_table('item'), intval($item_id));
\r
952 return DB::getValue($query);
\r
957 * This function gets the blog ID from the comment ID
\r
958 * @param int $comment_id
\r
961 function getBlogIDFromCommentID($comment_id)
\r
963 $query = sprintf('SELECT cblog AS result FROM %s WHERE cnumber=%d', sql_table('comment'), intval($comment_id));
\r
964 return DB::getValue($query);
\r
969 * This function gets the blog ID from the category ID
\r
970 * @param int $category_id
\r
973 function getBlogIDFromCatID($category_id)
\r
975 $query = sprintf('SELECT cblog AS result FROM %s WHERE catid=%d', sql_table('category'), intval($category_id));
\r
976 return DB::getValue($query);
\r
981 * This function gets the category ID from the category name
\r
985 function getCatIDFromName($name)
\r
987 $query = sprintf('SELECT catid AS result FROM %s WHERE cname=%s', sql_table('category'), DB::quoteValue($name));
\r
988 return DB::getValue($query);
\r
993 * This function performs a quick SQL query
\r
995 * @param string $query
\r
998 function quickQuery($query)
\r
1000 $row = DB::getRow($query);
\r
1001 return $row['result'];
\r
1003 function getPluginNameFromPid($pid) {
\r
1004 $query = sprintf('SELECT pfile FROM %s WHERE pid=%d', sql_table('plugin'), intval($pid));
\r
1005 return DB::getValue($query);
\r
1006 // return isset($obj->pfile) ? $obj->pfile : false;
\r
1009 function selector()
\r
1011 global $itemid, $blogid, $memberid, $query, $amount, $archivelist, $maxresults;
\r
1012 global $archive, $skinid, $blog, $memberinfo, $CONF, $member;
\r
1013 global $imagepopup, $catid, $special;
\r
1016 $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');
\r
1017 $action = requestVar('action');
\r
1019 if ( in_array($action, $actionNames) )
\r
1021 global $DIR_LIBS, $errormessage;
\r
1022 include_once($DIR_LIBS . 'ACTION.php');
\r
1023 $a = new Action();
\r
1024 $errorInfo = $a->doAction($action);
\r
1028 $errormessage = $errorInfo['message'];
\r
1032 // show error when headers already sent out
\r
1033 if ( headers_sent() && $CONF['alertOnHeadersSent'] )
\r
1035 // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)
\r
1036 if ( function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') )
\r
1038 headers_sent($hsFile, $hsLine);
\r
1039 $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';
\r
1047 '<p>The page headers have already been sent out' . $extraInfo . '. This could cause Nucleus not to work in the expected way.</p><p>Usually, this is caused by spaces or newlines at the end of the <code>config.php</code> file, at the end of the translation file or at the end of a plugin file. Please check this and try again.</p><p>If you don\'t want to see this error message again, without solving the problem, set <code>$CONF[\'alertOnHeadersSent\']</code> in <code>globalfunctions.php</code> to <code>0</code></p>',
\r
1048 'Page headers already sent'
\r
1053 // make is so ?archivelist without blogname or blogid shows the archivelist
\r
1054 // for the default weblog
\r
1055 if ( serverVar('QUERY_STRING') == 'archivelist' )
\r
1057 $archivelist = $CONF['DefaultBlog'];
\r
1060 // now decide which type of skin we need
\r
1063 // itemid given -> only show that item
\r
1066 if ( !$manager->existsItem($itemid,intval($CONF['allowFuture']),intval($CONF['allowDrafts'])) )
\r
1068 doError(_ERROR_NOSUCHITEM);
\r
1071 global $itemidprev, $itemidnext, $catid, $itemtitlenext, $itemtitleprev;
\r
1073 // 1. get timestamp, blogid and catid for item
\r
1074 $query = 'SELECT itime, iblog, icat FROM %s WHERE inumber=%d';
\r
1075 $query = sprintf($query, sql_table('item'), intval($itemid));
\r
1076 $row = DB::getRow($query);
\r
1078 // if a different blog id has been set through the request or selectBlog(),
\r
1081 if ( $blogid && (intval($blogid) != $row['iblog']) )
\r
1083 doError(_ERROR_NOSUCHITEM);
\r
1086 // if a category has been selected which doesn't match the item, ignore the
\r
1088 if ( ($catid != 0) && ($catid != $row['icat']) )
\r
1093 $blogid = $row['iblog'];
\r
1094 $timestamp = strtotime($row['itime']);
\r
1096 $b =& $manager->getBlog($blogid);
\r
1098 if ( !$b->isValidCategory($catid) )
\r
1100 $query = "SELECT inumber, ititle FROM %s WHERE itime<%s AND idraft=0 AND iblog=%d ORDER BY itime DESC LIMIT 1";
\r
1101 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), intval($blogid));
\r
1105 $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
1106 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), intval($blogid), intval($catid));
\r
1108 $row = DB::getRow($query);
\r
1112 $itemidprev = $row['inumber'];
\r
1113 $itemtitleprev = $row['ititle'];
\r
1116 // get next itemid and title
\r
1117 if ( !$b->isValidCategory($catid) )
\r
1119 $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
1120 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), DB::formatDateTime($b->getCorrectTime()), intval($blogid));
\r
1124 $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
1125 $query = sprintf($query, sql_table('item'), DB::formatDateTime($timestamp), DB::formatDateTime($b->getCorrectTime()), intval($blogid), intval($catid));
\r
1127 $row = DB::getRow($query);
\r
1131 $itemidnext = $row['inumber'];
\r
1132 $itemtitlenext = $row['ititle'];
\r
1135 elseif ( $archive )
\r
1138 $type = 'archive';
\r
1140 // get next and prev month links ...
\r
1141 global $archivenext, $archiveprev, $archivetype, $archivenextexists, $archiveprevexists;
\r
1143 // sql queries for the timestamp of the first and the last published item
\r
1144 $query = sprintf('SELECT UNIX_TIMESTAMP(itime) as result FROM %s WHERE idraft=0 ORDER BY itime ASC', sql_table('item'));
\r
1145 $first_timestamp = DB::getValue($query);
\r
1146 $query = sprintf('SELECT UNIX_TIMESTAMP(itime) as result FROM %s WHERE idraft=0 ORDER BY itime DESC', sql_table('item'));
\r
1147 $last_timestamp = DB::getValue($query);
\r
1149 sscanf($archive, '%d-%d-%d', $y, $m, $d);
\r
1153 $archivetype = _ARCHIVETYPE_DAY;
\r
1154 $t = mktime(0, 0, 0, $m, $d, $y);
\r
1155 // one day has 24 * 60 * 60 = 86400 seconds
\r
1156 $archiveprev = i18n::formatted_datetime('%Y-%m-%d', $t - 86400 );
\r
1157 // check for published items
\r
1158 if ( $t > $first_timestamp )
\r
1160 $archiveprevexists = true;
\r
1164 $archiveprevexists = false;
\r
1169 $archivenext = i18n::formatted_datetime('%Y-%m-%d', $t);
\r
1170 if ( $t < $last_timestamp )
\r
1172 $archivenextexists = true;
\r
1176 $archivenextexists = false;
\r
1179 elseif ( $m == 0 )
\r
1181 $archivetype = _ARCHIVETYPE_YEAR;
\r
1182 $t = mktime(0, 0, 0, 12, 31, $y - 1);
\r
1183 // one day before is in the previous year
\r
1184 $archiveprev = i18n::formatted_datetime('%Y', $t);
\r
1185 if ( $t > $first_timestamp )
\r
1187 $archiveprevexists = true;
\r
1191 $archiveprevexists = false;
\r
1194 // timestamp for the next year
\r
1195 $t = mktime(0, 0, 0, 1, 1, $y + 1);
\r
1196 $archivenext = i18n::formatted_datetime('%Y', $t);
\r
1197 if ( $t < $last_timestamp )
\r
1199 $archivenextexists = true;
\r
1203 $archivenextexists = false;
\r
1208 $archivetype = _ARCHIVETYPE_MONTH;
\r
1209 $t = mktime(0, 0, 0, $m, 1, $y);
\r
1210 // one day before is in the previous month
\r
1211 $archiveprev = i18n::formatted_datetime('%Y-%m', $t - 86400);
\r
1212 if ( $t > $first_timestamp )
\r
1214 $archiveprevexists = true;
\r
1218 $archiveprevexists = false;
\r
1221 // timestamp for the next month
\r
1222 $t = mktime(0, 0, 0, $m+1, 1, $y);
\r
1223 $archivenext = i18n::formatted_datetime('%Y-%m', $t);
\r
1224 if ( $t < $last_timestamp )
\r
1226 $archivenextexists = true;
\r
1230 $archivenextexists = false;
\r
1234 elseif ( $archivelist )
\r
1236 $type = 'archivelist';
\r
1238 if ( is_numeric($archivelist) )
\r
1240 $blogid = intVal($archivelist);
\r
1244 $blogid = getBlogIDFromName($archivelist);
\r
1249 doError(_ERROR_NOSUCHBLOG);
\r
1256 $query = stripslashes($query);
\r
1258 if ( is_numeric($blogid) )
\r
1260 $blogid = intVal($blogid);
\r
1264 $blogid = getBlogIDFromName($blogid);
\r
1269 doError(_ERROR_NOSUCHBLOG);
\r
1272 elseif ( $memberid )
\r
1276 if ( !Member::existsID($memberid) )
\r
1278 doError(_ERROR_NOSUCHMEMBER);
\r
1280 $memberinfo = $manager->getMember($memberid);
\r
1282 elseif ( $imagepopup )
\r
1284 // media object (images etc.)
\r
1285 $type = 'imagepopup';
\r
1287 // TODO: check if media-object exists
\r
1288 // TODO: set some vars?
\r
1292 // show regular index page
\r
1297 // any type of skin with catid
\r
1298 if ( $catid && !$blogid )
\r
1300 $blogid = getBlogIDFromCatID($catid);
\r
1303 // decide which blog should be displayed
\r
1306 $blogid = $CONF['DefaultBlog'];
\r
1309 $b =& $manager->getBlog($blogid);
\r
1310 $blog = $b; // references can't be placed in global variables?
\r
1312 if ( !$blog->isValid )
\r
1314 doError(_ERROR_NOSUCHBLOG);
\r
1317 // set catid if necessary
\r
1320 // check if the category is valid
\r
1321 if ( !$blog->isValidCategory($catid) )
\r
1323 doError(_ERROR_NOSUCHCATEGORY);
\r
1327 $blog->setSelectedCategory($catid);
\r
1331 // decide which skin should be used
\r
1332 if ( $skinid != '' && ($skinid == 0) )
\r
1334 selectSkin($skinid);
\r
1339 $skinid = $blog->getDefaultSkin();
\r
1342 //$special = requestVar('special'); //get at top of file as global
\r
1343 if ( !empty($special) && isValidShortName($special) )
\r
1345 $type = strtolower($special);
\r
1348 $skin = new SKIN($skinid);
\r
1350 if ( !$skin->isValid() )
\r
1352 doError(_ERROR_NOSUCHSKIN);
\r
1355 // set global skinpart variable so can determine quickly what is being parsed from any plugin or phpinclude
\r
1357 $skinpart = $type;
\r
1360 $skin->parse($type);
\r
1362 // check to see we should throw JustPosted event
\r
1363 $blog->checkJustPosted();
\r
1368 * Show error skin with given message. An optional skin-object to use can be given
\r
1370 function doError($msg, $skin = '')
\r
1372 global $errormessage, $CONF, $skinid, $blogid, $manager;
\r
1374 if ( $skin == '' )
\r
1376 if ( Skin::existsID($skinid) )
\r
1380 elseif ( $manager->existsBlogID($blogid) )
\r
1382 $blog =& $manager->getBlog($blogid);
\r
1383 $id = $blog->getDefaultSkin();
\r
1385 elseif ($CONF['DefaultBlog'] )
\r
1387 $blog =& $manager->getBlog($CONF['DefaultBlog']);
\r
1388 $id = $blog->getDefaultSkin();
\r
1392 // this statement should actually never be executed
\r
1393 $id = $CONF['BaseSkin'];
\r
1395 $skin = new Skin($id);
\r
1398 $skinid = $skin->getID();
\r
1399 $errormessage = $msg;
\r
1400 $skin->parse('error');
\r
1404 function getConfig() {
\r
1407 $query = sprintf('SELECT * FROM %s', sql_table('config'));
\r
1408 $res = DB::getResult($query);
\r
1410 foreach ( $res as $row )
\r
1412 $CONF[$row['name']] = $row['value'];
\r
1416 // some checks for names of blogs, categories, templates, members, ...
\r
1417 function isValidShortName($name) {
\r
1419 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
\r
1420 # original eregi: eregi('^[a-z0-9]+$', $name)
\r
1422 return preg_match('#^[a-z0-9]+$#i', $name);
\r
1426 function isValidDisplayName($name) {
\r
1428 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
\r
1429 # original eregi: eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name)
\r
1431 return preg_match('#^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$#i', $name);
\r
1435 function isValidCategoryName($name) {
\r
1439 function isValidTemplateName($name) {
\r
1441 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
\r
1442 # original eregi: eregi('^[a-z0-9/]+$', $name)
\r
1443 // added - and _ to valid characters as of 4.00
\r
1445 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
\r
1449 function isValidSkinName($name) {
\r
1451 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
\r
1452 # original eregi: eregi('^[a-z0-9/]+$', $name);
\r
1453 // added - and _ to valid characters as of 4.00
\r
1455 return preg_match('#^[a-z0-9/_\-]+$#i', $name);
\r
1459 // add and remove linebreaks
\r
1460 function addBreaks($var) {
\r
1461 return nl2br($var);
\r
1464 function removeBreaks($var) {
\r
1465 return preg_replace("/<br \/>([\r\n])/", "$1", $var);
\r
1469 * functions for use in index.php
\r
1471 function selectBlog($shortname) {
\r
1472 global $blogid, $archivelist;
\r
1473 $blogid = getBlogIDFromName($shortname);
\r
1475 // also force archivelist variable, if it is set
\r
1476 if ($archivelist) {
\r
1477 $archivelist = $blogid;
\r
1481 function selectSkin($skinname) {
\r
1483 $skinid = SKIN::getIdFromName($skinname);
\r
1487 * Can take either a category ID or a category name (be aware that
\r
1488 * multiple categories can have the same name)
\r
1490 function selectCategory($cat) {
\r
1492 if (is_numeric($cat) ) {
\r
1493 $catid = intval($cat);
\r
1495 $catid = getCatIDFromName($cat);
\r
1499 function selectItem($id) {
\r
1501 $itemid = intval($id);
\r
1504 function parseFile($filename, $includeMode = 'normal', $includePrefix = '')
\r
1508 if ( !$skinid || !existsID($skinid) )
\r
1510 $skin = new Skin($CONF['BaseSkin']);
\r
1514 $skin = new Skin($skinid);
\r
1517 $oldIncludeMode = Parser::getProperty('IncludeMode');
\r
1518 $oldIncludePrefix = Parser::getProperty('IncludePrefix');
\r
1520 $skin->parse('fileparse', $filename);
\r
1522 Parser::setProperty('IncludeMode', $oldIncludeMode);
\r
1523 Parser::setProperty('IncludePrefix', $oldIncludePrefix);
\r
1529 * Outputs a debug message
\r
1531 function debug($msg) {
\r
1532 echo '<p><b>' . $msg . "</b></p>\n";
\r
1536 function addToLog($level, $msg) {
\r
1537 ActionLog::add($level, $msg);
\r
1540 // shows a link to help file
\r
1541 function help($id) {
\r
1542 echo helpHtml($id);
\r
1545 function helpHtml($id) {
\r
1547 return helplink($id) . '<img src="' . $CONF['AdminURL'] . 'documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" title="' . _HELP_TT . '" /></a>';
\r
1550 function helplink($id) {
\r
1552 return '<a href="' . $CONF['AdminURL'] . 'documentation/help.html#'. $id . '" onclick="if (event && event.preventDefault) event.preventDefault(); return help(this.href);">';
\r
1556 * Includes a PHP file. This method can be called while parsing templates and skins
\r
1558 function includephp($filename) {
\r
1559 // make predefined variables global, so most simple scripts can be used here
\r
1561 // apache (names taken from PHP doc)
\r
1562 global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;
\r
1563 global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;
\r
1564 global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;
\r
1565 global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;
\r
1566 global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;
\r
1567 global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;
\r
1568 global $REQUEST_URI;
\r
1570 // php (taken from PHP doc)
\r
1571 global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;
\r
1572 global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;
\r
1575 global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;
\r
1577 if (@file_exists($filename) ) {
\r
1578 include($filename);
\r
1583 * Checks if a certain plugin exists
\r
1584 * @param string $plug
\r
1587 function checkPlugin($plug) {
\r
1589 global $DIR_PLUGINS;
\r
1591 # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
\r
1592 # original ereg_replace: ereg_replace( '[\\|/]', '', $plug) . '.php')
\r
1593 # important note that '\' must be matched with '\\\\' in preg* expressions
\r
1595 return file_exists($DIR_PLUGINS . preg_replace('#[\\\\|/]#', '', $plug) . '.php');
\r
1602 * @param string $querystr querystring to alter (e.g. foo=1&bar=2&x=y)
\r
1603 * @param string $param name of parameter to change (e.g. 'foo')
\r
1604 * @param string $value New value for that parameter (e.g. 3)
\r
1605 * @result string altered query string (for the examples above: foo=3&bar=2&x=y)
\r
1607 function alterQueryStr($querystr, $param, $value)
\r
1609 $vars = preg_split('#&#', $querystr);
\r
1612 for ( $i = 0; $i < count($vars); $i++ )
\r
1614 $v = preg_split('#=#', $vars[$i]);
\r
1616 if ( $v[0] == $param )
\r
1619 $vars[$i] = implode('=', $v);
\r
1626 $vars[] = "{$param}={$value}";
\r
1628 return ltrim(implode('&', $vars), '&');
\r
1631 // passes one variable as hidden input field (multiple fields for arrays)
\r
1632 // @see passRequestVars in varsx.x.x.php
\r
1633 function passVar($key, $value) {
\r
1635 if (is_array($value) ) {
\r
1636 for ($i = 0; $i < sizeof($value); $i++) {
\r
1637 passVar($key . '[' . $i . ']', $value[$i]);
\r
1643 // other values: do stripslashes if needed
\r
1644 ?><input type="hidden" name="<?php echo Entity::hsc($key)?>" value="<?php echo Entity::hsc(undoMagic($value) )?>" /><?php
\r
1647 function checkVars($aVars) {
\r
1648 global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;
\r
1650 foreach ($aVars as $varName) {
\r
1652 if (phpversion() >= '4.1.0') {
\r
1654 if ( isset($_GET[$varName])
\r
1655 || isset($_POST[$varName])
\r
1656 || isset($_COOKIE[$varName])
\r
1657 || isset($_ENV[$varName])
\r
1658 || isset($_SESSION[$varName])
\r
1659 || isset($_FILES[$varName])
\r
1661 die('Sorry. An error occurred.');
\r
1666 if ( isset($HTTP_GET_VARS[$varName])
\r
1667 || isset($HTTP_POST_VARS[$varName])
\r
1668 || isset($HTTP_COOKIE_VARS[$varName])
\r
1669 || isset($HTTP_ENV_VARS[$varName])
\r
1670 || isset($HTTP_SESSION_VARS[$varName])
\r
1671 || isset($HTTP_POST_FILES[$varName])
\r
1673 die('Sorry. An error occurred.');
\r
1682 * sanitizeParams()
\r
1683 * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.
\r
1689 function sanitizeParams()
\r
1695 // REQUEST_URI of $_SERVER
\r
1696 $str =& $_SERVER["REQUEST_URI"];
\r
1697 serverStringToArray($str, $array, $frontParam);
\r
1698 sanitizeArray($array);
\r
1699 arrayToServerString($array, $frontParam, $str);
\r
1701 // QUERY_STRING of $_SERVER
\r
1702 $str =& $_SERVER["QUERY_STRING"];
\r
1703 serverStringToArray($str, $array, $frontParam);
\r
1704 sanitizeArray($array);
\r
1705 arrayToServerString($array, $frontParam, $str);
\r
1708 convArrayForSanitizing($_GET, $array);
\r
1709 sanitizeArray($array);
\r
1710 revertArrayForSanitizing($array, $_GET);
\r
1712 // $_REQUEST (only GET param)
\r
1713 convArrayForSanitizing($_REQUEST, $array);
\r
1714 sanitizeArray($array);
\r
1715 revertArrayForSanitizing($array, $_REQUEST);
\r
1721 * ticketForPlugin()
\r
1723 * Check ticket when not checked in plugin's admin page
\r
1725 * Also avoid the access to plugin/index.php by guest user.
\r
1727 function ticketForPlugin()
\r
1729 global $CONF, $DIR_PLUGINS, $member, $ticketforplugin;
\r
1732 $ticketforplugin = array();
\r
1733 $ticketforplugin['ticket'] = FALSE;
\r
1735 /* $_SERVER['PATH_TRANSLATED']
\r
1736 * http://www.php.net/manual/en/reserved.variables.server.php
\r
1737 * Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly
\r
1738 * under the Apache 2 SAPI in contrast to the situation in Apache 1,
\r
1739 * where it's set to the same value as the SCRIPT_FILENAME server variable
\r
1740 * when it's not populated by Apache.
\r
1741 * This change was made to comply with the CGI specification
\r
1742 * that PATH_TRANSLATED should only exist if PATH_INFO is defined.
\r
1743 * Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.
\r
1746 /* Check if using plugin's php file. */
\r
1747 $p_translated = serverVar('SCRIPT_FILENAME');
\r
1749 if (!file_exists($p_translated) )
\r
1751 header("HTTP/1.0 404 Not Found");
\r
1755 $p_translated = str_replace('\\', '/', $p_translated);
\r
1756 $d_plugins = str_replace('\\', '/', $DIR_PLUGINS);
\r
1758 // This isn't plugin php file.
\r
1759 if ( i18n::strpos($p_translated, $d_plugins) !== 0 )
\r
1764 // Solve the plugin php file or admin directory
\r
1765 $phppath = i18n::substr($p_translated, i18n::strlen($d_plugins) );
\r
1766 // Remove the first "/" if exists.
\r
1767 $phppath = preg_replace('#^/#', '', $phppath);
\r
1768 // Remove the first "NP_" and the last ".php" if exists.
\r
1769 $path = preg_replace('#^NP_(.*)\.php$#', '$1', $phppath);
\r
1770 // Remove the "/" and beyond.
\r
1771 $path = preg_replace('#^([^/]*)/(.*)$#', '$1', $path);
\r
1773 // Solve the plugin name.
\r
1774 $plugins = array();
\r
1775 $query = sprintf('SELECT pfile FROM %s', sql_table('plugin'));
\r
1776 $res = DB::getResult($query);
\r
1778 foreach ( $res as $row )
\r
1780 $name = i18n::substr($row['pfile'], 3);
\r
1781 $plugins[strtolower($name)] = $name;
\r
1784 $res->closeCursor();
\r
1786 if (array_key_exists($path, $plugins))
\r
1788 $plugin_name = $plugins[$path];
\r
1790 else if (in_array($path, $plugins))
\r
1792 $plugin_name = $path;
\r
1796 header("HTTP/1.0 404 Not Found");
\r
1800 /* Return if not index.php */
\r
1801 if ( ($phppath != strtolower($plugin_name) . '/') && ($phppath != strtolower($plugin_name) . '/index.php') )
\r
1806 /* Exit if not logged in. */
\r
1807 if ( !$member->isLoggedIn() )
\r
1809 exit('You aren\'t logged in.');
\r
1812 global $manager, $DIR_LIBS, $DIR_LOCALES, $HTTP_GET_VARS, $HTTP_POST_VARS;
\r
1814 /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */
\r
1815 if (!($p_translated = serverVar('PATH_TRANSLATED') ) )
\r
1817 $p_translated = serverVar('SCRIPT_FILENAME');
\r
1820 if ($file = @file($p_translated) )
\r
1824 foreach($file as $line)
\r
1826 if (preg_match('/[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]/i', $prevline . $line) )
\r
1831 $prevline = $line;
\r
1835 /* Show a form if not valid ticket */
\r
1836 if ( ( i18n::strpos(serverVar('REQUEST_URI'), '?') !== FALSE || serverVar('QUERY_STRING')
\r
1837 || strtoupper(serverVar('REQUEST_METHOD') ) == 'POST')
\r
1838 && (!$manager->checkTicket() ) )
\r
1840 $oPluginAdmin = new PluginAdmin($plugin_name);
\r
1841 $oPluginAdmin->start();
\r
1842 echo '<p>' . _ERROR_BADTICKET . "</p>\n";
\r
1844 /* Show the form to confirm action */
\r
1845 // PHP 4.0.x support
\r
1846 $get = (isset($_GET) ) ? $_GET : $HTTP_GET_VARS;
\r
1847 $post = (isset($_POST) ) ? $_POST : $HTTP_POST_VARS;
\r
1849 // Resolve URI and QUERY_STRING
\r
1850 if ($uri = serverVar('REQUEST_URI') )
\r
1852 list($uri, $qstring) = preg_split('#\?#', $uri);
\r
1856 if ( !($uri = serverVar('PHP_SELF') ) )
\r
1858 $uri = serverVar('SCRIPT_NAME');
\r
1860 $qstring = serverVar('QUERY_STRING');
\r
1864 $qstring = '?' . $qstring;
\r
1867 echo '<p>' . _SETTINGS_UPDATE . ' : ' . _QMENU_PLUGINS . ' <span style="color:red;">' . Entity::hsc($plugin_name) . "</span> ?</p>\n";
\r
1869 switch(strtoupper(serverVar('REQUEST_METHOD') ) )
\r
1872 echo '<form method="POST" action="'.Entity::hsc($uri.$qstring).'">';
\r
1873 $manager->addTicketHidden();
\r
1874 _addInputTags($post);
\r
1878 echo '<form method="GET" action="'.Entity::hsc($uri).'">';
\r
1879 $manager->addTicketHidden();
\r
1880 _addInputTags($get);
\r
1886 echo '<input type="submit" value="' . _YES . '" /> ';
\r
1887 echo '<input type="button" value="' . _NO . '" onclick="history.back(); return false;" />';
\r
1890 $oPluginAdmin->end();
\r
1894 /* Create new ticket */
\r
1895 $ticket=$manager->addTicketToUrl('');
\r
1896 $ticketforplugin['ticket'] = preg_split($ticket, i18n::strpos($ticket, 'ticket=') + 7);
\r
1900 function _addInputTags(&$keys,$prefix=''){
\r
1901 foreach($keys as $key=>$value){
\r
1902 if ($prefix) $key=$prefix.'['.$key.']';
\r
1903 if (is_array($value)) _addInputTags($value,$key);
\r
1905 if (get_magic_quotes_gpc()) $value=stripslashes($value);
\r
1906 if ($key=='ticket') continue;
\r
1907 echo '<input type="hidden" name="'.Entity::hsc($key).
\r
1908 '" value="'.Entity::hsc($value).'" />'."\n";
\r
1914 * serverStringToArray()
\r
1915 * Convert the server string such as $_SERVER['REQUEST_URI']
\r
1916 * to arry like arry['blogid']=1 and array['page']=2 etc.
\r
1918 * @param string $uri string
\r
1919 * @param string &$query_elements elements of query according to application/x-www-form-urlencoded
\r
1920 * @param string &$hier_part hierarchical part includes path
\r
1923 * RFC 3986: Uniform Resource Identifiers (URI): Generic Syntax
\r
1924 * 3. Syntax Components
\r
1925 * http://www.ietf.org/rfc/rfc3986.txt
\r
1927 * Hypertext Markup Language - 2.0
\r
1928 * 8.2.1. The form-urlencoded Media Type
\r
1929 * http://tools.ietf.org/html/rfc1866#section-8.2.1
\r
1931 * $_SERVER > Language Reference > Predefined Variables > PHP Manual
\r
1932 * http://www.php.net/manual/en/reserved.variables.server.php
\r
1934 function serverStringToArray($uri, &$query_elements, &$hier_part)
\r
1937 $query_elements = array();
\r
1940 // split hierarchical part, e.g. /index.php, query and fragment, e.g. blogid=1&page=2#section1
\r
1941 if ( i18n::strpos($uri, "?") > 0 )
\r
1943 list($hier_part, $query_and_fragment) = preg_split("#\?#", $uri, 2);
\r
1947 $query_and_fragment = $uri;
\r
1951 // If there is no query like blogid=1&page=2, return
\r
1952 if ( i18n::strpos($uri, "=") == FALSE && !i18n::strlen($hier_part) )
\r
1954 $hier_part = $uri;
\r
1958 $query_elements = preg_split("#&#", $query_and_fragment);
\r
1963 * arrayToServerString()
\r
1964 * Convert array like array['blogid'] to server string
\r
1965 * such as $_SERVER['REQUEST_URI']
\r
1967 * @param array $query_elements elements of query according to application/x-www-form-urlencoded
\r
1968 * @param string $hier_part hier-part defined in RFC3986
\r
1969 * @param string &$uri return value
\r
1973 * RFC 3986: Uniform Resource Identifiers (URI): Generic Syntax
\r
1974 * 3. Syntax Components
\r
1975 * http://www.ietf.org/rfc/rfc3986.txt
\r
1977 * Hypertext Markup Language - 2.0
\r
1978 * 8.2.1. The form-urlencoded Media Type
\r
1979 * http://tools.ietf.org/html/rfc1866#section-8.2.1
\r
1981 * $_SERVER > Language Reference > Predefined Variables > PHP Manual
\r
1982 * http://www.php.net/manual/en/reserved.variables.server.php
\r
1984 function arrayToServerString($query_elements, $hier_part, &$uri)
\r
1986 if ( i18n::strpos($uri, "?") !== FALSE )
\r
1988 $uri = $hier_part . "?";
\r
1992 $uri = $hier_part;
\r
1994 if ( count($query_elements) > 0 )
\r
1996 $uri .= implode("&", $query_elements);
\r
2003 * Sanitize array parameters.
\r
2004 * This function checks both key and value.
\r
2005 * - check key if it inclues " (double quote), remove from array
\r
2006 * - check value if it includes \ (escape sequece), remove remaining string
\r
2008 * @param array &$array elements of query according to application/x-www-form-urlencoded
\r
2011 function sanitizeArray(&$array)
\r
2013 $excludeListForSanitization = array('query');
\r
2015 foreach ( $array as $k => $v )
\r
2017 // split to key and value
\r
2018 list($key, $val) = preg_split("#=#", $v, 2);
\r
2019 if ( !isset($val) )
\r
2024 // when magic quotes is on, need to use stripslashes,
\r
2025 // and then addslashes
\r
2026 if ( get_magic_quotes_gpc() )
\r
2028 $val = stripslashes($val);
\r
2031 // note that we must use addslashes here because this function is called before the db connection is made
\r
2032 // and sql_real_escape_string needs a db connection
\r
2033 $val = addslashes($val);
\r
2035 // if $key is included in exclude list, skip this param
\r
2036 if ( !in_array($key, $excludeListForSanitization) )
\r
2039 if ( i18n::strpos($val, '\\') > 0 )
\r
2041 list($val, $tmp) = preg_split('#\\\\#', $val);
\r
2044 // remove control code etc.
\r
2045 $val = strtr($val, "\0\r\n<>'\"", " ");
\r
2048 if ( preg_match('#\"#', $key) > 0 )
\r
2050 unset($array[$k]);
\r
2054 // set sanitized info
\r
2055 $array[$k] = sprintf("%s=%s", $key, $val);
\r
2062 * convArrayForSanitizing()
\r
2063 * Convert array for sanitizeArray function
\r
2065 * @param string $src array to be sanitized
\r
2066 * @param array &$array array to be temporarily stored
\r
2069 function convArrayForSanitizing($src, &$array)
\r
2072 foreach ( $src as $key => $val )
\r
2074 if ( !key_exists($key, $_GET) )
\r
2078 $array[] = sprintf("%s=%s", $key, $val);
\r
2085 * revertArrayForSanitizing()
\r
2086 * Revert array after sanitizeArray function
\r
2088 * @param array $array element of query according to application/x-www-form-urlencoded
\r
2089 * @param array &$dst combination of key and value
\r
2092 function revertArrayForSanitizing($array, &$dst)
\r
2094 foreach ( $array as $v )
\r
2096 list($key, $val) = preg_split("#=#", $v, 2);
\r
2097 $dst[$key] = $val;
\r
2104 * Stops processing the request and redirects to the given URL.
\r
2105 * - no actual contents should have been sent to the output yet
\r
2106 * - the URL will be stripped of illegal or dangerous characters
\r
2108 function redirect($url) {
\r
2109 $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%*]|i', '', $url);
\r
2110 header('Location: ' . $url);
\r
2115 * getBookmarklet()
\r
2116 * Returns the Javascript code for a bookmarklet that works on most modern browsers
\r
2118 * @param integer $blogid ID for weblog
\r
2119 * @return script to call Bookmarklet
\r
2121 function getBookmarklet($blogid, $width=600, $height=500)
\r
2128 . "if ( x.selection )"
\r
2130 . " Q=x.selection.createRange().text;"
\r
2132 . "else if ( y.getSelection )"
\r
2134 . " Q=y.getSelection();"
\r
2136 . "else if ( x.getSelection )"
\r
2138 . " Q=x.getSelection();"
\r
2140 . "wingm = window.open('{$CONF['AdminURL']}bookmarklet.php?blogid={$blogid}"
\r
2141 . " &logtext=' + encodeURIComponent(Q) +"
\r
2142 . " '&loglink=' + encodeURIComponent(x.location.href) +"
\r
2143 . " '&loglinktitle=' + encodeURIComponent(x.title),"
\r
2145 . " 'scrollbars=yes,width={$width},height={$height},left=10,top=10,status=yes,resizable=yes');"
\r
2146 . "wingm.focus();";
\r
2150 // END: functions from the end of file ADMIN.php
\r
2153 * Returns a variable or null if not set
\r
2155 * @param mixed Variable
\r
2156 * @return mixed Variable
\r
2158 function ifset(&$var) {
\r
2159 if (isset($var)) {
\r
2167 * Returns number of subscriber to an event
\r
2170 * @return number of subscriber(s)
\r
2172 function numberOfEventSubscriber($event) {
\r
2173 $query = sprintf('SELECT COUNT(*) as count FROM %s WHERE event=%s', sql_table('plugin_event'), DB::quoteValue($event));
\r
2174 $res = DB::getValue($query);
\r
2179 * sets $special global variable for use in index.php before selector()
\r
2181 * @param String id
\r
2184 function selectSpecialSkinType($id) {
\r
2186 $special = strtolower($id);
\r
2190 * cleans filename of uploaded file for writing to file system
\r
2192 * @param String str
\r
2193 * @return String cleaned filename ready for use
\r
2195 function cleanFileName($str) {
\r
2196 $str = strtolower($str);
\r
2197 $ext_point = i18n::strrpos($str,".");
\r
2198 if ($ext_point===false) return false;
\r
2199 $ext = i18n::substr($str,$ext_point,i18n::strlen($str));
\r
2200 $str = i18n::substr($str,0,$ext_point);
\r
2202 return preg_replace("/[^a-z0-9-]/","_",$str).$ext;
\r
2206 * Centralisation of the functions to send mail
\r
2207 * Deprecated since 4.0:
\r
2208 * Please use functions in NOTIFICATION class instead
\r
2210 function getMailFooter()
\r
2212 NOTIFICATION::get_mail_footer();
\r
2214 function isValidMailAddress($address)
\r
2216 return NOTIFICATION::address_validation($address);
\r
2219 * Centralisation of the functions that deals XML entities
\r
2220 * Deprecated since 4.0:
\r
2221 * Please use Entity::FunctionName(...) instead
\r
2223 function highlight($text, $expression, $highlight)
\r
2225 return Entity::highlight($text, $expression, $highlight);
\r
2227 function shorten($string, $maxlength, $suffix)
\r
2229 return Entity::shorten($string, $maxlength, $suffix);
\r
2231 function stringStripTags ($string)
\r
2233 return Entity::strip_tags($string);
\r
2235 function toAscii($string)
\r
2237 return Entity::anchor_footnoting($string);
\r
2239 function stringToAttribute ($string)
\r
2241 return Entity::hsc($string);
\r
2243 function stringToXML ($string)
\r
2245 return Entity::hen($string);
\r
2247 function encode_desc($data)
\r
2249 return Entity::hen($data);
\r
2252 * Centralisation of the functions that deals with locales
\r
2253 * This functions is based on the old way to deal with languages
\r
2254 * Deprecated since 4.0:
\r
2256 /* NOTE: use i18n::get_current_locale() directly instead of this */
\r
2257 function getLanguageName()
\r
2259 if( ($language = i18n::convert_locale_to_old_language_file_name(i18n::get_current_locale())) === FALSE )
\r
2261 $language ='english';
\r
2265 /* NOTE: this is completely deprecated because generating much warnings */
\r
2266 function selectLanguage($language)
\r
2269 include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');
\r
2273 /* NOTE: use i18n::get_available_locales() directly instead of this */
\r
2274 function checkLanguage($lang)
\r
2276 return ( preg_match('#^(.+)_(.+)_(.+)$#', $lang)
\r
2277 || i18n::convert_old_language_file_name_to_locale($lang) );
\r
2279 /* NOTE: use i18n::formatted_datetime() directly instead of this */
\r
2280 function formatDate($format, $timestamp, $default_format, &$blog)
\r
2282 $offset = date('Z', $timestamp);
\r
2285 $offset += $blog->getTimeOffset() * 3600;
\r
2287 return i18n::formatted_datetime($format, $timestamp, $offset, $default_format);
\r
2290 * NOTE: use DB::formatDateTime() directly instead of this
\r
2293 function mysqldate($timestamp)
\r
2295 return DB::formatDateTime($timestamp);
\r
2298 * Centralisation of the functions that generate links
\r
2299 * Deprecated since 4.0:
\r
2300 * Please use Link::FunctionName(...) instead
\r
2302 function createItemLink($itemid, $extra = '')
\r
2304 return Link::create_item_link($itemid, $extra);
\r
2306 function createMemberLink($memberid, $extra = '')
\r
2308 return Link::create_member_link($memberid, $extra);
\r
2310 function createCategoryLink($catid, $extra = '')
\r
2312 return Link::create_category_link($catid, $extra);
\r
2314 function createArchiveListLink($blogid = '', $extra = '')
\r
2316 return Link::create_archivelist_link($blogid, $extra);
\r
2318 function createArchiveLink($blogid, $archive, $extra = '')
\r
2320 return Link::create_archive_link($blogid, $archive, $extra);
\r
2322 function createBlogidLink($blogid, $params = '')
\r
2324 return Link::create_blogid_link($blogid, $params = '');
\r
2326 function createLink($type, $params)
\r
2328 return Link::create_link($type, $params);
\r
2330 function createBlogLink($url, $params)
\r
2332 return Link::create_blog_link($url, $params);
\r