OSDN Git Service

インストールスクリプトを統合
[nucleus-jp/nucleus-jp-ancient.git] / utf8 / nucleus / libs / globalfunctions.php
index 9fd88fa..421763c 100755 (executable)
@@ -1,29 +1,35 @@
 <?php\r
 \r
+/*\r
+ * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)\r
+ * Copyright (C) 2002-2009 The Nucleus Group\r
+ *\r
+ * This program is free software; you can redistribute it and/or\r
+ * modify it under the terms of the GNU General Public License\r
+ * as published by the Free Software Foundation; either version 2\r
+ * of the License, or (at your option) any later version.\r
+ * (see nucleus/documentation/index.html#license for more info)\r
+ */\r
 /**\r
-  * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)\r
-  * Copyright (C) 2002-2004 The Nucleus Group\r
-  *\r
-  * This program is free software; you can redistribute it and/or\r
-  * modify it under the terms of the GNU General Public License\r
-  * as published by the Free Software Foundation; either version 2\r
-  * of the License, or (at your option) any later version.\r
-  * (see nucleus/documentation/index.html#license for more info)\r
-  *\r
-  */\r
+ * @license http://nucleuscms.org/license.txt GNU General Public License\r
+ * @copyright Copyright (C) 2002-2009 The Nucleus Group\r
+ * @version $Id$\r
+ * $NucleusJP: globalfunctions.php,v 1.23.2.7 2008/02/05 08:30:08 kimitake Exp $\r
+ */\r
 \r
 // needed if we include globalfunctions from install.php\r
-global $nucleus, $CONF, $DIR_LIBS, $DIR_LANG, $manager, $member; \r
+global $nucleus, $CONF, $DIR_LIBS, $DIR_LANG, $manager, $member;\r
 \r
+$nucleus['version'] = 'v3.41RC';\r
+$nucleus['codename'] = '';\r
 \r
-checkVars(array('nucleus', 'CONF', 'DIR_LIBS', 'MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE', 'DIR_LANG', 'DIR_PLUGINS'));\r
+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'));\r
 \r
 $CONF['debug'] = 0;\r
-\r
-$nucleus['version'] = 'v3.15';\r
-if (getNucleusPatchLevel() > 0)\r
-{\r
-       $nucleus['version'] .= '/' . getNucleusPatchLevel();\r
+if ($CONF['debug']) {\r
+       error_reporting(E_ALL); // report all errors!\r
+} else {\r
+       error_reporting(E_ERROR | E_WARNING | E_PARSE);\r
 }\r
 \r
 /*\r
@@ -40,69 +46,74 @@ if (getNucleusPatchLevel() > 0)
                more of the installation files (install.php, install.sql, upgrades/\r
                directory) are still on the server.\r
 */\r
-$CONF['alertOnHeadersSent'] = 1;\r
+\r
+$CONF['alertOnHeadersSent']  = 1;\r
 $CONF['alertOnSecurityRisk'] = 1;\r
+/*$CONF['ItemURL']             = $CONF['Self'];\r
+$CONF['ArchiveURL']          = $CONF['Self'];\r
+$CONF['ArchiveListURL']      = $CONF['Self'];\r
+$CONF['MemberURL']           = $CONF['Self'];\r
+$CONF['SearchURL']           = $CONF['Self'];\r
+$CONF['BlogURL']             = $CONF['Self'];\r
+$CONF['CategoryURL']         = $CONF['Self'];\r
 \r
-/**\r
-  * returns the currently used version (100 = 1.00, 101 = 1.01, etc...)\r
-  */\r
-function getNucleusVersion() {\r
-       return 315;\r
-}\r
+// switch URLMode back to normal when $CONF['Self'] ends in .php\r
+// this avoids urls like index.php/item/13/index.php/item/15\r
+if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {\r
+       $CONF['URLMode'] = 'normal';\r
+}*/\r
 \r
-/**\r
- * power users can install patches in between nucleus releases. These patches\r
- * usually add new functionality in the plugin API and allow those to\r
- * be tested without having to install CVS.\r
- */\r
-function getNucleusPatchLevel() {\r
-       return 0;\r
+if (getNucleusPatchLevel() > 0) {\r
+       $nucleus['version'] .= '/' . getNucleusPatchLevel();\r
 }\r
 \r
-\r
-if ($CONF['debug']) {\r
-       error_reporting(E_ALL & ~E_NOTICE);     // report almost all errors!\r
-                                                                               // (no uninitialized vars and such)\r
-} else {\r
-       error_reporting(E_ERROR | E_WARNING | E_PARSE);\r
+// Avoid notices\r
+if (!isset($CONF['installscript'])) {\r
+       $CONF['installscript'] = 0;\r
 }\r
 \r
 // we will use postVar, getVar, ... methods instead of HTTP_GET_VARS or _GET\r
-if ($CONF['installscript']!=1){ // vars were already included in install.php\r
-  if (phpversion() >= '4.1.0')\r
-         include_once($DIR_LIBS . 'vars4.1.0.php');\r
-  else\r
-         include_once($DIR_LIBS . 'vars4.0.6.php');\r
+if ($CONF['installscript'] != 1) { // vars were already included in install.php\r
+       if (phpversion() >= '4.1.0') {\r
+               include_once($DIR_LIBS . 'vars4.1.0.php');\r
+       } else {\r
+               include_once($DIR_LIBS . 'vars4.0.6.php');\r
+       }\r
 }\r
 \r
-function intPostVar($name) { return intval(postVar($name));}\r
-function intGetVar($name) { return intval(getVar($name));}\r
-function intRequestVar($name) { return intval(requestVar($name)); }\r
-function intCookieVar($name) { return intval(cookieVar($name)); }\r
+// sanitize option\r
+$bLoggingSanitizedResult=0;\r
+$bSanitizeAndContinue=0;\r
+\r
+$orgRequestURI = serverVar('REQUEST_URI');\r
+sanitizeParams();\r
 \r
 // get all variables that can come from the request and put them in the global scope\r
-$blogid                        = requestVar('blogid');\r
-$itemid                        = intRequestVar('itemid');\r
-$catid                 = intRequestVar('catid');\r
-$skinid                        = requestVar('skinid');\r
-$memberid              = requestVar('memberid');\r
-$archivelist   = requestVar('archivelist');\r
-$imagepopup            = requestVar('imagepopup');\r
-$archive               = requestVar('archive');\r
-$query                 = requestVar('query');\r
-$highlight             = requestVar('highlight');\r
-$amount                        = requestVar('amount');\r
-$action                        = requestVar('action');\r
-$nextaction            = requestVar('nextaction');\r
-$maxresults     = requestVar('maxresults');\r
-$startpos       = intRequestVar('startpos');\r
-$errormessage  = '';\r
-$error                 = '';\r
-\r
-if (!headers_sent())\r
-       header('Generator: Nucleus ' . $nucleus['version']);\r
+$blogid       = requestVar('blogid');\r
+$itemid       = intRequestVar('itemid');\r
+$catid        = intRequestVar('catid');\r
+$skinid       = requestVar('skinid');\r
+$memberid     = requestVar('memberid');\r
+$archivelist  = requestVar('archivelist');\r
+$imagepopup   = requestVar('imagepopup');\r
+$archive      = requestVar('archive');\r
+$query        = requestVar('query');\r
+$highlight    = requestVar('highlight');\r
+$amount       = requestVar('amount');\r
+$action       = requestVar('action');\r
+$nextaction   = requestVar('nextaction');\r
+$maxresults   = requestVar('maxresults');\r
+$startpos     = intRequestVar('startpos');\r
+$errormessage = '';\r
+$error        = '';\r
+$virtualpath  = ((getVar('virtualpath') != null) ? getVar('virtualpath') : serverVar('PATH_INFO'));\r
+\r
+if (!headers_sent() ) {\r
+       header('Generator: Nucleus CMS ' . $nucleus['version']);\r
+}\r
 \r
 // include core classes that are needed for login & plugin handling\r
+include($DIR_LIBS . 'mysql.php');\r
 include($DIR_LIBS . 'MEMBER.php');\r
 include($DIR_LIBS . 'ACTIONLOG.php');\r
 include($DIR_LIBS . 'MANAGER.php');\r
@@ -113,15 +124,32 @@ $manager =& MANAGER::instance();
 // make sure there's no unnecessary escaping:\r
 set_magic_quotes_runtime(0);\r
 \r
+// Avoid notices\r
+if (!isset($CONF['UsingAdminArea'])) {\r
+       $CONF['UsingAdminArea'] = 0;\r
+}\r
+\r
 // only needed when updating logs\r
 if ($CONF['UsingAdminArea']) {\r
        include($DIR_LIBS . 'xmlrpc.inc.php');  // XML-RPC client classes\r
        include_once($DIR_LIBS . 'ADMIN.php');\r
 }\r
 \r
-\r
-// connect to sql\r
+// connect to database\r
 sql_connect();\r
+$SQLCount = 0;\r
+\r
+// logs sanitized result if need\r
+if ($orgRequestURI!==serverVar('REQUEST_URI')) {\r
+       $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";\r
+       $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');\r
+    if ($bLoggingSanitizedResult) {\r
+        addToLog(WARNING, $msg);\r
+    }\r
+    if (!$bSanitizeAndContinue) {\r
+        die("");\r
+    }\r
+}\r
 \r
 // makes sure database connection gets closed on script termination\r
 register_shutdown_function('sql_disconnect');\r
@@ -129,35 +157,98 @@ register_shutdown_function('sql_disconnect');
 // read config\r
 getConfig();\r
 \r
+// Properly set $CONF['Self'] and others if it's not set... usually when we are access from admin menu\r
+if (!isset($CONF['Self'])) {\r
+       $CONF['Self'] = $CONF['IndexURL'];\r
+       // strip trailing /\r
+       if ($CONF['Self'][strlen($CONF['Self']) -1] == "/") {\r
+               $CONF['Self'] = substr($CONF['Self'], 0, strlen($CONF['Self']) -1);\r
+       }\r
+\r
+/*     $CONF['ItemURL']        = $CONF['Self'];\r
+       $CONF['ArchiveURL']     = $CONF['Self'];\r
+       $CONF['ArchiveListURL'] = $CONF['Self'];\r
+       $CONF['MemberURL']      = $CONF['Self'];\r
+       $CONF['SearchURL']      = $CONF['Self'];\r
+       $CONF['BlogURL']        = $CONF['Self'];\r
+       $CONF['CategoryURL']    = $CONF['Self'];*/\r
+}\r
+\r
+$CONF['ItemURL'] = $CONF['Self'];\r
+$CONF['ArchiveURL'] = $CONF['Self'];\r
+$CONF['ArchiveListURL'] = $CONF['Self'];\r
+$CONF['MemberURL'] = $CONF['Self'];\r
+$CONF['SearchURL'] = $CONF['Self'];\r
+$CONF['BlogURL'] = $CONF['Self'];\r
+$CONF['CategoryURL'] = $CONF['Self'];\r
+\r
+// switch URLMode back to normal when $CONF['Self'] ends in .php\r
+// this avoids urls like index.php/item/13/index.php/item/15\r
+if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {\r
+       $CONF['URLMode'] = 'normal';\r
+}\r
+\r
 // automatically use simpler toolbar for mozilla\r
-if (($CONF['DisableJsTools'] == 0) && strstr(serverVar('HTTP_USER_AGENT'),'Mozilla/5.0') && strstr(serverVar('HTTP_USER_AGENT'),'Gecko'))\r
+if (($CONF['DisableJsTools'] == 0) && strstr(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0') && strstr(serverVar('HTTP_USER_AGENT'), 'Gecko') ) {\r
        $CONF['DisableJsTools'] = 2;\r
+}\r
 \r
 // login if cookies set\r
-\r
 $member = new MEMBER();\r
 \r
+// secure cookie key settings (either 'none', 0, 8, 16, 24, or 32)\r
+if (!isset($CONF['secureCookieKey'])) $CONF['secureCookieKey']=24;\r
+switch($CONF['secureCookieKey']){\r
+case 8:\r
+       $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));\r
+       break;\r
+case 16:\r
+       $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));\r
+       break;\r
+case 24:\r
+       $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+$/','',serverVar('REMOTE_ADDR'));\r
+       break;\r
+case 32:\r
+       $CONF['secureCookieKeyIP']=serverVar('REMOTE_ADDR');\r
+       break;\r
+default:\r
+       $CONF['secureCookieKeyIP']='';\r
+}\r
+\r
 // login/logout when required or renew cookies\r
 if ($action == 'login') {\r
        // Form Authentication\r
-       $login  = postVar('login');\r
-       $pw     = postVar('password');\r
+       $login = postVar('login');\r
+       $pw = postVar('password');\r
        $shared = intPostVar('shared'); // shared computer or not\r
 \r
-       if ($member->login($login,$pw)) {\r
+       $pw=substr($pw,0,40); // avoid md5 collision by using a long key\r
+\r
+       if ($member->login($login, $pw) ) {\r
 \r
                $member->newCookieKey();\r
                $member->setCookies($shared);\r
 \r
+               if ($CONF['secureCookieKey']!=='none') {\r
+                       // secure cookie key\r
+                       $member->setCookieKey(md5($member->getCookieKey().$CONF['secureCookieKeyIP']));\r
+                       $member->write();\r
+               }\r
+\r
                // allows direct access to parts of the admin area after logging in\r
-               if ($nextaction)\r
+               if ($nextaction) {\r
                        $action = $nextaction;\r
+               }\r
 \r
-               $manager->notify('LoginSuccess',array('member' => &$member));\r
+               $manager->notify('LoginSuccess', array('member' => &$member) );\r
+               $errormessage = '';\r
                ACTIONLOG::add(INFO, "Login successful for $login (sharedpc=$shared)");\r
        } else {\r
-               $manager->notify('LoginFailed',array('username' => $login));\r
-               ACTIONLOG::add(INFO, 'Login failed for ' . $login);\r
+               // errormessage for [%errordiv%]\r
+               $errormessage = 'Login failed for ' . $login;\r
+\r
+               $manager->notify('LoginFailed', array('username' => $login) );\r
+               ACTIONLOG::add(INFO, $errormessage);\r
        }\r
 /*\r
 \r
@@ -165,46 +256,61 @@ Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for det
 \r
 } elseif (serverVar('PHP_AUTH_USER') && serverVar('PHP_AUTH_PW')) {\r
        // HTTP Authentication\r
-       $login  = serverVar('PHP_AUTH_USER');\r
-       $pw     = serverVar('PHP_AUTH_PW');\r
-\r
-       if ($member->login($login,$pw)) {\r
-               $manager->notify('LoginSuccess',array('member' => &$member));\r
-               ACTIONLOG::add(INFO, "HTTP authentication successful for $login");\r
-       } else {\r
-               $manager->notify('LoginFailed',array('username' => $login));\r
-               ACTIONLOG::add(INFO, 'HTTP authentication failed for ' . $login);\r
-\r
-               //Since bad credentials, generate an apropriate error page\r
-               header("WWW-Authenticate: Basic realm=\"Nucleus {$nucleus['version']}\"");\r
-               header('HTTP/1.0 401 Unauthorized');\r
-               echo 'Invalid username or password';\r
-               exit;\r
-       }\r
+       $login  = serverVar('PHP_AUTH_USER');\r
+       $pw     = serverVar('PHP_AUTH_PW');\r
+\r
+       if ($member->login($login, $pw) ) {\r
+               $manager->notify('LoginSuccess',array('member' => &$member));\r
+               ACTIONLOG::add(INFO, "HTTP authentication successful for $login");\r
+       } else {\r
+               $manager->notify('LoginFailed',array('username' => $login));\r
+               ACTIONLOG::add(INFO, 'HTTP authentication failed for ' . $login);\r
+\r
+               //Since bad credentials, generate an apropriate error page\r
+               header("WWW-Authenticate: Basic realm=\"Nucleus CMS {$nucleus['version']}\"");\r
+               header('HTTP/1.0 401 Unauthorized');\r
+               echo 'Invalid username or password';\r
+               exit;\r
+       }\r
 */\r
 \r
-} elseif (($action == 'logout') && (!headers_sent()) && cookieVar('user')){\r
+} elseif (($action == 'logout') && (!headers_sent() ) && cookieVar($CONF['CookiePrefix'] . 'user') ) {\r
        // remove cookies on logout\r
-       setcookie('user','',(time()-2592000),$CONF['CookiePath'],$CONF['CookieDomain'],$CONF['CookieSecure']);\r
-       setcookie('loginkey','',(time()-2592000),$CONF['CookiePath'],$CONF['CookieDomain'],$CONF['CookieSecure']);\r
-       $manager->notify('Logout',array('username' => cookieVar('user')));\r
-} elseif (cookieVar('user')) {\r
+       setcookie($CONF['CookiePrefix'] . 'user', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);\r
+       setcookie($CONF['CookiePrefix'] . 'loginkey', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);\r
+       $manager->notify('Logout', array('username' => cookieVar($CONF['CookiePrefix'] . 'user') ) );\r
+} elseif (cookieVar($CONF['CookiePrefix'] . 'user') ) {\r
        // Cookie Authentication\r
-       $res = $member->cookielogin(cookieVar('user'), cookieVar('loginkey'));\r
+       $ck=cookieVar($CONF['CookiePrefix'] . 'loginkey');\r
+       // secure cookie key\r
+       $ck=substr($ck,0,32); // avoid md5 collision by using a long key\r
+       if ($CONF['secureCookieKey']!=='none') $ck=md5($ck.$CONF['secureCookieKeyIP']);\r
+       $res = $member->cookielogin(cookieVar($CONF['CookiePrefix'] . 'user'), $ck );\r
+       unset($ck);\r
 \r
        // renew cookies when not on a shared computer\r
-       if ($res && (cookieVar('sharedpc') != 1) && (!headers_sent()))\r
+       if ($res && (cookieVar($CONF['CookiePrefix'] . 'sharedpc') != 1) && (!headers_sent() ) ) {\r
+               $member->setCookieKey(cookieVar($CONF['CookiePrefix'] . 'loginkey'));\r
                $member->setCookies();\r
+       }\r
 }\r
 \r
 // login completed\r
-$manager->notify('PostAuthentication',array('loggedIn' => $member->isLoggedIn()));\r
+$manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );\r
+ticketForPlugin();\r
+\r
+// first, let's see if the site is disabled or not. always allow admin area access.\r
+if ($CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea']) {\r
+       redirect($CONF['DisableSiteURL']);\r
+       exit;\r
+}\r
 \r
 // load other classes\r
 include($DIR_LIBS . 'PARSER.php');\r
 include($DIR_LIBS . 'SKIN.php');\r
 include($DIR_LIBS . 'TEMPLATE.php');\r
 include($DIR_LIBS . 'BLOG.php');\r
+include($DIR_LIBS . 'BODYACTIONS.php');\r
 include($DIR_LIBS . 'COMMENTS.php');\r
 include($DIR_LIBS . 'COMMENT.php');\r
 //include($DIR_LIBS . 'ITEM.php');\r
@@ -212,24 +318,33 @@ include($DIR_LIBS . 'NOTIFICATION.php');
 include($DIR_LIBS . 'BAN.php');\r
 include($DIR_LIBS . 'PAGEFACTORY.php');\r
 include($DIR_LIBS . 'SEARCH.php');\r
+include($DIR_LIBS . 'entity.php');\r
 \r
 \r
 // set lastVisit cookie (if allowed)\r
-if (!headers_sent()) {\r
-       if ($CONF['LastVisit'])\r
-               setcookie('lastVisit',time(),time()+2592000,$CONF['CookiePath'],$CONF['CookieDomain'],$CONF['CookieSecure']);\r
-       else\r
-               setcookie('lastVisit','',(time()-2592000),$CONF['CookiePath'],$CONF['CookieDomain'],$CONF['CookieSecure']);\r
+if (!headers_sent() ) {\r
+       if ($CONF['LastVisit']) {\r
+               setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);\r
+       } else {\r
+               setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);\r
+       }\r
 }\r
 \r
 // read language file, only after user has been initialized\r
 $language = getLanguageName();\r
 include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');\r
 \r
