4 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
5 * Copyright (C) 2002-2007 The Nucleus Group
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 * (see nucleus/documentation/index.html#license for more info)
14 * @license http://nucleuscms.org/license.txt GNU General Public License
15 * @copyright Copyright (C) 2002-2007 The Nucleus Group
16 * @version $Id: globalfunctions.php,v 1.24 2008-02-08 09:31:22 kimitake Exp $
17 * $NucleusJP: globalfunctions.php,v 1.23.2.7 2008/02/05 08:30:08 kimitake Exp $
20 // needed if we include globalfunctions from install.php
21 global $nucleus, $CONF, $DIR_LIBS, $DIR_LANG, $manager, $member;
23 $nucleus['version'] = 'v3.4';
24 $nucleus['codename'] = '';
26 checkVars(array('nucleus', 'CONF', 'DIR_LIBS', 'MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE', 'DIR_LANG', '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'));
30 error_reporting(E_ALL); // report all errors!
32 error_reporting(E_ERROR | E_WARNING | E_PARSE);
36 if (!isset($CONF['Self'])) {
37 $CONF['Self'] = htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES);
41 Indicates when Nucleus should display startup errors. Set to 1 if you want
42 the error enabled (default), false otherwise
45 Displays an error when visiting a public Nucleus page and headers have
46 been sent out to early. This usually indicates an error in either a
47 configuration file or a language file, and could cause Nucleus to
50 Displays an error only when visiting the admin area, and when one or
51 more of the installation files (install.php, install.sql, upgrades/
52 directory) are still on the server.
54 $CONF['alertOnHeadersSent'] = 1;
55 $CONF['alertOnSecurityRisk'] = 1;
56 $CONF['ItemURL'] = $CONF['Self'];
57 $CONF['ArchiveURL'] = $CONF['Self'];
58 $CONF['ArchiveListURL'] = $CONF['Self'];
59 $CONF['MemberURL'] = $CONF['Self'];
60 $CONF['SearchURL'] = $CONF['Self'];
61 $CONF['BlogURL'] = $CONF['Self'];
62 $CONF['CategoryURL'] = $CONF['Self'];
64 // switch URLMode back to normal when $CONF['Self'] ends in .php
65 // this avoids urls like index.php/item/13/index.php/item/15
66 if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {
67 $CONF['URLMode'] = 'normal';
70 if (getNucleusPatchLevel() > 0) {
71 $nucleus['version'] .= '/' . getNucleusPatchLevel();
75 if (!isset($CONF['installscript'])) {
76 $CONF['installscript'] = 0;
79 // we will use postVar, getVar, ... methods instead of HTTP_GET_VARS or _GET
80 if ($CONF['installscript'] != 1) { // vars were already included in install.php
81 if (phpversion() >= '4.1.0') {
82 include_once($DIR_LIBS . 'vars4.1.0.php');
84 include_once($DIR_LIBS . 'vars4.0.6.php');
89 $bLoggingSanitizedResult=0;
90 $bSanitizeAndContinue=0;
92 $orgRequestURI = serverVar('REQUEST_URI');
95 // get all variables that can come from the request and put them in the global scope
96 $blogid = requestVar('blogid');
97 $itemid = intRequestVar('itemid');
98 $catid = intRequestVar('catid');
99 $skinid = requestVar('skinid');
100 $memberid = requestVar('memberid');
101 $archivelist = requestVar('archivelist');
102 $imagepopup = requestVar('imagepopup');
103 $archive = requestVar('archive');
104 $query = requestVar('query');
105 $highlight = requestVar('highlight');
106 $amount = requestVar('amount');
107 $action = requestVar('action');
108 $nextaction = requestVar('nextaction');
109 $maxresults = requestVar('maxresults');
110 $startpos = intRequestVar('startpos');
113 $virtualpath = ((getVar('virtualpath') != null) ? getVar('virtualpath') : serverVar('PATH_INFO'));
115 if (!headers_sent() ) {
116 header('Generator: Nucleus CMS ' . $nucleus['version']);
119 // include core classes that are needed for login & plugin handling
120 include($DIR_LIBS . 'mysql.php');
121 include($DIR_LIBS . 'MEMBER.php');
122 include($DIR_LIBS . 'ACTIONLOG.php');
123 include($DIR_LIBS . 'MANAGER.php');
124 include($DIR_LIBS . 'PLUGIN.php');
126 $manager =& MANAGER::instance();
128 // make sure there's no unnecessary escaping:
129 set_magic_quotes_runtime(0);
132 if (!isset($CONF['UsingAdminArea'])) {
133 $CONF['UsingAdminArea'] = 0;
136 // only needed when updating logs
137 if ($CONF['UsingAdminArea']) {
138 include($DIR_LIBS . 'xmlrpc.inc.php'); // XML-RPC client classes
139 include_once($DIR_LIBS . 'ADMIN.php');
142 // connect to database
146 // logs sanitized result if need
147 if ($orgRequestURI!==serverVar('REQUEST_URI')) {
148 $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";
149 $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');
150 if ($bLoggingSanitizedResult) {
151 addToLog(WARNING, $msg);
153 if (!$bSanitizeAndContinue) {
158 // makes sure database connection gets closed on script termination
159 register_shutdown_function('sql_disconnect');
164 // automatically use simpler toolbar for mozilla
165 if (($CONF['DisableJsTools'] == 0) && strstr(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0') && strstr(serverVar('HTTP_USER_AGENT'), 'Gecko') ) {
166 $CONF['DisableJsTools'] = 2;
169 // login if cookies set
170 $member = new MEMBER();
172 // secure cookie key settings (either 'none', 0, 8, 16, 24, or 32)
173 if (!isset($CONF['secureCookieKey'])) $CONF['secureCookieKey']=24;
174 switch($CONF['secureCookieKey']){
176 $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
179 $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
182 $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
185 $CONF['secureCookieKeyIP']=serverVar('REMOTE_ADDR');
188 $CONF['secureCookieKeyIP']='';
191 // login/logout when required or renew cookies
192 if ($action == 'login') {
193 // Form Authentication
194 $login = postVar('login');
195 $pw = postVar('password');
196 $shared = intPostVar('shared'); // shared computer or not
198 $pw=substr($pw,0,40); // avoid md5 collision by using a long key
200 if ($member->login($login, $pw) ) {
202 $member->newCookieKey();
203 $member->setCookies($shared);
205 if ($CONF['secureCookieKey']!=='none') {
207 $member->setCookieKey(md5($member->getCookieKey().$CONF['secureCookieKeyIP']));
211 // allows direct access to parts of the admin area after logging in
213 $action = $nextaction;
216 $manager->notify('LoginSuccess', array('member' => &$member) );
218 ACTIONLOG::add(INFO, "Login successful for $login (sharedpc=$shared)");
220 // errormessage for [%errordiv%]
221 $errormessage = 'Login failed for ' . $login;
223 $manager->notify('LoginFailed', array('username' => $login) );
224 ACTIONLOG::add(INFO, $errormessage);
228 Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details
230 } elseif (serverVar('PHP_AUTH_USER') && serverVar('PHP_AUTH_PW')) {
231 // HTTP Authentication
232 $login = serverVar('PHP_AUTH_USER');
233 $pw = serverVar('PHP_AUTH_PW');
235 if ($member->login($login, $pw) ) {
236 $manager->notify('LoginSuccess',array('member' => &$member));
237 ACTIONLOG::add(INFO, "HTTP authentication successful for $login");
239 $manager->notify('LoginFailed',array('username' => $login));
240 ACTIONLOG::add(INFO, 'HTTP authentication failed for ' . $login);
242 //Since bad credentials, generate an apropriate error page
243 header("WWW-Authenticate: Basic realm=\"Nucleus CMS {$nucleus['version']}\"");
244 header('HTTP/1.0 401 Unauthorized');
245 echo 'Invalid username or password';
250 } elseif (($action == 'logout') && (!headers_sent() ) && cookieVar($CONF['CookiePrefix'] . 'user') ) {
251 // remove cookies on logout
252 setcookie($CONF['CookiePrefix'] . 'user', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
253 setcookie($CONF['CookiePrefix'] . 'loginkey', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
254 $manager->notify('Logout', array('username' => cookieVar($CONF['CookiePrefix'] . 'user') ) );
255 } elseif (cookieVar($CONF['CookiePrefix'] . 'user') ) {
256 // Cookie Authentication
257 $ck=cookieVar($CONF['CookiePrefix'] . 'loginkey');
259 $ck=substr($ck,0,32); // avoid md5 collision by using a long key
260 if ($CONF['secureCookieKey']!=='none') $ck=md5($ck.$CONF['secureCookieKeyIP']);
261 $res = $member->cookielogin(cookieVar($CONF['CookiePrefix'] . 'user'), $ck );
264 // renew cookies when not on a shared computer
265 if ($res && (cookieVar($CONF['CookiePrefix'] . 'sharedpc') != 1) && (!headers_sent() ) ) {
266 $member->setCookieKey(cookieVar($CONF['CookiePrefix'] . 'loginkey'));
267 $member->setCookies();
272 $manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );
275 // first, let's see if the site is disabled or not. always allow admin area access.
276 if ($CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea']) {
277 redirect($CONF['DisableSiteURL']);
281 // load other classes
282 include($DIR_LIBS . 'PARSER.php');
283 include($DIR_LIBS . 'SKIN.php');
284 include($DIR_LIBS . 'TEMPLATE.php');
285 include($DIR_LIBS . 'BLOG.php');
286 include($DIR_LIBS . 'BODYACTIONS.php');
287 include($DIR_LIBS . 'COMMENTS.php');
288 include($DIR_LIBS . 'COMMENT.php');
289 //include($DIR_LIBS . 'ITEM.php');
290 include($DIR_LIBS . 'NOTIFICATION.php');
291 include($DIR_LIBS . 'BAN.php');
292 include($DIR_LIBS . 'PAGEFACTORY.php');
293 include($DIR_LIBS . 'SEARCH.php');
294 include($DIR_LIBS . 'entity.php');
297 // set lastVisit cookie (if allowed)
298 if (!headers_sent() ) {
299 if ($CONF['LastVisit']) {
300 setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
302 setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
306 // read language file, only after user has been initialized
307 $language = getLanguageName();
308 include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');
310 // check if valid charset
\r
311 if (!encoding_check(false,false,_CHARSET)) {
\r
312 foreach(array($_REQUEST, $_SERVER) as $input) {
\r
313 array_walk($input, 'encoding_check');
\r
318 Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details
320 // To remove after v2.5 is released and language files have been updated.
321 // Including this makes sure that language files for v2.5beta can still be used for v2.5final
322 // without having weird _SETTINGS_EXTAUTH string showing up in the admin area.
323 if (!defined('_MEMBERS_BYPASS'))
325 define('_SETTINGS_EXTAUTH', 'Enable External Authentication');
326 define('_WARNING_EXTAUTH', 'Warning: Enable only if needed.');
327 define('_MEMBERS_BYPASS', 'Use External Authentication');
332 // make sure the archivetype skinvar keeps working when _ARCHIVETYPE_XXX not defined
333 if (!defined('_ARCHIVETYPE_MONTH') ) {
334 define('_ARCHIVETYPE_DAY', 'day');
335 define('_ARCHIVETYPE_MONTH', 'month');
339 if ($CONF['URLMode'] == 'pathinfo') {
340 // initialize keywords if this hasn't been done before
341 if ($CONF['ItemKey'] == '') {
342 $CONF['ItemKey'] = 'item';
345 if ($CONF['ArchiveKey'] == '') {
346 $CONF['ArchiveKey'] = 'archive';
349 if ($CONF['ArchivesKey'] == '') {
350 $CONF['ArchivesKey'] = 'archives';
353 if ($CONF['MemberKey'] == '') {
354 $CONF['MemberKey'] = 'member';
357 if ($CONF['BlogKey'] == '') {
358 $CONF['BlogKey'] = 'blog';
361 if ($CONF['CategoryKey'] == '') {
362 $CONF['CategoryKey'] = 'category';
365 if ($CONF['SpecialskinKey'] == '') {
366 $CONF['SpecialskinKey'] = 'special';
373 'type' => basename(serverVar('SCRIPT_NAME') ), // e.g. item, blog, ...
374 'info' => $virtualpath,
375 'complete' => &$parsed
380 // default implementation
381 $data = explode("/", $virtualpath );
382 for ($i = 0; $i < sizeof($data); $i++) {
384 case $CONF['ItemKey']: // item/1 (blogid)
387 if ($i < sizeof($data) ) {
388 $itemid = intval($data[$i]);
392 case $CONF['ArchivesKey']: // archives/1 (blogid)
395 if ($i < sizeof($data) ) {
396 $archivelist = intval($data[$i]);
400 case $CONF['ArchiveKey']: // two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid)
401 if ((($i + 1) < sizeof($data) ) && (!strstr($data[$i + 1], '-') ) ) {
402 $blogid = intval($data[++$i]);
407 if ($i < sizeof($data) ) {
408 $archive = $data[$i];
412 case 'blogid': // blogid/1
413 case $CONF['BlogKey']: // blog/1
416 if ($i < sizeof($data) ) {
417 $blogid = intval($data[$i]);
421 case $CONF['CategoryKey']: // category/1 (catid)
425 if ($i < sizeof($data) ) {
426 $catid = intval($data[$i]);
430 case $CONF['MemberKey']:
433 if ($i < sizeof($data) ) {
434 $memberid = intval($data[$i]);
438 case $CONF['SpecialskinKey']:
441 if ($i < sizeof($data) ) {
442 $_REQUEST['special'] = $data[$i];
453 function intPostVar($name) {
454 return intval(postVar($name) );
457 function intGetVar($name) {
458 return intval(getVar($name) );
461 function intRequestVar($name) {
462 return intval(requestVar($name) );
465 function intCookieVar($name) {
466 return intval(cookieVar($name) );
470 * returns the currently used version (100 = 1.00, 101 = 1.01, etc...)
472 function getNucleusVersion() {
477 * power users can install patches in between nucleus releases. These patches
478 * usually add new functionality in the plugin API and allow those to
479 * be tested without having to install CVS.
481 function getNucleusPatchLevel() {
486 * Connects to mysql server
488 function sql_connect() {
489 global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_CONN;
491 $MYSQL_CONN = @mysql_connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD) or startUpError('<p>Could not connect to MySQL database.</p>', 'Connect Error');
492 mysql_select_db($MYSQL_DATABASE) or startUpError('<p>Could not select database: ' . mysql_error() . '</p>', 'Connect Error');
498 * returns a prefixed nucleus table name
500 function sql_table($name) {
501 global $MYSQL_PREFIX;
504 return $MYSQL_PREFIX . 'nucleus_' . $name;
506 return 'nucleus_' . $name;
510 function sendContentType($contenttype, $pagetype = '', $charset = _CHARSET) {
511 global $manager, $CONF;
513 if (!headers_sent() ) {
514 // if content type is application/xhtml+xml, only send it to browsers
515 // that can handle it (IE6 cannot). Otherwise, send text/html
517 // v2.5: For admin area pages, keep sending text/html (unless it's a debug version)
518 // application/xhtml+xml still causes too much problems with the javascript implementations
520 // v3.3: ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,
521 // application/xhtml+xml seems to be working, so we're going to use it if we can.
523 // Note: reverted the following function in JP version
528 ($contenttype == 'application/xhtml+xml')
529 && (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') )
531 $contenttype = 'text/html';
536 ($contenttype == 'application/xhtml+xml')
537 && (($CONF['UsingAdminArea'] && !$CONF['debug']) || !stristr(serverVar('HTTP_ACCEPT'),'application/xhtml+xml'))
540 $contenttype = 'text/html';
544 'PreSendContentType',
546 'contentType' => &$contenttype,
547 'charset' => &$charset,
548 'pageType' => $pagetype
552 // strip strange characters
553 $contenttype = preg_replace('|[^a-z0-9-+./]|i', '', $contenttype);
554 $charset = preg_replace('|[^a-z0-9-_]|i', '', $charset);
556 if ($charset != '') {
557 header('Content-Type: ' . $contenttype . '; charset=' . $charset);
559 header('Content-Type: ' . $contenttype);
562 // check if valid charset
\r
563 if (!encoding_check(false,false,$charset)) {
\r
564 foreach(array($_REQUEST, $_SERVER) as $input) {
\r
565 array_walk($input, 'encoding_check');
\r
572 * Errors before the database connection has been made
574 function startUpError($msg, $title) {
575 if (!defined('_CHARSET')) define('_CHARSET','iso-8859-1');
\r
576 header('Content-Type: text/html; charset=' . _CHARSET);
\r
578 <html xmlns="http://www.w3.org/1999/xhtml">
579 <head><meta http-equiv="Content-Type" content="text/html; charset=<?php echo _CHARSET?>" />
\r
580 <title><?php echo htmlspecialchars($title)?></title></head>
582 <h1><?php echo htmlspecialchars($title)?></h1>
590 * disconnects from SQL server
592 function sql_disconnect() {
597 * executes an SQL query
599 function sql_query($query) {
602 $res = mysql_query($query) or print("mySQL error with query $query: " . mysql_error() . '<p />');
608 * Highlights a specific query in a given HTML text (not within HTML tags) and returns it
611 * text to be highlighted
613 * regular expression to be matched (can be an array of expressions as well)
615 * highlight to be used (use \\0 to indicate the matched expression)
618 function highlight($text, $expression, $highlight) {
619 if (!$highlight || !$expression) {
623 if (is_array($expression) && (count($expression) == 0) ) {
627 // add a tag in front (is needed for preg_match_all to work correct)
628 $text = '<!--h-->' . $text;
630 // split the HTML up so we have HTML tags
631 // $matches[0][i] = HTML + text
632 // $matches[1][i] = HTML
633 // $matches[2][i] = text
634 preg_match_all('/(<[^>]+>)([^<>]*)/', $text, $matches);
636 // throw it all together again while applying the highlight to the text pieces
638 for ($i = 0; $i < sizeof($matches[2]); $i++) {
640 $result .= $matches[1][$i];
643 if (is_array($expression) ) {
644 foreach ($expression as $regex) {
646 $matches[2][$i] = @eregi_replace($regex, $highlight, $matches[2][$i]);
650 $result .= $matches[2][$i];
652 $result .= @eregi_replace($expression, $highlight, $matches[2][$i]);
660 * Parses a query into an array of expressions that can be passed on to the highlight method
662 function parseHighlight($query) {
663 // TODO: add more intelligent splitting logic
666 $query = preg_replace('/\'|"/', '', $query);
672 $aHighlight = explode(' ', $query);
674 for ($i = 0; $i < count($aHighlight); $i++) {
675 $aHighlight[$i] = trim($aHighlight[$i]);
677 if (strlen($aHighlight[$i]) < 3) {
678 unset($aHighlight[$i]);
682 if (count($aHighlight) == 1) {
683 return $aHighlight[0];
690 * Checks if email address is valid
692 function isValidMailAddress($address) {
693 if (preg_match('/^[a-zA-Z+0-9\._-]+@[a-zA-Z0-9\._-]+\.[A-Za-z]{2,5}$/', $address)) {
701 // some helper functions
702 function getBlogIDFromName($name) {
703 return quickQuery('SELECT bnumber as result FROM ' . sql_table('blog') . ' WHERE bshortname="' . addslashes($name) . '"');
706 function getBlogNameFromID($id) {
707 return quickQuery('SELECT bname as result FROM ' . sql_table('blog') . ' WHERE bnumber=' . intval($id) );
710 function getBlogIDFromItemID($itemid) {
711 return quickQuery('SELECT iblog as result FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid) );
714 function getBlogIDFromCommentID($commentid) {
715 return quickQuery('SELECT cblog as result FROM ' . sql_table('comment') . ' WHERE cnumber=' . intval($commentid) );
718 function getBlogIDFromCatID($catid) {
719 return quickQuery('SELECT cblog as result FROM ' . sql_table('category') . ' WHERE catid=' . intval($catid) );
722 function getCatIDFromName($name) {
723 return quickQuery('SELECT catid as result FROM ' . sql_table('category') . ' WHERE cname="' . addslashes($name) . '"');
726 function quickQuery($q) {
727 $res = sql_query($q);
728 $obj = mysql_fetch_object($res);
732 function getPluginNameFromPid($pid) {
733 $res = sql_query('SELECT pfile FROM ' . sql_table('plugin') . ' WHERE pid=' . intval($pid) );
734 $obj = mysql_fetch_object($res);
738 function selector() {
739 global $itemid, $blogid, $memberid, $query, $amount, $archivelist, $maxresults;
740 global $archive, $skinid, $blog, $memberinfo, $CONF, $member;
741 global $imagepopup, $catid;
744 $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');
745 $action = requestVar('action');
747 if (in_array($action, $actionNames) ) {
748 global $DIR_LIBS, $errormessage;
749 include_once($DIR_LIBS . 'ACTION.php');
751 $errorInfo = $a->doAction($action);
754 $errormessage = $errorInfo['message'];
758 // show error when headers already sent out
759 if (headers_sent() && $CONF['alertOnHeadersSent']) {
761 // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)
762 if (function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') ) {
763 headers_sent($hsFile, $hsLine);
764 $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';
770 '<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 language 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>',
771 'Page headers already sent'
776 // make is so ?archivelist without blogname or blogid shows the archivelist
777 // for the default weblog
778 if (serverVar('QUERY_STRING') == 'archivelist') {
779 $archivelist = $CONF['DefaultBlog'];
782 // now decide which type of skin we need
784 // itemid given -> only show that item
787 if (!$manager->existsItem($itemid,0,0) ) {
788 doError(_ERROR_NOSUCHITEM);
791 global $itemidprev, $itemidnext, $catid, $itemtitlenext, $itemtitleprev;
793 // 1. get timestamp, blogid and catid for item
794 $query = 'SELECT itime, iblog, icat FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid);
795 $res = sql_query($query);
796 $obj = mysql_fetch_object($res);
798 // if a different blog id has been set through the request or selectBlog(),
800 // if ($blogid && (intval($blogid) != $obj->iblog) ) {
801 // doError(_ERROR_NOSUCHITEM);
803 if ($blogid && (intval($blogid) != $obj->iblog) ) {
804 if (!headers_sent()) {
805 $b =& $manager->getBlog($obj->iblog);
806 $CONF['ItemURL'] = $b->getURL();
807 if ($CONF['URLMode'] == 'pathinfo' and substr($CONF['ItemURL'],-1) == '/')
808 $CONF['ItemURL'] = substr($CONF['ItemURL'], 0, -1);
809 $correctURL = createItemLink($itemid, '');
810 redirect($correctURL);
813 doError(_ERROR_NOSUCHITEM);
817 // if a category has been selected which doesn't match the item, ignore the
819 if (($catid != 0) && ($catid != $obj->icat) ) {
823 $blogid = $obj->iblog;
824 $timestamp = strtotime($obj->itime);
826 $b =& $manager->getBlog($blogid);
828 if ($b->isValidCategory($catid) ) {
829 $catextra = ' and icat=' . $catid;
832 // get previous itemid and title
833 $query = 'SELECT inumber, ititle FROM ' . sql_table('item') . ' WHERE itime<' . mysqldate($timestamp) . ' and idraft=0 and iblog=' . $blogid . $catextra . ' ORDER BY itime DESC LIMIT 1';
834 $res = sql_query($query);
836 $obj = mysql_fetch_object($res);
839 $itemidprev = $obj->inumber;
840 $itemtitleprev = $obj->ititle;
843 // get next itemid and title
844 $query = 'SELECT inumber, ititle FROM ' . sql_table('item') . ' WHERE itime>' . mysqldate($timestamp) . ' and itime <= ' . mysqldate($b->getCorrectTime()) . ' and idraft=0 and iblog=' . $blogid . $catextra . ' ORDER BY itime ASC LIMIT 1';
845 $res = sql_query($query);
847 $obj = mysql_fetch_object($res);
850 $itemidnext = $obj->inumber;
851 $itemtitlenext = $obj->ititle;
854 } elseif ($archive) {
858 // get next and prev month links ...
859 global $archivenext, $archiveprev, $archivetype, $archivenextexists, $archiveprevexists;
861 // sql queries for the timestamp of the first and the last published item
862 $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 AND iblog=".(int)($blogid ? $blogid : $CONF['DefaultBlog'])." ORDER BY itime ASC";
863 $first_timestamp=quickQuery ($query);
864 $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 AND iblog=".(int)($blogid ? $blogid : $CONF['DefaultBlog'])." ORDER BY itime DESC";
865 $last_timestamp=quickQuery ($query);
867 sscanf($archive, '%d-%d-%d', $y, $m, $d);
870 $archivetype = _ARCHIVETYPE_DAY;
871 $t = mktime(0, 0, 0, $m, $d, $y);
872 // one day has 24 * 60 * 60 = 86400 seconds
873 $archiveprev = strftime('%Y-%m-%d', $t - 86400 );
874 // check for published items
875 if ($t > $first_timestamp) {
876 $archiveprevexists = true;
879 $archiveprevexists = false;
884 $archivenext = strftime('%Y-%m-%d', $t);
885 if ($t < $last_timestamp) {
886 $archivenextexists = true;
889 $archivenextexists = false;
893 $archivetype = _ARCHIVETYPE_MONTH;
894 $t = mktime(0, 0, 0, $m, 1, $y);
895 // one day before is in the previous month
896 $archiveprev = strftime('%Y-%m', $t - 86400);
897 if ($t > $first_timestamp) {
898 $archiveprevexists = true;
901 $archiveprevexists = false;
904 // timestamp for the next month
905 $t = mktime(0, 0, 0, $m+1, 1, $y);
906 $archivenext = strftime('%Y-%m', $t);
907 if ($t < $last_timestamp) {
908 $archivenextexists = true;
911 $archivenextexists = false;
915 } elseif ($archivelist) {
916 $type = 'archivelist';
918 if (is_numeric($archivelist)) {
919 $blogid = intVal($archivelist);
921 $blogid = getBlogIDFromName($archivelist);
925 doError(_ERROR_NOSUCHBLOG);
931 $query = stripslashes($query);
932 if(preg_match("/^(\xA1{2}|\xe3\x80{2}|\x20)+$/",$query)){
935 $order = (_CHARSET == 'EUC-JP') ? 'EUC-JP, UTF-8,' : 'UTF-8, EUC-JP,';
936 $query = mb_convert_encoding($query, _CHARSET, $order.' JIS, SJIS, ASCII');
937 if (is_numeric($blogid)) {
938 $blogid = intVal($blogid);
940 $blogid = getBlogIDFromName($blogid);
944 doError(_ERROR_NOSUCHBLOG);
947 } elseif ($memberid) {
950 if (!MEMBER::existsID($memberid) ) {
951 doError(_ERROR_NOSUCHMEMBER);
954 $memberinfo = $manager->getMember($memberid);
956 } elseif ($imagepopup) {
957 // media object (images etc.)
958 $type = 'imagepopup';
960 // TODO: check if media-object exists
961 // TODO: set some vars?
963 // show regular index page
968 // decide which blog should be displayed
970 $blogid = $CONF['DefaultBlog'];
973 $b =& $manager->getBlog($blogid);
974 $blog = $b; // references can't be placed in global variables?
976 if (!$blog->isValid) {
977 doError(_ERROR_NOSUCHBLOG);
980 // set catid if necessary
982 $blog->setSelectedCategory($catid);
985 // decide which skin should be used
986 if ($skinid != '' && ($skinid == 0) ) {
991 $skinid = $blog->getDefaultSkin();
994 $special = requestVar('special');
995 if (!empty($special) && isValidShortName($special)) {
996 $type = strtolower($special);
999 $skin = new SKIN($skinid);
1001 if (!$skin->isValid) {
1002 doError(_ERROR_NOSUCHSKIN);
1006 $skin->parse($type);
1008 // check to see we should throw JustPosted event
1009 $blog->checkJustPosted();
1013 * Show error skin with given message. An optional skin-object to use can be given
1015 function doError($msg, $skin = '') {
1016 global $errormessage, $CONF, $skinid, $blogid, $manager;
1020 if (SKIN::existsID($skinid) ) {
1021 $skin = new SKIN($skinid);
1022 } elseif ($manager->existsBlogID($blogid) ) {
1023 $blog =& $manager->getBlog($blogid);
1024 $skin = new SKIN($blog->getDefaultSkin() );
1025 } elseif ($CONF['DefaultBlog']) {
1026 $blog =& $manager->getBlog($CONF['DefaultBlog']);
1027 $skin = new SKIN($blog->getDefaultSkin() );
1029 // this statement should actually never be executed
1030 $skin = new SKIN($CONF['BaseSkin']);
1035 $errormessage = $msg;
1036 $skin->parse('error');
1040 function getConfig() {
1043 $query = 'SELECT * FROM ' . sql_table('config');
1044 $res = sql_query($query);
1046 while ($obj = mysql_fetch_object($res) ) {
1047 $CONF[$obj->name] = $obj->value;
1051 // some checks for names of blogs, categories, templates, members, ...
1052 function isValidShortName($name) {
1053 return eregi('^[a-z0-9]+$', $name);
1056 function isValidDisplayName($name) {
1057 return eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name);
1060 function isValidCategoryName($name) {
1064 function isValidTemplateName($name) {
1065 return eregi('^[a-z0-9/]+$', $name);
1068 function isValidSkinName($name) {
1069 return eregi('^[a-z0-9/]+$', $name);
1072 // add and remove linebreaks
1073 function addBreaks($var) {
1077 function removeBreaks($var) {
1078 return preg_replace("/<br \/>([\r\n])/", "$1", $var);
1081 // shortens a text string to maxlength ($toadd) is what needs to be added
1082 // at the end (end length is <= $maxlength)
1083 function shorten($text, $maxlength, $toadd) {
1084 // 1. remove entities...
1085 // $trans = get_html_translation_table(HTML_ENTITIES);
1086 $trans = get_html_translation_table(HTML_SPECIALCHARS); // for Japanese
1087 $trans = array_flip($trans);
1088 $text = strtr($text, $trans);
1090 // 2. the actual shortening
1091 if (strlen($text) > $maxlength)
1092 $text = mb_strimwidth($text, 0, $maxlength, $toadd, _CHARSET);
1097 * Converts a unix timestamp to a mysql DATETIME format, and places
1100 function mysqldate($timestamp) {
1101 return '"' . date('Y-m-d H:i:s', $timestamp) . '"';
1105 * functions for use in index.php
1107 function selectBlog($shortname) {
1108 global $blogid, $archivelist;
1109 $blogid = getBlogIDFromName($shortname);
1111 // also force archivelist variable, if it is set
1113 $archivelist = $blogid;
1117 function selectSkin($skinname) {
1119 $skinid = SKIN::getIdFromName($skinname);
1123 * Can take either a category ID or a category name (be aware that
1124 * multiple categories can have the same name)
1126 function selectCategory($cat) {
1128 if (is_numeric($cat) ) {
1129 $catid = intval($cat);
1131 $catid = getCatIDFromName($cat);
1135 function selectItem($id) {
1137 $itemid = intval($id);
1140 // force the use of a language file (warning: can cause warnings)
1141 function selectLanguage($language) {
1143 include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');
1146 function parseFile($filename, $includeMode = 'normal', $includePrefix = '') {
1147 $handler = new ACTIONS('fileparser');
1148 $parser = new PARSER(SKIN::getAllowedActionsForType('fileparser'), $handler);
1149 $handler->parser =& $parser;
1151 // set IncludeMode properties of parser
1152 PARSER::setProperty('IncludeMode', $includeMode);
1153 PARSER::setProperty('IncludePrefix', $includePrefix);
1155 if (!file_exists($filename) ) {
1156 doError('A file is missing');
1159 $fsize = filesize($filename);
1166 $fd = fopen ($filename, 'r');
1167 $contents = fread ($fd, $fsize);
1170 // parse file contents
1171 $parser->parse($contents);
1175 * Outputs a debug message
1177 function debug($msg) {
1178 echo '<p><b>' . $msg . "</b></p>\n";
1182 function addToLog($level, $msg) {
1183 ACTIONLOG::add($level, $msg);
1186 // shows a link to help file
1187 function help($id) {
1191 function helpHtml($id) {
1192 return helplink($id) . '<img src="documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" /></a>';
1195 function helplink($id) {
1196 return '<a href="documentation/help.html#'. $id . '" onclick="if (event && event.preventDefault) event.preventDefault(); return help(this.href);">';
1199 function getMailFooter() {
1200 $message = "\n\n-----------------------------";
1201 $message .= "\n Powered by Nucleus CMS";
1202 $message .= "\n(http://www.nucleuscms.org/)";
1207 * Returns the name of the language to use
1208 * preference priority: member - site
1209 * defaults to english when no good language found
1211 * checks if file exists, etc...
1213 function getLanguageName() {
1214 global $CONF, $member;
1216 if ($member && $member->isLoggedIn() ) {
1217 // try to use members language
1218 $memlang = $member->getLanguage();
1220 if (($memlang != '') && (checkLanguage($memlang) ) ) {
1225 // use default language
1226 if (checkLanguage($CONF['Language']) ) {
1227 return $CONF['Language'];
1234 * Includes a PHP file. This method can be called while parsing templates and skins
1236 function includephp($filename) {
1237 // make predefined variables global, so most simple scripts can be used here
1239 // apache (names taken from PHP doc)
1240 global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;
1241 global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;
1242 global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;
1243 global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;
1244 global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;
1245 global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;
1246 global $REQUEST_URI;
1248 // php (taken from PHP doc)
1249 global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;
1250 global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;
1253 global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;
1255 if (@file_exists($filename) ) {
1261 * Checks if a certain language/plugin exists
1263 function checkLanguage($lang) {
1265 return file_exists($DIR_LANG . ereg_replace( '[\\|/]', '', $lang) . '.php');
1268 function checkPlugin($plug) {
1269 global $DIR_PLUGINS;
1270 return file_exists($DIR_PLUGINS . ereg_replace( '[\\|/]', '', $plug) . '.php');
1274 * Centralisation of the functions that generate links
1276 function createItemLink($itemid, $extra = '') {
1277 return createLink('item', array('itemid' => $itemid, 'extra' => $extra) );
1280 function createMemberLink($memberid, $extra = '') {
1281 return createLink('member', array('memberid' => $memberid, 'extra' => $extra) );
1284 function createCategoryLink($catid, $extra = '') {
1285 return createLink('category', array('catid' => $catid, 'extra' => $extra) );
1288 function createArchiveListLink($blogid = '', $extra = '') {
1289 return createLink('archivelist', array('blogid' => $blogid, 'extra' => $extra) );
1292 function createArchiveLink($blogid, $archive, $extra = '') {
1293 return createLink('archive', array('blogid' => $blogid, 'archive' => $archive, 'extra' => $extra) );
1296 function createBlogidLink($blogid, $params = '') {
1297 return createLink('blog', array('blogid' => $blogid, 'extra' => $params) );
1300 function createLink($type, $params) {
1301 global $manager, $CONF;
1304 $usePathInfo = ($CONF['URLMode'] == 'pathinfo');
1306 // ask plugins first
1314 'params' => $params,
1315 'completed' => &$created,
1321 // if a plugin created the URL, return it
1326 // default implementation
1330 $url = $CONF['ItemURL'] . '/' . $CONF['ItemKey'] . '/' . $params['itemid'];
1332 $url = $CONF['ItemURL'] . '?itemid=' . $params['itemid'];
1338 $url = $CONF['MemberURL'] . '/' . $CONF['MemberKey'] . '/' . $params['memberid'];
1340 $url = $CONF['MemberURL'] . '?memberid=' . $params['memberid'];
1346 $url = $CONF['CategoryURL'] . '/' . $CONF['CategoryKey'] . '/' . $params['catid'];
1348 $url = $CONF['CategoryURL'] . '?catid=' . $params['catid'];
1353 if (!$params['blogid']) {
1354 $params['blogid'] = $CONF['DefaultBlog'];
1358 $url = $CONF['ArchiveListURL'] . '/' . $CONF['ArchivesKey'] . '/' . $params['blogid'];
1360 $url = $CONF['ArchiveListURL'] . '?archivelist=' . $params['blogid'];
1366 $url = $CONF['ArchiveURL'] . '/' . $CONF['ArchiveKey'] . '/'.$params['blogid'].'/' . $params['archive'];
1368 $url = $CONF['ArchiveURL'] . '?blogid='.$params['blogid'].'&archive=' . $params['archive'];
1374 $url = $CONF['BlogURL'] . '/' . $CONF['BlogKey'] . '/' . $params['blogid'];
1376 $url = $CONF['BlogURL'] . '?blogid=' . $params['blogid'];
1381 return addLinkParams($url, (isset($params['extra'])? $params['extra'] : null));
1384 function createBlogLink($url, $params) {
1386 if ($CONF['URLMode'] == 'normal') {
1387 if (strpos($url, '?') === FALSE && is_array($params)) {
1388 $fParam = reset($params);
1389 $fKey = key($params);
1390 array_shift($params);
1391 $url .= '?' . $fKey . '=' . $fParam;
1393 } elseif ($CONF['URLMode'] == 'pathinfo' && substr($url, -1) == '/') {
1394 $url = substr($url, 0, -1);
1396 return addLinkParams($url, $params);
1399 function addLinkParams($link, $params) {
1402 if (is_array($params) ) {
1404 if ($CONF['URLMode'] == 'pathinfo') {
1406 foreach ($params as $param => $value) {
1407 $link .= '/' . $param . '/' . urlencode($value);
1412 foreach ($params as $param => $value) {
1413 $link .= '&' . $param . '=' . urlencode($value);
1424 * querystring to alter (e.g. foo=1&bar=2&x=y)
1426 * name of parameter to change (e.g. 'foo')
1428 * New value for that parameter (e.g. 3)
1430 * altered query string (for the examples above: foo=3&bar=2&x=y)
1432 function alterQueryStr($querystr, $param, $value) {
1433 $vars = explode('&', $querystr);
1436 for ($i = 0; $i < count($vars); $i++) {
1437 $v = explode('=', $vars[$i]);
1439 if ($v[0] == $param) {
1441 $vars[$i] = implode('=', $v);
1448 $vars[] = $param . '=' . $value;
1451 return ltrim(implode('&', $vars), '&');
1454 // passes one variable as hidden input field (multiple fields for arrays)
1455 // @see passRequestVars in varsx.x.x.php
1456 function passVar($key, $value) {
1458 if (is_array($value) ) {
1459 for ($i = 0; $i < sizeof($value); $i++) {
1460 passVar($key . '[' . $i . ']', $value[$i]);
1466 // other values: do stripslashes if needed
1467 ?><input type="hidden" name="<?php echo htmlspecialchars($key)?>" value="<?php echo htmlspecialchars(undoMagic($value) )?>" /><?php
1471 Date format functions (to be used from [%date(..)%] skinvars
1473 function formatDate($format, $timestamp, $defaultFormat, &$blog) {
1474 // apply blog offset (#42)
1475 $boffset = $blog ? $blog->getTimeOffset() * 3600 : 0;
1476 $offset = date('Z', $timestamp) + $boffset;
1487 $tz .= sprintf("%02d%02d", floor($offset / 3600), round(($offset % 3600) / 60) );
1488 return date('D, j M Y H:i:s ', $timestamp) . $tz;
1491 $timestamp -= $offset;
1492 return date('D, j M Y H:i:s ', $timestamp) . 'GMT';
1495 $timestamp -= $offset;
1496 return date('Y-m-d\TH:i:s\Z', $timestamp);
1506 $tz .= sprintf("%02d:%02d", floor($offset / 3600), round(($offset % 3600) / 60) );
1507 return date('Y-m-d\TH:i:s', $timestamp) . $tz;
1510 return strftime($format ? $format : $defaultFormat, $timestamp);
1514 function encoding_check($val, $key, $encoding=false, $exclude=false) {
\r
1516 When 3rd argument is set, return if checked already.
\r
1517 When 4th argument is set, set the excluded key(s).
\r
1519 static $search=false, $checked=array(), $excludes=array();
\r
1520 if ($exclude!==false) {
\r
1521 if (is_array($exclude)) {
\r
1522 foreach($exclude as $v) $excludes[$v]=true;
\r
1523 } else $excludes[$excludes]=true;
\r
1526 if ($encoding!==false) {
\r
1527 switch($encoding=strtolower($encoding)){
\r
1529 $search='/^([\x00-\x7F]+'.
\r
1530 '|[\xC2-\xDF][\x80-\xBF]'.
\r
1531 '|[\xE0-\xEF][\x80-\xBF][\x80-\xBF]'.
\r
1532 '|[\xF0-\xF7][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.
\r
1533 '|[\xF8-\xFB][\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.
\r
1534 '|[\xFC-\xFD][\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF])*/';
\r
1537 $search='/^([\x00-\x7F]+'.
\r
1538 '|[\x8E][\xA0-\xDF]'.
\r
1539 '|[\x8F]?[\xA1-\xFE][\xA1-\xFE])*/';
\r
1542 $search='/^([\x00-\x7F]+'.
\r
1543 '|[\xA1-\xF7][\xA1-\xFE])*/';
\r
1546 // Note that shift_jis is only supported for output.
\r
1547 // Using shift_jis in DB is prohibited.
\r
1548 $search='/^([\x00-\x7F\xA1-\xDF]+'.
\r
1549 '|[\x81-\x9F\xE0-\xFC][\x40-\xFC])*/';
\r
1553 if (preg_match('/^iso\-8859\-[0-9]{1,2}$/',$encoding)) break;
\r
1554 if (preg_match('/^windows\-125[0-8]$/',$encoding)) break;
\r
1555 startUpError('<p>Unknown or non-supported encoding.</p>', 'Encoding Error');
\r
1558 if (isset($checked[$encoding])) return true; // Already checked.
\r
1559 $checked[$encoding]=true;
\r
1561 if ($key===false) return false; // Not yet checked.
\r
1562 if ($search===false) return true; // non-multibyte encoding
\r
1563 if (isset($excludes[$key])) return true; // This key isn't checked.
\r
1564 if (is_array($val)) {
\r
1565 array_walk($val, 'encoding_check');
\r
1567 preg_match($search,$val,$m);
\r
1568 $val2 = (string)$m[0];
\r
1569 if (!($val2 === (string)$val)) {
\r
1570 startUpError('<p>Invalid input.</p>', 'Input Error');
\r
1574 preg_match($search,$key,$m);
\r
1575 $key2 = (string)$m[0];
\r
1576 if (!($key2 === (string)$key)) {
\r
1577 startUpError('<p>Invalid input.</p>', 'Input Error');
\r
1583 function checkVars($aVars) {
1584 global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;
1586 foreach ($aVars as $varName) {
1588 if (phpversion() >= '4.1.0') {
1590 if ( isset($_GET[$varName])
1591 || isset($_POST[$varName])
1592 || isset($_COOKIE[$varName])
1593 || isset($_ENV[$varName])
1594 || isset($_SESSION[$varName])
1595 || isset($_FILES[$varName])
1597 die('Sorry. An error occurred.');
1602 if ( isset($HTTP_GET_VARS[$varName])
1603 || isset($HTTP_POST_VARS[$varName])
1604 || isset($HTTP_COOKIE_VARS[$varName])
1605 || isset($HTTP_ENV_VARS[$varName])
1606 || isset($HTTP_SESSION_VARS[$varName])
1607 || isset($HTTP_POST_FILES[$varName])
1609 die('Sorry. An error occurred.');
1618 * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.
1621 function sanitizeParams()
1623 global $HTTP_SERVER_VARS;
1629 // REQUEST_URI of $HTTP_SERVER_VARS
1630 $str =& $HTTP_SERVER_VARS["REQUEST_URI"];
1631 serverStringToArray($str, $array, $frontParam);
1632 sanitizeArray($array);
1633 arrayToServerString($array, $frontParam, $str);
1635 // QUERY_STRING of $HTTP_SERVER_VARS
1636 $str =& $HTTP_SERVER_VARS["QUERY_STRING"];
1637 serverStringToArray($str, $array, $frontParam);
1638 sanitizeArray($array);
1639 arrayToServerString($array, $frontParam, $str);
1641 if (phpversion() >= '4.1.0') {
1642 // REQUEST_URI of $_SERVER
1643 $str =& $_SERVER["REQUEST_URI"];
1644 serverStringToArray($str, $array, $frontParam);
1645 sanitizeArray($array);
1646 arrayToServerString($array, $frontParam, $str);
1648 // QUERY_STRING of $_SERVER
1649 $str =& $_SERVER["QUERY_STRING"];
1650 serverStringToArray($str, $array, $frontParam);
1651 sanitizeArray($array);
1652 arrayToServerString($array, $frontParam, $str);
1656 convArrayForSanitizing($_GET, $array);
1657 sanitizeArray($array);
1658 revertArrayForSanitizing($array, $_GET);
1660 // $_REQUEST (only GET param)
1661 convArrayForSanitizing($_REQUEST, $array);
1662 sanitizeArray($array);
1663 revertArrayForSanitizing($array, $_REQUEST);
1667 * Check ticket when not checked in plugin's admin page
1669 * Also avoid the access to plugin/index.php by guest user.
1671 function ticketForPlugin(){
1672 global $CONF,$DIR_PLUGINS,$member,$ticketforplugin;
1675 $ticketforplugin=array();
1676 $ticketforplugin['ticket']=false;
1678 /* Check if using plugin's php file. */
1679 if ($p_translated=serverVar('PATH_TRANSLATED')) {
1680 if (!file_exists($p_translated)) $p_translated='';
1682 if (!$p_translated) {
1683 $p_translated=serverVar('SCRIPT_FILENAME');
1684 if (!file_exists($p_translated)) {
1685 header("HTTP/1.0 404 Not Found");
1689 $p_translated=str_replace('\\','/',$p_translated);
1690 $d_plugins=str_replace('\\','/',$DIR_PLUGINS);
1691 if (strpos($p_translated,$d_plugins)!==0) return;// This isn't plugin php file.
1693 /* Solve the plugin php file or admin directory */
1694 $phppath=substr($p_translated,strlen($d_plugins));
1695 $phppath=preg_replace('!^/!','',$phppath);// Remove the first "/" if exists.
1696 $path=preg_replace('/^NP_(.*)\.php$/','$1',$phppath); // Remove the first "NP_" and the last ".php" if exists.
1697 $path=preg_replace('!^([^/]*)/(.*)$!','$1',$path); // Remove the "/" and beyond.
1699 /* Solve the plugin name. */
1701 $query='SELECT pfile FROM '.sql_table('plugin');
1702 $res=sql_query($query);
1703 while($row=mysql_fetch_row($res)) {
1704 $name=substr($row[0],3);
1705 $plugins[strtolower($name)]=$name;
1707 mysql_free_result($res);
1708 if ($plugins[$path]) $plugin_name=$plugins[$path];
1709 else if (in_array($path,$plugins)) $plugin_name=$path;
1711 header("HTTP/1.0 404 Not Found");
1715 /* Return if not index.php */
1716 if ( $phppath!=strtolower($plugin_name).'/'
1717 && $phppath!=strtolower($plugin_name).'/index.php' ) return;
1719 /* Exit if not logged in. */
1720 if ( !$member->isLoggedIn() ) exit("You aren't logged in.");
1722 global $manager,$DIR_LIBS,$DIR_LANG,$HTTP_GET_VARS,$HTTP_POST_VARS;
1724 /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */
1725 if (!($p_translated=serverVar('PATH_TRANSLATED'))) $p_translated=serverVar('SCRIPT_FILENAME');
1726 if ($file=@file($p_translated)) {
1728 foreach($file as $line) {
1729 if (preg_match('/[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]/i',$prevline.$line)) return;
1734 /* Show a form if not valid ticket */
1735 if ( ( strstr(serverVar('REQUEST_URI'),'?') || serverVar('QUERY_STRING')
1736 || strtoupper(serverVar('REQUEST_METHOD'))=='POST' )
1737 && (!$manager->checkTicket()) ){
1739 if (!class_exists('PluginAdmin')) {
1740 $language = getLanguageName();
1741 include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');
1742 include($DIR_LIBS . 'PLUGINADMIN.php');
1744 if (!(function_exists('mb_strimwidth') || extension_loaded('mbstring'))) {
1745 if (file_exists($DIR_LIBS.'mb_emulator/mb-emulator.php')) {
1746 global $mbemu_internals;
1747 include_once($DIR_LIBS.'mb_emulator/mb-emulator.php');
1750 $oPluginAdmin = new PluginAdmin($plugin_name);
1751 $oPluginAdmin->start();
1752 echo '<p>' . _ERROR_BADTICKET . "</p>\n";
1754 /* Show the form to confirm action */
1755 // PHP 4.0.x support
1756 $get= (isset($_GET)) ? $_GET : $HTTP_GET_VARS;
1757 $post= (isset($_POST)) ? $_POST : $HTTP_POST_VARS;
1758 // Resolve URI and QUERY_STRING
1759 if ($uri=serverVar('REQUEST_URI')) {
1760 list($uri,$qstring)=explode('?',$uri);
1762 if ( !($uri=serverVar('PHP_SELF')) ) $uri=serverVar('SCRIPT_NAME');
1763 $qstring=serverVar('QUERY_STRING');
1765 if ($qstring) $qstring='?'.$qstring;
1766 echo '<p>'._SETTINGS_UPDATE.' : '._QMENU_PLUGINS.' <span style="color:red;">'.
1767 htmlspecialchars($plugin_name)."</span> ?</p>\n";
1768 switch(strtoupper(serverVar('REQUEST_METHOD'))){
1770 echo '<form method="POST" action="'.htmlspecialchars($uri.$qstring).'">';
1771 $manager->addTicketHidden();
1772 _addInputTags($post);
1775 echo '<form method="GET" action="'.htmlspecialchars($uri).'">';
1776 $manager->addTicketHidden();
1777 _addInputTags($get);
1781 echo '<input type="submit" value="'._YES.'" /> ';
1782 echo '<input type="button" value="'._NO.'" onclick="history.back(); return false;" />';
1785 $oPluginAdmin->end();
1789 /* Create new ticket */
1790 $ticket=$manager->addTicketToUrl('');
1791 $ticketforplugin['ticket']=substr($ticket,strpos($ticket,'ticket=')+7);
1793 function _addInputTags(&$keys,$prefix=''){
1794 foreach($keys as $key=>$value){
1795 if ($prefix) $key=$prefix.'['.$key.']';
1796 if (is_array($value)) _addInputTags($value,$key);
1798 if (get_magic_quotes_gpc()) $value=stripslashes($value);
1799 if ($key=='ticket') continue;
1800 echo '<input type="hidden" name="'.htmlspecialchars($key).
1801 '" value="'.htmlspecialchars($value).'" />'."\n";
1807 * Convert the server string such as $_SERVER['REQUEST_URI']
1808 * to arry like arry['blogid']=1 and array['page']=2 etc.
1810 function serverStringToArray($str, &$array, &$frontParam)
1816 // split front param, e.g. /index.php, and others, e.g. blogid=1&page=2
1817 if (strstr($str, "?")){
1818 list($frontParam, $args) = preg_split("/\?/", $str, 2);
1825 // If there is no args like blogid=1&page=2, return
1826 if (!strstr($str, "=") && !strlen($frontParam)) {
1831 $array = explode("&", $args);
1835 * Convert array like array['blogid'] to server string
1836 * such as $_SERVER['REQUEST_URI']
1838 function arrayToServerString($array, $frontParam, &$str)
1840 if (strstr($str, "?")) {
1841 $str = $frontParam . "?";
1845 if (count($array)) {
1846 $str .= implode("&", $array);
1851 * Sanitize array parameters.
1852 * This function checks both key and value.
1853 * - check key if it inclues " (double quote), remove from array
1854 * - check value if it includes \ (escape sequece), remove remaining string
1856 function sanitizeArray(&$array)
1858 $excludeListForSanitization = array('query');
1859 // $excludeListForSanitization = array();
1861 foreach ($array as $k => $v) {
1863 // split to key and value
1864 list($key, $val) = preg_split("/=/", $v, 2);
1869 // when magic quotes is on, need to use stripslashes,
1870 // and then addslashes
1871 if (get_magic_quotes_gpc()) {
1872 $val = stripslashes($val);
1874 $val = addslashes($val);
1876 // if $key is included in exclude list, skip this param
1877 if (!in_array($key, $excludeListForSanitization)) {
1880 @list($val, $tmp) = explode('\\', $val);
1882 // remove control code etc.
1883 $val = strtr($val, "\0\r\n<>'\"", " ");
1886 if (preg_match('/\"/i', $key)) {
1891 // set sanitized info
1892 $array[$k] = sprintf("%s=%s", $key, $val);
1898 * Convert array for sanitizeArray function
1900 function convArrayForSanitizing($src, &$array)
1903 foreach ($src as $key => $val) {
1904 if (key_exists($key, $_GET)) {
1905 array_push($array, sprintf("%s=%s", $key, $val));
1911 * Revert array after sanitizeArray function
1913 function revertArrayForSanitizing($array, &$dst)
1915 foreach ($array as $v) {
1916 list($key, $val) = preg_split("/=/", $v, 2);
1922 * Stops processing the request and redirects to the given URL.
1923 * - no actual contents should have been sent to the output yet
1924 * - the URL will be stripped of illegal or dangerous characters
1926 function redirect($url) {
1927 $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%]|i', '', $url);
1928 header('Location: ' . $url);
1933 * Strip HTML tags from a string
1934 * This function is a bit more intelligent than a regular call to strip_tags(),
1935 * because it also deletes the contents of certain tags and cleans up any
1936 * unneeded whitespace.
1938 function stringStripTags ($string) {
1939 $string = preg_replace("/<del[^>]*>.+<\/del[^>]*>/isU", '', $string);
1940 $string = preg_replace("/<script[^>]*>.+<\/script[^>]*>/isU", '', $string);
1941 $string = preg_replace("/<style[^>]*>.+<\/style[^>]*>/isU", '', $string);
1942 $string = str_replace('>', '> ', $string);
1943 $string = str_replace('<', ' <', $string);
1944 $string = strip_tags($string);
1945 $string = preg_replace("/\s+/", " ", $string);
1946 $string = trim($string);
1951 * Make a string containing HTML safe for use in a HTML attribute
1952 * Tags are stripped and entities are normalized
1954 function stringToAttribute ($string) {
1955 $string = stringStripTags($string);
1956 $string = entity::named_to_numeric($string);
1957 $string = entity::normalize_numeric($string);
1959 if (_CHARSET == 'UTF-8') {
1960 $string = entity::numeric_to_utf8($string);
1963 $string = entity::specialchars($string, 'html');
1964 $string = entity::numeric_to_named($string);
1969 * Make a string containing HTML safe for use in a XML document
1970 * Tags are stripped, entities are normalized and named entities are
1971 * converted to numeric entities.
1973 function stringToXML ($string) {
1974 $string = stringStripTags($string);
1975 $string = entity::named_to_numeric($string);
1976 $string = entity::normalize_numeric($string);
1978 if (_CHARSET == 'UTF-8') {
1979 $string = entity::numeric_to_utf8($string);
1982 $string = entity::specialchars($string, 'xml');
1986 // START: functions from the end of file BLOG.php
1987 // used for mail notification (html -> text)
1988 function toAscii($html) {
1989 // strip off most tags
1990 $html = strip_tags($html,'<a>');
1991 $to_replace = "/<a[^>]*href=[\"\']([^\"^']*)[\"\'][^>]*>([^<]*)<\/a>/i";
1993 $ascii = preg_replace_callback ($to_replace, '_links_add', $html);
1994 $ascii .= "\n\n" . _links_list();
1995 return strip_tags($ascii);
1998 function _links_init() {
2000 $tmp_links = array();
2003 function _links_add($match) {
2005 array_push($tmp_links, $match[1]);
2006 return $match[2] . ' [' . sizeof($tmp_links) .']';
2009 function _links_list() {
2013 foreach ($tmp_links as $current) {
2014 $output .= "[$i] $current\n";
2019 // END: functions from the end of file BLOG.php
2021 // START: functions from the end of file ADMIN.php
2023 * @todo document this
2025 function encode_desc(&$data)
2026 { //_$to_entities = get_html_translation_table(HTML_ENTITIES);
2027 $to_entities = get_html_translation_table(HTML_SPECIALCHARS);
2028 $from_entities = array_flip($to_entities);
2029 $data = str_replace('<br />','\n',$data); //hack
2030 $data = strtr($data,$from_entities);
2031 $data = strtr($data,$to_entities);
2032 $data = str_replace('\n','<br />',$data); //hack
2037 * Returns the Javascript code for a bookmarklet that works on most modern browsers
2041 function getBookmarklet($blogid) {
2045 $document = 'document';
2046 $bookmarkletline = "javascript:Q='';x=".$document.";y=window;if(x.selection){Q=x.selection.createRange().text;}else if(y.getSelection){Q=y.getSelection();}else if(x.getSelection){Q=x.getSelection();}wingm=window.open('";
2047 $bookmarkletline .= $CONF['AdminURL'] . "bookmarklet.php?blogid=$blogid";
2048 $bookmarkletline .="&logtext='+escape(Q)+'&loglink='+escape(x.location.href)+'&loglinktitle='+escape(x.title),'nucleusbm','scrollbars=yes,width=600,height=550,left=10,top=10,status=yes,resizable=yes');wingm.focus();";
2050 return $bookmarkletline;
2052 // END: functions from the end of file ADMIN.php
2055 * Returns a variable or null if not set
2057 * @param mixed Variable
2058 * @return mixed Variable
2060 function ifset(&$var) {
2069 * Returns number of subscriber to an event
2072 * @return number of subscriber(s)
2074 function numberOfEventSubscriber($event) {
2075 $query = 'SELECT COUNT(*) as count FROM ' . sql_table('plugin_event') . ' WHERE event=\'' . $event . '\'';
2076 $res = sql_query($query);
2077 $obj = mysql_fetch_object($res);