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.16 2007-02-28 21:12:33 kmorimatsu Exp $
17 * $NucleusJP: globalfunctions.php,v 1.15 2007/02/17 04:39:59 shizuki Exp $
20 // needed if we include globalfunctions from install.php
21 global $nucleus, $CONF, $DIR_LIBS, $DIR_LANG, $manager, $member;
23 //$nucleus['version'] = 'v3.3SVN';
24 //$nucleus['codename'] = 'Lithium';
25 $nucleus['version'] = 'v3.3';
26 $nucleus['codename'] = '';
28 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'));
32 error_reporting(E_ALL); // report all errors!
34 error_reporting(E_ERROR | E_WARNING | E_PARSE);
38 if (!isset($CONF['Self'])) {
39 $CONF['Self'] = $_SERVER['PHP_SELF'];
43 Indicates when Nucleus should display startup errors. Set to 1 if you want
44 the error enabled (default), false otherwise
47 Displays an error when visiting a public Nucleus page and headers have
48 been sent out to early. This usually indicates an error in either a
49 configuration file or a language file, and could cause Nucleus to
52 Displays an error only when visiting the admin area, and when one or
53 more of the installation files (install.php, install.sql, upgrades/
54 directory) are still on the server.
56 $CONF['alertOnHeadersSent'] = 1;
57 $CONF['alertOnSecurityRisk'] = 1;
58 $CONF['ItemURL'] = $CONF['Self'];
59 $CONF['ArchiveURL'] = $CONF['Self'];
60 $CONF['ArchiveListURL'] = $CONF['Self'];
61 $CONF['MemberURL'] = $CONF['Self'];
62 $CONF['SearchURL'] = $CONF['Self'];
63 $CONF['BlogURL'] = $CONF['Self'];
64 $CONF['CategoryURL'] = $CONF['Self'];
66 // switch URLMode back to normal when $CONF['Self'] ends in .php
67 // this avoids urls like index.php/item/13/index.php/item/15
68 if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {
69 $CONF['URLMode'] = 'normal';
72 if (getNucleusPatchLevel() > 0) {
73 $nucleus['version'] .= '/' . getNucleusPatchLevel();
77 if (!isset($CONF['installscript'])) {
78 $CONF['installscript'] = 0;
81 // we will use postVar, getVar, ... methods instead of HTTP_GET_VARS or _GET
82 if ($CONF['installscript'] != 1) { // vars were already included in install.php
83 if (phpversion() >= '4.1.0') {
84 include_once($DIR_LIBS . 'vars4.1.0.php');
86 include_once($DIR_LIBS . 'vars4.0.6.php');
91 $bLoggingSanitizedResult=0;
92 $bSanitizeAndContinue=0;
94 $orgRequestURI = serverVar('REQUEST_URI');
97 // get all variables that can come from the request and put them in the global scope
98 $blogid = requestVar('blogid');
99 $itemid = intRequestVar('itemid');
100 $catid = intRequestVar('catid');
101 $skinid = requestVar('skinid');
102 $memberid = requestVar('memberid');
103 $archivelist = requestVar('archivelist');
104 $imagepopup = requestVar('imagepopup');
105 $archive = requestVar('archive');
106 $query = requestVar('query');
107 $highlight = requestVar('highlight');
108 $amount = requestVar('amount');
109 $action = requestVar('action');
110 $nextaction = requestVar('nextaction');
111 $maxresults = requestVar('maxresults');
112 $startpos = intRequestVar('startpos');
115 $virtualpath = ((getVar('virtualpath') != null) ? getVar('virtualpath') : serverVar('PATH_INFO'));
117 if (!headers_sent() ) {
118 header('Generator: Nucleus CMS ' . $nucleus['version']);
121 // include core classes that are needed for login & plugin handling
122 include($DIR_LIBS . 'mysql.php');
123 include($DIR_LIBS . 'MEMBER.php');
124 include($DIR_LIBS . 'ACTIONLOG.php');
125 include($DIR_LIBS . 'MANAGER.php');
126 include($DIR_LIBS . 'PLUGIN.php');
128 $manager =& MANAGER::instance();
130 // make sure there's no unnecessary escaping:
131 set_magic_quotes_runtime(0);
134 if (!isset($CONF['UsingAdminArea'])) {
135 $CONF['UsingAdminArea'] = 0;
138 // only needed when updating logs
139 if ($CONF['UsingAdminArea']) {
140 include($DIR_LIBS . 'xmlrpc.inc.php'); // XML-RPC client classes
141 include_once($DIR_LIBS . 'ADMIN.php');
144 // connect to database
148 // logs sanitized result if need
149 if ($orgRequestURI!==serverVar('REQUEST_URI')) {
150 $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";
151 $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');
152 if ($bLoggingSanitizedResult) {
153 addToLog(WARNING, $msg);
155 if (!$bSanitizeAndContinue) {
160 // makes sure database connection gets closed on script termination
161 register_shutdown_function('sql_disconnect');
166 // automatically use simpler toolbar for mozilla
167 if (($CONF['DisableJsTools'] == 0) && strstr(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0') && strstr(serverVar('HTTP_USER_AGENT'), 'Gecko') ) {
168 $CONF['DisableJsTools'] = 2;
171 // login if cookies set
172 $member = new MEMBER();
174 // login/logout when required or renew cookies
175 if ($action == 'login') {
176 // Form Authentication
177 $login = postVar('login');
178 $pw = postVar('password');
179 $shared = intPostVar('shared'); // shared computer or not
181 if ($member->login($login, $pw) ) {
183 $member->newCookieKey();
184 $member->setCookies($shared);
186 // allows direct access to parts of the admin area after logging in
188 $action = $nextaction;
191 $manager->notify('LoginSuccess', array('member' => &$member) );
193 ACTIONLOG::add(INFO, "Login successful for $login (sharedpc=$shared)");
195 // errormessage for [%errordiv%]
196 $errormessage = 'Login failed for ' . $login;
198 $manager->notify('LoginFailed', array('username' => $login) );
199 ACTIONLOG::add(INFO, $errormessage);
203 Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details
205 } elseif (serverVar('PHP_AUTH_USER') && serverVar('PHP_AUTH_PW')) {
206 // HTTP Authentication
207 $login = serverVar('PHP_AUTH_USER');
208 $pw = serverVar('PHP_AUTH_PW');
210 if ($member->login($login, $pw) ) {
211 $manager->notify('LoginSuccess',array('member' => &$member));
212 ACTIONLOG::add(INFO, "HTTP authentication successful for $login");
214 $manager->notify('LoginFailed',array('username' => $login));
215 ACTIONLOG::add(INFO, 'HTTP authentication failed for ' . $login);
217 //Since bad credentials, generate an apropriate error page
218 header("WWW-Authenticate: Basic realm=\"Nucleus CMS {$nucleus['version']}\"");
219 header('HTTP/1.0 401 Unauthorized');
220 echo 'Invalid username or password';
225 } elseif (($action == 'logout') && (!headers_sent() ) && cookieVar($CONF['CookiePrefix'] . 'user') ) {
226 // remove cookies on logout
227 setcookie($CONF['CookiePrefix'] . 'user', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
228 setcookie($CONF['CookiePrefix'] . 'loginkey', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
229 $manager->notify('Logout', array('username' => cookieVar($CONF['CookiePrefix'] . 'user') ) );
230 } elseif (cookieVar($CONF['CookiePrefix'] . 'user') ) {
231 // Cookie Authentication
232 $res = $member->cookielogin(cookieVar($CONF['CookiePrefix'] . 'user'), cookieVar($CONF['CookiePrefix'] . 'loginkey') );
234 // renew cookies when not on a shared computer
235 if ($res && (cookieVar($CONF['CookiePrefix'] . 'sharedpc') != 1) && (!headers_sent() ) ) {
236 $member->setCookies();
242 $manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );
244 // first, let's see if the site is disabled or not. always allow admin area access.
245 if ($CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea']) {
246 redirect($CONF['DisableSiteURL']);
250 // load other classes
251 include($DIR_LIBS . 'PARSER.php');
252 include($DIR_LIBS . 'SKIN.php');
253 include($DIR_LIBS . 'TEMPLATE.php');
254 include($DIR_LIBS . 'BLOG.php');
255 include($DIR_LIBS . 'BODYACTIONS.php');
256 include($DIR_LIBS . 'COMMENTS.php');
257 include($DIR_LIBS . 'COMMENT.php');
258 //include($DIR_LIBS . 'ITEM.php');
259 include($DIR_LIBS . 'NOTIFICATION.php');
260 include($DIR_LIBS . 'BAN.php');
261 include($DIR_LIBS . 'PAGEFACTORY.php');
262 include($DIR_LIBS . 'SEARCH.php');
263 include($DIR_LIBS . 'entity.php');
266 // set lastVisit cookie (if allowed)
267 if (!headers_sent() ) {
268 if ($CONF['LastVisit']) {
269 setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
271 setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
275 // read language file, only after user has been initialized
276 $language = getLanguageName();
277 include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');
280 Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details
282 // To remove after v2.5 is released and language files have been updated.
283 // Including this makes sure that language files for v2.5beta can still be used for v2.5final
284 // without having weird _SETTINGS_EXTAUTH string showing up in the admin area.
285 if (!defined('_MEMBERS_BYPASS'))
287 define('_SETTINGS_EXTAUTH', 'Enable External Authentication');
288 define('_WARNING_EXTAUTH', 'Warning: Enable only if needed.');
289 define('_MEMBERS_BYPASS', 'Use External Authentication');
294 // make sure the archivetype skinvar keeps working when _ARCHIVETYPE_XXX not defined
295 if (!defined('_ARCHIVETYPE_MONTH') ) {
296 define('_ARCHIVETYPE_DAY', 'day');
297 define('_ARCHIVETYPE_MONTH', 'month');
301 if ($CONF['URLMode'] == 'pathinfo') {
302 // initialize keywords if this hasn't been done before
303 if ($CONF['ItemKey'] == '') {
304 $CONF['ItemKey'] = 'item';
307 if ($CONF['ArchiveKey'] == '') {
308 $CONF['ArchiveKey'] = 'archive';
311 if ($CONF['ArchivesKey'] == '') {
312 $CONF['ArchivesKey'] = 'archives';
315 if ($CONF['MemberKey'] == '') {
316 $CONF['MemberKey'] = 'member';
319 if ($CONF['BlogKey'] == '') {
320 $CONF['BlogKey'] = 'blog';
323 if ($CONF['CategoryKey'] == '') {
324 $CONF['CategoryKey'] = 'category';
331 'type' => basename(serverVar('SCRIPT_NAME') ), // e.g. item, blog, ...
332 'info' => $virtualpath,
333 'complete' => &$parsed
338 // default implementation
339 $data = explode("/", $virtualpath );
340 for ($i = 0; $i < sizeof($data); $i++) {
342 case $CONF['ItemKey']: // item/1 (blogid)
345 if ($i < sizeof($data) ) {
346 $itemid = intval($data[$i]);
350 case $CONF['ArchivesKey']: // archives/1 (blogid)
353 if ($i < sizeof($data) ) {
354 $archivelist = intval($data[$i]);
358 case $CONF['ArchiveKey']: // two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid)
359 if ((($i + 1) < sizeof($data) ) && (!strstr($data[$i + 1], '-') ) ) {
360 $blogid = intval($data[++$i]);
365 if ($i < sizeof($data) ) {
366 $archive = $data[$i];
370 case 'blogid': // blogid/1
371 case $CONF['BlogKey']: // blog/1
374 if ($i < sizeof($data) ) {
375 $blogid = intval($data[$i]);
379 case $CONF['CategoryKey']: // category/1 (catid)
383 if ($i < sizeof($data) ) {
384 $catid = intval($data[$i]);
388 case $CONF['MemberKey']:
391 if ($i < sizeof($data) ) {
392 $memberid = intval($data[$i]);
399 if ($i < sizeof($data) ) {
400 $_REQUEST['special'] = $data[$i];
411 function intPostVar($name) {
412 return intval(postVar($name) );
415 function intGetVar($name) {
416 return intval(getVar($name) );
419 function intRequestVar($name) {
420 return intval(requestVar($name) );
423 function intCookieVar($name) {
424 return intval(cookieVar($name) );
428 * returns the currently used version (100 = 1.00, 101 = 1.01, etc...)
430 function getNucleusVersion() {
435 * power users can install patches in between nucleus releases. These patches
436 * usually add new functionality in the plugin API and allow those to
437 * be tested without having to install CVS.
439 function getNucleusPatchLevel() {
444 * Connects to mysql server
446 function sql_connect() {
447 global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_CONN;
449 $MYSQL_CONN = @mysql_connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD) or startUpError('<p>Could not connect to MySQL database.</p>', 'Connect Error');
450 mysql_select_db($MYSQL_DATABASE) or startUpError('<p>Could not select database: ' . mysql_error() . '</p>', 'Connect Error');
456 * returns a prefixed nucleus table name
458 function sql_table($name) {
459 global $MYSQL_PREFIX;
462 return $MYSQL_PREFIX . 'nucleus_' . $name;
464 return 'nucleus_' . $name;
468 function sendContentType($contenttype, $pagetype = '', $charset = _CHARSET) {
469 global $manager, $CONF;
471 if (!headers_sent() ) {
472 // if content type is application/xhtml+xml, only send it to browsers
473 // that can handle it (IE6 cannot). Otherwise, send text/html
475 // v2.5: For admin area pages, keep sending text/html (unless it's a debug version)
476 // application/xhtml+xml still causes too much problems with the javascript implementations
478 // v3.3: ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,
479 // application/xhtml+xml seems to be working, so we're going to use it if we can.
481 // Note: reverted the following function in JP version
486 ($contenttype == 'application/xhtml+xml')
487 && (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') )
489 $contenttype = 'text/html';
494 ($contenttype == 'application/xhtml+xml')
495 && (($CONF['UsingAdminArea'] && !$CONF['debug']) || !stristr(serverVar('HTTP_ACCEPT'),'application/xhtml+xml'))
498 $contenttype = 'text/html';
502 'PreSendContentType',
504 'contentType' => &$contenttype,
505 'charset' => &$charset,
506 'pageType' => $pagetype
510 // strip strange characters
511 $contenttype = preg_replace('|[^a-z0-9-+./]|i', '', $contenttype);
512 $charset = preg_replace('|[^a-z0-9-_]|i', '', $charset);
514 if ($charset != '') {
515 header('Content-Type: ' . $contenttype . '; charset=' . $charset);
517 header('Content-Type: ' . $contenttype);
523 * Errors before the database connection has been made
525 function startUpError($msg, $title) {
527 <html xmlns="http://www.w3.org/1999/xhtml">
528 <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
529 <title><?php echo htmlspecialchars($title)?></title></head>
531 <h1><?php echo htmlspecialchars($title)?></h1>
539 * disconnects from SQL server
541 function sql_disconnect() {
546 * executes an SQL query
548 function sql_query($query) {
551 $res = mysql_query($query) or print("mySQL error with query $query: " . mysql_error() . '<p />');
557 * Highlights a specific query in a given HTML text (not within HTML tags) and returns it
560 * text to be highlighted
562 * regular expression to be matched (can be an array of expressions as well)
564 * highlight to be used (use \\0 to indicate the matched expression)
567 function highlight($text, $expression, $highlight) {
568 if (!$highlight || !$expression) {
572 if (is_array($expression) && (count($expression) == 0) ) {
576 // add a tag in front (is needed for preg_match_all to work correct)
577 $text = '<!--h-->' . $text;
579 // split the HTML up so we have HTML tags
580 // $matches[0][i] = HTML + text
581 // $matches[1][i] = HTML
582 // $matches[2][i] = text
583 preg_match_all('/(<[^>]+>)([^<>]*)/', $text, $matches);
585 // throw it all together again while applying the highlight to the text pieces
587 for ($i = 0; $i < sizeof($matches[2]); $i++) {
589 $result .= $matches[1][$i];
592 if (is_array($expression) ) {
593 foreach ($expression as $regex) {
595 $matches[2][$i] = @eregi_replace($regex, $highlight, $matches[2][$i]);
599 $result .= $matches[2][$i];
601 $result .= @eregi_replace($expression, $highlight, $matches[2][$i]);
609 * Parses a query into an array of expressions that can be passed on to the highlight method
611 function parseHighlight($query) {
612 // TODO: add more intelligent splitting logic
615 $query = preg_replace('/\'|"/', '', $query);
621 $aHighlight = explode(' ', $query);
623 for ($i = 0; $i < count($aHighlight); $i++) {
624 $aHighlight[$i] = trim($aHighlight[$i]);
626 if (strlen($aHighlight[$i]) < 3) {
627 unset($aHighlight[$i]);
631 if (count($aHighlight) == 1) {
632 return $aHighlight[0];
639 * Checks if email address is valid
641 function isValidMailAddress($address) {
642 if (preg_match('/^[a-zA-Z+0-9\._-]+@[a-zA-Z0-9\._-]+\.[A-Za-z]{2,5}$/', $address)) {
650 // some helper functions
651 function getBlogIDFromName($name) {
652 return quickQuery('SELECT bnumber as result FROM ' . sql_table('blog') . ' WHERE bshortname="' . addslashes($name) . '"');
655 function getBlogNameFromID($id) {
656 return quickQuery('SELECT bname as result FROM ' . sql_table('blog') . ' WHERE bnumber=' . intval($id) );
659 function getBlogIDFromItemID($itemid) {
660 return quickQuery('SELECT iblog as result FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid) );
663 function getBlogIDFromCommentID($commentid) {
664 return quickQuery('SELECT cblog as result FROM ' . sql_table('comment') . ' WHERE cnumber=' . intval($commentid) );
667 function getBlogIDFromCatID($catid) {
668 return quickQuery('SELECT cblog as result FROM ' . sql_table('category') . ' WHERE catid=' . intval($catid) );
671 function getCatIDFromName($name) {
672 return quickQuery('SELECT catid as result FROM ' . sql_table('category') . ' WHERE cname="' . addslashes($name) . '"');
675 function quickQuery($q) {
676 $res = sql_query($q);
677 $obj = mysql_fetch_object($res);
681 function getPluginNameFromPid($pid) {
682 $res = sql_query('SELECT pfile FROM ' . sql_table('plugin') . ' WHERE pid=' . intval($pid) );
683 $obj = mysql_fetch_object($res);
687 function selector() {
688 global $itemid, $blogid, $memberid, $query, $amount, $archivelist, $maxresults;
689 global $archive, $skinid, $blog, $memberinfo, $CONF, $member;
690 global $imagepopup, $catid;
693 $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');
694 $action = requestVar('action');
696 if (in_array($action, $actionNames) ) {
697 global $DIR_LIBS, $errormessage;
698 include_once($DIR_LIBS . 'ACTION.php');
700 $errorInfo = $a->doAction($action);
703 $errormessage = $errorInfo['message'];
707 // show error when headers already sent out
708 if (headers_sent() && $CONF['alertOnHeadersSent']) {
710 // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)
711 if (function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') ) {
712 headers_sent($hsFile, $hsLine);
713 $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';
719 '<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>',
720 'Page headers already sent'
725 // make is so ?archivelist without blogname or blogid shows the archivelist
726 // for the default weblog
727 if (serverVar('QUERY_STRING') == 'archivelist') {
728 $archivelist = $CONF['DefaultBlog'];
731 // now decide which type of skin we need
733 // itemid given -> only show that item
736 if (!$manager->existsItem($itemid,0,0) ) {
737 doError(_ERROR_NOSUCHITEM);
740 global $itemidprev, $itemidnext, $catid, $itemtitlenext, $itemtitleprev;
742 // 1. get timestamp, blogid and catid for item
743 $query = 'SELECT itime, iblog, icat FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid);
744 $res = sql_query($query);
745 $obj = mysql_fetch_object($res);
747 // if a different blog id has been set through the request or selectBlog(),
749 // if ($blogid && (intval($blogid) != $obj->iblog) ) {
750 // doError(_ERROR_NOSUCHITEM);
752 if ($blogid && (intval($blogid) != $obj->iblog)) {
753 if (!headers_sent()) {
754 $b =& $manager->getBlog($obj->iblog);
755 $CONF['ItemURL'] = $b->getURL();
756 if ($CONF['URLMode'] == 'pathinfo' and substr($CONF['ItemURL'],-1) == '/')
757 $CONF['ItemURL'] = substr($CONF['ItemURL'], 0, -1);
758 $correctURL = createItemLink($itemid, '');
759 redirect($correctURL);
762 doError(_ERROR_NOSUCHITEM);
766 // if a category has been selected which doesn't match the item, ignore the
768 if (($catid != 0) && ($catid != $obj->icat) ) {
772 $blogid = $obj->iblog;
773 $timestamp = strtotime($obj->itime);
775 $b =& $manager->getBlog($blogid);
777 if ($b->isValidCategory($catid) ) {
778 $catextra = ' and icat=' . $catid;
781 // get previous itemid and title
782 $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';
783 $res = sql_query($query);
785 $obj = mysql_fetch_object($res);
788 $itemidprev = $obj->inumber;
789 $itemtitleprev = $obj->ititle;
792 // get next itemid and title
793 $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';
794 $res = sql_query($query);
796 $obj = mysql_fetch_object($res);
799 $itemidnext = $obj->inumber;
800 $itemtitlenext = $obj->ititle;
803 } elseif ($archive) {
807 // get next and prev month links
808 global $archivenext, $archiveprev, $archivetype;
810 sscanf($archive, '%d-%d-%d', $y, $m, $d);
813 $archivetype = _ARCHIVETYPE_DAY;
814 $t = mktime(0, 0, 0, $m, $d, $y);
815 $archiveprev = strftime('%Y-%m-%d', $t - (24 * 60 * 60) );
816 $archivenext = strftime('%Y-%m-%d', $t + (24 * 60 * 60) );
818 $archivetype = _ARCHIVETYPE_MONTH;
819 $t = mktime(0, 0, 0, $m, 1, $y);
820 $archiveprev = strftime('%Y-%m', $t - (1 * 24 * 60 * 60) );
821 $archivenext = strftime('%Y-%m', $t + (32 * 24 * 60 * 60) );
824 } elseif ($archivelist) {
825 $type = 'archivelist';
827 if (is_numeric($archivelist)) {
828 $blogid = intVal($archivelist);
830 $blogid = getBlogIDFromName($archivelist);
834 doError(_ERROR_NOSUCHBLOG);
840 $query = stripslashes($query);
841 if(preg_match("/^(\xA1{2}|\xe3\x80{2}|\x20)+$/",$query)){
844 $order = (_CHARSET == 'EUC-JP') ? 'EUC-JP, UTF-8,' : 'UTF-8, EUC-JP,';
845 $query = mb_convert_encoding($query, _CHARSET, $order.' JIS, SJIS, ASCII');
846 if (is_numeric($blogid)) {
847 $blogid = intVal($blogid);
849 $blogid = getBlogIDFromName($blogid);
853 doError(_ERROR_NOSUCHBLOG);
856 } elseif ($memberid) {
859 if (!MEMBER::existsID($memberid) ) {
860 doError(_ERROR_NOSUCHMEMBER);
863 $memberinfo = $manager->getMember($memberid);
865 } elseif ($imagepopup) {
866 // media object (images etc.)
867 $type = 'imagepopup';
869 // TODO: check if media-object exists
870 // TODO: set some vars?
872 // show regular index page
877 // decide which blog should be displayed
879 $blogid = $CONF['DefaultBlog'];
882 $b =& $manager->getBlog($blogid);
883 $blog = $b; // references can't be placed in global variables?
885 if (!$blog->isValid) {
886 doError(_ERROR_NOSUCHBLOG);
889 // set catid if necessary
891 $blog->setSelectedCategory($catid);
894 // decide which skin should be used
895 if ($skinid != '' && ($skinid == 0) ) {
900 $skinid = $blog->getDefaultSkin();
903 $special = requestVar('special');
904 if (!empty($special) && isValidShortName($special)) {
905 $type = strtolower($special);
908 $skin = new SKIN($skinid);
910 if (!$skin->isValid) {
911 doError(_ERROR_NOSUCHSKIN);
919 * Show error skin with given message. An optional skin-object to use can be given
921 function doError($msg, $skin = '') {
922 global $errormessage, $CONF, $skinid, $blogid, $manager;
926 if (SKIN::existsID($skinid) ) {
927 $skin = new SKIN($skinid);
928 } elseif ($manager->existsBlogID($blogid) ) {
929 $blog =& $manager->getBlog($blogid);
930 $skin = new SKIN($blog->getDefaultSkin() );
931 } elseif ($CONF['DefaultBlog']) {
932 $blog =& $manager->getBlog($CONF['DefaultBlog']);
933 $skin = new SKIN($blog->getDefaultSkin() );
935 // this statement should actually never be executed
936 $skin = new SKIN($CONF['BaseSkin']);
941 $errormessage = $msg;
942 $skin->parse('error');
946 function getConfig() {
949 $query = 'SELECT * FROM ' . sql_table('config');
950 $res = sql_query($query);
952 while ($obj = mysql_fetch_object($res) ) {
953 $CONF[$obj->name] = $obj->value;
957 // some checks for names of blogs, categories, templates, members, ...
958 function isValidShortName($name) {
959 return eregi('^[a-z0-9]+$', $name);
962 function isValidDisplayName($name) {
963 return eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name);
966 function isValidCategoryName($name) {
970 function isValidTemplateName($name) {
971 return eregi('^[a-z0-9/]+$', $name);
974 function isValidSkinName($name) {
975 return eregi('^[a-z0-9/]+$', $name);
978 // add and remove linebreaks
979 function addBreaks($var) {
983 function removeBreaks($var) {
984 return preg_replace("/<br \/>([\r\n])/", "$1", $var);
987 // shortens a text string to maxlength ($toadd) is what needs to be added
988 // at the end (end length is <= $maxlength)
989 function shorten($text, $maxlength, $toadd) {
990 // 1. remove entities...
991 $trans = get_html_translation_table(HTML_ENTITIES);
992 $trans = array_flip($trans);
993 $text = strtr($text, $trans);
995 // 2. the actual shortening
996 if (strlen($text) > $maxlength)
997 $text = mb_strimwidth($text, 0, $maxlength, $toadd, _CHARSET);
1002 * Converts a unix timestamp to a mysql DATETIME format, and places
1005 function mysqldate($timestamp) {
1006 return '"' . date('Y-m-d H:i:s', $timestamp) . '"';
1010 * functions for use in index.php
1012 function selectBlog($shortname) {
1013 global $blogid, $archivelist;
1014 $blogid = getBlogIDFromName($shortname);
1016 // also force archivelist variable, if it is set
1018 $archivelist = $blogid;
1022 function selectSkin($skinname) {
1024 $skinid = SKIN::getIdFromName($skinname);
1028 * Can take either a category ID or a category name (be aware that
1029 * multiple categories can have the same name)
1031 function selectCategory($cat) {
1033 if (is_numeric($cat) ) {
1034 $catid = intval($cat);
1036 $catid = getCatIDFromName($cat);
1040 function selectItem($id) {
1042 $itemid = intval($id);
1045 // force the use of a language file (warning: can cause warnings)
1046 function selectLanguage($language) {
1048 include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');
1051 function parseFile($filename, $includeMode = 'normal', $includePrefix = '') {
1052 $handler = new ACTIONS('fileparser');
1053 $parser = new PARSER(SKIN::getAllowedActionsForType('fileparser'), $handler);
1054 $handler->parser =& $parser;
1056 // set IncludeMode properties of parser
1057 PARSER::setProperty('IncludeMode', $includeMode);
1058 PARSER::setProperty('IncludePrefix', $includePrefix);
1060 if (!file_exists($filename) ) {
1061 doError('A file is missing');
1064 $fsize = filesize($filename);
1071 $fd = fopen ($filename, 'r');
1072 $contents = fread ($fd, $fsize);
1075 // parse file contents
1076 $parser->parse($contents);
1080 * Outputs a debug message
1082 function debug($msg) {
1083 echo '<p><b>' . $msg . "</b></p>\n";
1087 function addToLog($level, $msg) {
1088 ACTIONLOG::add($level, $msg);
1091 // shows a link to help file
1092 function help($id) {
1096 function helpHtml($id) {
1097 return helplink($id) . '<img src="documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" /></a>';
1100 function helplink($id) {
1101 return '<a href="documentation/help.html#'. $id . '" onclick="if (event && event.preventDefault) event.preventDefault(); return help(this.href);">';
1104 function getMailFooter() {
1105 $message = "\n\n-----------------------------";
1106 $message .= "\n Powered by Nucleus CMS";
1107 $message .= "\n(http://www.nucleuscms.org/)";
1112 * Returns the name of the language to use
1113 * preference priority: member - site
1114 * defaults to english when no good language found
1116 * checks if file exists, etc...
1118 function getLanguageName() {
1119 global $CONF, $member;
1121 if ($member && $member->isLoggedIn() ) {
1122 // try to use members language
1123 $memlang = $member->getLanguage();
1125 if (($memlang != '') && (checkLanguage($memlang) ) ) {
1130 // use default language
1131 if (checkLanguage($CONF['Language']) ) {
1132 return $CONF['Language'];
1139 * Includes a PHP file. This method can be called while parsing templates and skins
1141 function includephp($filename) {
1142 // make predefined variables global, so most simple scripts can be used here
1144 // apache (names taken from PHP doc)
1145 global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;
1146 global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;
1147 global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;
1148 global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;
1149 global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;
1150 global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;
1151 global $REQUEST_URI;
1153 // php (taken from PHP doc)
1154 global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;
1155 global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;
1158 global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;
1160 if (@file_exists($filename) ) {
1166 * Checks if a certain language/plugin exists
1168 function checkLanguage($lang) {
1170 return file_exists($DIR_LANG . ereg_replace( '[\\|/]', '', $lang) . '.php');
1173 function checkPlugin($plug) {
1174 global $DIR_PLUGINS;
1175 return file_exists($DIR_PLUGINS . ereg_replace( '[\\|/]', '', $plug) . '.php');
1179 * Centralisation of the functions that generate links
1181 function createItemLink($itemid, $extra = '') {
1182 return createLink('item', array('itemid' => $itemid, 'extra' => $extra) );
1185 function createMemberLink($memberid, $extra = '') {
1186 return createLink('member', array('memberid' => $memberid, 'extra' => $extra) );
1189 function createCategoryLink($catid, $extra = '') {
1190 return createLink('category', array('catid' => $catid, 'extra' => $extra) );
1193 function createArchiveListLink($blogid = '', $extra = '') {
1194 return createLink('archivelist', array('blogid' => $blogid, 'extra' => $extra) );
1197 function createArchiveLink($blogid, $archive, $extra = '') {
1198 return createLink('archive', array('blogid' => $blogid, 'archive' => $archive, 'extra' => $extra) );
1201 function createBlogidLink($blogid, $params = '') {
1202 return createLink('blog', array('blogid' => $blogid, 'extra' => $params) );
1205 function createLink($type, $params) {
1206 global $manager, $CONF;
1209 $usePathInfo = ($CONF['URLMode'] == 'pathinfo');
1211 // ask plugins first
1219 'params' => $params,
1220 'completed' => &$created,
1226 // if a plugin created the URL, return it
1231 // default implementation
1235 $url = $CONF['ItemURL'] . '/' . $CONF['ItemKey'] . '/' . $params['itemid'];
1237 $url = $CONF['ItemURL'] . '?itemid=' . $params['itemid'];
1243 $url = $CONF['MemberURL'] . '/' . $CONF['MemberKey'] . '/' . $params['memberid'];
1245 $url = $CONF['MemberURL'] . '?memberid=' . $params['memberid'];
1251 $url = $CONF['CategoryURL'] . '/' . $CONF['CategoryKey'] . '/' . $params['catid'];
1253 $url = $CONF['CategoryURL'] . '?catid=' . $params['catid'];
1258 if (!$params['blogid']) {
1259 $params['blogid'] = $CONF['DefaultBlog'];
1263 $url = $CONF['ArchiveListURL'] . '/' . $CONF['ArchivesKey'] . '/' . $params['blogid'];
1265 $url = $CONF['ArchiveListURL'] . '?archivelist=' . $params['blogid'];
1271 $url = $CONF['ArchiveURL'] . '/' . $CONF['ArchiveKey'] . '/'.$params['blogid'].'/' . $params['archive'];
1273 $url = $CONF['ArchiveURL'] . '?blogid='.$params['blogid'].'&archive=' . $params['archive'];
1279 $url = $CONF['BlogURL'] . '/' . $CONF['BlogKey'] . '/' . $params['blogid'];
1281 $url = $CONF['BlogURL'] . '?blogid=' . $params['blogid'];
1286 return addLinkParams($url, (isset($params['extra'])? $params['extra'] : null));
1289 function createBlogLink($url, $params) {
1290 return addLinkParams($url . '?', $params);
1293 function addLinkParams($link, $params) {
1296 if (is_array($params) ) {
1298 if ($CONF['URLMode'] == 'pathinfo') {
1300 foreach ($params as $param => $value) {
1301 $link .= '/' . $param . '/' . urlencode($value);
1306 foreach ($params as $param => $value) {
1307 $link .= '&' . $param . '=' . urlencode($value);
1318 * querystring to alter (e.g. foo=1&bar=2&x=y)
1320 * name of parameter to change (e.g. 'foo')
1322 * New value for that parameter (e.g. 3)
1324 * altered query string (for the examples above: foo=3&bar=2&x=y)
1326 function alterQueryStr($querystr, $param, $value) {
1327 $vars = explode('&', $querystr);
1330 for ($i = 0; $i < count($vars); $i++) {
1331 $v = explode('=', $vars[$i]);
1333 if ($v[0] == $param) {
1335 $vars[$i] = implode('=', $v);
1342 $vars[] = $param . '=' . $value;
1345 return ltrim(implode('&', $vars), '&');
1348 // passes one variable as hidden input field (multiple fields for arrays)
1349 // @see passRequestVars in varsx.x.x.php
1350 function passVar($key, $value) {
1352 if (is_array($value) ) {
1353 for ($i = 0; $i < sizeof($value); $i++) {
1354 passVar($key . '[' . $i . ']', $value[$i]);
1360 // other values: do stripslashes if needed
1361 ?><input type="hidden" name="<?php echo htmlspecialchars($key)?>" value="<?php echo htmlspecialchars(undoMagic($value) )?>" /><?php
1365 Date format functions (to be used from [%date(..)%] skinvars
1367 function formatDate($format, $timestamp, $defaultFormat, &$blog) {
1368 // apply blog offset (#42)
1369 $boffset = $blog ? $blog->getTimeOffset() * 3600 : 0;
1370 $offset = date('Z', $timestamp) + $boffset;
1381 $tz .= sprintf("%02d%02d", floor($offset / 3600), round(($offset % 3600) / 60) );
1382 return date('D, j M Y H:i:s ', $timestamp) . $tz;
1385 $timestamp -= $offset;
1386 return date('D, j M Y H:i:s ', $timestamp) . 'GMT';
1389 $timestamp -= $offset;
1390 return date('Y-m-d\TH:i:s\Z', $timestamp);
1400 $tz .= sprintf("%02d:%02d", floor($offset / 3600), round(($offset % 3600) / 60) );
1401 return date('Y-m-d\TH:i:s', $timestamp) . $tz;
1404 return strftime($format ? $format : $defaultFormat, $timestamp);
1408 function checkVars($aVars) {
1409 global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;
1411 foreach ($aVars as $varName) {
1413 if (phpversion() >= '4.1.0') {
1415 if ( isset($_GET[$varName])
1416 || isset($_POST[$varName])
1417 || isset($_COOKIE[$varName])
1418 || isset($_ENV[$varName])
1419 || isset($_SESSION[$varName])
1420 || isset($_FILES[$varName])
1422 die('Sorry. An error occurred.');
1427 if ( isset($HTTP_GET_VARS[$varName])
1428 || isset($HTTP_POST_VARS[$varName])
1429 || isset($HTTP_COOKIE_VARS[$varName])
1430 || isset($HTTP_ENV_VARS[$varName])
1431 || isset($HTTP_SESSION_VARS[$varName])
1432 || isset($HTTP_POST_FILES[$varName])
1434 die('Sorry. An error occurred.');
1443 * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.
1446 function sanitizeParams()
1448 global $HTTP_SERVER_VARS;
1454 // REQUEST_URI of $HTTP_SERVER_VARS
1455 $str =& $HTTP_SERVER_VARS["REQUEST_URI"];
1456 serverStringToArray($str, $array, $frontParam);
1457 sanitizeArray($array);
1458 arrayToServerString($array, $frontParam, $str);
1460 // QUERY_STRING of $HTTP_SERVER_VARS
1461 $str =& $HTTP_SERVER_VARS["QUERY_STRING"];
1462 serverStringToArray($str, $array, $frontParam);
1463 sanitizeArray($array);
1464 arrayToServerString($array, $frontParam, $str);
1466 if (phpversion() >= '4.1.0') {
1467 // REQUEST_URI of $_SERVER
1468 $str =& $_SERVER["REQUEST_URI"];
1469 serverStringToArray($str, $array, $frontParam);
1470 sanitizeArray($array);
1471 arrayToServerString($array, $frontParam, $str);
1473 // QUERY_STRING of $_SERVER
1474 $str =& $_SERVER["QUERY_STRING"];
1475 serverStringToArray($str, $array, $frontParam);
1476 sanitizeArray($array);
1477 arrayToServerString($array, $frontParam, $str);
1481 convArrayForSanitizing($_GET, $array);
1482 sanitizeArray($array);
1483 revertArrayForSanitizing($array, $_GET);
1485 // $_REQUEST (only GET param)
1486 convArrayForSanitizing($_REQUEST, $array);
1487 sanitizeArray($array);
1488 revertArrayForSanitizing($array, $_REQUEST);
1492 * Check ticket when not checked in plugin's admin page
1494 * Also avoid the access to plugin/index.php by guest user.
1496 function ticketForPlugin(){
1497 global $CONF,$DIR_PLUGINS,$member,$ticketforplugin;
1500 $ticketforplugin=array();
1501 $ticketforplugin['ticket']=false;
1503 /* Check if using plugin's php file. */
1504 if ($p_translated=serverVar('PATH_TRANSLATED')) {
1505 if (!file_exists($p_translated)) $p_translated='';
1507 if (!$p_translated) {
1508 $p_translated=serverVar('SCRIPT_FILENAME');
1509 if (!file_exists($p_translated)) {
1510 header("HTTP/1.0 404 Not Found");
1514 $p_translated=str_replace('\\','/',$p_translated);
1515 $d_plugins=str_replace('\\','/',$DIR_PLUGINS);
1516 if (strpos($p_translated,$d_plugins)!==0) return;// This isn't plugin php file.
1518 /* Solve the plugin php file or admin directory */
1519 $phppath=substr($p_translated,strlen($d_plugins));
1520 $phppath=preg_replace('!^/!','',$phppath);// Remove the first "/" if exists.
1521 $path=preg_replace('/^NP_([.]*)\.php$/','$1',$phppath); // Remove the first "NP_" and the last ".php" if exists.
1522 $path=preg_replace('!^([^/]*)/(.*)$!','$1',$path); // Remove the "/" and beyond.
1524 /* Solve the plugin name. */
1526 $query='SELECT pfile FROM '.sql_table('plugin');
1527 $res=sql_query($query);
1528 while($row=mysql_fetch_row($res)) {
1529 $name=substr($row[0],3);
1530 $plugins[strtolower($name)]=$name;
1532 mysql_free_result($res);
1533 if ($plugins[$path]) $plugin_name=$plugins[$path];
1534 else if (array_key_exists($path,$plugins)) $plugin_name=$path;
1536 header("HTTP/1.0 404 Not Found");
1540 /* Return if not index.php */
1541 if ( $phppath!=strtolower($plugin_name).'/'
1542 && $phppath!=strtolower($plugin_name).'/index.php' ) return;
1544 /* Exit if not logged in. */
1545 if ( !$member->isLoggedIn() ) exit("You aren't logged in.");
1547 global $manager,$DIR_LIBS,$DIR_LANG,$HTTP_GET_VARS,$HTTP_POST_VARS;
1549 /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */
1550 if (!($p_translated=serverVar('PATH_TRANSLATED'))) $p_translated=serverVar('SCRIPT_FILENAME');
1551 if ($file=@file($p_translated)) {
1553 foreach($file as $line) {
1554 if (preg_match('/[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]/i',$prevline.$line)) return;
1559 /* Show a form if not valid ticket */
1560 if ( ( strstr(serverVar('REQUEST_URI'),'?') || serverVar('QUERY_STRING')
1561 || strtoupper(serverVar('REQUEST_METHOD'))=='POST' )
1562 && (!$manager->checkTicket()) ){
1564 if (!class_exists('PluginAdmin')) {
1565 $language = getLanguageName();
1566 include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');
1567 include($DIR_LIBS . 'PLUGINADMIN.php');
1569 if (!(function_exists('mb_strimwidth') || extension_loaded('mbstring'))) {
1570 if (file_exists($DIR_LIBS.'mb_emulator/mb-emulator.php')) {
1571 global $mbemu_internals;
1572 include_once($DIR_LIBS.'mb_emulator/mb-emulator.php');
1575 $oPluginAdmin = new PluginAdmin($plugin_name);
1576 $oPluginAdmin->start();
1577 echo '<p>' . _ERROR_BADTICKET . "</p>\n";
1579 /* Show the form to confirm action */
1580 // PHP 4.0.x support
1581 $get= (isset($_GET)) ? $_GET : $HTTP_GET_VARS;
1582 $post= (isset($_POST)) ? $_POST : $HTTP_POST_VARS;
1583 // Resolve URI and QUERY_STRING
1584 if ($uri=serverVar('REQUEST_URI')) {
1585 list($uri,$qstring)=explode('?',$uri);
1587 if ( !($uri=serverVar('PHP_SELF')) ) $uri=serverVar('SCRIPT_NAME');
1588 $qstring=serverVar('QUERY_STRING');
1590 if ($qstring) $qstring='?'.$qstring;
1591 echo '<p>'._SETTINGS_UPDATE.' : '._QMENU_PLUGINS.' <span style="color:red;">'.
1592 htmlspecialchars($plugin_name)."</span> ?</p>\n";
1593 switch(strtoupper(serverVar('REQUEST_METHOD'))){
1595 echo '<form method="POST" action="'.htmlspecialchars($uri.$qstring).'">';
1596 $manager->addTicketHidden();
1597 _addInputTags($post);
1600 echo '<form method="GET" action="'.htmlspecialchars($uri).'">';
1601 $manager->addTicketHidden();
1602 _addInputTags($get);
1606 echo '<input type="submit" value="'._YES.'" /> ';
1607 echo '<input type="button" value="'._NO.'" onclick="history.back(); return false;" />';
1610 $oPluginAdmin->end();
1614 /* Create new ticket */
1615 $ticket=$manager->addTicketToUrl('');
1616 $ticketforplugin['ticket']=substr($ticket,strpos($ticket,'ticket=')+7);
1618 function _addInputTags(&$keys,$prefix=''){
1619 foreach($keys as $key=>$value){
1620 if ($prefix) $key=$prefix.'['.$key.']';
1621 if (is_array($value)) _addInputTags($value,$key);
1623 if (get_magic_quotes_gpc()) $value=stripslashes($value);
1624 if ($key=='ticket') continue;
1625 echo '<input type="hidden" name="'.htmlspecialchars($key).
1626 '" value="'.htmlspecialchars($value).'" />'."\n";
1632 * Convert the server string such as $_SERVER['REQUEST_URI']
1633 * to arry like arry['blogid']=1 and array['page']=2 etc.
1635 function serverStringToArray($str, &$array, &$frontParam)
1641 // split front param, e.g. /index.php, and others, e.g. blogid=1&page=2
1642 if (strstr($str, "?")){
1643 list($frontParam, $args) = preg_split("/\?/", $str, 2);
1650 // If there is no args like blogid=1&page=2, return
1651 if (!strstr($str, "=") && !strlen($frontParam)) {
1656 $array = explode("&", $args);
1660 * Convert array like array['blogid'] to server string
1661 * such as $_SERVER['REQUEST_URI']
1663 function arrayToServerString($array, $frontParam, &$str)
1665 if (strstr($str, "?")) {
1666 $str = $frontParam . "?";
1670 if (count($array)) {
1671 $str .= implode("&", $array);
1676 * Sanitize array parameters.
1677 * This function checks both key and value.
1678 * - check key if it inclues " (double quote), remove from array
1679 * - check value if it includes \ (escape sequece), remove remaining string
1681 function sanitizeArray(&$array)
1683 $excludeListForSanitization = array('query');
1684 // $excludeListForSanitization = array();
1686 foreach ($array as $k => $v) {
1688 // split to key and value
1689 list($key, $val) = preg_split("/=/", $v, 2);
1694 // when magic quotes is on, need to use stripslashes,
1695 // and then addslashes
1696 if (get_magic_quotes_gpc()) {
1697 $val = stripslashes($val);
1699 $val = addslashes($val);
1701 // if $key is included in exclude list, skip this param
1702 if (!in_array($key, $excludeListForSanitization)) {
1705 list($val, $tmp) = explode('\\', $val);
1707 // remove control code etc.
1708 $val = strtr($val, "\0\r\n<>'\"", " ");
1711 if (preg_match('/\"/i', $key)) {
1716 // set sanitized info
1717 $array[$k] = sprintf("%s=%s", $key, $val);
1723 * Convert array for sanitizeArray function
1725 function convArrayForSanitizing($src, &$array)
1728 foreach ($src as $key => $val) {
1729 if (key_exists($key, $_GET)) {
1730 array_push($array, sprintf("%s=%s", $key, $val));
1736 * Revert array after sanitizeArray function
1738 function revertArrayForSanitizing($array, &$dst)
1740 foreach ($array as $v) {
1741 list($key, $val) = preg_split("/=/", $v, 2);
1747 * Stops processing the request and redirects to the given URL.
1748 * - no actual contents should have been sent to the output yet
1749 * - the URL will be stripped of illegal or dangerous characters
1751 function redirect($url) {
1752 $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%]|i', '', $url);
1753 header('Location: ' . $url);
1758 * Strip HTML tags from a string
1759 * This function is a bit more intelligent than a regular call to strip_tags(),
1760 * because it also deletes the contents of certain tags and cleans up any
1761 * unneeded whitespace.
1763 function stringStripTags ($string) {
1764 $string = preg_replace("/<del[^>]*>.+<\/del[^>]*>/isU", '', $string);
1765 $string = preg_replace("/<script[^>]*>.+<\/script[^>]*>/isU", '', $string);
1766 $string = preg_replace("/<style[^>]*>.+<\/style[^>]*>/isU", '', $string);
1767 $string = str_replace('>', '> ', $string);
1768 $string = str_replace('<', ' <', $string);
1769 $string = strip_tags($string);
1770 $string = preg_replace("/\s+/", " ", $string);
1771 $string = trim($string);
1776 * Make a string containing HTML safe for use in a HTML attribute
1777 * Tags are stripped and entities are normalized
1779 function stringToAttribute ($string) {
1780 $string = stringStripTags($string);
1781 $string = entity::named_to_numeric($string);
1782 $string = entity::normalize_numeric($string);
1784 if (_CHARSET == 'UTF-8') {
1785 $string = entity::numeric_to_utf8($string);
1788 $string = entity::specialchars($string, 'html');
1789 $string = entity::numeric_to_named($string);
1794 * Make a string containing HTML safe for use in a XML document
1795 * Tags are stripped, entities are normalized and named entities are
1796 * converted to numeric entities.
1798 function stringToXML ($string) {
1799 $string = stringStripTags($string);
1800 $string = entity::named_to_numeric($string);
1801 $string = entity::normalize_numeric($string);
1803 if (_CHARSET == 'UTF-8') {
1804 $string = entity::numeric_to_utf8($string);
1807 $string = entity::specialchars($string, 'xml');
1811 // START: functions from the end of file BLOG.php
1812 // used for mail notification (html -> text)
1813 function toAscii($html) {
1814 // strip off most tags
1815 $html = strip_tags($html,'<a>');
1816 $to_replace = "/<a[^>]*href=[\"\']([^\"^']*)[\"\'][^>]*>([^<]*)<\/a>/i";
1818 $ascii = preg_replace_callback ($to_replace, '_links_add', $html);
1819 $ascii .= "\n\n" . _links_list();
1820 return strip_tags($ascii);
1823 function _links_init() {
1825 $tmp_links = array();
1828 function _links_add($match) {
1830 array_push($tmp_links, $match[1]);
1831 return $match[2] . ' [' . sizeof($tmp_links) .']';
1834 function _links_list() {
1838 foreach ($tmp_links as $current) {
1839 $output .= "[$i] $current\n";
1844 // END: functions from the end of file BLOG.php
1846 // START: functions from the end of file ADMIN.php
1848 * @todo document this
1850 function encode_desc(&$data)
1851 { //_$to_entities = get_html_translation_table(HTML_ENTITIES);
1852 $to_entities = get_html_translation_table(HTML_SPECIALCHARS);
1853 $from_entities = array_flip($to_entities);
1854 $data = str_replace('<br />','\n',$data); //hack
1855 $data = strtr($data,$from_entities);
1856 $data = strtr($data,$to_entities);
1857 $data = str_replace('\n','<br />',$data); //hack
1862 * Returns the Javascript code for a bookmarklet that works on most modern browsers
1866 function getBookmarklet($blogid) {
1870 $document = 'document';
1871 $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('";
1872 $bookmarkletline .= $CONF['AdminURL'] . "bookmarklet.php?blogid=$blogid";
1873 $bookmarkletline .="&logtext='+escape(Q)+'&loglink='+escape(x.location.href)+'&loglinktitle='+escape(x.title),'nucleusbm','scrollbars=yes,width=600,height=500,left=10,top=10,status=yes,resizable=yes');wingm.focus();";
1875 return $bookmarkletline;
1877 // END: functions from the end of file ADMIN.php
1880 * Returns a variable or null if not set
1882 * @param mixed Variable
1883 * @return mixed Variable
1885 function ifset(&$var) {