+// check if valid charset\r
+if (!encoding_check(false, false, _CHARSET)) {\r
+       foreach(array($_GET, $_POST) as $input) {\r
+               array_walk($input, 'encoding_check');\r
+       }\r
+}\r
+\r
 /*\r
        Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details\r
-       \r
-// To remove after v2.5 is released and language files have been updated. \r
+\r
+// To remove after v2.5 is released and language files have been updated.\r
 // Including this makes sure that language files for v2.5beta can still be used for v2.5final\r
 // without having weird _SETTINGS_EXTAUTH string showing up in the admin area.\r
 if (!defined('_MEMBERS_BYPASS'))\r
@@ -241,80 +356,221 @@ if (!defined('_MEMBERS_BYPASS'))
 \r
 */\r
 \r
+// make sure the archivetype skinvar keeps working when _ARCHIVETYPE_XXX not defined\r
+if (!defined('_ARCHIVETYPE_MONTH') ) {\r
+       define('_ARCHIVETYPE_DAY', 'day');\r
+       define('_ARCHIVETYPE_MONTH', 'month');\r
+}\r
+\r
 // decode path_info\r
 if ($CONF['URLMode'] == 'pathinfo') {\r
-       $data = explode("/",serverVar('PATH_INFO'));\r
-       for ($i=0;$i<sizeof($data);$i++) {\r
-               switch ($data[$i]) {\r
-                       case 'item':                    // item/1 (blogid)\r
-                               $i++;\r
-                               if ($i<sizeof($data)) $itemid = intval($data[$i]);\r
-                               break;\r
-                       case 'archives':                // archives/1 (blogid)\r
-                               $i++;\r
-                               if ($i<sizeof($data)) $archivelist = intval($data[$i]);\r
-                               break;\r
-                       case 'archive':                 // two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid)\r
-                               if ((($i+1)<sizeof($data)) && (!strstr($data[$i+1],'-')) ){\r
-                                       $blogid = intval($data[++$i]);\r
-                               }\r
-                               $i++;\r
-                               if ($i<sizeof($data)) $archive = $data[$i];\r
-                               break;\r
-                       case 'blogid':                  // blogid/1\r
-                       case 'blog':                    // blog/1\r
-                               $i++;\r
-                               if ($i<sizeof($data)) $blogid = intval($data[$i]);\r
-                               break;\r
-                       case 'category':                // category/1 (catid)\r
-                       case 'catid':\r
-                               $i++;\r
-                               if ($i<sizeof($data)) $catid = intval($data[$i]);\r
-                               break;\r
-                       case 'member':\r
-                               $i++;\r
-                               if ($i<sizeof($data)) $memberid = intval($data[$i]);\r
-                               break;\r
-                       default:\r
-                               // skip...\r
+       // initialize keywords if this hasn't been done before\r
+       if (!isset($CONF['ItemKey']) || $CONF['ItemKey'] == '') {\r
+               $CONF['ItemKey'] = 'item';\r
+       }\r
+\r
+       if (!isset($CONF['ArchiveKey']) || $CONF['ArchiveKey'] == '') {\r
+               $CONF['ArchiveKey'] = 'archive';\r
+       }\r
+\r
+       if (!isset($CONF['ArchivesKey']) || $CONF['ArchivesKey'] == '') {\r
+               $CONF['ArchivesKey'] = 'archives';\r
+       }\r
+\r
+       if (!isset($CONF['MemberKey']) || $CONF['MemberKey'] == '') {\r
+               $CONF['MemberKey'] = 'member';\r
+       }\r
+\r
+       if (!isset($CONF['BlogKey']) || $CONF['BlogKey'] == '') {\r
+               $CONF['BlogKey'] = 'blog';\r
+       }\r
+\r
+       if (!isset($CONF['CategoryKey']) || $CONF['CategoryKey'] == '') {\r
+               $CONF['CategoryKey'] = 'category';\r
+       }\r
+\r
+       if (!isset($CONF['SpecialskinKey']) || $CONF['SpecialskinKey'] == '') {\r
+               $CONF['SpecialskinKey'] = 'special';\r
+       }\r
+\r
+       $parsed = false;\r
+       $manager->notify(\r
+               'ParseURL',\r
+               array(\r
+                       'type' => basename(serverVar('SCRIPT_NAME') ), // e.g. item, blog, ...\r
+                       'info' => $virtualpath,\r
+                       'complete' => &$parsed\r
+               )\r
+       );\r
+\r
+       if (!$parsed) {\r
+               // default implementation\r
+               $data = explode("/", $virtualpath );\r
+               for ($i = 0; $i < sizeof($data); $i++) {\r
+                       switch ($data[$i]) {\r
+                               case $CONF['ItemKey']: // item/1 (blogid)\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $itemid = intval($data[$i]);\r
+                                       }\r
+                                       break;\r
+\r
+                               case $CONF['ArchivesKey']: // archives/1 (blogid)\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $archivelist = intval($data[$i]);\r
+                                       }\r
+                                       break;\r
+\r
+                               case $CONF['ArchiveKey']: // two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid)\r
+                                       if ((($i + 1) < sizeof($data) ) && (!strstr($data[$i + 1], '-') ) ) {\r
+                                               $blogid = intval($data[++$i]);\r
+                                       }\r
+\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $archive = $data[$i];\r
+                                       }\r
+                                       break;\r
+\r
+                               case 'blogid': // blogid/1\r
+                               case $CONF['BlogKey']: // blog/1\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $blogid = intval($data[$i]);\r
+                                       }\r
+                                       break;\r
+\r
+                               case $CONF['CategoryKey']: // category/1 (catid)\r
+                               case 'catid':\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $catid = intval($data[$i]);\r
+                                       }\r
+                                       break;\r
+\r
+                               case $CONF['MemberKey']:\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $memberid = intval($data[$i]);\r
+                                       }\r
+                                       break;\r
+\r
+                case $CONF['SpecialskinKey']:\r
+                    $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                       $_REQUEST['special'] = $data[$i];\r
+                    }\r
+                    break;\r
+\r
+                               default:\r
+                                       // skip...\r
+                       }\r
                }\r
        }\r
 }\r
 \r
+function intPostVar($name) {\r
+       return intval(postVar($name) );\r
+}\r
+\r
+function intGetVar($name) {\r
+       return intval(getVar($name) );\r
+}\r
+\r
+function intRequestVar($name) {\r
+       return intval(requestVar($name) );\r
+}\r
+\r
+function intCookieVar($name) {\r
+       return intval(cookieVar($name) );\r
+}\r
+\r
+/**\r
+  * returns the currently used version (100 = 1.00, 101 = 1.01, etc...)\r
+  */\r
+function getNucleusVersion() {\r
+       return 341;\r
+}\r
+\r
+/**\r
+ * power users can install patches in between nucleus releases. These patches\r
+ * usually add new functionality in the plugin API and allow those to\r
+ * be tested without having to install CVS.\r
+ */\r
+function getNucleusPatchLevel() {\r
+       return 0;\r
+}\r
+\r
 /**\r
   * Connects to mysql server\r
   */\r
 function sql_connect() {\r
-       global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE;\r
-\r
-       $connection = @mysql_connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD) or startUpError('<p>Could not connect to MySQL database.</p>','Connect Error');\r
-       mysql_select_db($MYSQL_DATABASE) or startUpError('<p>Could not select database: '. mysql_error().'</p>', 'Connect Error');\r
+       global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_CONN;\r
+\r
+       $MYSQL_CONN = @mysql_connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD) or startUpError('<p>Could not connect to MySQL database.</p>', 'Connect Error');\r
+       mysql_select_db($MYSQL_DATABASE) or startUpError('<p>Could not select database: ' . mysql_error() . '</p>', 'Connect Error');\r
+\r
+/*/ <add for garble measure>\r
+       $resource = sql_query("show variables LIKE 'character_set_database'");\r
+       $fetchDat = mysql_fetch_assoc($resource);\r
+       $charset  = $fetchDat['Value'];\r
+       $mySqlVer = implode('.', array_map('intval', explode('.', mysql_get_server_info($MYSQL_CONN))));\r
+       if ($mySqlVer >= '5.0.7' && phpversion() >= '5.2.3') {\r
+               mysql_set_charset($charset);\r
+       } else {\r
+               sql_query("SET NAMES " . $charset);\r
+       }\r
+// </add for garble measure>*/\r
 \r
-       return $connection;\r
+       return $MYSQL_CONN;\r
 }\r
 \r
 /**\r
  * returns a prefixed nucleus table name\r
  */\r
-function sql_table($name)\r
-{\r
+function sql_table($name) {\r
        global $MYSQL_PREFIX;\r
 \r
-       if ($MYSQL_PREFIX)\r
+       if ($MYSQL_PREFIX) {\r
                return $MYSQL_PREFIX . 'nucleus_' . $name;\r
-       else\r
+       } else {\r
                return 'nucleus_' . $name;\r
+       }\r
 }\r
 \r
 function sendContentType($contenttype, $pagetype = '', $charset = _CHARSET) {\r
        global $manager, $CONF;\r
-       \r
-       if (!headers_sent()) {\r
+\r
+       if (!headers_sent() ) {\r
                // if content type is application/xhtml+xml, only send it to browsers\r
                // that can handle it (IE6 cannot). Otherwise, send text/html\r
-               \r
+\r
                // v2.5: For admin area pages, keep sending text/html (unless it's a debug version)\r
                //       application/xhtml+xml still causes too much problems with the javascript implementations\r
+\r
+               // v3.3: ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,\r
+               //       application/xhtml+xml seems to be working, so we're going to use it if we can.\r
+               //\r
+               // Note: reverted the following function in JP version\r
+               //\r
+       /*\r
+               // v3.3 code\r
+               if (\r
+                               ($contenttype == 'application/xhtml+xml')\r
+                       &&      (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') )\r
+                       ) {\r
+                       $contenttype = 'text/html';\r
+               }\r
+       */\r
+               // v3.2x code\r
                if (\r
                                ($contenttype == 'application/xhtml+xml')\r
                        &&      (($CONF['UsingAdminArea'] && !$CONF['debug']) || !stristr(serverVar('HTTP_ACCEPT'),'application/xhtml+xml'))\r
@@ -322,7 +578,7 @@ function sendContentType($contenttype, $pagetype = '', $charset = _CHARSET) {
                {\r
                        $contenttype = 'text/html';\r
                }\r
-                       \r
+\r
                $manager->notify(\r
                        'PreSendContentType',\r
                        array(\r
@@ -331,26 +587,36 @@ function sendContentType($contenttype, $pagetype = '', $charset = _CHARSET) {
                                'pageType' => $pagetype\r
                        )\r
                );\r
-               \r
+\r
                // strip strange characters\r
                $contenttype = preg_replace('|[^a-z0-9-+./]|i', '', $contenttype);\r
                $charset = preg_replace('|[^a-z0-9-_]|i', '', $charset);\r
-               \r
-               header('Content-Type: ' . $contenttype . '; charset=' . $charset);                      \r
-       }\r
-       \r
-       \r
 \r
-       \r
+               if ($charset != '') {\r
+                       header('Content-Type: ' . $contenttype . '; charset=' . $charset);\r
+               } else {\r
+                       header('Content-Type: ' . $contenttype);\r
+               }\r
+\r
+               // check if valid charset\r
+               if (!encoding_check(false,false,$charset)) {\r
+                       foreach(array($_GET, $_POST) as $input) {\r
+                               array_walk($input, 'encoding_check');\r
+                       }\r
+               }\r
+       }\r
 }\r
 \r
 /**\r
  * Errors before the database connection has been made\r
  */\r
 function startUpError($msg, $title) {\r
+       if (!defined('_CHARSET')) define('_CHARSET', 'iso-8859-1');\r
+       header('Content-Type: text/html; charset=' . _CHARSET);\r
        ?>\r
-       <html xmlns="http://www.w3.org/1999/xhtml">\r
-               <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title><?php echo htmlspecialchars($title)?></title></head>\r
+       <html <?php echo _HTML_XML_NAME_SPACE_AND_LANG_CODE; ?>>\r
+               <head><meta http-equiv="Content-Type" content="text/html; charset=<?php echo _CHARSET?>" />\r
+               <title><?php echo htmlspecialchars($title)?></title></head>\r
                <body>\r
                        <h1><?php echo htmlspecialchars($title)?></h1>\r
                        <?php echo $msg?>\r
@@ -370,6 +636,8 @@ function sql_disconnect() {
   * executes an SQL query\r
   */\r
 function sql_query($query) {\r
+       global $SQLCount;\r
+       $SQLCount++;\r
        $res = mysql_query($query) or print("mySQL error with query $query: " . mysql_error() . '<p />');\r
        return $res;\r
 }\r
@@ -387,12 +655,16 @@ function sql_query($query) {
  *\r
  */\r
 function highlight($text, $expression, $highlight) {\r
-       if (!$highlight || !$expression) return $text;\r
-       if (is_array($expression) && (count($expression) == 0))\r
+       if (!$highlight || !$expression) {\r
+               return $text;\r
+       }\r
+\r
+       if (is_array($expression) && (count($expression) == 0) ) {\r
                return $text;\r
+       }\r
 \r
        // add a tag in front (is needed for preg_match_all to work correct)\r
-       $text = '<!--h-->'.$text;\r
+       $text = '<!--h-->' . $text;\r
 \r
        // split the HTML up so we have HTML tags\r
        // $matches[0][i] = HTML + text\r
@@ -403,15 +675,20 @@ function highlight($text, $expression, $highlight) {
        // throw it all together again while applying the highlight to the text pieces\r
        $result = '';\r
        for ($i = 0; $i < sizeof($matches[2]); $i++) {\r
-               if ($i != 0) $result .= $matches[1][$i];\r
+               if ($i != 0) {\r
+                       $result .= $matches[1][$i];\r
+               }\r
+\r
+               if (is_array($expression) ) {\r
+                       foreach ($expression as $regex) {\r
+                               if ($regex) {\r
+                                       $matches[2][$i] = @eregi_replace($regex, $highlight, $matches[2][$i]);\r
+                               }\r
+                       }\r
 \r
-               if (is_array($expression)) {\r
-                       foreach ($expression as $regex)\r
-                               if ($regex)\r
-                                       $matches[2][$i] = @eregi_replace($regex,$highlight,$matches[2][$i]);\r
                        $result .= $matches[2][$i];\r
                } else {\r
-                       $result .= @eregi_replace($expression,$highlight,$matches[2][$i]);\r
+                       $result .= @eregi_replace($expression, $highlight, $matches[2][$i]);\r
                }\r
        }\r
 \r
@@ -425,54 +702,66 @@ function parseHighlight($query) {
        // TODO: add more intelligent splitting logic\r
 \r
        // get rid of quotes\r
-       $query = preg_replace('/\'|"/','',$query);\r
+       $query = preg_replace('/\'|"/', '', $query);\r
 \r
-       if (!query) return array();\r
+       if (!query) {\r
+               return array();\r
+       }\r
 \r
        $aHighlight = explode(' ', $query);\r
 \r
-       for ($i = 0; $i<count($aHighlight); $i++) {\r
+       for ($i = 0; $i < count($aHighlight); $i++) {\r
                $aHighlight[$i] = trim($aHighlight[$i]);\r
-               if (strlen($aHighlight[$i]) < 3)\r
+\r
+               if (strlen($aHighlight[$i]) < 3) {\r
                        unset($aHighlight[$i]);\r
+               }\r
        }\r
 \r
-       if (count($aHighlight) == 1)\r
+       if (count($aHighlight) == 1) {\r
                return $aHighlight[0];\r
-       else\r
+       } else {\r
                return $aHighlight;\r
+       }\r
 }\r
 \r
 /**\r
   * Checks if email address is valid\r
   */\r
 function isValidMailAddress($address) {\r
-       if (preg_match('/^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+\.[A-Za-z]{2,5}$/', $address))\r
+       if (preg_match('/^[a-zA-Z+0-9\._-]+@[a-zA-Z0-9\._-]+\.[A-Za-z]{2,5}$/', $address)) {\r
                return 1;\r
-       else\r
+       } else {\r
                return 0;\r
+       }\r
 }\r
 \r
 \r
 // some helper functions\r
 function getBlogIDFromName($name) {\r
-       return quickQuery('SELECT bnumber as result FROM '.sql_table('blog').' WHERE bshortname="'.addslashes($name).'"');\r
+       return quickQuery('SELECT bnumber as result FROM ' . sql_table('blog') . ' WHERE bshortname="' . addslashes($name) . '"');\r
 }\r
+\r
 function getBlogNameFromID($id) {\r
-       return quickQuery('SELECT bname as result FROM '.sql_table('blog').' WHERE bnumber='.intval($id));\r
+       return quickQuery('SELECT bname as result FROM ' . sql_table('blog') . ' WHERE bnumber=' . intval($id) );\r
 }\r
+\r
 function getBlogIDFromItemID($itemid) {\r
-       return quickQuery('SELECT iblog as result FROM '.sql_table('item').' WHERE inumber='.intval($itemid));\r
+       return quickQuery('SELECT iblog as result FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid) );\r
 }\r
+\r
 function getBlogIDFromCommentID($commentid) {\r
-       return quickQuery('SELECT cblog as result FROM '.sql_table('comment').' WHERE cnumber='.intval($commentid));\r
+       return quickQuery('SELECT cblog as result FROM ' . sql_table('comment') . ' WHERE cnumber=' . intval($commentid) );\r
 }\r
+\r
 function getBlogIDFromCatID($catid) {\r
-       return quickQuery('SELECT cblog as result FROM '.sql_table('category').' WHERE catid='.intval($catid));\r
+       return quickQuery('SELECT cblog as result FROM ' . sql_table('category') . ' WHERE catid=' . intval($catid) );\r
 }\r
+\r
 function getCatIDFromName($name) {\r
-       return quickQuery('SELECT catid as result FROM '.sql_table('category').' WHERE cname="'.addslashes($name).'"');\r
+       return quickQuery('SELECT catid as result FROM ' . sql_table('category') . ' WHERE cname="' . addslashes($name) . '"');\r
 }\r
+\r
 function quickQuery($q) {\r
        $res = sql_query($q);\r
        $obj = mysql_fetch_object($res);\r
@@ -480,7 +769,8 @@ function quickQuery($q) {
 }\r
 \r
 function getPluginNameFromPid($pid) {\r
-       $obj = mysql_fetch_object(sql_query('SELECT pfile FROM '.sql_table('plugin').' WHERE pid='.intval($pid)));\r
+       $res = sql_query('SELECT pfile FROM ' . sql_table('plugin') . ' WHERE pid=' . intval($pid) );\r
+       $obj = mysql_fetch_object($res);\r
        return $obj->pfile;\r
 }\r
 \r
@@ -490,27 +780,33 @@ function selector() {
        global $imagepopup, $catid;\r
        global $manager;\r
 \r
-       // first, let's see if the site is disabled or not\r
-       if ($CONF['DisableSite'] && !$member->isAdmin()) {\r
-               redirect($CONF['DisableSiteURL']);\r
-               exit;\r
-       }\r
+       $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');\r
+       $action = requestVar('action');\r
+\r
+       if (in_array($action, $actionNames) ) {\r
+               global $DIR_LIBS, $errormessage;\r
+               include_once($DIR_LIBS . 'ACTION.php');\r
+               $a = new ACTION();\r
+               $errorInfo = $a->doAction($action);\r
 \r
+               if ($errorInfo) {\r
+                       $errormessage = $errorInfo['message'];\r
+               }\r
+       }\r
 \r
        // show error when headers already sent out\r
        if (headers_sent() && $CONF['alertOnHeadersSent']) {\r
 \r
                // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)\r
-               if (function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=')) {\r
+               if (function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') ) {\r
                        headers_sent($hsFile, $hsLine);\r
-                       $extraInfo = ' in <code>'.$hsFile.'</code> line <code>'.$hsLine.'</code>';\r
+                       $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';\r
                } else {\r
                        $extraInfo = '';\r
                }\r
 \r
-\r
                startUpError(\r
-                       '<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>',\r
+                       '<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>',\r
                        'Page headers already sent'\r
                );\r
                exit;\r
@@ -518,51 +814,79 @@ function selector() {
 \r
        // make is so ?archivelist without blogname or blogid shows the archivelist\r
        // for the default weblog\r
-       if (serverVar('QUERY_STRING') == 'archivelist')\r
+       if (serverVar('QUERY_STRING') == 'archivelist') {\r
                $archivelist = $CONF['DefaultBlog'];\r
+       }\r
 \r
        // now decide which type of skin we need\r
        if ($itemid) {\r
                // itemid given -> only show that item\r
                $type = 'item';\r
-               if (!$manager->existsItem($itemid,0,0))\r
-                       doError(_ERROR_NOSUCHITEM);\r
 \r
+               if (!$manager->existsItem($itemid,0,0) ) {\r
+                       doError(_ERROR_NOSUCHITEM);\r
+               }\r
 \r
                global $itemidprev, $itemidnext, $catid, $itemtitlenext, $itemtitleprev;\r
 \r
-               // 1. get timestamp and blogid for item\r
-               $query = 'SELECT itime, iblog FROM '.sql_table('item').' WHERE inumber=' . intval($itemid);\r
+               // 1. get timestamp, blogid and catid for item\r
+               $query = 'SELECT itime, iblog, icat FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid);\r
                $res = sql_query($query);\r
                $obj = mysql_fetch_object($res);\r
 \r
                // if a different blog id has been set through the request or selectBlog(),\r
                // deny access\r
-               if ($blogid && (intval($blogid) != $obj->iblog))\r
-                       doError(_ERROR_NOSUCHITEM);\r
+//             if ($blogid && (intval($blogid) != $obj->iblog) ) {\r
+//                     doError(_ERROR_NOSUCHITEM);\r
+//             }\r
+               if ($blogid && (intval($blogid) != $obj->iblog) ) {\r
+                       if (!headers_sent()) {\r
+                               $b =& $manager->getBlog($obj->iblog);\r
+                               $CONF['ItemURL'] = $b->getURL();\r
+                               if ($CONF['URLMode'] == 'pathinfo' and substr($CONF['ItemURL'],-1) == '/')\r
+                                       $CONF['ItemURL'] = substr($CONF['ItemURL'], 0, -1);\r
+                               $correctURL = createItemLink($itemid, '');\r
+                               redirect($correctURL);\r
+                               exit;\r
+                       } else {\r
+                               doError(_ERROR_NOSUCHITEM);\r
+                       }\r
+               }\r
+\r
+               // if a category has been selected which doesn't match the item, ignore the\r
+               // category. #85\r
+               if (($catid != 0) && ($catid != $obj->icat) ) {\r
+                       $catid = 0;\r
+               }\r
 \r
                $blogid = $obj->iblog;\r
                $timestamp = strtotime($obj->itime);\r
 \r
                $b =& $manager->getBlog($blogid);\r
-               if ($b->isValidCategory($catid))\r
+\r
+               if ($b->isValidCategory($catid) ) {\r
                        $catextra = ' and icat=' . $catid;\r
+               } else {\r
+                       $catextra = '';\r
+               }\r
 \r
                // get previous itemid and title\r
-               $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';\r
+               $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';\r
                $res = sql_query($query);\r
 \r
                $obj = mysql_fetch_object($res);\r
+\r
                if ($obj) {\r
                        $itemidprev = $obj->inumber;\r
                        $itemtitleprev = $obj->ititle;\r
-       }\r
+               }\r
 \r
                // get next itemid and title\r
-               $query = 'SELECT inumber, ititle FROM '.sql_table('item').' WHERE itime>' . mysqldate($timestamp) . ' and itime <= ' . mysqldate(time()) . ' and idraft=0 and iblog=' . $blogid . $catextra . ' ORDER BY itime ASC LIMIT 1';\r
+               $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';\r
                $res = sql_query($query);\r
 \r
                $obj = mysql_fetch_object($res);\r
+\r
                if ($obj) {\r
                        $itemidnext = $obj->inumber;\r
                        $itemtitlenext = $obj->ititle;\r
@@ -572,48 +896,103 @@ function selector() {
                // show archive\r
                $type = 'archive';\r
 \r
-               // get next and prev month links\r
-               global $archivenext, $archiveprev, $archivetype;\r
+               // get next and prev month links ...\r
+               global $archivenext, $archiveprev, $archivetype, $archivenextexists, $archiveprevexists;\r
+\r
+               // sql queries for the timestamp of the first and the last published item\r
+               $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";\r
+               $first_timestamp=quickQuery ($query);\r
+               $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";\r
+               $last_timestamp=quickQuery ($query);\r
+\r
+               sscanf($archive, '%d-%d-%d', $y, $m, $d);\r
 \r
-               sscanf($archive,'%d-%d-%d',$y,$m,$d);\r
                if ($d != 0) {\r
                        $archivetype = _ARCHIVETYPE_DAY;\r
-                       $t = mktime(0,0,0,$m,$d,$y);\r
-                       $archiveprev = strftime('%Y-%m-%d',$t - (24*60*60));\r
-                       $archivenext = strftime('%Y-%m-%d',$t + (24*60*60));\r
+                       $t = mktime(0, 0, 0, $m, $d, $y);\r
+                       // one day has 24 * 60 * 60 = 86400 seconds\r
+                       $archiveprev = strftime('%Y-%m-%d', $t - 86400 );\r
+                       // check for published items\r
+                       if ($t > $first_timestamp) {\r
+                               $archiveprevexists = true;\r
+                       }\r
+                       else {\r
+                               $archiveprevexists = false;\r
+                       }\r
+\r
+                       // one day later\r
+                       $t += 86400;\r
+                       $archivenext = strftime('%Y-%m-%d', $t);\r
+                       if ($t < $last_timestamp) {\r
+                               $archivenextexists = true;\r
+                       }\r
+                       else {\r
+                               $archivenextexists = false;\r
+                       }\r
 \r
                } else {\r
                        $archivetype = _ARCHIVETYPE_MONTH;\r
-                       $t = mktime(0,0,0,$m,1,$y);\r
-                       $archiveprev = strftime('%Y-%m',$t - (1*24*60*60));\r
-                       $archivenext = strftime('%Y-%m',$t + (32*24*60*60));\r
-               }\r
+                       $t = mktime(0, 0, 0, $m, 1, $y);\r
+                       // one day before is in the previous month\r
+                       $archiveprev = strftime('%Y-%m', $t - 86400);\r
+                       if ($t > $first_timestamp) {\r
+                               $archiveprevexists = true;\r
+                       }\r
+                       else {\r
+                               $archiveprevexists = false;\r
+                       }\r
 \r
+                       // timestamp for the next month\r
+                       $t = mktime(0, 0, 0, $m+1, 1, $y);\r
+                       $archivenext = strftime('%Y-%m', $t);\r
+                       if ($t < $last_timestamp) {\r
+                               $archivenextexists = true;\r
+                       }\r
+                       else {\r
+                               $archivenextexists = false;\r
+                       }\r
+               }\r
 \r
        } elseif ($archivelist) {\r
                $type = 'archivelist';\r
-               if (intval($archivelist) != 0)\r
-                       $blogid = $archivelist;\r
-               else\r
+\r
+               if (is_numeric($archivelist)) {\r
+                       $blogid = intVal($archivelist);\r
+               } else {\r
                        $blogid = getBlogIDFromName($archivelist);\r
-               if (!$blogid) doError(_ERROR_NOSUCHBLOG);\r
+               }\r
+\r
+               if (!$blogid) {\r
+                       doError(_ERROR_NOSUCHBLOG);\r
+               }\r
+\r
        } elseif ($query) {\r
-           global $startpos;\r
+               global $startpos;\r
                $type = 'search';\r
                $query = stripslashes($query);\r
-               if(preg_match("/^(\xA1{2}|\xe3\x80{2}|\x20)+$/",$query)){\r
+               if(preg_match("/^(\xA1{2}|\xe3\x80{2}|\x20)+$/", $query)){\r
                                        $type = 'index';\r
                }\r
                $order = (_CHARSET == 'EUC-JP') ? 'EUC-JP, UTF-8,' : 'UTF-8, EUC-JP,';\r
-               $query = mb_convert_encoding($query, _CHARSET, $order.' JIS, SJIS, ASCII');\r
-               if (intval($blogid)==0)\r
+               $query = mb_convert_encoding($query, _CHARSET, $order . ' JIS, SJIS, ASCII');\r
+               if (is_numeric($blogid)) {\r
+                       $blogid = intVal($blogid);\r
+               } else {\r
                        $blogid = getBlogIDFromName($blogid);\r
-               if (!$blogid) doError(_ERROR_NOSUCHBLOG);\r
+               }\r
+\r
+               if (!$blogid) {\r
+                       doError(_ERROR_NOSUCHBLOG);\r
+               }\r
+\r
        } elseif ($memberid) {\r
                $type = 'member';\r
-               if (!MEMBER::existsID($memberid))\r
+\r
+               if (!MEMBER::existsID($memberid) ) {\r
                        doError(_ERROR_NOSUCHMEMBER);\r
-               $memberinfo = MEMBER::createFromID($memberid);\r
+               }\r
+\r
+               $memberinfo = $manager->getMember($memberid);\r
 \r
        } elseif ($imagepopup) {\r
                // media object (images etc.)\r
@@ -623,36 +1002,52 @@ function selector() {
                // TODO: set some vars?\r
        } else {\r
                // show regular index page\r
-           global $startpos;\r
+               global $startpos;\r
                $type = 'index';\r
        }\r
 \r
        // decide which blog should be displayed\r
-       if (!$blogid)\r
+       if (!$blogid) {\r
                $blogid = $CONF['DefaultBlog'];\r
+       }\r
 \r
        $b =& $manager->getBlog($blogid);\r
        $blog = $b;     // references can't be placed in global variables?\r
-       if (!$blog->isValid)\r
+\r
+       if (!$blog->isValid) {\r
                doError(_ERROR_NOSUCHBLOG);\r
+       }\r
 \r
        // set catid if necessary\r
-       if ($catid)\r
+       if ($catid) {\r
                $blog->setSelectedCategory($catid);\r
+       }\r
 \r
        // decide which skin should be used\r
-       if ($skinid != '' && ($skinid == 0))\r
+       if ($skinid != '' && ($skinid == 0) ) {\r
                selectSkin($skinid);\r
-       if (!$skinid)\r
+       }\r
+\r
+       if (!$skinid) {\r
                $skinid = $blog->getDefaultSkin();\r
+       }\r
+\r
+       $special = requestVar('special');\r
+       if (!empty($special) && isValidShortName($special)) {\r
+               $type = strtolower($special);\r
+       }\r
 \r
-       \r
        $skin = new SKIN($skinid);\r
-       if (!$skin->isValid)\r
+\r
+       if (!$skin->isValid) {\r
                doError(_ERROR_NOSUCHSKIN);\r
+       }\r
 \r
        // parse the skin\r
        $skin->parse($type);\r
+\r
+       // check to see we should throw JustPosted event\r
+       $blog->checkJustPosted();\r
 }\r
 \r
 /**\r
@@ -662,18 +1057,20 @@ function doError($msg, $skin = '') {
        global $errormessage, $CONF, $skinid, $blogid, $manager;\r
 \r
        if ($skin == '') {\r
-               if (SKIN::existsID($skinid)) {\r
+\r
+               if (SKIN::existsID($skinid) ) {\r
                        $skin = new SKIN($skinid);\r
-               } elseif ($manager->existsBlogID($blogid)) {\r
+               } elseif ($manager->existsBlogID($blogid) ) {\r
                        $blog =& $manager->getBlog($blogid);\r
-                       $skin = new SKIN($blog->getDefaultSkin());\r
+                       $skin = new SKIN($blog->getDefaultSkin() );\r
                } elseif ($CONF['DefaultBlog']) {\r
                        $blog =& $manager->getBlog($CONF['DefaultBlog']);\r
-                       $skin = new SKIN($blog->getDefaultSkin());\r
+                       $skin = new SKIN($blog->getDefaultSkin() );\r
                } else {\r
                        // this statement should actually never be executed\r
                        $skin = new SKIN($CONF['BaseSkin']);\r
                }\r
+\r
        }\r
 \r
        $errormessage = $msg;\r
@@ -684,56 +1081,58 @@ function doError($msg, $skin = '') {
 function getConfig() {\r
        global $CONF;\r
 \r
-       $query = 'SELECT * FROM '.sql_table('config');\r
+       $query = 'SELECT * FROM ' . sql_table('config');\r
        $res = sql_query($query);\r
-       while ($obj = mysql_fetch_object($res)) {\r
+\r
+       while ($obj = mysql_fetch_object($res) ) {\r
                $CONF[$obj->name] = $obj->value;\r
        }\r
 }\r
 \r
 // some checks for names of blogs, categories, templates, members, ...\r
-function isValidShortName($name) {             return eregi('^[a-z0-9]+$', $name); }\r
-function isValidDisplayName($name) {   return eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name); }\r
-function isValidCategoryName($name) {  return 1; } \r
-function isValidTemplateName($name) {  return eregi('^[a-z0-9/]+$', $name); }\r
-function isValidSkinName($name) {              return eregi('^[a-z0-9/]+$', $name); }\r
-\r
-// add and remove linebreaks\r
-function addBreaks($var) {                             return nl2br($var); }\r
-function removeBreaks($var) {                  return preg_replace("/<br \/>([\r\n])/","$1",$var); }\r
+function isValidShortName($name) {\r
+       return eregi('^[a-z0-9]+$', $name);\r
+}\r
 \r
-/**\r
-  * Generate a 'pronouncable' password\r
-  * (http://www.zend.com/codex.php?id=215&single=1)\r
-  */\r
-function genPassword($length){\r
+function isValidDisplayName($name) {\r
+       return eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name);\r
+}\r
 \r
-    srand((double)microtime()*1000000);\r
+function isValidCategoryName($name) {\r
+       return 1;\r
+}\r
 \r
-    $vowels = array('a', 'e', 'i', 'o', 'u');\r
-    $cons = array('b', 'c', 'd', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'u', 'v', 'w', 'tr',\r
-    'cr', 'br', 'fr', 'th', 'dr', 'ch', 'ph', 'wr', 'st', 'sp', 'sw', 'pr', 'sl', 'cl');\r
+function isValidTemplateName($name) {\r
+       return eregi('^[a-z0-9/]+$', $name);\r
+}\r
 \r
-    $num_vowels = count($vowels);\r
-    $num_cons = count($cons);\r
+function isValidSkinName($name) {\r
+       return eregi('^[a-z0-9/]+$', $name);\r
+}\r
 \r
-    for($i = 0; $i < $length; $i++){\r
-        $password .= $cons[rand(0, $num_cons - 1)] . $vowels[rand(0, $num_vowels - 1)];\r
-    }\r
+// add and remove linebreaks\r
+function addBreaks($var) {\r
+       return nl2br($var);\r
+}\r
 \r
-    return substr($password, 0, $length);\r
+function removeBreaks($var) {\r
+       return preg_replace("/<br \/>([\r\n])/", "$1", $var);\r
 }\r
 \r
 // shortens a text string to maxlength ($toadd) is what needs to be added\r
 // at the end (end length is <= $maxlength)\r
 function shorten($text, $maxlength, $toadd) {\r
        // 1. remove entities...\r
-       $trans = get_html_translation_table(HTML_ENTITIES);\r
+//     $trans = get_html_translation_table(HTML_ENTITIES);\r
+       $trans = get_html_translation_table(HTML_SPECIALCHARS); // for Japanese\r
        $trans = array_flip($trans);\r
-       $text = strtr($text, $trans);\r
+       $text  = strtr($text, $trans);\r
+\r
        // 2. the actual shortening\r
-       if (strlen($text) > $maxlength)\r
-               $text = mb_strimwidth($text, 0, $maxlength, $toadd, _CHARSET);\r
+       if (strlen($text) > $maxlength) {\r
+//             $text = substr($text, 0, $maxlength - strlen($toadd) ) . $toadd;\r
+               $text = mb_strimwidth($text, 0, $maxlength, $toadd, _CHARSET); // for Japanese\r
+       }\r
        return $text;\r
 }\r
 \r
@@ -742,7 +1141,7 @@ function shorten($text, $maxlength, $toadd) {
   * quotes around it.\r
   */\r
 function mysqldate($timestamp) {\r
-       return '"' . date('Y-m-d H:i:s',$timestamp) . '"';\r
+       return '"' . date('Y-m-d H:i:s', $timestamp) . '"';\r
 }\r
 \r
 /**\r
@@ -753,8 +1152,9 @@ function selectBlog($shortname) {
        $blogid = getBlogIDFromName($shortname);\r
 \r
        // also force archivelist variable, if it is set\r
-       if ($archivelist)\r
+       if ($archivelist) {\r
                $archivelist = $blogid;\r
+       }\r
 }\r
 \r
 function selectSkin($skinname) {\r
@@ -768,13 +1168,14 @@ function selectSkin($skinname) {
  */\r
 function selectCategory($cat) {\r
        global $catid;\r
-       if (is_numeric($cat))\r
+       if (is_numeric($cat) ) {\r
                $catid = intval($cat);\r
-       else\r
+       } else {\r
                $catid = getCatIDFromName($cat);\r
+       }\r
 }\r
 \r
-function selectItem($id){\r
+function selectItem($id) {\r
        global $itemid;\r
        $itemid = intval($id);\r
 }\r
@@ -785,16 +1186,24 @@ function selectLanguage($language) {
        include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');\r
 }\r
 \r
-function parseFile($filename) {\r
+function parseFile($filename, $includeMode = 'normal', $includePrefix = '') {\r
        $handler = new ACTIONS('fileparser');\r
        $parser = new PARSER(SKIN::getAllowedActionsForType('fileparser'), $handler);\r
        $handler->parser =& $parser;\r
 \r
-       if (!file_exists($filename)) doError('A file is missing');\r
+       // set IncludeMode properties of parser\r
+       PARSER::setProperty('IncludeMode', $includeMode);\r
+       PARSER::setProperty('IncludePrefix', $includePrefix);\r
+\r
+       if (!file_exists($filename) ) {\r
+               doError('A file is missing');\r
+       }\r
 \r
        $fsize = filesize($filename);\r
-       if ($fsize <= 0)\r
+\r
+       if ($fsize <= 0) {\r
                return;\r
+       }\r
 \r
        // read file\r
        $fd = fopen ($filename, 'r');\r
@@ -813,7 +1222,9 @@ function debug($msg) {
 }\r
 \r
 // shortcut\r
-function addToLog($level, $msg) { ACTIONLOG::add($level, $msg); }\r
+function addToLog($level, $msg) {\r
+       ACTIONLOG::add($level, $msg);\r
+}\r
 \r
 // shows a link to help file\r
 function help($id) {\r
@@ -821,11 +1232,13 @@ function help($id) {
 }\r
 \r
 function helpHtml($id) {\r
-       return helplink($id) . '<img src="documentation/icon-help.gif" width="15" height="15" alt="'._HELP_TT.'" /></a>';\r
+       global $CONF;\r
+       return helplink($id) . '<img src="' . $CONF['AdminURL'] . 'documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" title="' . _HELP_TT . '" /></a>';\r
 }\r
 \r
 function helplink($id) {\r
-       return '<a href="documentation/help.html#'. $id . '" onclick="if (event &amp;&amp; event.preventDefault) event.preventDefault(); return help(this.href);">';\r
+       global $CONF;\r
+       return '<a href="' . $CONF['AdminURL'] . 'documentation/help.html#'. $id . '" onclick="if (event &amp;&amp; event.preventDefault) event.preventDefault(); return help(this.href);">';\r
 }\r
 \r
 function getMailFooter() {\r
@@ -845,19 +1258,21 @@ function getMailFooter() {
 function getLanguageName() {\r
        global $CONF, $member;\r
 \r
-       if ($member) {\r
+       if ($member && $member->isLoggedIn() ) {\r
                // try to use members language\r
                $memlang = $member->getLanguage();\r
 \r
-               if (($memlang != '') && (checkLanguage($memlang)))\r
+               if (($memlang != '') && (checkLanguage($memlang) ) ) {\r
                        return $memlang;\r
+               }\r
        }\r
 \r
        // use default language\r
-       if (checkLanguage($CONF['Language']))\r
+       if (checkLanguage($CONF['Language']) ) {\r
                return $CONF['Language'];\r
-       else\r
+       } else {\r
                return 'english';\r
+       }\r
 }\r
 \r
 /**\r
@@ -882,7 +1297,9 @@ function includephp($filename) {
        // other\r
        global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;\r
 \r
-       if (@file_exists($filename)) include($filename);\r
+       if (@file_exists($filename) ) {\r
+               include($filename);\r
+       }\r
 }\r
 \r
 /**\r
@@ -892,99 +1309,158 @@ function checkLanguage($lang) {
        global $DIR_LANG ;\r
        return file_exists($DIR_LANG . ereg_replace( '[\\|/]', '', $lang) . '.php');\r
 }\r
+\r
 function checkPlugin($plug) {\r
        global $DIR_PLUGINS;\r
        return file_exists($DIR_PLUGINS . ereg_replace( '[\\|/]', '', $plug) . '.php');\r
 }\r
 \r
-\r
-$CONF['ItemURL'] = $CONF['Self'];\r
-$CONF['ArchiveURL'] = $CONF['Self'];\r
-$CONF['ArchiveListURL'] = $CONF['Self'];\r
-$CONF['MemberURL'] = $CONF['Self'];\r
-$CONF['SearchURL'] = $CONF['Self'];\r
-$CONF['BlogURL'] = $CONF['Self'];\r
-$CONF['CategoryURL'] = $CONF['Self'];\r
-\r
-// switch URLMode back to normal when $CONF['Self'] ends in .php\r
-// this avoids urls like index.php/item/13/index.php/item/15\r
-if (   ($CONF['URLMode'] == 'pathinfo')\r
-       &&      (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php')\r
-       ) {\r
-       $CONF['URLMode'] = 'normal';\r
-}\r
-\r
 /**\r
   * Centralisation of the functions that generate links\r
   */\r
 function createItemLink($itemid, $extra = '') {\r
-       global $CONF;\r
-       if ($CONF['URLMode'] == 'pathinfo')\r
-               $link = $CONF['ItemURL'] . '/item/' . $itemid;\r
-       else\r
-               $link = $CONF['ItemURL'] . '?itemid=' . $itemid;\r
-       return addLinkParams($link, $extra);\r
+       return createLink('item', array('itemid' => $itemid, 'extra' => $extra) );\r
 }\r
+\r
 function createMemberLink($memberid, $extra = '') {\r
-       global $CONF;\r
-       if ($CONF['URLMode'] == 'pathinfo')\r
-               $link = $CONF['MemberURL'] . '/member/' . $memberid;\r
-       else\r
-               $link = $CONF['MemberURL'] . '?memberid=' . $memberid;\r
-       return addLinkParams($link, $extra);\r
+       return createLink('member', array('memberid' => $memberid, 'extra' => $extra) );\r
 }\r
+\r
 function createCategoryLink($catid, $extra = '') {\r
-       global $CONF;\r
-       if ($CONF['URLMode'] == 'pathinfo')\r
-               $link = $CONF['CategoryURL'] . '/category/' . $catid;\r
-       else\r
-               $link = $CONF['CategoryURL'] . '?catid=' . $catid;\r
-       return addLinkParams($link, $extra);\r
+       return createLink('category', array('catid' => $catid, 'extra' => $extra) );\r
 }\r
+\r
 function createArchiveListLink($blogid = '', $extra = '') {\r
-       global $CONF;\r
-       if (!$blogid)\r
-               $blogid = $CONF['DefaultBlog'];\r
-       if ($CONF['URLMode'] == 'pathinfo')\r
-               $link = $CONF['ArchiveListURL'] . '/archives/' . $blogid;\r
-       else\r
-               $link = $CONF['ArchiveListURL'] . '?archivelist=' . $blogid;\r
-       return addLinkParams($link, $extra);\r
+       return createLink('archivelist', array('blogid' => $blogid, 'extra' => $extra) );\r
 }\r
+\r
 function createArchiveLink($blogid, $archive, $extra = '') {\r
-       global $CONF;\r
-       if ($CONF['URLMode'] == 'pathinfo')\r
-               $link = $CONF['ArchiveURL'] . '/archive/'.$blogid.'/' . $archive;\r
-       else\r
-               $link = $CONF['ArchiveURL'] . '?blogid='.$blogid.'&amp;archive=' . $archive;\r
-       return addLinkParams($link, $extra);\r
-}\r
-function createBlogLink($url, $params) {\r
-       return addLinkParams($url . '?', $params);\r
+       return createLink('archive', array('blogid' => $blogid, 'archive' => $archive, 'extra' => $extra) );\r
 }\r
+\r
 function createBlogidLink($blogid, $params = '') {\r
-       global $CONF;\r
-       if ($CONF['URLMode'] == 'pathinfo')\r
-               $link = $CONF['BlogURL'] . '/blog/' . $blogid;\r
-       else\r
-               $link = $CONF['BlogURL'] . '?blogid=' . $blogid;\r
-       return addLinkParams($link, $params);\r
+       return createLink('blog', array('blogid' => $blogid, 'extra' => $params) );\r
+}\r
+\r
+function createLink($type, $params) {\r
+       global $manager, $CONF;\r
+\r
+       $generatedURL = '';\r
+       $usePathInfo = ($CONF['URLMode'] == 'pathinfo');\r
+\r
+       // ask plugins first\r
+       $created = false;\r
+\r
+       if ($usePathInfo) {\r
+               $manager->notify(\r
+                       'GenerateURL',\r
+                       array(\r
+                               'type' => $type,\r
+                               'params' => $params,\r
+                               'completed' => &$created,\r
+                               'url' => &$url\r
+                       )\r
+               );\r
+       }\r
+\r
+       // if a plugin created the URL, return it\r
+       if ($created) {\r
+               return $url;\r
+       }\r
+\r
+       // default implementation\r
+       switch ($type) {\r
+               case 'item':\r
+                       if ($usePathInfo) {\r
+                               $url = $CONF['ItemURL'] . '/' . $CONF['ItemKey'] . '/' . $params['itemid'];\r
+                       } else {\r
+                               $url = $CONF['ItemURL'] . '?itemid=' . $params['itemid'];\r
+                       }\r
+                       break;\r
+\r
+               case 'member':\r
+                       if ($usePathInfo) {\r
+                               $url = $CONF['MemberURL'] . '/' . $CONF['MemberKey'] . '/' . $params['memberid'];\r
+                       } else {\r
+                               $url = $CONF['MemberURL'] . '?memberid=' . $params['memberid'];\r
+                       }\r
+                       break;\r
+\r
+               case 'category':\r
+                       if ($usePathInfo) {\r
+                               $url = $CONF['CategoryURL'] . '/' . $CONF['CategoryKey'] . '/' . $params['catid'];\r
+                       } else {\r
+                               $url = $CONF['CategoryURL'] . '?catid=' . $params['catid'];\r
+                       }\r
+                       break;\r
+\r
+               case 'archivelist':\r
+                       if (!$params['blogid']) {\r
+                               $params['blogid'] = $CONF['DefaultBlog'];\r
+                       }\r
+\r
+                       if ($usePathInfo) {\r
+                               $url = $CONF['ArchiveListURL'] . '/' . $CONF['ArchivesKey'] . '/' . $params['blogid'];\r
+                       } else {\r
+                               $url = $CONF['ArchiveListURL'] . '?archivelist=' . $params['blogid'];\r
+                       }\r
+                       break;\r
+\r
+               case 'archive':\r
+                       if ($usePathInfo) {\r
+                               $url = $CONF['ArchiveURL'] . '/' . $CONF['ArchiveKey'] . '/'.$params['blogid'].'/' . $params['archive'];\r
+                       } else {\r
+                               $url = $CONF['ArchiveURL'] . '?blogid='.$params['blogid'].'&amp;archive=' . $params['archive'];\r
+                       }\r
+                       break;\r
+\r
+               case 'blog':\r
+                       if ($usePathInfo) {\r
+                               $url = $CONF['BlogURL'] . '/' . $CONF['BlogKey'] . '/' . $params['blogid'];\r
+                       } else {\r
+                               $url = $CONF['BlogURL'] . '?blogid=' . $params['blogid'];\r
+                       }\r
+                       break;\r
+       }\r
+\r
+       return addLinkParams($url, (isset($params['extra'])? $params['extra'] : null));\r
 }\r
 \r
+function createBlogLink($url, $params) {\r
+    global $CONF;\r
+    if ($CONF['URLMode'] == 'normal') {\r
+        if (strpos($url, '?') === FALSE && is_array($params)) {\r
+            $fParam = reset($params);\r
+            $fKey   = key($params);\r
+            array_shift($params);\r
+            $url .= '?' . $fKey . '=' . $fParam;\r
+        }\r
+    } elseif ($CONF['URLMode'] == 'pathinfo' && substr($url, -1) == '/') {\r
+        $url = substr($url, 0, -1);\r
+    }\r
+       return addLinkParams($url, $params);\r
+}\r
 \r
 function addLinkParams($link, $params) {\r
        global $CONF;\r
-       if (is_array($params)) {\r
+\r
+       if (is_array($params) ) {\r
+\r
                if ($CONF['URLMode'] == 'pathinfo')     {\r
+\r
                        foreach ($params as $param => $value) {\r
                                $link .= '/' . $param . '/' . urlencode($value);\r
                        }\r
+\r
                } else {\r
+\r
                        foreach ($params as $param => $value) {\r
                                $link .= '&amp;' . $param . '=' . urlencode($value);\r
                        }\r
+\r
                }\r
        }\r
+\r
        return $link;\r
 }\r
 \r
@@ -995,99 +1471,663 @@ function addLinkParams($link, $params) {
  *             name of parameter to change (e.g. 'foo')\r
  * @param $value\r
  *             New value for that parameter (e.g. 3)\r
- * @result \r
+ * @result\r
  *             altered query string (for the examples above: foo=3&bar=2&x=y)\r
  */\r
 function alterQueryStr($querystr, $param, $value) {\r
-    $vars = explode("&", $querystr);\r
-    $set  = false;\r
-    for ($i=0;$i<count($vars);$i++) {\r
-        $v = explode('=',$vars[$i]);\r
-        if ($v[0] == $param) {\r
-            $v[1]     = $value;\r
-            $vars[$i] = implode('=', $v);\r
-            $set      = true;\r
-            break;\r
-        }\r
-    }\r
-    if (!$set) {$vars[] = $param . '=' . $value;}\r
-    return ltrim(implode('&', $vars), '&');\r
+       $vars = explode('&', $querystr);\r
+       $set  = false;\r
+\r
+       for ($i = 0; $i < count($vars); $i++) {\r
+               $v = explode('=', $vars[$i]);\r
+\r
+               if ($v[0] == $param) {\r
+                       $v[1] = $value;\r
+                       $vars[$i] = implode('=', $v);\r
+                       $set = true;\r
+                       break;\r
+               }\r
+       }\r
+\r
+       if (!$set) {\r
+               $vars[] = $param . '=' . $value;\r
+       }\r
+\r
+       return ltrim(implode('&', $vars), '&');\r
 }\r
 \r
 // passes one variable as hidden input field (multiple fields for arrays)\r
 // @see passRequestVars in varsx.x.x.php\r
 function passVar($key, $value) {\r
        // array ?\r
-       if (is_array($value)) {\r
-               for ($i=0;$i<sizeof($value);$i++)\r
-                       passVar($key.'['.$i.']',$value[$i]);\r
-                       return;\r
+       if (is_array($value) ) {\r
+               for ($i = 0; $i < sizeof($value); $i++) {\r
+                       passVar($key . '[' . $i . ']', $value[$i]);\r
+               }\r
+\r
+               return;\r
        }\r
 \r
        // other values: do stripslashes if needed\r
-       ?><input type="hidden" name="<?php echo htmlspecialchars($key)?>" value="<?php echo htmlspecialchars(undoMagic($value))?>" /><?php\r
+       ?><input type="hidden" name="<?php echo htmlspecialchars($key)?>" value="<?php echo htmlspecialchars(undoMagic($value) )?>" /><?php\r
 }\r
 \r
 /*\r
        Date format functions (to be used from [%date(..)%] skinvars\r
 */\r
-function formatDate($format, $timestamp, $defaultFormat) {\r
-       if ($format == 'rfc822') { \r
-               return date('r', $timestamp); \r
-       } else if ($format == 'rfc822GMT') { \r
-               return gmdate('r', $timestamp); \r
-       } else if ($format == 'utc') { \r
-               return gmdate('Y-m-d\TH:i:s\Z', $timestamp); \r
-       } else if ($format == 'iso8601') {\r
-               $tz = date('O', $timestamp);\r
-        $tz = substr($tz, 0, 3) . ':' . substr($tz, 3, 2);     \r
-               return gmdate('Y-m-d\TH:i:s', $timestamp) . $tz;\r
-       } else {  \r
-               return strftime($format ? $format : $defaultFormat,$timestamp); \r
-       }  \r
-\r
-}\r
-\r
-function checkVars($aVars)\r
-{\r
+function formatDate($format, $timestamp, $defaultFormat, &$blog) {\r
+       // apply blog offset (#42)\r
+       $boffset = $blog ? $blog->getTimeOffset() * 3600 : 0;\r
+       $offset = date('Z', $timestamp) + $boffset;\r
+\r
+       switch ($format) {\r
+               case 'rfc822':\r
+                       if ($offset >= 0) {\r
+                               $tz = '+';\r
+                       } else {\r
+                               $tz = '-';\r
+                               $offset = -$offset;\r
+                       }\r
+\r
+                       $tz .= sprintf("%02d%02d", floor($offset / 3600), round(($offset % 3600) / 60) );\r
+                       return date('D, j M Y H:i:s ', $timestamp) . $tz;\r
+\r
+               case 'rfc822GMT':\r
+                       $timestamp -= $offset;\r
+                       return date('D, j M Y H:i:s ', $timestamp) . 'GMT';\r
+\r
+               case 'utc':\r
+                       $timestamp -= $offset;\r
+                       return date('Y-m-d\TH:i:s\Z', $timestamp);\r
+\r
+               case 'iso8601':\r
+                       if ($offset >= 0) {\r
+                               $tz = '+';\r
+                       } else {\r
+                               $tz = '-';\r
+                               $offset = -$offset;\r
+                       }\r
+\r
+                       $tz .= sprintf("%02d:%02d", floor($offset / 3600), round(($offset % 3600) / 60) );\r
+                       return date('Y-m-d\TH:i:s', $timestamp) . $tz;\r
+\r
+               default :\r
+                       return strftime($format ? $format : $defaultFormat, $timestamp);\r
+       }\r
+}\r
+\r
+function encoding_check($val, $key, $encoding=false, $exclude=false) {\r
+       /*\r
+         Set $CONF['DisableEncodingCheck']=1 only for special occasion, e.g. install script.\r
+         Don't set this permanently in nucleus_config table.\r
+       */\r
+       global $CONF;\r
+//     if (!empty($CONF['DisableEncodingCheck'])) return true;\r
+       /*\r
+         When 3rd argument is set, return if checked already.\r
+         When 4th argument is set, set the excluded key(s).\r
+       */\r
+       static $search=false, $checked=array(), $excludes=array();\r
+       if ($exclude!==false) {\r
+               if (is_array($exclude)) {\r
+                       foreach($exclude as $v) $excludes[$v]=true;\r
+               } else $excludes[$exclude]=true;\r
+               return;\r
+       }\r
+       if ($encoding!==false) {\r
+               switch($encoding=strtolower($encoding)){\r
+                       case 'utf-8':\r
+                               $search='/([\x00-\x7F]+'.\r
+                                       '|[\xC2-\xDF][\x80-\xBF]'.\r
+                                       '|[\xE0-\xEF][\x80-\xBF][\x80-\xBF]'.\r
+                                       '|[\xF0-\xF7][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.\r
+                                       '|[\xF8-\xFB][\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.\r
+                                       '|[\xFC-\xFD][\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF])/';\r
+                                       break;\r
+                       case 'euc-jp':\r
+                               $search='/([\x00-\x7F]+'.\r
+                                       '|[\x8E][\xA0-\xDF]'.\r
+                                       '|[\x8F]?[\xA1-\xFE][\xA1-\xFE])/';\r
+                               break;\r
+                       case 'gb2312':\r
+                               $search='/([\x00-\x7F]+'.\r
+                                       '|[\xA1-\xF7][\xA1-\xFE])/';\r
+                               break;\r
+                       case 'shift_jis':\r
+                               // Note that shift_jis is only supported for output.\r
+                               // Using shift_jis in DB is prohibited.\r
+                               $search='/([\x00-\x7F\xA1-\xDF]+'.\r
+                                       '|[\x81-\x9F\xE0-\xFC][\x40-\xFC])/';\r
+                               break;\r
+                       default:\r
+                               $search=false;\r
+                               if (preg_match('/^iso\-8859\-[0-9]{1,2}$/',$encoding)) break;\r
+                               if (preg_match('/^windows\-125[0-8]$/',$encoding)) break;\r
+                               startUpError('<p>Unknown or non-supported encoding.</p>', 'Encoding Error');\r
+                               exit;\r
+               }\r
+               if (isset($checked[$encoding])) return true; // Already checked.\r
+               $checked[$encoding]=true;\r
+       }\r
+       if ($key===false) return false; // Not yet checked.\r
+       if ($search===false) return true; // non-multibyte encoding\r
+       if (isset($excludes[$key])) return true; // This key isn't checked.\r
+       if (is_array($val)) {\r
+               array_walk($val, 'encoding_check');\r
+       } else {\r
+               $result=preg_replace($search,'',$val);\r
+               if (strlen($result)!=0) {\r
+                       startUpError('<p>Invalid input.</p>', 'Input Error');\r
+                       exit;\r
+               }\r
+       }\r
+       $result=preg_replace($search,'',$key);\r
+       if (strlen($result)!=0) {\r
+               startUpError('<p>Invalid input.</p>', 'Input Error');\r
+               exit;\r
+       }\r
+       return true;\r
+}\r
+\r
+function checkVars($aVars) {\r
        global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;\r
-       foreach ($aVars as $varName)\r
-       {\r
-               if (phpversion() >= '4.1.0')\r
-               {\r
-                       if (   isset($_GET[$varName]) \r
-                               || isset($_POST[$varName]) \r
+\r
+       foreach ($aVars as $varName) {\r
+\r
+               if (phpversion() >= '4.1.0') {\r
+\r
+                       if (   isset($_GET[$varName])\r
+                               || isset($_POST[$varName])\r
                                || isset($_COOKIE[$varName])\r
                                || isset($_ENV[$varName])\r
                                || isset($_SESSION[$varName])\r
                                || isset($_FILES[$varName])\r
-                       ){\r
+                       ) {\r
                                die('Sorry. An error occurred.');\r
                        }\r
+\r
                } else {\r
-                       if (   isset($HTTP_GET_VARS[$varName]) \r
-                               || isset($HTTP_POST_VARS[$varName]) \r
+\r
+                       if (   isset($HTTP_GET_VARS[$varName])\r
+                               || isset($HTTP_POST_VARS[$varName])\r
                                || isset($HTTP_COOKIE_VARS[$varName])\r
                                || isset($HTTP_ENV_VARS[$varName])\r
                                || isset($HTTP_SESSION_VARS[$varName])\r
                                || isset($HTTP_POST_FILES[$varName])\r
-                       ){\r
+                       ) {\r
                                die('Sorry. An error occurred.');\r
                        }\r
+\r
+               }\r
+       }\r
+}\r
+\r
+\r
+/**\r
+ * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.\r
+ * to avoid XSS\r
+ */\r
+function sanitizeParams()\r
+{\r
+       global $HTTP_SERVER_VARS;\r
+\r
+       $array = array();\r
+       $str = '';\r
+       $frontParam = '';\r
+\r
+       // REQUEST_URI of $HTTP_SERVER_VARS\r
+       $str =& $HTTP_SERVER_VARS["REQUEST_URI"];\r
+       serverStringToArray($str, $array, $frontParam);\r
+       sanitizeArray($array);\r
+       arrayToServerString($array, $frontParam, $str);\r
+\r
+       // QUERY_STRING of $HTTP_SERVER_VARS\r
+       $str =& $HTTP_SERVER_VARS["QUERY_STRING"];\r
+       serverStringToArray($str, $array, $frontParam);\r
+       sanitizeArray($array);\r
+       arrayToServerString($array, $frontParam, $str);\r
+\r
+       if (phpversion() >= '4.1.0') {\r
+               // REQUEST_URI of $_SERVER\r
+               $str =& $_SERVER["REQUEST_URI"];\r
+               serverStringToArray($str, $array, $frontParam);\r
+               sanitizeArray($array);\r
+               arrayToServerString($array, $frontParam, $str);\r
+\r
+               // QUERY_STRING of $_SERVER\r
+               $str =& $_SERVER["QUERY_STRING"];\r
+               serverStringToArray($str, $array, $frontParam);\r
+               sanitizeArray($array);\r
+               arrayToServerString($array, $frontParam, $str);\r
+       }\r
+\r
+       // $_GET\r
+       convArrayForSanitizing($_GET, $array);\r
+       sanitizeArray($array);\r
+       revertArrayForSanitizing($array, $_GET);\r
+\r
+       // $_REQUEST (only GET param)\r
+       convArrayForSanitizing($_REQUEST, $array);\r
+       sanitizeArray($array);\r
+       revertArrayForSanitizing($array, $_REQUEST);\r
+}\r
+\r
+/**\r
+ * Check ticket when not checked in plugin's admin page\r
+ * to avoid CSRF.\r
+ * Also avoid the access to plugin/index.php by guest user.\r
+ */\r
+function ticketForPlugin(){\r
+       global $CONF,$DIR_PLUGINS,$member,$ticketforplugin;\r
+\r
+       /* initialize */\r
+       $ticketforplugin=array();\r
+       $ticketforplugin['ticket']=false;\r
+\r
+       /* Check if using plugin's php file. */\r
+       if ($p_translated=serverVar('PATH_TRANSLATED')) {\r
+               if (!file_exists($p_translated)) $p_translated='';\r
+       }\r
+       if (!$p_translated) {\r
+               $p_translated=serverVar('SCRIPT_FILENAME');\r
+               if (!file_exists($p_translated)) {\r
+                       header("HTTP/1.0 404 Not Found");\r
+                       exit('');\r
+               }\r
+       }\r
+       $p_translated=str_replace('\\','/',$p_translated);\r
+       $d_plugins=str_replace('\\','/',$DIR_PLUGINS);\r
+       if (strpos($p_translated,$d_plugins)!==0) return;// This isn't plugin php file.\r
+\r
+       /* Solve the plugin php file or admin directory */\r
+       $phppath=substr($p_translated,strlen($d_plugins));\r
+       $phppath=preg_replace('!^/!','',$phppath);// Remove the first "/" if exists.\r
+       $path=preg_replace('/^NP_(.*)\.php$/','$1',$phppath); // Remove the first "NP_" and the last ".php" if exists.\r
+       $path=preg_replace('!^([^/]*)/(.*)$!','$1',$path); // Remove the "/" and beyond.\r
+\r
+       /* Solve the plugin name. */\r
+       $plugins=array();\r
+       $query='SELECT pfile FROM '.sql_table('plugin');\r
+       $res=sql_query($query);\r
+       while($row=mysql_fetch_row($res)) {\r
+               $name=substr($row[0],3);\r
+               $plugins[strtolower($name)]=$name;\r
+       }\r
+       mysql_free_result($res);\r
+       if ($plugins[$path]) $plugin_name=$plugins[$path];\r
+       else if (in_array($path,$plugins)) $plugin_name=$path;\r
+       else {\r
+               header("HTTP/1.0 404 Not Found");\r
+               exit('');\r
+       }\r
+\r
+       /* Return if not index.php */\r
+       if ( $phppath!=strtolower($plugin_name).'/'\r
+               && $phppath!=strtolower($plugin_name).'/index.php' ) return;\r
+\r
+       /* Exit if not logged in. */\r
+       if ( !$member->isLoggedIn() ) exit("You aren't logged in.");\r
+\r
+       global $manager,$DIR_LIBS,$DIR_LANG,$HTTP_GET_VARS,$HTTP_POST_VARS;\r
+\r
+       /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */\r
+       if (!($p_translated=serverVar('PATH_TRANSLATED'))) $p_translated=serverVar('SCRIPT_FILENAME');\r
+       if ($file=@file($p_translated)) {\r
+               $prevline='';\r
+               foreach($file as $line) {\r
+                       if (preg_match('/[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]/i',$prevline.$line)) return;\r
+                       $prevline=$line;\r
+               }\r
+       }\r
+\r
+       /* Show a form if not valid ticket */\r
+       if ( ( strstr(serverVar('REQUEST_URI'),'?') || serverVar('QUERY_STRING')\r
+                       || strtoupper(serverVar('REQUEST_METHOD'))=='POST' )\r
+                               && (!$manager->checkTicket()) ){\r
+\r
+               if (!class_exists('PluginAdmin')) {\r
+                       $language = getLanguageName();\r
+                       include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');\r
+                       include($DIR_LIBS . 'PLUGINADMIN.php');\r
+               }\r
+               if (!(function_exists('mb_strimwidth') || extension_loaded('mbstring'))) {\r
+                       if (file_exists($DIR_LIBS.'mb_emulator/mb-emulator.php')) {\r
+                               global $mbemu_internals;\r
+                               include_once($DIR_LIBS.'mb_emulator/mb-emulator.php');\r
+                       }\r
+               }\r
+               $oPluginAdmin = new PluginAdmin($plugin_name);\r
+               $oPluginAdmin->start();\r
+               echo '<p>' . _ERROR_BADTICKET . "</p>\n";\r
+\r
+               /* Show the form to confirm action */\r
+               // PHP 4.0.x support\r
+               $get=  (isset($_GET))  ? $_GET  : $HTTP_GET_VARS;\r
+               $post= (isset($_POST)) ? $_POST : $HTTP_POST_VARS;\r
+               // Resolve URI and QUERY_STRING\r
+               if ($uri=serverVar('REQUEST_URI')) {\r
+                       list($uri,$qstring)=explode('?',$uri);\r
+               } else {\r
+                       if ( !($uri=serverVar('PHP_SELF')) ) $uri=serverVar('SCRIPT_NAME');\r
+                       $qstring=serverVar('QUERY_STRING');\r
+               }\r
+               if ($qstring) $qstring='?'.$qstring;\r
+               echo '<p>'._SETTINGS_UPDATE.' : '._QMENU_PLUGINS.' <span style="color:red;">'.\r
+                       htmlspecialchars($plugin_name)."</span> ?</p>\n";\r
+               switch(strtoupper(serverVar('REQUEST_METHOD'))){\r
+               case 'POST':\r
+                       echo '<form method="POST" action="'.htmlspecialchars($uri.$qstring).'">';\r
+                       $manager->addTicketHidden();\r
+                       _addInputTags($post);\r
+                       break;\r
+               case 'GET':\r
+                       echo '<form method="GET" action="'.htmlspecialchars($uri).'">';\r
+                       $manager->addTicketHidden();\r
+                       _addInputTags($get);\r
+               default:\r
+                       break;\r
+               }\r
+               echo '<input type="submit" value="'._YES.'" />&nbsp;&nbsp;&nbsp;&nbsp;';\r
+               echo '<input type="button" value="'._NO.'" onclick="history.back(); return false;" />';\r
+               echo "</form>\n";\r
+\r
+               $oPluginAdmin->end();\r
+               exit;\r
+       }\r
+\r
+       /* Create new ticket */\r
+       $ticket=$manager->addTicketToUrl('');\r
+       $ticketforplugin['ticket']=substr($ticket,strpos($ticket,'ticket=')+7);\r
+}\r
+function _addInputTags(&$keys,$prefix=''){\r
+       foreach($keys as $key=>$value){\r
+               if ($prefix) $key=$prefix.'['.$key.']';\r
+               if (is_array($value)) _addInputTags($value,$key);\r
+               else {\r
+                       if (get_magic_quotes_gpc()) $value=stripslashes($value);\r
+                       if ($key=='ticket') continue;\r
+                       echo '<input type="hidden" name="'.htmlspecialchars($key).\r
+                               '" value="'.htmlspecialchars($value).'" />'."\n";\r
+               }\r
+       }\r
+}\r
+\r
+/**\r
+ * Convert the server string such as $_SERVER['REQUEST_URI']\r
+ * to arry like arry['blogid']=1 and array['page']=2 etc.\r
+ */\r
+function serverStringToArray($str, &$array, &$frontParam)\r
+{\r
+       // init param\r
+       $array = array();\r
+       $fronParam = "";\r
+\r
+       // split front param, e.g. /index.php, and others, e.g. blogid=1&page=2\r
+       if (strstr($str, "?")){\r
+               list($frontParam, $args) = preg_split("/\?/", $str, 2);\r
+       }\r
+       else {\r
+               $args = $str;\r
+               $frontParam = "";\r
+       }\r
+\r
+       // If there is no args like blogid=1&page=2, return\r
+       if (!strstr($str, "=") && !strlen($frontParam)) {\r
+               $frontParam = $str;\r
+               return;\r
+       }\r
+\r
+       $array = explode("&", $args);\r
+}\r
+\r
+/**\r
+ * Convert array like array['blogid'] to server string\r
+ * such as $_SERVER['REQUEST_URI']\r
+ */\r
+function arrayToServerString($array, $frontParam, &$str)\r
+{\r
+       if (strstr($str, "?")) {\r
+               $str = $frontParam . "?";\r
+       } else {\r
+               $str = $frontParam;\r
+       }\r
+       if (count($array)) {\r
+               $str .= implode("&", $array);\r
+       }\r
+}\r
+\r
+/**\r
+ * Sanitize array parameters.\r
+ * This function checks both key and value.\r
+ * - check key if it inclues " (double quote),  remove from array\r
+ * - check value if it includes \ (escape sequece), remove remaining string\r
+ */\r
+function sanitizeArray(&$array)\r
+{\r
+       $excludeListForSanitization = array('query');\r
+//     $excludeListForSanitization = array();\r
+\r
+       foreach ($array as $k => $v) {\r
+\r
+               // split to key and value\r
+               list($key, $val) = preg_split("/=/", $v, 2);\r
+               if (!isset($val)) {\r
+                       continue;\r
+               }\r
+\r
+               // when magic quotes is on, need to use stripslashes,\r
+               // and then addslashes\r
+               if (get_magic_quotes_gpc()) {\r
+                       $val = stripslashes($val);\r
+               }\r
+               $val = addslashes($val);\r
+\r
+               // if $key is included in exclude list, skip this param\r
+               if (!in_array($key, $excludeListForSanitization)) {\r
+\r
+                       // check value\r
+                       if (strpos($val, '\\')) {\r
+                               list($val, $tmp) = explode('\\', $val);\r
+                       }\r
+\r
+                       // remove control code etc.\r
+                       $val = strtr($val, "\0\r\n<>'\"", "       ");\r
+\r
+                       // check key\r
+                       if (preg_match('/\"/i', $key)) {\r
+                               unset($array[$k]);\r
+                               continue;\r
+                       }\r
+\r
+                       // set sanitized info\r
+                       $array[$k] = sprintf("%s=%s", $key, $val);\r
+               }\r
+       }\r
+}\r
+\r
+/**\r
+ * Convert array for sanitizeArray function\r
+ */\r
+function convArrayForSanitizing($src, &$array)\r
+{\r
+       $array = array();\r
+       foreach ($src as $key => $val) {\r
+               if (key_exists($key, $_GET)) {\r
+                       array_push($array, sprintf("%s=%s", $key, $val));\r
                }\r
        }\r
 }\r
 \r
-/** \r
+/**\r
+ * Revert array after sanitizeArray function\r
+ */\r
+function revertArrayForSanitizing($array, &$dst)\r
+{\r
+       foreach ($array as $v) {\r
+               list($key, $val) = preg_split("/=/", $v, 2);\r
+               $dst[$key] = $val;\r
+       }\r
+}\r
+\r
+/**\r
  * Stops processing the request and redirects to the given URL.\r
  * - no actual contents should have been sent to the output yet\r
  * - the URL will be stripped of illegal or dangerous characters\r
  */\r
-function redirect($url)\r
-{\r
-       $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%]|i', '', $url);\r
+function redirect($url) {\r
+       $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%*]|i', '', $url);\r
        header('Location: ' . $url);\r
        exit;\r
 }\r
 \r
-?>\r
+/**\r
+ * Strip HTML tags from a string\r
+ * This function is a bit more intelligent than a regular call to strip_tags(),\r
+ * because it also deletes the contents of certain tags and cleans up any\r
+ * unneeded whitespace.\r
+ */\r
+function stringStripTags ($string) {\r
+       $string = preg_replace("/<del[^>]*>.+<\/del[^>]*>/isU", '', $string);\r
+       $string = preg_replace("/<script[^>]*>.+<\/script[^>]*>/isU", '', $string);\r
+       $string = preg_replace("/<style[^>]*>.+<\/style[^>]*>/isU", '', $string);\r
+       $string = str_replace('>', '> ', $string);\r
+       $string = str_replace('<', ' <', $string);\r
+       $string = strip_tags($string);\r
+       $string = preg_replace("/\s+/", " ", $string);\r
+       $string = trim($string);\r
+       return $string;\r
+}\r
+\r
+/**\r
+ * Make a string containing HTML safe for use in a HTML attribute\r
+ * Tags are stripped and entities are normalized\r
+ */\r
+function stringToAttribute ($string) {\r
+       $string = stringStripTags($string);\r
+       $string = entity::named_to_numeric($string);\r
+       $string = entity::normalize_numeric($string);\r
+\r
+       if (_CHARSET == 'UTF-8') {\r
+               $string = entity::numeric_to_utf8($string);\r
+       }\r
+\r
+       $string = entity::specialchars($string, 'html');\r
+       $string = entity::numeric_to_named($string);\r
+       return $string;\r
+}\r
+\r
+/**\r
+ * Make a string containing HTML safe for use in a XML document\r
+ * Tags are stripped, entities are normalized and named entities are\r
+ * converted to numeric entities.\r
+ */\r
+function stringToXML ($string) {\r
+       $string = stringStripTags($string);\r
+       $string = entity::named_to_numeric($string);\r
+       $string = entity::normalize_numeric($string);\r
+\r
+       if (_CHARSET == 'UTF-8') {\r
+               $string = entity::numeric_to_utf8($string);\r
+       }\r
+\r
+       $string = entity::specialchars($string, 'xml');\r
+       return $string;\r
+}\r
+\r
+// START: functions from the end of file BLOG.php\r
+// used for mail notification (html -> text)\r
+function toAscii($html) {\r
+       // strip off most tags\r
+       $html = strip_tags($html,'<a>');\r
+       $to_replace = "/<a[^>]*href=[\"\']([^\"^']*)[\"\'][^>]*>([^<]*)<\/a>/i";\r
+       _links_init();\r
+       $ascii = preg_replace_callback ($to_replace, '_links_add', $html);\r
+       $ascii .= "\n\n" . _links_list();\r
+       return strip_tags($ascii);\r
+}\r
+\r
+function _links_init() {\r
+   global $tmp_links;\r
+   $tmp_links = array();\r
+}\r
+\r
+function _links_add($match) {\r
+   global $tmp_links;\r
+   array_push($tmp_links, $match[1]);\r
+   return $match[2] . ' [' . sizeof($tmp_links) .']';\r
+}\r
+\r
+function _links_list() {\r
+   global $tmp_links;\r
+   $output = '';\r
+   $i = 1;\r
+   foreach ($tmp_links as $current) {\r
+         $output .= "[$i] $current\n";\r
+         $i++;\r
+   }\r
+   return $output;\r
+}\r
+// END: functions from the end of file BLOG.php\r
+\r
+// START: functions from the end of file ADMIN.php\r
+/**\r
+ * @todo document this\r
+ */\r
+function encode_desc(&$data)\r
+{\r
+//     _$to_entities = get_html_translation_table(HTML_ENTITIES);\r
+       $to_entities = get_html_translation_table(HTML_SPECIALCHARS); // for Japanese\r
+       $from_entities = array_flip($to_entities);\r
+       $data = str_replace('<br />', '\n', $data); //hack\r
+       $data = strtr($data,$from_entities);\r
+       $data = strtr($data,$to_entities);\r
+       $data = str_replace('\n', '<br />', $data); //hack\r
+       return $data;\r
+}\r
+\r
+/**\r
+ * Returns the Javascript code for a bookmarklet that works on most modern browsers\r
+ *\r
+ * @param blogid\r
+ */\r
+function getBookmarklet($blogid) {\r
+       global $CONF;\r
+\r
+       // normal\r
+       $document = 'document';\r
+       $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('";\r
+       $bookmarkletline .= $CONF['AdminURL'] . "bookmarklet.php?blogid=$blogid";\r
+       $bookmarkletline .="&logtext='+escape(Q)+'&loglink='+escape(x.location.href)+'&loglinktitle='+escape(x.title),'nucleusbm','toolbar=no,scrollbars=no,width=600,height=550,left=10,top=10,status=no,resizable=yes');wingm.focus();";\r
+\r
+       return $bookmarkletline;\r
+}\r
+// END: functions from the end of file ADMIN.php\r
+\r
+/**\r
+ * Returns a variable or null if not set\r
+ *\r
+ * @param mixed Variable\r
+ * @return mixed Variable\r
+ */\r
+function ifset(&$var) {\r
+       if (isset($var)) {\r
+               return $var;\r
+       }\r
+\r
+       return null;\r
+}\r
+\r
+/**\r
+ * Returns number of subscriber to an event\r
+ *\r
+ * @param event\r
+ * @return number of subscriber(s)\r
+ */\r
+function numberOfEventSubscriber($event) {\r
+       $query = 'SELECT COUNT(*) as count FROM ' . sql_table('plugin_event') . ' WHERE event=\'' . $event . '\'';\r
+       $res = sql_query($query);\r
+       $obj = mysql_fetch_object($res);\r
+       return $obj->count;\r
+}\r
+\r
+?>
\ No newline at end of file