OSDN Git Service

Some minor PHP 5.3 compatibility fixes
authorshizuki <shizuki@1ca29b6e-896d-4ea0-84a5-967f57386b96>
Wed, 29 Jul 2009 07:01:40 +0000 (07:01 +0000)
committershizuki <shizuki@1ca29b6e-896d-4ea0-84a5-967f57386b96>
Wed, 29 Jul 2009 07:01:40 +0000 (07:01 +0000)
The ereg_replace when being "language file" reading, is changed to preg_replace.

git-svn-id: https://svn.sourceforge.jp/svnroot/nucleus-jp/nucleus-jp/trunk@1044 1ca29b6e-896d-4ea0-84a5-967f57386b96

utf8/nucleus/libs/MANAGER.php
utf8/nucleus/libs/SEARCH.php
utf8/nucleus/libs/globalfunctions.php
utf8/nucleus/libs/sql/mysql.php
utf8/nucleus/libs/sql/pdo.php
utf8/nucleus/libs/xmlrpc.inc.php
utf8/nucleus/plugins/NP_Ping.php
utf8/nucleus/plugins/NP_SecurityEnforcer.php
utf8/nucleus/plugins/NP_Text.php

index c8662ee..26c283e 100755 (executable)
  */
 class MANAGER {
 
-       /**
-        * Cached ITEM, BLOG, PLUGIN, KARMA and MEMBER objects. When these objects are requested
-        * through the global $manager object (getItem, getBlog, ...), only the first call
-        * will create an object. Subsequent calls will return the same object.
-        *
-        * The $items, $blogs, ... arrays map an id to an object (for plugins, the name is used
-        * rather than an ID)
-        */
-       var $items;
-       var $blogs;
-       var $plugins;
-       var $karma;
-       var $templates;
-       var $members;
-
-       /**
-        * cachedInfo to avoid repeated SQL queries (see pidInstalled/pluginInstalled/getPidFromName)
-        * e.g. which plugins exists?
-        *
-        * $cachedInfo['installedPlugins'] = array($pid -> $name)
-        */
-       var $cachedInfo;
-
-       /**
-         * The plugin subscriptionlist
-         *
-         * The subcription array has the following structure
-         *             $subscriptions[$EventName] = array containing names of plugin classes to be
-         *                                                                      notified when that event happens
-         */
-       var $subscriptions;
-
-       /**
-         * Returns the only instance of this class. Creates the instance if it
-         * does not yet exists. Users should use this function as
-         * $manager =& MANAGER::instance(); to get a reference to the object
-         * instead of a copy
-         */
-       function &instance() {
-               static $instance = array();
-               if (empty($instance)) {
-                       $instance[0] =& new MANAGER();
-               }
-               return $instance[0];
-       }
-
-       /**
-         * The constructor of this class initializes the object caches
-         */
-       function MANAGER() {
-               $this->items = array();
-               $this->blogs = array();
-               $this->plugins = array();
-               $this->karma = array();
-               $this->parserPrefs = array();
-               $this->cachedInfo = array();
-       }
-
-       /**
-         * Returns the requested item object. If it is not in the cache, it will
-         * first be loaded and then placed in the cache.
-         * Intended use: $item =& $manager->getItem(1234)
-         */
-       function &getItem($itemid, $allowdraft, $allowfuture) {
-               $item =& $this->items[$itemid];
-
-               // check the draft and future rules if the item was already cached
-               if ($item) {
-                       if ((!$allowdraft) && ($item['draft']))
-                               return 0;
-
-                       $blog =& $this->getBlog(getBlogIDFromItemID($itemid));
-                       if ((!$allowfuture) && ($item['timestamp'] > $blog->getCorrectTime()))
-                               return 0;
-               }
-               if (!$item) {
-                       // load class if needed
-                       $this->loadClass('ITEM');
-                       // load item object
-                       $item = ITEM::getitem($itemid, $allowdraft, $allowfuture);
-                       $this->items[$itemid] = $item;
-               }
-               return $item;
-       }
-
-       /**
-         * Loads a class if it has not yet been loaded
-         */
-       function loadClass($name) {
-               $this->_loadClass($name, $name . '.php');
-       }
-
-       /**
-         * Checks if an item exists
-         */
-       function existsItem($id,$future,$draft) {
-               $this->_loadClass('ITEM','ITEM.php');
-               return ITEM::exists($id,$future,$draft);
-       }
-
-       /**
-         * Checks if a category exists
-         */
-       function existsCategory($id) {
-               return (quickQuery('SELECT COUNT(*) as result FROM '.sql_table('category').' WHERE catid='.intval($id)) > 0);
-       }
-
-       /**
-         * Returns the blog object for a given blogid
-         */
-       function &getBlog($blogid) {
-               $blog =& $this->blogs[$blogid];
-
-               if (!$blog) {
-                       // load class if needed
-                       $this->_loadClass('BLOG','BLOG.php');
-                       // load blog object
-                       $blog =& new BLOG($blogid);
-                       $this->blogs[$blogid] =& $blog;
-               }
-               return $blog;
-       }
-
-       /**
-         * Checks if a blog exists
-         */
-       function existsBlog($name) {
-               $this->_loadClass('BLOG','BLOG.php');
-               return BLOG::exists($name);
-       }
-
-       /**
-         * Checks if a blog id exists
-         */
-       function existsBlogID($id) {
-               $this->_loadClass('BLOG','BLOG.php');
-               return BLOG::existsID($id);
-       }
-
-       /**
-        * Returns a previously read template
-        */
-       function &getTemplate($templateName) {
-               $template =& $this->templates[$templateName];
-
-               if (!$template) {
-                       $template = TEMPLATE::read($templateName);
-                       $this->templates[$templateName] =& $template;
-               }
-               return $template;
-       }
-
-       /**
-        * Returns a KARMA object (karma votes)
-        */
-       function &getKarma($itemid) {
-               $karma =& $this->karma[$itemid];
-
-               if (!$karma) {
-                       // load class if needed
-                       $this->_loadClass('KARMA','KARMA.php');
-                       // create KARMA object
-                       $karma =& new KARMA($itemid);
-                       $this->karma[$itemid] =& $karma;
-               }
-               return $karma;
-       }
-
-       /**
-        * Returns a MEMBER object
-        */
-       function &getMember($memberid) {
-               $mem =& $this->members[$memberid];
-
-               if (!$mem) {
-                       // load class if needed
-                       $this->_loadClass('MEMBER','MEMBER.php');
-                       // create MEMBER object
-                       $mem =& MEMBER::createFromID($memberid);
-                       $this->members[$memberid] =& $mem;
-               }
-               return $mem;
-       }
-
-       /**
-        * Set the global parser preferences
-        */
-       function setParserProperty($name, $value) {
-               $this->parserPrefs[$name] = $value;
-       }
-
-       /**
-        * Get the global parser preferences
-        */
-       function getParserProperty($name) {
-               return $this->parserPrefs[$name];
-       }
-
-       /**
-         * A helper function to load a class
-         
-         * private
-         */
-       function _loadClass($name, $filename) {
-               if (!class_exists($name)) {
-                               global $DIR_LIBS;
-                               include($DIR_LIBS . $filename);
-               }
-       }
-
-       /**
-         * A helper function to load a plugin
-         
-         *     private
-         */
-       function _loadPlugin($name) {
-               if (!class_exists($name)) {
-                               global $DIR_PLUGINS;
-
-                               $fileName = $DIR_PLUGINS . $name . '.php';
-
-                               if (!file_exists($fileName))
-                               {
-                                       ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOTFOUND, $name));
-                                       return 0;
-                               }
-
-                               // load plugin
-                               include($fileName);
-
-                               // check if class exists (avoid errors in eval'd code)
-                               if (!class_exists($name))
-                               {
-                                       ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOCLASS, $name));
-                                       return 0;
-                               }
-
-                               // add to plugin array
-                               eval('$this->plugins[$name] =& new ' . $name . '();');
-
-                               // get plugid
-                               $this->plugins[$name]->plugid = $this->getPidFromName($name);
-
-                               // unload plugin if a prefix is used and the plugin cannot handle this^
-                               global $MYSQL_PREFIX;
-                               if (($MYSQL_PREFIX != '') && !$this->plugins[$name]->supportsFeature('SqlTablePrefix'))
-                               {
-                                       unset($this->plugins[$name]);
-                                       ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINTABLEPREFIX_NOTSUPPORT, $name));
-                                       return 0;
-                               }
-
-                               // unload plugin if using non-mysql handler and plugin does not support it 
-                               global $MYSQL_HANDLER;
-                               if ((!in_array('mysql',$MYSQL_HANDLER)) && !$this->plugins[$name]->supportsFeature('SqlApi'))
-                               {
-                                       unset($this->plugins[$name]);
-                                       ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINSQLAPI_NOTSUPPORT, $name));
-                                       return 0;
-                               }
-
-                               // call init method
-                               $this->plugins[$name]->init();
-
-               }
-       }
-
-       /**
-        * Returns a PLUGIN object
-        */
-       function &getPlugin($name) {
-               // retrieve the name of the plugin in the right capitalisation
-               $name = $this->getUpperCaseName ($name);
-               // get the plugin       
-               $plugin =& $this->plugins[$name];
-
-               if (!$plugin) {
-                       // load class if needed
-                       $this->_loadPlugin($name);
-                       $plugin =& $this->plugins[$name];
-               }
-               return $plugin;
-       }
-
-       /**
-         * Checks if the given plugin IS loaded or not
-         */
-       function &pluginLoaded($name) {
-               $plugin =& $this->plugins[$name];
-               return $plugin;
-       }
-
-       function &pidLoaded($pid) {
-               $plugin=false;
-               reset($this->plugins);
-               while (list($name) = each($this->plugins)) {
-                       if ($pid!=$this->plugins[$name]->getId()) continue;
-                       $plugin= & $this->plugins[$name];
-                       break;
-               }
-               return $plugin;
-       }
-
-       /**
-         * checks if the given plugin IS installed or not
-         */
-       function pluginInstalled($name) {
-               $this->_initCacheInfo('installedPlugins');
-               return ($this->getPidFromName($name) != -1);
-       }
-
-       function pidInstalled($pid) {
-               $this->_initCacheInfo('installedPlugins');
-               return ($this->cachedInfo['installedPlugins'][$pid] != '');
-       }
-
-       function getPidFromName($name) {
-               $this->_initCacheInfo('installedPlugins');
-               foreach ($this->cachedInfo['installedPlugins'] as $pid => $pfile)
-               {
-                       if (strtolower($pfile) == strtolower($name))
-                               return $pid;
-               }
-               return -1;
-       }
-
-       /**
-         * Retrieve the name of a plugin in the right capitalisation
-         */
-       function getUpperCaseName ($name) {
-               $this->_initCacheInfo('installedPlugins');
-               foreach ($this->cachedInfo['installedPlugins'] as $pid => $pfile)
-               {
-                       if (strtolower($pfile) == strtolower($name))
-                               return $pfile;
-               }
-               return -1;
-       }
-
-       function clearCachedInfo($what) {
-               unset($this->cachedInfo[$what]);
-       }
-
-       /**
-        * Loads some info on the first call only
-        */
-       function _initCacheInfo($what)
-       {
-               if (isset($this->cachedInfo[$what]) && is_array($this->cachedInfo[$what]))
-                       return;
-               switch ($what)
-               {
-                       // 'installedPlugins' = array ($pid => $name)
-                       case 'installedPlugins':
-                               $this->cachedInfo['installedPlugins'] = array();
-                               $res = sql_query('SELECT pid, pfile FROM ' . sql_table('plugin'));
-                               while ($o = sql_fetch_object($res))
-                               {
-                                       $this->cachedInfo['installedPlugins'][$o->pid] = $o->pfile;
-                               }
-                               break;
-               }
-       }
-
-       /**
-         * A function to notify plugins that something has happened. Only the plugins
-         * that are subscribed to the event will get notified.
-         * Upon the first call, the list of subscriptions will be fetched from the
-         * database. The plugins itsself will only get loaded when they are first needed
-         *
-         * @param $eventName
-         *             Name of the event (method to be called on plugins)
-         * @param $data
-         *             Can contain any type of data, depending on the event type. Usually this is
-         *             an itemid, blogid, ... but it can also be an array containing multiple values
-         */
-       function notify($eventName, $data) {
-               // load subscription list if needed
-               if (!is_array($this->subscriptions))
-                       $this->_loadSubscriptions();
-
-
-               // get listening objects
-               $listeners = false;
-               if (isset($this->subscriptions[$eventName])) {
-                       $listeners = $this->subscriptions[$eventName];
-               }
-
-               // notify all of them
-               if (is_array($listeners)) {
-                       foreach($listeners as $listener) {
-                               // load class if needed
-                               $this->_loadPlugin($listener);
-                               // do notify (if method exists)
-                               if (method_exists($this->plugins[$listener], 'event_' . $eventName))
-                                       call_user_func(array(&$this->plugins[$listener],'event_' . $eventName), &$data);
-                       }
-               }
-
-       }
-
-       /**
-         * Loads plugin subscriptions
-         */
-       function _loadSubscriptions() {
-               // initialize as array
-               $this->subscriptions = array();
-
-               $res = sql_query('SELECT p.pfile as pfile, e.event as event FROM '.sql_table('plugin_event').' as e, '.sql_table('plugin').' as p WHERE e.pid=p.pid ORDER BY p.porder ASC');
-               while ($o = sql_fetch_object($res)) {
-                       $pluginName = $o->pfile;
-                       $eventName = $o->event;
-                       $this->subscriptions[$eventName][] = $pluginName;
-               }
-
-       }
-
-       /*
-               Ticket functions. These are uses by the admin area to make it impossible to simulate certain GET/POST
-               requests. tickets are user specific
-       */
-
-       var $currentRequestTicket = '';
-
-       /**
-        * GET requests: Adds ticket to URL (URL should NOT be html-encoded!, ticket is added at the end)
-        */
-       function addTicketToUrl($url)
-       {
-               $ticketCode = 'ticket=' . $this->_generateTicket();
-               if (strstr($url, '?'))
-                       return $url . '&' . $ticketCode;
-               else
-                       return $url . '?' . $ticketCode;
-       }
-
-       /**
-        * POST requests: Adds ticket as hidden formvar
-        */
-       function addTicketHidden()
-       {
-               $ticket = $this->_generateTicket();
-
-               echo '<input type="hidden" name="ticket" value="', htmlspecialchars($ticket), '" />';
-       }
-
-       /**
-        * Get a new ticket
-        * (xmlHTTPRequest AutoSaveDraft uses this to refresh the ticket)
-        */
-       function getNewTicket()
-       {
-               $this->currentRequestTicket = '';
-               return $this->_generateTicket();
-       }
-
-       /**
-        * Checks the ticket that was passed along with the current request
-        */
-       function checkTicket()
-       {
-               global $member;
-
-               // get ticket from request
-               $ticket = requestVar('ticket');
-
-               // no ticket -> don't allow
-               if ($ticket == '')
-                       return false;
-
-               // remove expired tickets first
-               $this->_cleanUpExpiredTickets();
-
-               // get member id
-               if (!$member->isLoggedIn())
-                       $memberId = -1;
-               else
-                       $memberId = $member->getID();
-
-               // check if ticket is a valid one
-               $query = 'SELECT COUNT(*) as result FROM ' . sql_table('tickets') . ' WHERE member=' . intval($memberId). ' and ticket=\''.addslashes($ticket).'\'';
-               if (quickQuery($query) == 1)
-               {
-                       // [in the original implementation, the checked ticket was deleted. This would lead to invalid
-                       //  tickets when using the browsers back button and clicking another link/form
-                       //  leaving the keys in the database is not a real problem, since they're member-specific and
-                       //  only valid for a period of one hour
-                       // ]
-                       // sql_query('DELETE FROM '.sql_table('tickets').' WHERE member=' . intval($memberId). ' and ticket=\''.addslashes($ticket).'\'');
-                       return true;
-               } else {
-                       // not a valid ticket
-                       return false;
-               }
-
-       }
-
-       /**
-        * (internal method) Removes the expired tickets
-        */
-       function _cleanUpExpiredTickets()
-       {
-               // remove tickets older than 1 hour
-               $oldTime = time() - 60 * 60;
-               $query = 'DELETE FROM ' . sql_table('tickets'). ' WHERE ctime < \'' . date('Y-m-d H:i:s',$oldTime) .'\'';
-               sql_query($query);
-       }
-
-       /**
-        * (internal method) Generates/returns a ticket (one ticket per page request)
-        */
-       function _generateTicket()
-       {
-               if ($this->currentRequestTicket == '')
-               {
-                       // generate new ticket (only one ticket will be generated per page request)
-                       // and store in database
-                       global $member;
-                       // get member id
-                       if (!$member->isLoggedIn())
-                               $memberId = -1;
-                       else
-                               $memberId = $member->getID();
-
-                       $ok = false;
-                       while (!$ok)
-                       {
-                               // generate a random token
-                               srand((double)microtime()*1000000);
-                               $ticket = md5(uniqid(rand(), true));
-
-                               // add in database as non-active
-                               $query = 'INSERT INTO ' . sql_table('tickets') . ' (ticket, member, ctime) ';
-                               $query .= 'VALUES (\'' . addslashes($ticket). '\', \'' . intval($memberId). '\', \'' . date('Y-m-d H:i:s',time()) . '\')';
-                               if (sql_query($query))
-                                       $ok = true;
-                       }
-
-                       $this->currentRequestTicket = $ticket;
-               }
-               return $this->currentRequestTicket;
-       }
+    /**
+     * Cached ITEM, BLOG, PLUGIN, KARMA and MEMBER objects. When these objects are requested
+     * through the global $manager object (getItem, getBlog, ...), only the first call
+     * will create an object. Subsequent calls will return the same object.
+     *
+     * The $items, $blogs, ... arrays map an id to an object (for plugins, the name is used
+     * rather than an ID)
+     */
+    var $items;
+    var $blogs;
+    var $plugins;
+    var $karma;
+    var $templates;
+    var $members;
+
+    /**
+     * cachedInfo to avoid repeated SQL queries (see pidInstalled/pluginInstalled/getPidFromName)
+     * e.g. which plugins exists?
+     *
+     * $cachedInfo['installedPlugins'] = array($pid -> $name)
+     */
+    var $cachedInfo;
+
+    /**
+      * The plugin subscriptionlist
+      *
+      * The subcription array has the following structure
+      *     $subscriptions[$EventName] = array containing names of plugin classes to be
+      *                                  notified when that event happens
+      */
+    var $subscriptions;
+
+    /**
+      * Returns the only instance of this class. Creates the instance if it
+      * does not yet exists. Users should use this function as
+      * $manager =& MANAGER::instance(); to get a reference to the object
+      * instead of a copy
+      */
+    function &instance() {
+        static $instance = array();
+        if (empty($instance)) {
+            $instance[0] =& new MANAGER();
+        }
+        return $instance[0];
+    }
+
+    /**
+      * The constructor of this class initializes the object caches
+      */
+    function MANAGER() {
+        $this->items = array();
+        $this->blogs = array();
+        $this->plugins = array();
+        $this->karma = array();
+        $this->parserPrefs = array();
+        $this->cachedInfo = array();
+    }
+
+    /**
+      * Returns the requested item object. If it is not in the cache, it will
+      * first be loaded and then placed in the cache.
+      * Intended use: $item =& $manager->getItem(1234)
+      */
+    function &getItem($itemid, $allowdraft, $allowfuture) {
+        $item =& $this->items[$itemid];
+
+        // check the draft and future rules if the item was already cached
+        if ($item) {
+            if ((!$allowdraft) && ($item['draft']))
+                return 0;
+
+            $blog =& $this->getBlog(getBlogIDFromItemID($itemid));
+            if ((!$allowfuture) && ($item['timestamp'] > $blog->getCorrectTime()))
+                return 0;
+        }
+        if (!$item) {
+            // load class if needed
+            $this->loadClass('ITEM');
+            // load item object
+            $item = ITEM::getitem($itemid, $allowdraft, $allowfuture);
+            $this->items[$itemid] = $item;
+        }
+        return $item;
+    }
+
+    /**
+      * Loads a class if it has not yet been loaded
+      */
+    function loadClass($name) {
+        $this->_loadClass($name, $name . '.php');
+    }
+
+    /**
+      * Checks if an item exists
+      */
+    function existsItem($id,$future,$draft) {
+        $this->_loadClass('ITEM','ITEM.php');
+        return ITEM::exists($id,$future,$draft);
+    }
+
+    /**
+      * Checks if a category exists
+      */
+    function existsCategory($id) {
+        return (quickQuery('SELECT COUNT(*) as result FROM '.sql_table('category').' WHERE catid='.intval($id)) > 0);
+    }
+
+    /**
+      * Returns the blog object for a given blogid
+      */
+    function &getBlog($blogid) {
+        $blog =& $this->blogs[$blogid];
+
+        if (!$blog) {
+            // load class if needed
+            $this->_loadClass('BLOG','BLOG.php');
+            // load blog object
+            $blog =& new BLOG($blogid);
+            $this->blogs[$blogid] =& $blog;
+        }
+        return $blog;
+    }
+
+    /**
+      * Checks if a blog exists
+      */
+    function existsBlog($name) {
+        $this->_loadClass('BLOG','BLOG.php');
+        return BLOG::exists($name);
+    }
+
+    /**
+      * Checks if a blog id exists
+      */
+    function existsBlogID($id) {
+        $this->_loadClass('BLOG','BLOG.php');
+        return BLOG::existsID($id);
+    }
+
+    /**
+     * Returns a previously read template
+     */
+    function &getTemplate($templateName) {
+        $template =& $this->templates[$templateName];
+
+        if (!$template) {
+            $template = TEMPLATE::read($templateName);
+            $this->templates[$templateName] =& $template;
+        }
+        return $template;
+    }
+
+    /**
+     * Returns a KARMA object (karma votes)
+     */
+    function &getKarma($itemid) {
+        $karma =& $this->karma[$itemid];
+
+        if (!$karma) {
+            // load class if needed
+            $this->_loadClass('KARMA','KARMA.php');
+            // create KARMA object
+            $karma =& new KARMA($itemid);
+            $this->karma[$itemid] =& $karma;
+        }
+        return $karma;
+    }
+
+    /**
+     * Returns a MEMBER object
+     */
+    function &getMember($memberid) {
+        $mem =& $this->members[$memberid];
+
+        if (!$mem) {
+            // load class if needed
+            $this->_loadClass('MEMBER','MEMBER.php');
+            // create MEMBER object
+            $mem =& MEMBER::createFromID($memberid);
+            $this->members[$memberid] =& $mem;
+        }
+        return $mem;
+    }
+
+    /**
+     * Set the global parser preferences
+     */
+    function setParserProperty($name, $value) {
+        $this->parserPrefs[$name] = $value;
+    }
+
+    /**
+     * Get the global parser preferences
+     */
+    function getParserProperty($name) {
+        return $this->parserPrefs[$name];
+    }
+
+    /**
+      * A helper function to load a class
+      * 
+      * private
+      */
+    function _loadClass($name, $filename) {
+        if (!class_exists($name)) {
+                global $DIR_LIBS;
+                include($DIR_LIBS . $filename);
+        }
+    }
+
+    /**
+      * A helper function to load a plugin
+      * 
+      * private
+      */
+    function _loadPlugin($name) {
+        if (!class_exists($name)) {
+                global $DIR_PLUGINS;
+
+                $fileName = $DIR_PLUGINS . $name . '.php';
+
+                if (!file_exists($fileName))
+                {
+                    ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOTFOUND, $name));
+                    return 0;
+                }
+
+                // load plugin
+                include($fileName);
+
+                // check if class exists (avoid errors in eval'd code)
+                if (!class_exists($name))
+                {
+                    ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINFILE_NOCLASS, $name));
+                    return 0;
+                }
+
+                // add to plugin array
+                eval('$this->plugins[$name] =& new ' . $name . '();');
+
+                // get plugid
+                $this->plugins[$name]->plugid = $this->getPidFromName($name);
+
+                // unload plugin if a prefix is used and the plugin cannot handle this^
+                global $MYSQL_PREFIX;
+                if (($MYSQL_PREFIX != '') && !$this->plugins[$name]->supportsFeature('SqlTablePrefix'))
+                {
+                    unset($this->plugins[$name]);
+                    ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINTABLEPREFIX_NOTSUPPORT, $name));
+                    return 0;
+                }
+
+                // unload plugin if using non-mysql handler and plugin does not support it 
+                global $MYSQL_HANDLER;
+                if ((!in_array('mysql',$MYSQL_HANDLER)) && !$this->plugins[$name]->supportsFeature('SqlApi'))
+                {
+                    unset($this->plugins[$name]);
+                    ACTIONLOG::add(WARNING, sprintf(_MANAGER_PLUGINSQLAPI_NOTSUPPORT, $name));
+                    return 0;
+                }
+
+                // call init method
+                $this->plugins[$name]->init();
+
+        }
+    }
+
+    /**
+     * Returns a PLUGIN object
+     */
+    function &getPlugin($name) {
+        // retrieve the name of the plugin in the right capitalisation
+        $name = $this->getUpperCaseName ($name);
+        // get the plugin   
+        $plugin =& $this->plugins[$name];
+
+        if (!$plugin) {
+            // load class if needed
+            $this->_loadPlugin($name);
+            $plugin =& $this->plugins[$name];
+        }
+        return $plugin;
+    }
+
+    /**
+      * Checks if the given plugin IS loaded or not
+      */
+    function &pluginLoaded($name) {
+        $plugin =& $this->plugins[$name];
+        return $plugin;
+    }
+
+    function &pidLoaded($pid) {
+        $plugin=false;
+        reset($this->plugins);
+        while (list($name) = each($this->plugins)) {
+            if ($pid!=$this->plugins[$name]->getId()) continue;
+            $plugin= & $this->plugins[$name];
+            break;
+        }
+        return $plugin;
+    }
+
+    /**
+      * checks if the given plugin IS installed or not
+      */
+    function pluginInstalled($name) {
+        $this->_initCacheInfo('installedPlugins');
+        return ($this->getPidFromName($name) != -1);
+    }
+
+    function pidInstalled($pid) {
+        $this->_initCacheInfo('installedPlugins');
+        return ($this->cachedInfo['installedPlugins'][$pid] != '');
+    }
+
+    function getPidFromName($name) {
+        $this->_initCacheInfo('installedPlugins');
+        foreach ($this->cachedInfo['installedPlugins'] as $pid => $pfile)
+        {
+            if (strtolower($pfile) == strtolower($name))
+                return $pid;
+        }
+        return -1;
+    }
+
+    /**
+      * Retrieve the name of a plugin in the right capitalisation
+      */
+    function getUpperCaseName ($name) {
+        $this->_initCacheInfo('installedPlugins');
+        foreach ($this->cachedInfo['installedPlugins'] as $pid => $pfile)
+        {
+            if (strtolower($pfile) == strtolower($name))
+                return $pfile;
+        }
+        return -1;
+    }
+
+    function clearCachedInfo($what) {
+        unset($this->cachedInfo[$what]);
+    }
+
+    /**
+     * Loads some info on the first call only
+     */
+    function _initCacheInfo($what)
+    {
+        if (isset($this->cachedInfo[$what]) && is_array($this->cachedInfo[$what]))
+            return;
+        switch ($what)
+        {
+            // 'installedPlugins' = array ($pid => $name)
+            case 'installedPlugins':
+                $this->cachedInfo['installedPlugins'] = array();
+                $res = sql_query('SELECT pid, pfile FROM ' . sql_table('plugin'));
+                while ($o = sql_fetch_object($res))
+                {
+                    $this->cachedInfo['installedPlugins'][$o->pid] = $o->pfile;
+                }
+                break;
+        }
+    }
+
+    /**
+      * A function to notify plugins that something has happened. Only the plugins
+      * that are subscribed to the event will get notified.
+      * Upon the first call, the list of subscriptions will be fetched from the
+      * database. The plugins itsself will only get loaded when they are first needed
+      *
+      * @param $eventName
+      *     Name of the event (method to be called on plugins)
+      * @param $data
+      *     Can contain any type of data, depending on the event type. Usually this is
+      *     an itemid, blogid, ... but it can also be an array containing multiple values
+      */
+    function notify($eventName, $data) {
+        // load subscription list if needed
+        if (!is_array($this->subscriptions))
+            $this->_loadSubscriptions();
+
+
+        // get listening objects
+        $listeners = false;
+        if (isset($this->subscriptions[$eventName])) {
+            $listeners = $this->subscriptions[$eventName];
+        }
+
+        // notify all of them
+        if (is_array($listeners)) {
+            foreach($listeners as $listener) {
+                // load class if needed
+                $this->_loadPlugin($listener);
+                // do notify (if method exists)
+                if (isset($this->plugins[$listener]) && method_exists($this->plugins[$listener], 'event_' . $eventName))
+                    call_user_func(array(&$this->plugins[$listener],'event_' . $eventName), &$data);
+            }
+        }
+
+    }
+
+    /**
+      * Loads plugin subscriptions
+      */
+    function _loadSubscriptions() {
+        // initialize as array
+        $this->subscriptions = array();
+
+        $res = sql_query('SELECT p.pfile as pfile, e.event as event FROM '.sql_table('plugin_event').' as e, '.sql_table('plugin').' as p WHERE e.pid=p.pid ORDER BY p.porder ASC');
+        while ($o = sql_fetch_object($res)) {
+            $pluginName = $o->pfile;
+            $eventName = $o->event;
+            $this->subscriptions[$eventName][] = $pluginName;
+        }
+
+    }
+
+    /*
+        Ticket functions. These are uses by the admin area to make it impossible to simulate certain GET/POST
+        requests. tickets are user specific
+    */
+
+    var $currentRequestTicket = '';
+
+    /**
+     * GET requests: Adds ticket to URL (URL should NOT be html-encoded!, ticket is added at the end)
+     */
+    function addTicketToUrl($url)
+    {
+        $ticketCode = 'ticket=' . $this->_generateTicket();
+        if (strstr($url, '?'))
+            return $url . '&' . $ticketCode;
+        else
+            return $url . '?' . $ticketCode;
+    }
+
+    /**
+     * POST requests: Adds ticket as hidden formvar
+     */
+    function addTicketHidden()
+    {
+        $ticket = $this->_generateTicket();
+
+        echo '<input type="hidden" name="ticket" value="', htmlspecialchars($ticket), '" />';
+    }
+
+    /**
+     * Get a new ticket
+     * (xmlHTTPRequest AutoSaveDraft uses this to refresh the ticket)
+     */
+    function getNewTicket()
+    {
+        $this->currentRequestTicket = '';
+        return $this->_generateTicket();
+    }
+
+    /**
+     * Checks the ticket that was passed along with the current request
+     */
+    function checkTicket()
+    {
+        global $member;
+
+        // get ticket from request
+        $ticket = requestVar('ticket');
+
+        // no ticket -> don't allow
+        if ($ticket == '')
+            return false;
+
+        // remove expired tickets first
+        $this->_cleanUpExpiredTickets();
+
+        // get member id
+        if (!$member->isLoggedIn())
+            $memberId = -1;
+        else
+            $memberId = $member->getID();
+
+        // check if ticket is a valid one
+        $query = 'SELECT COUNT(*) as result FROM ' . sql_table('tickets') . ' WHERE member=' . intval($memberId). ' and ticket=\''.addslashes($ticket).'\'';
+        if (quickQuery($query) == 1)
+        {
+            // [in the original implementation, the checked ticket was deleted. This would lead to invalid
+            //  tickets when using the browsers back button and clicking another link/form
+            //  leaving the keys in the database is not a real problem, since they're member-specific and
+            //  only valid for a period of one hour
+            // ]
+            // sql_query('DELETE FROM '.sql_table('tickets').' WHERE member=' . intval($memberId). ' and ticket=\''.addslashes($ticket).'\'');
+            return true;
+        } else {
+            // not a valid ticket
+            return false;
+        }
+
+    }
+
+    /**
+     * (internal method) Removes the expired tickets
+     */
+    function _cleanUpExpiredTickets()
+    {
+        // remove tickets older than 1 hour
+        $oldTime = time() - 60 * 60;
+        $query = 'DELETE FROM ' . sql_table('tickets'). ' WHERE ctime < \'' . date('Y-m-d H:i:s',$oldTime) .'\'';
+        sql_query($query);
+    }
+
+    /**
+     * (internal method) Generates/returns a ticket (one ticket per page request)
+     */
+    function _generateTicket()
+    {
+        if ($this->currentRequestTicket == '')
+        {
+            // generate new ticket (only one ticket will be generated per page request)
+            // and store in database
+            global $member;
+            // get member id
+            if (!$member->isLoggedIn())
+                $memberId = -1;
+            else
+                $memberId = $member->getID();
+
+            $ok = false;
+            while (!$ok)
+            {
+                // generate a random token
+                srand((double)microtime()*1000000);
+                $ticket = md5(uniqid(rand(), true));
+
+                // add in database as non-active
+                $query = 'INSERT INTO ' . sql_table('tickets') . ' (ticket, member, ctime) ';
+                $query .= 'VALUES (\'' . addslashes($ticket). '\', \'' . intval($memberId). '\', \'' . date('Y-m-d H:i:s',time()) . '\')';
+                if (sql_query($query))
+                    $ok = true;
+            }
+
+            $this->currentRequestTicket = $ticket;
+        }
+        return $this->currentRequestTicket;
+    }
 
 }
 
index b04c625..20d8348 100755 (executable)
  * @version $NucleusJP: SEARCH.php,v 1.7 2006/07/20 08:01:52 kimitake Exp $
  */
 
+class SEARCH
+{
 
+    var $querystring;
+    var $marked;
+    var $inclusive;
+    var $blogs;
 
-class SEARCH {
-
-       var $querystring;
-       var $marked;
-       var $inclusive;
-       var $blogs;
-
-
-       function SEARCH($text) {
-               global $blogid;
+    function SEARCH($text)
+    {
+        global $blogid;
 //             $text = preg_replace ("/[<,>,=,?,!,#,^,(,),[,\],:,;,\\\,%]/","",$text);
-
-
-               /* * * for jp * * * * * * * * * * */
-               $this->encoding = strtolower(preg_replace('|[^a-z0-9-_]|i', '', _CHARSET));
-               if ($this->encoding != 'utf-8') {
-                       $text = mb_convert_encoding($text, "UTF-8", $this->encoding);
-               }
-               $text = str_replace ("\xE3\x80\x80",' ',$text);
-               $text = preg_replace ("/[<>=?!#^()[\]:;\\%]/","",$text);
-
-               $this->ascii = '[\x00-\x7F]';
-               $this->two = '[\xC0-\xDF][\x80-\xBF]';
-               $this->three = '[\xE0-\xEF][\x80-\xBF][\x80-\xBF]';
-
-               $this->jpmarked      = $this->boolean_mark_atoms_jp($text);
-               /* * * * * * * * * * * * * * * * */
-
-               $this->querystring      = $text;
-//             $this->marked           = $this->boolean_mark_atoms($text);
-               $this->inclusive        = $this->boolean_inclusive_atoms($text);
-               $this->blogs            = array();
-
-               // get all public searchable blogs, no matter what, include the current blog allways.
-               $res = sql_query('SELECT bnumber FROM '.sql_table('blog').' WHERE bincludesearch=1 ');
-               while ($obj = sql_fetch_object($res)) 
-                       $this->blogs[] = intval($obj->bnumber);
-               }
-
-       function  boolean_sql_select($match){
-               if (strlen($this->inclusive) > 0) {
-                       /* build sql for determining score for each record */
-                       $result=explode(" ",$this->inclusive);
-                       for($cth=0;$cth<count($result);$cth++){
-                               if(strlen($result[$cth])>=4){
-                                       $stringsum_long .=  " $result[$cth] ";
-                               }else{
-                                       $stringsum_a[] = ' '.$this->boolean_sql_select_short($result[$cth],$match).' ';
-                               }
-                       }
-
-                       if(strlen($stringsum_long)>0){
-                               $stringsum_long = addslashes($stringsum_long);
-                               $stringsum_a[] = " match ($match) against ('$stringsum_long') ";
-                       }
-
-                       $stringsum .= implode("+",$stringsum_a);
-
-                       return $stringsum;
-               }
-       }
-
-       
-
-       function boolean_inclusive_atoms($string){
-               $result=trim($string);
-               $result=preg_replace("/([[:space:]]{2,})/",' ',$result);
-
-               /* convert normal boolean operators to shortened syntax */
-               $result=eregi_replace(' not ',' -',$result);
-               $result=eregi_replace(' and ',' ',$result);
-               $result=eregi_replace(' or ',',',$result);
-
-               /* drop unnecessary spaces */
-               $result=str_replace(' ,',',',$result);
-               $result=str_replace(', ',',',$result);
-               $result=str_replace('- ','-',$result);
-               $result=str_replace('+','',$result);
-
-               /* strip exlusive atoms */
-               $result=preg_replace(
-//                     "(\-\([A-Za-z0-9]{1,}[A-Za-z0-9\-\.\_\,]{0,}\))",
-                       "(\-\(([A-Za-z0-9]|$this->two|$this->three){1,}([A-Za-z0-9\-\.\_\,]|$this->two|$this->three){0,}\))",
-                       '',
-                       $result);
+        /* * * for jp * * * * * * * * * * */
+        $this->encoding = strtolower(preg_replace('|[^a-z0-9-_]|i', '', _CHARSET));
+        if ($this->encoding != 'utf-8') {
+            $text = mb_convert_encoding($text, "UTF-8", $this->encoding);
+        }
+        $text = str_replace ("\xE3\x80\x80",' ',$text);
+        $text = preg_replace ("/[<>=?!#^()[\]:;\\%]/","",$text);
+
+        $this->ascii       = '[\x00-\x7F]';
+        $this->two         = '[\xC0-\xDF][\x80-\xBF]';
+        $this->three       = '[\xE0-\xEF][\x80-\xBF][\x80-\xBF]';
+
+        $this->jpmarked    = $this->boolean_mark_atoms_jp($text);
+        /* * * * * * * * * * * * * * * * */
+
+        $this->querystring = $text;
+//             $this->marked      = $this->boolean_mark_atoms($text);
+        $this->inclusive   = $this->boolean_inclusive_atoms($text);
+        $this->blogs       = array();
+
+        // get all public searchable blogs, no matter what, include the current blog allways.
+        $res = sql_query('SELECT bnumber FROM ' . sql_table('blog') . ' WHERE bincludesearch=1 ');
+        while ($obj = sql_fetch_object($res)) {
+            $this->blogs[] = intval($obj->bnumber);
+        }
+    }
+
+    function  boolean_sql_select($match)
+    {
+        if (!isset($stringsum)) {
+            $stringsum = '';
+        }
+        if (strlen($this->inclusive) > 0) {
+            /* build sql for determining score for each record */
+            $result=explode(" ",$this->inclusive);
+            if (!isset($stringsum_long)) {
+                $stringsum_long = '';
+            }
+            for ($cth = 0; $cth < count($result); $cth++) {
+                if (strlen($result[$cth])>=4) {
+                    $stringsum_long .=  " $result[$cth] ";
+                } else {
+                    $stringsum_a[] = ' ' . $this->boolean_sql_select_short($result[$cth], $match) . ' ';
+                }
+            }
+
+            if (strlen($stringsum_long) > 0) {
+                $stringsum_long = addslashes($stringsum_long);
+                $stringsum_a[]  = " match ($match) against ('$stringsum_long') ";
+            }
+
+            $stringsum .= implode("+", $stringsum_a);
+
+            return $stringsum;
+        }
+    }
+
+    
+
+    function boolean_inclusive_atoms($string)
+    {
+        $result = trim($string);
+        $result = preg_replace("/([[:space:]]{2,})/", ' ', $result);
+
+        /* convert normal boolean operators to shortened syntax */
+        $result = eregi_replace(' not ', ' -', $result);
+        $result = eregi_replace(' and ', ' ',  $result);
+        $result = eregi_replace(' or ',  ', ', $result);
+
+        /* drop unnecessary spaces */
+        $result = str_replace(' ,', ',', $result);
+        $result = str_replace(', ', ',', $result);
+        $result = str_replace('- ', '-', $result);
+        $result = str_replace('+',  '',  $result);
+
+        /* strip exlusive atoms */
+        $result = preg_replace(
+//            "(\-\([A-Za-z0-9]{1,}[A-Za-z0-9\-\.\_\,]{0,}\))",
+            "(\-\(([A-Za-z0-9]|$this->two|$this->three){1,}([A-Za-z0-9\-\.\_\,]|$this->two|$this->three){0,}\))",
+            '',
+            $result);
 
 /*             $result=preg_replace(
 //                     "(\-[A-Za-z0-9]{1,}[A-Za-z0-9\-\.\_]{0,})",
-                       "(\-([A-Za-z0-9]|$this->two|$this->three){1,}([A-Za-z0-9\-\.\_\,]|$this->two|$this->three){0,})",
-                       '',
-                       $result);
+            "(\-([A-Za-z0-9]|$this->two|$this->three){1,}([A-Za-z0-9\-\.\_\,]|$this->two|$this->three){0,})",
+            '',
+            $result);
 */
-               $result=str_replace('(',' ',$result);
-               $result=str_replace(')',' ',$result);
-               $result=str_replace(',',' ',$result);
-               if ($this->encoding != 'utf-8') {
-                       $result = mb_convert_encoding($result, $this->encoding, "UTF-8");
-               }
-               return $result;
-       }
-
-       function boolean_sql_where($match){
+        $result = str_replace('(', ' ', $result);
+        $result = str_replace(')', ' ', $result);
+        $result = str_replace(',', ' ', $result);
+        if ($this->encoding != 'utf-8') {
+            $result = mb_convert_encoding($result, $this->encoding, "UTF-8");
+        }
+        return $result;
+    }
+
+    function boolean_sql_where($match)
+    {
 /*
-               $result = $this->marked;
-               $result = preg_replace(
-                       "/foo\[\(\'([^\)]{4,})\'\)\]bar/e",
-                       " 'match ('.\$match.') against (\''.\$this->copyvalue(\"$1\").'\') > 0 ' ",
-
-
-
-
-
-
-                       $result);
-
-               $result = preg_replace(
-                       "/foo\[\(\'([^\)]{1,3})\'\)\]bar/e",
-                       " '('.\$this->boolean_sql_where_short(\"$1\",\"$match\").')' ",
-
-
-
-
-
-                       $result);
+        $result = $this->marked;
+        $result = preg_replace(
+            "/foo\[\(\'([^\)]{4,})\'\)\]bar/e",
+            " 'match ('.\$match.') against (\''.\$this->copyvalue(\"$1\").'\') > 0 ' ",
+            $result);
+        $result = preg_replace(
+            "/foo\[\(\'([^\)]{1,3})\'\)\]bar/e",
+            " '('.\$this->boolean_sql_where_short(\"$1\",\"$match\").')' ",
+            $result);
 */
-               $result = $this->jpmarked; /* for jp */
-               $result = $this->boolean_sql_where_jp_short($result,$match);/* for jp */
-               if ($this->encoding != 'utf-8') {
-                       $result = mb_convert_encoding($result, $this->encoding, "UTF-8");
-               }
-               return $result;
-
-       }
-
-
-
-       // there must be a simple way to simply copy a value with backslashes in it through
-       // the preg_replace, but I cannot currently find it (karma 2003-12-30)
-       function copyvalue($foo) {
-               return $foo;
-
-
-       }
-
-
-
+        $result = $this->jpmarked; /* for jp */
+        $result = $this->boolean_sql_where_jp_short($result, $match);/* for jp */
+        if ($this->encoding != 'utf-8') {
+            $result = mb_convert_encoding($result, $this->encoding, "UTF-8");
+        }
+        return $result;
+    }
+
+    // there must be a simple way to simply copy a value with backslashes in it through
+    // the preg_replace, but I cannot currently find it (karma 2003-12-30)
+    function copyvalue($foo)
+    {
+        return $foo;
+    }
 /*
-
-
-
-
-
-
-
-       function boolean_mark_atoms($string){
-               $result=trim($string);
-               $result=preg_replace("/([[:space:]]{2,})/",' ',$result);
-
-               // convert normal boolean operators to shortened syntax
-               $result=eregi_replace(' not ',' -',$result);
-               $result=eregi_replace(' and ',' ',$result);
-               $result=eregi_replace(' or ',',',$result);
-
-
-               // strip excessive whitespace
-               $result=str_replace('( ','(',$result);
-               $result=str_replace(' )',')',$result);
-               $result=str_replace(', ',',',$result);
-               $result=str_replace(' ,',',',$result);
-               $result=str_replace('- ','-',$result);
-               $result=str_replace('+','',$result);
-
-               // remove double spaces (we might have introduced some new ones above)
-               $result=trim($result);
-               $result=preg_replace("/([[:space:]]{2,})/",' ',$result);
-
-               // apply arbitrary function to all 'word' atoms
-
-               $result_a = explode(" ",$result);
-               for($word=0;$word<count($result_a);$word++){
-                       $result_a[$word] = "foo[('".$result_a[$word]."')]bar";
-               }
-               $result = implode(" ",$result_a);
-
-               // dispatch ' ' to ' AND '
-               $result=str_replace(' ',' AND ',$result);
-
-               // dispatch ',' to ' OR '
-               $result=str_replace(',',' OR ',$result);
-
-               // dispatch '-' to ' NOT '
-               $result=str_replace(' -',' NOT ',$result);
-               return $result;
-       }
-
-       function boolean_sql_where_short($string,$match){
-               $match_a = explode(',',$match);
-               for($ith=0;$ith<count($match_a);$ith++){
-                       $like_a[$ith] = " $match_a[$ith] LIKE '% $string %' ";
-               }
-               $like = implode(" OR ",$like_a);
-
-               return $like;
-       }
+    function boolean_mark_atoms($string){
+        $result=trim($string);
+        $result=preg_replace("/([[:space:]]{2,})/",' ',$result);
+
+        // convert normal boolean operators to shortened syntax
+        $result=eregi_replace(' not ',' -',$result);
+        $result=eregi_replace(' and ',' ',$result);
+        $result=eregi_replace(' or ',',',$result);
+
+        // strip excessive whitespace
+        $result=str_replace('( ','(',$result);
+        $result=str_replace(' )',')',$result);
+        $result=str_replace(', ',',',$result);
+        $result=str_replace(' ,',',',$result);
+        $result=str_replace('- ','-',$result);
+        $result=str_replace('+','',$result);
+
+        // remove double spaces (we might have introduced some new ones above)
+        $result=trim($result);
+        $result=preg_replace("/([[:space:]]{2,})/",' ',$result);
+
+        // apply arbitrary function to all 'word' atoms
+
+        $result_a = explode(" ",$result);
+        for($word=0;$word<count($result_a);$word++){
+            $result_a[$word] = "foo[('".$result_a[$word]."')]bar";
+        }
+        $result = implode(" ",$result_a);
+
+        // dispatch ' ' to ' AND '
+        $result=str_replace(' ',' AND ',$result);
+
+        // dispatch ',' to ' OR '
+        $result=str_replace(',',' OR ',$result);
+
+        // dispatch '-' to ' NOT '
+        $result=str_replace(' -',' NOT ',$result);
+        return $result;
+    }
+
+    function boolean_sql_where_short($string,$match){
+        $match_a = explode(',',$match);
+        for($ith=0;$ith<count($match_a);$ith++){
+            $like_a[$ith] = " $match_a[$ith] LIKE '% $string %' ";
+        }
+        $like = implode(" OR ",$like_a);
+
+        return $like;
+    }
 */
 
-       function boolean_sql_select_short($string,$match){
-               $match_a = explode(',',$match);
-               $score_unit_weight = .2;
-               for($ith=0;$ith<count($match_a);$ith++){
-                       $score_a[$ith] =
-                                                       " $score_unit_weight*(
-                                                       LENGTH(" . addslashes($match_a[$ith]) . ") -
-                                                       LENGTH(REPLACE(LOWER(" . addslashes($match_a[$ith]) . "),LOWER('" . addslashes($string) . "'),'')))
-                                                       /LENGTH('" . addslashes($string) . "') ";
-               }
-               $score = implode(" + ",$score_a);
-
-               return $score;
-       }
+    function boolean_sql_select_short($string, $match)
+    {
+        $match_a           = explode(',', $match);
+        $score_unit_weight = .2;
+        for ($ith = 0; $ith< count($match_a); $ith++){
+            $score_a[$ith] =
+                            " $score_unit_weight*(
+                            LENGTH(" . addslashes($match_a[$ith]) . ") -
+                            LENGTH(REPLACE(LOWER(" . addslashes($match_a[$ith]) . "),LOWER('" . addslashes($string) . "'),'')))
+                            /LENGTH('" . addslashes($string) . "') ";
+        }
+        $score = implode(" + ", $score_a);
+
+        return $score;
+    }
 
 /***********************************************
-       Make "WHERE" (jp)
+    Make "WHERE" (jp)
 ***********************************************/
 
-       function boolean_mark_atoms_jp($string){
-
-               $result=trim($string);
-               $result=preg_replace("/([[:space:]]{2,})/",' ',$result);
-               
-               /* convert normal boolean operators to shortened syntax */
-               $result=eregi_replace(' not ',' -',$result);
-               $result=eregi_replace(' and ',' ',$result);
-               $result=eregi_replace(' or ',',',$result);
-
-               /* strip excessive whitespace */
-               $result=str_replace(', ',',',$result);
-               $result=str_replace(' ,',',',$result);
-               $result=str_replace('- ','-',$result);
-               $result=str_replace('+','',$result);
-               
-               $result=str_replace(',',' ,',$result);
-
-               return $result;
-       }
-
-       function boolean_sql_where_jp_short($string,$match){
-               $match_a = explode(',',$match);
-                       $key_a = explode(' ',$string);
-                       
-               for($ith=0;$ith<count($match_a);$ith++){
+    function boolean_mark_atoms_jp($string)
+    {
+        $result = trim($string);
+        $result = preg_replace("/([[:space:]]{2,})/", ' ', $result);
+        
+        /* convert normal boolean operators to shortened syntax */
+        $result = eregi_replace(' not ', ' -', $result);
+        $result = eregi_replace(' and ', ' ',  $result);
+        $result = eregi_replace(' or ',  ',',  $result);
+
+        /* strip excessive whitespace */
+        $result = str_replace(', ', ',',  $result);
+        $result = str_replace(' ,', ',',  $result);
+        $result = str_replace('- ', '-',  $result);
+        $result = str_replace('+',  '',   $result);
+        $result = str_replace(',',  ' ,', $result);
+
+        return $result;
+    }
+
+    function boolean_sql_where_jp_short($string, $match)
+    {
+        $match_a = explode(',', $match);
+        $key_a   = explode(' ', $string);
+
+        for ($ith=0; $ith<count($match_a); $ith++) {
 //                     $temp_a[$ith] = "(i.$match_a[$ith] LIKE '%" . addslashes($key_a[0]) . "%') ";
-                       $temp_a[$ith] = "(i.$match_a[$ith] LIKE "
-                                                       . preg_match('/[a-zA-Z]/', $key_a[0]) ?
-                                                               '' :
-                                                               'BINARY'
-                                                       . " '%" . addslashes($key_a[0]) . "%') ";
-               }
-               $like = '('.implode(' or ',$temp_a).')';
-
-               for($kn=1; $kn<count($key_a); $kn++){
-                       if(substr($key_a[$kn],0,1) == ","){
-                               for($ith=0;$ith<count($match_a);$ith++){
+            $binKey       = preg_match('/[a-zA-Z]/', $key_a[0]) ? '' : 'BINARY';
+            $temp_a[$ith] = "(i.$match_a[$ith] LIKE " . $binKey . " '%" . addslashes($key_a[0]) . "%') ";
+        }
+        $like = '('.implode(' or ',$temp_a).')';
+
+        for ($kn = 1; $kn < count($key_a); $kn++) {
+            $binKey       = preg_match('/[a-zA-Z]/', $key_a[$kn]) ? '' : 'BINARY';
+            if (substr($key_a[$kn], 0, 1) == ",") {
+                for($ith = 0; $ith < count($match_a); $ith++) {
 //                                     $temp_a[$ith] = " (i.$match_a[$ith] LIKE '%" . addslashes(substr($key_a[$kn],1)) . "%') ";
-                                       $temp_a[$ith] = " (i.$match_a[$ith] LIKE "
-                                                                       . preg_match('/[a-zA-Z]/',$key_a[$kn]) ?
-                                                                               '' :
-                                                                               'BINARY'
-                                                                       . " '%" . addslashes(substr($key_a[$kn],1)) . "%') ";
-                               }
-                               $like .=' OR ('. implode(' or ',$temp_a).')';
-                       }elseif(substr($key_a[$kn],0,1) != '-'){
-                               for($ith=0;$ith<count($match_a);$ith++){
+                    $temp_a[$ith] = " (i.$match_a[$ith] LIKE " . $binKey . " '%" . addslashes(substr($key_a[$kn], 1)) . "%') ";
+                }
+                $like .=' OR ('. implode(' or ', $temp_a).')';
+            }elseif(substr($key_a[$kn],0,1) != '-'){
+                for($ith=0;$ith<count($match_a);$ith++){
 //                                     $temp_a[$ith] = " (i.$match_a[$ith] LIKE '%" . addslashes($key_a[$kn]) . "%') ";
-                                       $temp_a[$ith] = " (i.$match_a[$ith] LIKE "
-                                                                 . preg_match('/[a-zA-Z]/', $key_a[$kn]) ?
-                                                                               '' :
-                                                                               'BINARY'
-                                                                 . " '%" . addslashes($key_a[$kn]) . "%') ";
-                               }
-                               $like .=' AND ('. implode(' or ',$temp_a).')';
-                       }else{
-                               for($ith=0;$ith<count($match_a);$ith++){
+                    $temp_a[$ith] = " (i.$match_a[$ith] LIKE " . $binKey . " '%" . addslashes($key_a[$kn]) . "%') ";
+                }
+                $like .=' AND ('. implode(' or ', $temp_a).')';
+            }else{
+                for($ith=0;$ith<count($match_a);$ith++){
 //                                     $temp_a[$ith] = " NOT(i.$match_a[$ith] LIKE '%" . addslashes(substr($key_a[$kn],1)) . "%') ";
-                                       $temp_a[$ith] = " NOT(i.$match_a[$ith] LIKE "
-                                                                 . preg_match('/[a-zA-Z]/', $key_a[$kn]) ?
-                                                                               '' :
-                                                                               'BINARY'
-                                                                 . " '%" . addslashes(substr($key_a[$kn],1)) . "%') ";
-                               }
-                               $like .=' AND ('. implode(' and ',$temp_a).')';
-                       }
-               }
-               
-               $like = '('.$like.')';
-               return $like;
-       }
+                    $temp_a[$ith] = " NOT(i.$match_a[$ith] LIKE " . $binKey . " '%" . addslashes(substr($key_a[$kn], 1)) . "%') ";
+                }
+                $like .=' AND ('. implode(' and ', $temp_a).')';
+            }
+        }
+        
+        $like = '('.$like.')';
+        return $like;
+    }
 
 /***********************************************/
 }
index 68f5a0d..2ce6031 100755 (executable)
@@ -27,29 +27,30 @@ checkVars(array('nucleus', 'CONF', 'DIR_LIBS', 'MYSQL_HOST', 'MYSQL_USER', 'MYSQ
 \r
 $CONF['debug'] = 0;\r
 if ($CONF['debug']) {\r
-       error_reporting(E_ALL); // report all errors!\r
+    error_reporting(E_ALL); // report all errors!\r
 } else {\r
-       error_reporting(E_ERROR | E_WARNING | E_PARSE);\r
+    ini_set('display_errors','0');\r
+    error_reporting(E_ERROR | E_WARNING | E_PARSE);\r
 }\r
 \r
 /*\r
-       Indicates when Nucleus should display startup errors. Set to 1 if you want\r
-       the error enabled (default), false otherwise\r
-\r
-       alertOnHeadersSent\r
-               Displays an error when visiting a public Nucleus page and headers have\r
-               been sent out to early. This usually indicates an error in either a\r
-               configuration file or a language file, and could cause Nucleus to\r
-               malfunction\r
-       alertOnSecurityRisk\r
-               Displays an error only when visiting the admin area, and when one or\r
-               more of the installation files (install.php, install.sql, upgrades/\r
-               directory) are still on the server.\r
+    Indicates when Nucleus should display startup errors. Set to 1 if you want\r
+    the error enabled (default), false otherwise\r
+\r
+    alertOnHeadersSent\r
+        Displays an error when visiting a public Nucleus page and headers have\r
+        been sent out to early. This usually indicates an error in either a\r
+        configuration file or a language file, and could cause Nucleus to\r
+        malfunction\r
+    alertOnSecurityRisk\r
+        Displays an error only when visiting the admin area, and when one or\r
+        more of the installation files (install.php, install.sql, upgrades/\r
+        directory) are still on the server.\r
 */\r
 \r
 $CONF['alertOnHeadersSent']  = 1;\r
 $CONF['alertOnSecurityRisk'] = 1;\r
-/*$CONF['ItemURL']             = $CONF['Self'];\r
+/*$CONF['ItemURL']           = $CONF['Self'];\r
 $CONF['ArchiveURL']          = $CONF['Self'];\r
 $CONF['ArchiveListURL']      = $CONF['Self'];\r
 $CONF['MemberURL']           = $CONF['Self'];\r
@@ -60,25 +61,25 @@ $CONF['CategoryURL']         = $CONF['Self'];
 // 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
+    $CONF['URLMode'] = 'normal';\r
 }*/\r
 \r
 if (getNucleusPatchLevel() > 0) {\r
-       $nucleus['version'] .= '/' . getNucleusPatchLevel();\r
+    $nucleus['version'] .= '/' . getNucleusPatchLevel();\r
 }\r
 \r
 // Avoid notices\r
 if (!isset($CONF['installscript'])) {\r
-       $CONF['installscript'] = 0;\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
-       }\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
 // sanitize option\r
@@ -110,16 +111,16 @@ $special      = requestVar('special');
 $virtualpath  = ((getVar('virtualpath') != null) ? getVar('virtualpath') : serverVar('PATH_INFO'));\r
 \r
 if (!headers_sent() ) {\r
-       header('Generator: Nucleus CMS ' . $nucleus['version']);\r
+    header('Generator: Nucleus CMS ' . $nucleus['version']);\r
 }\r
 \r
 // include core classes that are needed for login & plugin handling\r
 // added for 3.5 sql_* wrapper\r
 global $MYSQL_HANDLER;\r
 if (!isset($MYSQL_HANDLER))\r
-       $MYSQL_HANDLER = array('mysql','');\r
+    $MYSQL_HANDLER = array('mysql','');\r
 if ($MYSQL_HANDLER[0] == '')\r
-       $MYSQL_HANDLER[0] = 'mysql';\r
+    $MYSQL_HANDLER[0] = 'mysql';\r
 include_once($DIR_LIBS . 'sql/'.$MYSQL_HANDLER[0].'.php');\r
 // end new for 3.5 sql_* wrapper\r
 include_once($DIR_LIBS . 'mysql.php');\r
@@ -131,17 +132,20 @@ include($DIR_LIBS . 'PLUGIN.php');
 $manager =& MANAGER::instance();\r
 \r
 // make sure there's no unnecessary escaping:\r
-set_magic_quotes_runtime(0);\r
+//set_magic_quotes_runtime(0);\r
+if (version_compare(PHP_VERSION, '5.3.0', '<')) {\r
+    ini_set('magic_quotes_runtime', '0');\r
+}\r
 \r
 // Avoid notices\r
 if (!isset($CONF['UsingAdminArea'])) {\r
-       $CONF['UsingAdminArea'] = 0;\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
+    include($DIR_LIBS . 'xmlrpc.inc.php');  // XML-RPC client classes\r
+    include_once($DIR_LIBS . 'ADMIN.php');\r
 }\r
 \r
 // connect to database\r
@@ -150,8 +154,8 @@ $SQLCount = 0;
 \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
+    $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";\r
+    $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');\r
     if ($bLoggingSanitizedResult) {\r
         addToLog(WARNING, $msg);\r
     }\r
@@ -168,19 +172,19 @@ getConfig();
 \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
+    $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
+    $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
@@ -194,12 +198,12 @@ $CONF['CategoryURL'] = $CONF['Self'];
 // 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
+    $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
-       $CONF['DisableJsTools'] = 2;\r
+    $CONF['DisableJsTools'] = 2;\r
 }\r
 \r
 // login if cookies set\r
@@ -209,99 +213,99 @@ $member = new MEMBER();
 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
+    $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
+    $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
+    $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+$/','',serverVar('REMOTE_ADDR'));\r
+    break;\r
 case 32:\r
-       $CONF['secureCookieKeyIP']=serverVar('REMOTE_ADDR');\r
-       break;\r
+    $CONF['secureCookieKeyIP']=serverVar('REMOTE_ADDR');\r
+    break;\r
 default:\r
-       $CONF['secureCookieKeyIP']='';\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
-       $shared = intPostVar('shared'); // shared computer or not\r
-\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
-                       $action = $nextaction;\r
-               }\r
-\r
-               $manager->notify('LoginSuccess', array('member' => &$member, 'username' => $login) );\r
-               $errormessage = '';\r
-               ACTIONLOG::add(INFO, "Login successful for $login (sharedpc=$shared)");\r
-       } else {\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
+    // Form Authentication\r
+    $login = postVar('login');\r
+    $pw = postVar('password');\r
+    $shared = intPostVar('shared'); // shared computer or not\r
+\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
+            $action = $nextaction;\r
+        }\r
+\r
+        $manager->notify('LoginSuccess', array('member' => &$member, 'username' => $login) );\r
+        $errormessage = '';\r
+        ACTIONLOG::add(INFO, "Login successful for $login (sharedpc=$shared)");\r
+    } else {\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
 Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details\r
 \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 CMS {$nucleus['version']}\"");\r
-               header('HTTP/1.0 401 Unauthorized');\r
-               echo 'Invalid username or password';\r
-               exit;\r
-       }\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 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($CONF['CookiePrefix'] . 'user') ) {\r
-       // remove cookies on logout\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
+    // remove cookies on logout\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
-       $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($CONF['CookiePrefix'] . 'sharedpc') != 1) && (!headers_sent() ) ) {\r
-               $member->setCookieKey(cookieVar($CONF['CookiePrefix'] . 'loginkey'));\r
-               $member->setCookies();\r
-       }\r
+    // Cookie Authentication\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($CONF['CookiePrefix'] . 'sharedpc') != 1) && (!headers_sent() ) ) {\r
+        $member->setCookieKey(cookieVar($CONF['CookiePrefix'] . 'loginkey'));\r
+        $member->setCookies();\r
+    }\r
 }\r
 \r
 // login completed\r
@@ -310,8 +314,8 @@ ticketForPlugin();
 \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
+    redirect($CONF['DisableSiteURL']);\r
+    exit;\r
 }\r
 \r
 // load other classes\r
@@ -332,182 +336,183 @@ include($DIR_LIBS . 'entity.php');
 \r
 // set lastVisit cookie (if allowed)\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
+    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
+//include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');\r
+include($DIR_LANG . preg_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
+    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
+    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
 // 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
 {\r
-       define('_SETTINGS_EXTAUTH',                     'Enable External Authentication');\r
-       define('_WARNING_EXTAUTH',                      'Warning: Enable only if needed.');\r
-       define('_MEMBERS_BYPASS',                       'Use External Authentication');\r
+    define('_SETTINGS_EXTAUTH',         'Enable External Authentication');\r
+    define('_WARNING_EXTAUTH',          'Warning: Enable only if needed.');\r
+    define('_MEMBERS_BYPASS',           'Use External Authentication');\r
 }\r
 \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
-       define('_ARCHIVETYPE_YEAR', 'year');\r
+    define('_ARCHIVETYPE_DAY', 'day');\r
+    define('_ARCHIVETYPE_MONTH', 'month');\r
+    define('_ARCHIVETYPE_YEAR', 'year');\r
 }\r
 \r
 // decode path_info\r
 if ($CONF['URLMode'] == 'pathinfo') {\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
+    // 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
+                    if ($i < sizeof($data) ) {\r
+                        $_REQUEST['special'] = $data[$i];\r
                     }\r
                     break;\r
 \r
-                               default:\r
-                                       // skip...\r
-                       }\r
-               }\r
-       }\r
+                default:\r
+                    // skip...\r
+            }\r
+        }\r
+    }\r
 }\r
 \r
 function intPostVar($name) {\r
-       return intval(postVar($name) );\r
+    return intval(postVar($name) );\r
 }\r
 \r
 function intGetVar($name) {\r
-       return intval(getVar($name) );\r
+    return intval(getVar($name) );\r
 }\r
 \r
 function intRequestVar($name) {\r
-       return intval(requestVar($name) );\r
+    return intval(requestVar($name) );\r
 }\r
 \r
 function intCookieVar($name) {\r
-       return intval(cookieVar($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
+    return 350;\r
 }\r
 \r
 /**\r
@@ -516,7 +521,7 @@ function getNucleusVersion() {
  * be tested without having to install CVS.\r
  */\r
 function getNucleusPatchLevel() {\r
-       return 0;\r
+    return 0;\r
 }\r
 \r
 /**\r
@@ -526,15 +531,15 @@ function getNucleusPatchLevel() {
  * e.g. 3.41 or 3.41/02\r
  */\r
 function getLatestVersion() {\r
-       if (!function_exists('curl_init')) return false;\r
-       $crl = curl_init();\r
-       $timeout = 5;\r
-       curl_setopt ($crl, CURLOPT_URL,'http://nucleuscms.org/version_check.php');\r
-       curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);\r
-       curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);\r
-       $ret = curl_exec($crl);\r
-       curl_close($crl);\r
-       return $ret;\r
+    if (!function_exists('curl_init')) return false;\r
+    $crl = curl_init();\r
+    $timeout = 5;\r
+    curl_setopt ($crl, CURLOPT_URL,'http://nucleuscms.org/version_check.php');\r
+    curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);\r
+    curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);\r
+    $ret = curl_exec($crl);\r
+    curl_close($crl);\r
+    return $ret;\r
 \r
 }\r
 \r
@@ -543,86 +548,86 @@ function getLatestVersion() {
   */\r
 /* moved to $DIR_LIBS/sql/*.php handler files\r
 function sql_connect() {\r
-       global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_CONN;\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
+    $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
-       return $MYSQL_CONN;\r
+    return $MYSQL_CONN;\r
 }*/\r
 \r
 /**\r
  * returns a prefixed nucleus table name\r
  */\r
 function sql_table($name) {\r
-       global $MYSQL_PREFIX;\r
+    global $MYSQL_PREFIX;\r
 \r
-       if ($MYSQL_PREFIX) {\r
-               return $MYSQL_PREFIX . 'nucleus_' . $name;\r
-       } else {\r
-               return 'nucleus_' . $name;\r
-       }\r
+    if ($MYSQL_PREFIX) {\r
+        return $MYSQL_PREFIX . 'nucleus_' . $name;\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
-               // 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
-               // 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
-                       )\r
-               {\r
-                       $contenttype = 'text/html';\r
-               }\r
-\r
-               $manager->notify(\r
-                       'PreSendContentType',\r
-                       array(\r
-                               'contentType' => &$contenttype,\r
-                               'charset' => &$charset,\r
-                               'pageType' => $pagetype\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
-               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
+    global $manager, $CONF;\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
+        // 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
+            )\r
+        {\r
+            $contenttype = 'text/html';\r
+        }\r
+\r
+        $manager->notify(\r
+            'PreSendContentType',\r
+            array(\r
+                'contentType' => &$contenttype,\r
+                'charset' => &$charset,\r
+                'pageType' => $pagetype\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
+        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
@@ -630,18 +635,18 @@ function sendContentType($contenttype, $pagetype = '', $charset = _CHARSET) {
  */\r
 /* moved to $DIR_LIBS/sql/*.php handler files\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 <?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
-               </body>\r
-       </html>\r
-       <?php   exit;\r
+    if (!defined('_CHARSET')) define('_CHARSET', 'iso-8859-1');\r
+    header('Content-Type: text/html; charset=' . _CHARSET);\r
+    ?>\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
+        </body>\r
+    </html>\r
+    <?php   exit;\r
 }*/\r
 \r
 /**\r
@@ -649,7 +654,7 @@ function startUpError($msg, $title) {
   */\r
 /* moved to $DIR_LIBS/sql/*.php handler files\r
 function sql_disconnect() {\r
-       @mysql_close();\r
+    @mysql_close();\r
 }*/\r
 \r
 /**\r
@@ -657,10 +662,10 @@ function sql_disconnect() {
   */\r
 /* moved to $DIR_LIBS/sql/*.php handler files\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
+    global $SQLCount;\r
+    $SQLCount++;\r
+    $res = mysql_query($query) or print("mySQL error with query $query: " . mysql_error() . '<p />');\r
+    return $res;\r
 }*/\r
 \r
 \r
@@ -676,535 +681,536 @@ function sql_query($query) {
  *\r
  */\r
 function highlight($text, $expression, $highlight) {\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
-\r
-       // split the HTML up so we have HTML tags\r
-       // $matches[0][i] = HTML + text\r
-       // $matches[1][i] = HTML\r
-       // $matches[2][i] = text\r
-       preg_match_all('/(<[^>]+>)([^<>]*)/', $text, $matches);\r
-\r
-       // 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) {\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
-                       $result .= $matches[2][$i];\r
-               } else {\r
-                       $result .= @eregi_replace($expression, $highlight, $matches[2][$i]);\r
-               }\r
-       }\r
-\r
-       return $result;\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
+\r
+    // split the HTML up so we have HTML tags\r
+    // $matches[0][i] = HTML + text\r
+    // $matches[1][i] = HTML\r
+    // $matches[2][i] = text\r
+    preg_match_all('/(<[^>]+>)([^<>]*)/', $text, $matches);\r
+\r
+    // 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) {\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
+            $result .= $matches[2][$i];\r
+        } else {\r
+            $result .= @eregi_replace($expression, $highlight, $matches[2][$i]);\r
+        }\r
+    }\r
+\r
+    return $result;\r
 }\r
 \r
 /**\r
  * Parses a query into an array of expressions that can be passed on to the highlight method\r
  */\r
 function parseHighlight($query) {\r
-       // TODO: add more intelligent splitting logic\r
+    // TODO: add more intelligent splitting logic\r
 \r
-       // get rid of quotes\r
-       $query = preg_replace('/\'|"/', '', $query);\r
+    // get rid of quotes\r
+    $query = preg_replace('/\'|"/', '', $query);\r
 \r
-       if (!$query) {\r
-               return array();\r
-       }\r
+    if (!$query) {\r
+        return array();\r
+    }\r
 \r
-       $aHighlight = explode(' ', $query);\r
+    $aHighlight = explode(' ', $query);\r
 \r
-       for ($i = 0; $i < count($aHighlight); $i++) {\r
-               $aHighlight[$i] = trim($aHighlight[$i]);\r
+    for ($i = 0; $i < count($aHighlight); $i++) {\r
+        $aHighlight[$i] = trim($aHighlight[$i]);\r
 \r
 //             if (strlen($aHighlight[$i]) < 3) {\r
 //                     unset($aHighlight[$i]);\r
 //             }\r
-       }\r
+    }\r
 \r
-       if (count($aHighlight) == 1) {\r
-               return $aHighlight[0];\r
-       } else {\r
-               return $aHighlight;\r
-       }\r
+    if (count($aHighlight) == 1) {\r
+        return $aHighlight[0];\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-Z+0-9\._-]+@[a-zA-Z0-9\._-]+\.[A-Za-z]{2,5}$/', $address)) {\r
-               return 1;\r
-       } else {\r
-               return 0;\r
-       }\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
+        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 = sql_fetch_object($res);\r
-       return $obj->result;\r
+    $res = sql_query($q);\r
+    $obj = sql_fetch_object($res);\r
+    return isset($obj->result) ? $obj->result : false;\r
 }\r
 \r
 function getPluginNameFromPid($pid) {\r
-       $res = sql_query('SELECT pfile FROM ' . sql_table('plugin') . ' WHERE pid=' . intval($pid) );\r
-       $obj = sql_fetch_object($res);\r
-       return $obj->pfile;\r
+    $res = sql_query('SELECT pfile FROM ' . sql_table('plugin') . ' WHERE pid=' . intval($pid) );\r
+    $obj = sql_fetch_object($res);\r
+    return isset($obj->pfile) ? $obj->pfile : false;\r
 }\r
 \r
 function selector() {\r
-       global $itemid, $blogid, $memberid, $query, $amount, $archivelist, $maxresults;\r
-       global $archive, $skinid, $blog, $memberinfo, $CONF, $member;\r
-       global $imagepopup, $catid, $special;\r
-       global $manager;\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
-                       headers_sent($hsFile, $hsLine);\r
-                       $extraInfo = sprintf(_GFUNCTIONS_HEADERSALREADYSENT_FILE,$hsFile,$hsLine);\r
-               } else {\r
-                       $extraInfo = '';\r
-               }\r
-\r
-               startUpError(\r
-                       sprintf(_GFUNCTIONS_HEADERSALREADYSENT_TXT,$extraInfo),\r
-                       _GFUNCTIONS_HEADERSALREADYSENT_TITLE\r
-               );\r
-               exit;\r
-       }\r
-\r
-       // make is so ?archivelist without blogname or blogid shows the archivelist\r
-       // for the default weblog\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
-\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, 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 = sql_fetch_object($res);\r
-\r
-               // if a different blog id has been set through the request or selectBlog(),\r
-               // deny access\r
+    global $itemid, $blogid, $memberid, $query, $amount, $archivelist, $maxresults;\r
+    global $archive, $skinid, $blog, $memberinfo, $CONF, $member;\r
+    global $imagepopup, $catid, $special;\r
+    global $manager;\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
+            headers_sent($hsFile, $hsLine);\r
+            $extraInfo = sprintf(_GFUNCTIONS_HEADERSALREADYSENT_FILE,$hsFile,$hsLine);\r
+        } else {\r
+            $extraInfo = '';\r
+        }\r
+\r
+        startUpError(\r
+            sprintf(_GFUNCTIONS_HEADERSALREADYSENT_TXT,$extraInfo),\r
+            _GFUNCTIONS_HEADERSALREADYSENT_TITLE\r
+        );\r
+        exit;\r
+    }\r
+\r
+    // make is so ?archivelist without blogname or blogid shows the archivelist\r
+    // for the default weblog\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
+\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, 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 = sql_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
 //             }\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
-\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
-               $res = sql_query($query);\r
-\r
-               $obj = sql_fetch_object($res);\r
-\r
-               if ($obj) {\r
-                       $itemidprev = $obj->inumber;\r
-                       $itemtitleprev = $obj->ititle;\r
-               }\r
-\r
-               // get next itemid and title\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 = sql_fetch_object($res);\r
-\r
-               if ($obj) {\r
-                       $itemidnext = $obj->inumber;\r
-                       $itemtitlenext = $obj->ititle;\r
-               }\r
-\r
-       } elseif ($archive) {\r
-               // show archive\r
-               $type = 'archive';\r
-\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
-               if ($d != 0) {\r
-                       $archivetype = _ARCHIVETYPE_DAY;\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
-               } elseif ($m == 0) {\r
-                       $archivetype = _ARCHIVETYPE_YEAR;\r
-                       $t = mktime(0, 0, 0, 12, 31, $y - 1);\r
-                       // one day before is in the previous year\r
-                       $archiveprev = strftime('%Y', $t);\r
-                       if ($t > $first_timestamp) {\r
-                               $archiveprevexists = true;\r
-                       }\r
-                       else {\r
-                               $archiveprevexists = false;\r
-                       }\r
-\r
-                       // timestamp for the next year\r
-                       $t = mktime(0, 0, 0, 1, 1, $y + 1);\r
-                       $archivenext = strftime('%Y', $t);\r
-                       if ($t < $last_timestamp) {\r
-                               $archivenextexists = true;\r
-                       }\r
-                       else {\r
-                               $archivenextexists = false;\r
-                       }\r
-               } else {\r
-                       $archivetype = _ARCHIVETYPE_MONTH;\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
-\r
-               if (is_numeric($archivelist)) {\r
-                       $blogid = intVal($archivelist);\r
-               } else {\r
-                       $blogid = getBlogIDFromName($archivelist);\r
-               }\r
-\r
-               if (!$blogid) {\r
-                       doError(_ERROR_NOSUCHBLOG);\r
-               }\r
-\r
-       } elseif ($query) {\r
-               global $startpos;\r
-               $type = 'search';\r
-               $query = stripslashes($query);\r
-               if(preg_match("/^(\xA1{2}|\xe3\x80{2}|\x20)+$/", $query)){\r
-                                       $type = 'index';\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
+\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
+        $res = sql_query($query);\r
+\r
+        $obj = sql_fetch_object($res);\r
+\r
+        if ($obj) {\r
+            $itemidprev = $obj->inumber;\r
+            $itemtitleprev = $obj->ititle;\r
+        }\r
+\r
+        // get next itemid and title\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 = sql_fetch_object($res);\r
+\r
+        if ($obj) {\r
+            $itemidnext = $obj->inumber;\r
+            $itemtitlenext = $obj->ititle;\r
+        }\r
+\r
+    } elseif ($archive) {\r
+        // show archive\r
+        $type = 'archive';\r
+\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
+        if ($d != 0) {\r
+            $archivetype = _ARCHIVETYPE_DAY;\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
+        } elseif ($m == 0) {\r
+            $archivetype = _ARCHIVETYPE_YEAR;\r
+            $t = mktime(0, 0, 0, 12, 31, $y - 1);\r
+            // one day before is in the previous year\r
+            $archiveprev = strftime('%Y', $t);\r
+            if ($t > $first_timestamp) {\r
+                $archiveprevexists = true;\r
+            }\r
+            else {\r
+                $archiveprevexists = false;\r
+            }\r
+\r
+            // timestamp for the next year\r
+            $t = mktime(0, 0, 0, 1, 1, $y + 1);\r
+            $archivenext = strftime('%Y', $t);\r
+            if ($t < $last_timestamp) {\r
+                $archivenextexists = true;\r
+            }\r
+            else {\r
+                $archivenextexists = false;\r
+            }\r
+        } else {\r
+            $archivetype = _ARCHIVETYPE_MONTH;\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
+\r
+        if (is_numeric($archivelist)) {\r
+            $blogid = intVal($archivelist);\r
+        } else {\r
+            $blogid = getBlogIDFromName($archivelist);\r
+        }\r
+\r
+        if (!$blogid) {\r
+            doError(_ERROR_NOSUCHBLOG);\r
+        }\r
+\r
+    } elseif ($query) {\r
+        global $startpos;\r
+        $type = 'search';\r
+        $query = stripslashes($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
-               switch(strtolower(_CHARSET)){\r
-                       case 'utf-8':\r
-                               $order = 'ASCII, UTF-8, EUC-JP, JIS, SJIS, EUC-CN, ISO-8859-1';\r
-                               break;\r
-                       case 'gb2312':\r
-                               $order = 'ASCII, EUC-CN, EUC-JP, UTF-8, JIS, SJIS, ISO-8859-1';\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
-                               $order = 'ASCII, SJIS, EUC-JP, UTF-8, JIS, EUC-CN, ISO-8859-1';\r
-                               break;\r
-                       default:\r
-                               // euc-jp,iso-8859-x,windows-125x\r
-                               $order = 'ASCII, EUC-JP, UTF-8, JIS, SJIS, EUC-CN, ISO-8859-1';\r
-                               break;\r
-               }\r
-               $query = mb_convert_encoding($query, _CHARSET, $order);\r
-               if (is_numeric($blogid)) {\r
-                       $blogid = intVal($blogid);\r
-               } else {\r
-                       $blogid = getBlogIDFromName($blogid);\r
-               }\r
-\r
-               if (!$blogid) {\r
-                       doError(_ERROR_NOSUCHBLOG);\r
-               }\r
-\r
-       } elseif ($memberid) {\r
-               $type = 'member';\r
-\r
-               if (!MEMBER::existsID($memberid) ) {\r
-                       doError(_ERROR_NOSUCHMEMBER);\r
-               }\r
-\r
-               $memberinfo = $manager->getMember($memberid);\r
-\r
-       } elseif ($imagepopup) {\r
-               // media object (images etc.)\r
-               $type = 'imagepopup';\r
-\r
-               // TODO: check if media-object exists\r
-               // TODO: set some vars?\r
-       } else {\r
-               // show regular index page\r
-               global $startpos;\r
-               $type = 'index';\r
-       }\r
-\r
-       // any type of skin with catid\r
-       if ($catid && !$blogid) {\r
-               $blogid = getBlogIDFromCatID($catid);\r
-       }\r
-\r
-       // decide which blog should be displayed\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
-\r
-       if (!$blog->isValid) {\r
-               doError(_ERROR_NOSUCHBLOG);\r
-       }\r
-\r
-       // set catid if necessary\r
-       if ($catid) {\r
-               // check if the category is valid\r
-               if (!$blog->isValidCategory($catid)) {\r
-                       doError(_ERROR_NOSUCHCATEGORY);\r
-               } else {\r
-                       $blog->setSelectedCategory($catid);\r
-               }\r
-       }\r
-\r
-       // decide which skin should be used\r
-       if ($skinid != '' && ($skinid == 0) ) {\r
-               selectSkin($skinid);\r
-       }\r
-\r
-       if (!$skinid) {\r
-               $skinid = $blog->getDefaultSkin();\r
-       }\r
-\r
-       //$special = requestVar('special'); //get at top of file as global\r
-       if (!empty($special) && isValidShortName($special)) {\r
-               $type = strtolower($special);\r
-       }\r
-\r
-       $skin = new SKIN($skinid);\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
+        switch(strtolower(_CHARSET)){\r
+            case 'utf-8':\r
+                $order = 'ASCII, UTF-8, EUC-JP, JIS, SJIS, EUC-CN, ISO-8859-1';\r
+                break;\r
+            case 'gb2312':\r
+                $order = 'ASCII, EUC-CN, EUC-JP, UTF-8, JIS, SJIS, ISO-8859-1';\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
+                $order = 'ASCII, SJIS, EUC-JP, UTF-8, JIS, EUC-CN, ISO-8859-1';\r
+                break;\r
+            default:\r
+                // euc-jp,iso-8859-x,windows-125x\r
+                $order = 'ASCII, EUC-JP, UTF-8, JIS, SJIS, EUC-CN, ISO-8859-1';\r
+                break;\r
+        }\r
+        $query = mb_convert_encoding($query, _CHARSET, $order);\r
+        if (is_numeric($blogid)) {\r
+            $blogid = intVal($blogid);\r
+        } else {\r
+            $blogid = getBlogIDFromName($blogid);\r
+        }\r
+\r
+        if (!$blogid) {\r
+            doError(_ERROR_NOSUCHBLOG);\r
+        }\r
+\r
+    } elseif ($memberid) {\r
+        $type = 'member';\r
+\r
+        if (!MEMBER::existsID($memberid) ) {\r
+            doError(_ERROR_NOSUCHMEMBER);\r
+        }\r
+\r
+        $memberinfo = $manager->getMember($memberid);\r
+\r
+    } elseif ($imagepopup) {\r
+        // media object (images etc.)\r
+        $type = 'imagepopup';\r
+\r
+        // TODO: check if media-object exists\r
+        // TODO: set some vars?\r
+    } else {\r
+        // show regular index page\r
+        global $startpos;\r
+        $type = 'index';\r
+    }\r
+\r
+    // any type of skin with catid\r
+    if ($catid && !$blogid) {\r
+        $blogid = getBlogIDFromCatID($catid);\r
+    }\r
+\r
+    // decide which blog should be displayed\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
+\r
+    if (!$blog->isValid) {\r
+        doError(_ERROR_NOSUCHBLOG);\r
+    }\r
+\r
+    // set catid if necessary\r
+    if ($catid) {\r
+        // check if the category is valid\r
+        if (!$blog->isValidCategory($catid)) {\r
+            doError(_ERROR_NOSUCHCATEGORY);\r
+        } else {\r
+            $blog->setSelectedCategory($catid);\r
+        }\r
+    }\r
+\r
+    // decide which skin should be used\r
+    if ($skinid != '' && ($skinid == 0) ) {\r
+        selectSkin($skinid);\r
+    }\r
+\r
+    if (!$skinid) {\r
+        $skinid = $blog->getDefaultSkin();\r
+    }\r
+\r
+    //$special = requestVar('special'); //get at top of file as global\r
+    if (!empty($special) && isValidShortName($special)) {\r
+        $type = strtolower($special);\r
+    }\r
+\r
+    $skin = new SKIN($skinid);\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
   * Show error skin with given message. An optional skin-object to use can be given\r
   */\r
 function doError($msg, $skin = '') {\r
-       global $errormessage, $CONF, $skinid, $blogid, $manager;\r
-\r
-       if ($skin == '') {\r
-\r
-               if (SKIN::existsID($skinid) ) {\r
-                       $skin = new SKIN($skinid);\r
-               } elseif ($manager->existsBlogID($blogid) ) {\r
-                       $blog =& $manager->getBlog($blogid);\r
-                       $skin = new SKIN($blog->getDefaultSkin() );\r
-               } elseif ($CONF['DefaultBlog']) {\r
-                       $blog =& $manager->getBlog($CONF['DefaultBlog']);\r
-                       $skin = new SKIN($blog->getDefaultSkin() );\r
-               } else {\r
-                       // this statement should actually never be executed\r
-                       $skin = new SKIN($CONF['BaseSkin']);\r
-               }\r
+    global $errormessage, $CONF, $skinid, $blogid, $manager;\r
+\r
+    if ($skin == '') {\r
+\r
+        if (SKIN::existsID($skinid) ) {\r
+            $skin = new SKIN($skinid);\r
+        } elseif ($manager->existsBlogID($blogid) ) {\r
+            $blog =& $manager->getBlog($blogid);\r
+            $skin = new SKIN($blog->getDefaultSkin() );\r
+        } elseif ($CONF['DefaultBlog']) {\r
+            $blog =& $manager->getBlog($CONF['DefaultBlog']);\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
 \r
-       $skinid = $skin->id;\r
-       $errormessage = $msg;\r
-       $skin->parse('error');\r
-       exit;\r
+    $skinid = $skin->id;\r
+    $errormessage = $msg;\r
+    $skin->parse('error');\r
+    exit;\r
 }\r
 \r
 function getConfig() {\r
-       global $CONF;\r
+    global $CONF;\r
 \r
-       $query = 'SELECT * FROM ' . sql_table('config');\r
-       $res = sql_query($query);\r
+    $query = 'SELECT * FROM ' . sql_table('config');\r
+    $res = sql_query($query);\r
 \r
-       while ($obj = sql_fetch_object($res) ) {\r
-               $CONF[$obj->name] = $obj->value;\r
-       }\r
+    while ($obj = sql_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) {\r
-       return eregi('^[a-z0-9]+$', $name);\r
+    return eregi('^[a-z0-9]+$', $name);\r
 }\r
 \r
 function isValidDisplayName($name) {\r
-       return eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name);\r
+    return eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name);\r
 }\r
 \r
 function isValidCategoryName($name) {\r
-       return 1;\r
+    return 1;\r
 }\r
 \r
 function isValidTemplateName($name) {\r
-       return eregi('^[a-z0-9/]+$', $name);\r
+    return eregi('^[a-z0-9/]+$', $name);\r
 }\r
 \r
 function isValidSkinName($name) {\r
-       return eregi('^[a-z0-9/]+$', $name);\r
+    return eregi('^[a-z0-9/]+$', $name);\r
 }\r
 \r
 // add and remove linebreaks\r
 function addBreaks($var) {\r
-       return nl2br($var);\r
+    return nl2br($var);\r
 }\r
 \r
 function removeBreaks($var) {\r
-       return preg_replace("/<br \/>([\r\n])/", "$1", $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
+    // 1. remove 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
+    $trans = get_html_translation_table(HTML_SPECIALCHARS); // for Japanese\r
+    $trans = array_flip($trans);\r
+    $text  = strtr($text, $trans);\r
 \r
-       // 2. the actual shortening\r
-       if (strlen($text) > $maxlength) {\r
+    // 2. the actual shortening\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
+        $text = mb_strimwidth($text, 0, $maxlength, $toadd, _CHARSET); // for Japanese\r
+    }\r
+\r
+    return $text;\r
 }\r
 \r
 /**\r
@@ -1212,25 +1218,25 @@ 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
   * functions for use in index.php\r
   */\r
 function selectBlog($shortname) {\r
-       global $blogid, $archivelist;\r
-       $blogid = getBlogIDFromName($shortname);\r
+    global $blogid, $archivelist;\r
+    $blogid = getBlogIDFromName($shortname);\r
 \r
-       // also force archivelist variable, if it is set\r
-       if ($archivelist) {\r
-               $archivelist = $blogid;\r
-       }\r
+    // also force archivelist variable, if it is set\r
+    if ($archivelist) {\r
+        $archivelist = $blogid;\r
+    }\r
 }\r
 \r
 function selectSkin($skinname) {\r
-       global $skinid;\r
-       $skinid = SKIN::getIdFromName($skinname);\r
+    global $skinid;\r
+    $skinid = SKIN::getIdFromName($skinname);\r
 }\r
 \r
 /**\r
@@ -1238,85 +1244,86 @@ function selectSkin($skinname) {
  * multiple categories can have the same name)\r
  */\r
 function selectCategory($cat) {\r
-       global $catid;\r
-       if (is_numeric($cat) ) {\r
-               $catid = intval($cat);\r
-       } else {\r
-               $catid = getCatIDFromName($cat);\r
-       }\r
+    global $catid;\r
+    if (is_numeric($cat) ) {\r
+        $catid = intval($cat);\r
+    } else {\r
+        $catid = getCatIDFromName($cat);\r
+    }\r
 }\r
 \r
 function selectItem($id) {\r
-       global $itemid;\r
-       $itemid = intval($id);\r
+    global $itemid;\r
+    $itemid = intval($id);\r
 }\r
 \r
 // force the use of a language file (warning: can cause warnings)\r
 function selectLanguage($language) {\r
-       global $DIR_LANG;\r
-       include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');\r
+    global $DIR_LANG;\r
+//    include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');\r
+    include($DIR_LANG . preg_replace( '@\\|/@', '', $language) . '.php');\r
 }\r
 \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
+    $handler = new ACTIONS('fileparser');\r
+    $parser = new PARSER(SKIN::getAllowedActionsForType('fileparser'), $handler);\r
+    $handler->parser =& $parser;\r
 \r
-       // set IncludeMode properties of parser\r
-       PARSER::setProperty('IncludeMode', $includeMode);\r
-       PARSER::setProperty('IncludePrefix', $includePrefix);\r
+    // set IncludeMode properties of parser\r
+    PARSER::setProperty('IncludeMode', $includeMode);\r
+    PARSER::setProperty('IncludePrefix', $includePrefix);\r
 \r
-       if (!file_exists($filename) ) {\r
-               doError(_GFUNCTIONS_PARSEFILE_FILEMISSING);\r
-       }\r
+    if (!file_exists($filename) ) {\r
+        doError(_GFUNCTIONS_PARSEFILE_FILEMISSING);\r
+    }\r
 \r
-       $fsize = filesize($filename);\r
+    $fsize = filesize($filename);\r
 \r
-       if ($fsize <= 0) {\r
-               return;\r
-       }\r
+    if ($fsize <= 0) {\r
+        return;\r
+    }\r
 \r
-       // read file\r
-       $fd = fopen ($filename, 'r');\r
-       $contents = fread ($fd, $fsize);\r
-       fclose ($fd);\r
+    // read file\r
+    $fd = fopen ($filename, 'r');\r
+    $contents = fread ($fd, $fsize);\r
+    fclose ($fd);\r
 \r
-       // parse file contents\r
-       $parser->parse($contents);\r
+    // parse file contents\r
+    $parser->parse($contents);\r
 }\r
 \r
 /**\r
   * Outputs a debug message\r
   */\r
 function debug($msg) {\r
-       echo '<p><b>' . $msg . "</b></p>\n";\r
+    echo '<p><b>' . $msg . "</b></p>\n";\r
 }\r
 \r
 // shortcut\r
 function addToLog($level, $msg) {\r
-       ACTIONLOG::add($level, $msg);\r
+    ACTIONLOG::add($level, $msg);\r
 }\r
 \r
 // shows a link to help file\r
 function help($id) {\r
-       echo helpHtml($id);\r
+    echo helpHtml($id);\r
 }\r
 \r
 function helpHtml($id) {\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
+    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
-       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
+    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
-       $message = "\n\n-----------------------------";\r
-       $message .=  "\n   Powered by Nucleus CMS";\r
-       $message .=  "\n(http://www.nucleuscms.org/)";\r
-       return $message;\r
+    $message = "\n\n-----------------------------";\r
+    $message .=  "\n   Powered by Nucleus CMS";\r
+    $message .=  "\n(http://www.nucleuscms.org/)";\r
+    return $message;\r
 }\r
 \r
 /**\r
@@ -1327,174 +1334,176 @@ function getMailFooter() {
   * checks if file exists, etc...\r
   */\r
 function getLanguageName() {\r
-       global $CONF, $member;\r
+    global $CONF, $member;\r
 \r
-       if ($member && $member->isLoggedIn() ) {\r
-               // try to use members language\r
-               $memlang = $member->getLanguage();\r
+    if ($member && $member->isLoggedIn() ) {\r
+        // try to use members language\r
+        $memlang = $member->getLanguage();\r
 \r
-               if (($memlang != '') && (checkLanguage($memlang) ) ) {\r
-                       return $memlang;\r
-               }\r
-       }\r
+        if (($memlang != '') && (checkLanguage($memlang) ) ) {\r
+            return $memlang;\r
+        }\r
+    }\r
 \r
-       // use default language\r
-       if (checkLanguage($CONF['Language']) ) {\r
-               return $CONF['Language'];\r
-       } else {\r
-               return 'english';\r
-       }\r
+    // use default language\r
+    if (checkLanguage($CONF['Language']) ) {\r
+        return $CONF['Language'];\r
+    } else {\r
+        return 'english';\r
+    }\r
 }\r
 \r
 /**\r
   * Includes a PHP file. This method can be called while parsing templates and skins\r
   */\r
 function includephp($filename) {\r
-       // make predefined variables global, so most simple scripts can be used here\r
-\r
-       // apache (names taken from PHP doc)\r
-       global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;\r
-       global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;\r
-       global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;\r
-       global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;\r
-       global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;\r
-       global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;\r
-       global $REQUEST_URI;\r
-\r
-       // php (taken from PHP doc)\r
-       global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;\r
-       global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;\r
-\r
-       // other\r
-       global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;\r
-\r
-       if (@file_exists($filename) ) {\r
-               include($filename);\r
-       }\r
+    // make predefined variables global, so most simple scripts can be used here\r
+\r
+    // apache (names taken from PHP doc)\r
+    global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;\r
+    global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;\r
+    global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;\r
+    global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;\r
+    global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;\r
+    global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;\r
+    global $REQUEST_URI;\r
+\r
+    // php (taken from PHP doc)\r
+    global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;\r
+    global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;\r
+\r
+    // other\r
+    global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;\r
+\r
+    if (@file_exists($filename) ) {\r
+        include($filename);\r
+    }\r
 }\r
 \r
 /**\r
   * Checks if a certain language/plugin exists\r
   */\r
 function checkLanguage($lang) {\r
-       global $DIR_LANG ;\r
-       return file_exists($DIR_LANG . ereg_replace( '[\\|/]', '', $lang) . '.php');\r
+    global $DIR_LANG ;\r
+//    return file_exists($DIR_LANG . ereg_replace( '[\\|/]', '', $lang) . '.php');\r
+    return file_exists($DIR_LANG . preg_replace( '@\\|/@', '', $lang) . '.php');\r
 }\r
 \r
 function checkPlugin($plug) {\r
-       global $DIR_PLUGINS;\r
-       return file_exists($DIR_PLUGINS . ereg_replace( '[\\|/]', '', $plug) . '.php');\r
+    global $DIR_PLUGINS;\r
+    return file_exists($DIR_PLUGINS . ereg_replace( '[\\|/]', '', $plug) . '.php');\r
+//    return file_exists($DIR_PLUGINS . preg_replace( '@\\|/@', '', $plug) . '.php');\r
 }\r
 \r
 /**\r
   * Centralisation of the functions that generate links\r
   */\r
 function createItemLink($itemid, $extra = '') {\r
-       return createLink('item', array('itemid' => $itemid, 'extra' => $extra) );\r
+    return createLink('item', array('itemid' => $itemid, 'extra' => $extra) );\r
 }\r
 \r
 function createMemberLink($memberid, $extra = '') {\r
-       return createLink('member', array('memberid' => $memberid, 'extra' => $extra) );\r
+    return createLink('member', array('memberid' => $memberid, 'extra' => $extra) );\r
 }\r
 \r
 function createCategoryLink($catid, $extra = '') {\r
-       return createLink('category', array('catid' => $catid, 'extra' => $extra) );\r
+    return createLink('category', array('catid' => $catid, 'extra' => $extra) );\r
 }\r
 \r
 function createArchiveListLink($blogid = '', $extra = '') {\r
-       return createLink('archivelist', array('blogid' => $blogid, 'extra' => $extra) );\r
+    return createLink('archivelist', array('blogid' => $blogid, 'extra' => $extra) );\r
 }\r
 \r
 function createArchiveLink($blogid, $archive, $extra = '') {\r
-       return createLink('archive', array('blogid' => $blogid, 'archive' => $archive, 'extra' => $extra) );\r
+    return createLink('archive', array('blogid' => $blogid, 'archive' => $archive, 'extra' => $extra) );\r
 }\r
 \r
 function createBlogidLink($blogid, $params = '') {\r
-       return createLink('blog', array('blogid' => $blogid, 'extra' => $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
+    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
@@ -1509,30 +1518,30 @@ function createBlogLink($url, $params) {
     } elseif ($CONF['URLMode'] == 'pathinfo' && substr($url, -1) == '/') {\r
         $url = substr($url, 0, -1);\r
     }\r
-       return addLinkParams($url, $params);\r
+    return addLinkParams($url, $params);\r
 }\r
 \r
 function addLinkParams($link, $params) {\r
-       global $CONF;\r
+    global $CONF;\r
 \r
-       if (is_array($params) ) {\r
+    if (is_array($params) ) {\r
 \r
-               if ($CONF['URLMode'] == 'pathinfo')     {\r
+        if ($CONF['URLMode'] == 'pathinfo') {\r
 \r
-                       foreach ($params as $param => $value) {\r
-                               $link .= '/' . $param . '/' . urlencode($value);\r
-                       }\r
+            foreach ($params as $param => $value) {\r
+                $link .= '/' . $param . '/' . urlencode($value);\r
+            }\r
 \r
-               } else {\r
+        } else {\r
 \r
-                       foreach ($params as $param => $value) {\r
-                               $link .= '&amp;' . $param . '=' . urlencode($value);\r
-                       }\r
+            foreach ($params as $param => $value) {\r
+                $link .= '&amp;' . $param . '=' . urlencode($value);\r
+            }\r
 \r
-               }\r
-       }\r
+        }\r
+    }\r
 \r
-       return $link;\r
+    return $link;\r
 }\r
 \r
 /**\r
@@ -1546,185 +1555,185 @@ function addLinkParams($link, $params) {
  *             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
+    $vars = explode('&', $querystr);\r
+    $set  = false;\r
 \r
-       for ($i = 0; $i < count($vars); $i++) {\r
-               $v = explode('=', $vars[$i]);\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
+        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
+    if (!$set) {\r
+        $vars[] = $param . '=' . $value;\r
+    }\r
 \r
-       return ltrim(implode('&', $vars), '&');\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
-               }\r
+    // array ?\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
+        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
+    // other values: do stripslashes if needed\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
+    Date format functions (to be used from [%date(..)%] skinvars\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
+    // 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
-         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
+      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
-\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
-                               die('Sorry. An error occurred.');\r
-                       }\r
+    global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;\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
+                die('Sorry. An error occurred.');\r
+            }\r
+\r
+        } else {\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
+                die('Sorry. An error occurred.');\r
+            }\r
 \r
-               } else {\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
-                               die('Sorry. An error occurred.');\r
-                       }\r
-\r
-               }\r
-       }\r
+        }\r
+    }\r
 }\r
 \r
 \r
@@ -1734,47 +1743,47 @@ function checkVars($aVars) {
  */\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
+    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
@@ -1783,138 +1792,139 @@ function sanitizeParams()
  * 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=sql_fetch_row($res)) {\r
-               $name=substr($row[0],3);\r
-               $plugins[strtolower($name)]=$name;\r
-       }\r
-       sql_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(_GFUNCTIONS_YOU_AERNT_LOGGEDIN);\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
+    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=sql_fetch_row($res)) {\r
+        $name=substr($row[0],3);\r
+        $plugins[strtolower($name)]=$name;\r
+    }\r
+    sql_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(_GFUNCTIONS_YOU_AERNT_LOGGEDIN);\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_LANG . preg_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
+    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
@@ -1923,26 +1933,26 @@ function _addInputTags(&$keys,$prefix=''){
  */\r
 function serverStringToArray($str, &$array, &$frontParam)\r
 {\r
-       // init param\r
-       $array = array();\r
-       $fronParam = "";\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
+    // 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
+    // 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
+    $array = explode("&", $args);\r
 }\r
 \r
 /**\r
@@ -1951,14 +1961,14 @@ function serverStringToArray($str, &$array, &$frontParam)
  */\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
+    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
@@ -1969,45 +1979,45 @@ function arrayToServerString($array, $frontParam, &$str)
  */\r
 function sanitizeArray(&$array)\r
 {\r
-       $excludeListForSanitization = array('query');\r
+    $excludeListForSanitization = array('query');\r
 //     $excludeListForSanitization = array();\r
 \r
-       foreach ($array as $k => $v) {\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
+        // 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
+        // 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
+        // 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
+            // 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
+            // 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
+            // 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
+            // set sanitized info\r
+            $array[$k] = sprintf("%s=%s", $key, $val);\r
+        }\r
+    }\r
 }\r
 \r
 /**\r
@@ -2015,12 +2025,12 @@ function sanitizeArray(&$array)
  */\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
+    $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
@@ -2028,10 +2038,10 @@ function convArrayForSanitizing($src, &$array)
  */\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
+    foreach ($array as $v) {\r
+        list($key, $val) = preg_split("/=/", $v, 2);\r
+        $dst[$key] = $val;\r
+    }\r
 }\r
 \r
 /**\r
@@ -2040,9 +2050,9 @@ function revertArrayForSanitizing($array, &$dst)
  * - the URL will be stripped of illegal or dangerous characters\r
  */\r
 function redirect($url) {\r
-       $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%*]|i', '', $url);\r
-       header('Location: ' . $url);\r
-       exit;\r
+    $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%*]|i', '', $url);\r
+    header('Location: ' . $url);\r
+    exit;\r
 }\r
 \r
 /**\r
@@ -2052,15 +2062,15 @@ function redirect($url) {
  * 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
+    $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
@@ -2068,17 +2078,17 @@ function stringStripTags ($string) {
  * 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
+    $string = stringStripTags($string);\r
+    $string = entity::named_to_numeric($string);\r
+    $string = entity::normalize_numeric($string);\r
 \r
-       if (strtoupper(_CHARSET) == 'UTF-8') {\r
-               $string = entity::numeric_to_utf8($string);\r
-       }\r
+    if (strtoupper(_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
+    $string = entity::specialchars($string, 'html');\r
+    $string = entity::numeric_to_named($string);\r
+    return $string;\r
 }\r
 \r
 /**\r
@@ -2087,28 +2097,28 @@ function stringToAttribute ($string) {
  * 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
+    $string = stringStripTags($string);\r
+    $string = entity::named_to_numeric($string);\r
+    $string = entity::normalize_numeric($string);\r
 \r
-       if (strtoupper(_CHARSET) == 'UTF-8') {\r
-               $string = entity::numeric_to_utf8($string);\r
-       }\r
+    if (strtoupper(_CHARSET) == 'UTF-8') {\r
+        $string = entity::numeric_to_utf8($string);\r
+    }\r
 \r
-       $string = entity::specialchars($string, 'xml');\r
-       return $string;\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
+    // 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
@@ -2127,8 +2137,8 @@ function _links_list() {
    $output = '';\r
    $i = 1;\r
    foreach ($tmp_links as $current) {\r
-         $output .= "[$i] $current\n";\r
-         $i++;\r
+      $output .= "[$i] $current\n";\r
+      $i++;\r
    }\r
    return $output;\r
 }\r
@@ -2141,13 +2151,13 @@ function _links_list() {
 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
+    $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
@@ -2156,15 +2166,15 @@ function encode_desc(&$data)
  * @param blogid\r
  */\r
 function getBookmarklet($blogid) {\r
-       global $CONF;\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
+    // 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
+    return $bookmarkletline;\r
 }\r
 // END: functions from the end of file ADMIN.php\r
 \r
@@ -2175,11 +2185,11 @@ function getBookmarklet($blogid) {
  * @return mixed Variable\r
  */\r
 function ifset(&$var) {\r
-       if (isset($var)) {\r
-               return $var;\r
-       }\r
+    if (isset($var)) {\r
+        return $var;\r
+    }\r
 \r
-       return null;\r
+    return null;\r
 }\r
 \r
 /**\r
@@ -2189,15 +2199,15 @@ function ifset(&$var) {
  * @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 = sql_fetch_object($res);\r
-       return $obj->count;\r
+    $query = 'SELECT COUNT(*) as count FROM ' . sql_table('plugin_event') . ' WHERE event=\'' . $event . '\'';\r
+    $res = sql_query($query);\r
+    $obj = sql_fetch_object($res);\r
+    return $obj->count;\r
 }\r
 \r
 function selectSpecialSkinType($id) {\r
-       global $special;\r
-       $special = strtolower($id);\r
+    global $special;\r
+    $special = strtolower($id);\r
 }\r
 \r
 ?>
\ No newline at end of file
index beeeb80..f465906 100755 (executable)
@@ -63,7 +63,7 @@ if (function_exists('mysql_query') && !function_exists('sql_fetch_assoc'))
         $MYSQL_CONN = @mysql_connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD) or startUpError('<p>Could not connect to MySQL database.</p>', 'Connect Error');
         mysql_select_db($MYSQL_DATABASE) or startUpError('<p>Could not select database: ' . mysql_error() . '</p>', 'Connect Error');
 
-/*/ <add for garble measure>
+// <add for garble measure>
         $resource = sql_query("show variables LIKE 'character_set_database'");
         $fetchDat = sql_fetch_assoc($resource);
         $charset  = $fetchDat['Value'];
index a29c2f0..53992dc 100755 (executable)
@@ -183,7 +183,7 @@ if (!function_exists('sql_fetch_assoc'))
 
             //$SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$MYSQL_DATABASE, $MYSQL_USER, $MYSQL_PASSWORD);
             
-/*/ <add for garble measure>
+// <add for garble measure>
             if (strpos($MYSQL_HANDLER[1], 'mysql') === 0) {
                 $resource = $SQL_DBH->query("show variables LIKE 'character_set_database'");
                 $resource->bindColumn('Value', $charset);
index f04bab5..a4798b7 100755 (executable)
 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 // OF THE POSSIBILITY OF SUCH DAMAGE.
 
-       if(!function_exists('xml_parser_create'))
-       {
-               // For PHP 4 onward, XML functionality is always compiled-in on windows:
-               // no more need to dl-open it. It might have been compiled out on *nix...
-               if(strtoupper(substr(PHP_OS, 0, 3) != 'WIN'))
-               {
-                       dl('xml.so');
-               }
-       }
-
-       // Try to be backward compat with php < 4.2 (are we not being nice ?)
-       $phpversion = phpversion();
-       if($phpversion[0] == '4' && $phpversion[2] < 2)
-       {
-               // give an opportunity to user to specify where to include other files from
-               if(!defined('PHP_XMLRPC_COMPAT_DIR'))
-               {
-                       define('PHP_XMLRPC_COMPAT_DIR',dirname(__FILE__).'/compat/');
-               }
-               if($phpversion[2] == '0')
-               {
-                       if($phpversion[4] < 6)
-                       {
-                               include(PHP_XMLRPC_COMPAT_DIR.'is_callable.php');
-                       }
-                       include(PHP_XMLRPC_COMPAT_DIR.'is_scalar.php');
-                       include(PHP_XMLRPC_COMPAT_DIR.'array_key_exists.php');
-                       include(PHP_XMLRPC_COMPAT_DIR.'version_compare.php');
-               }
-               include(PHP_XMLRPC_COMPAT_DIR.'var_export.php');
-               include(PHP_XMLRPC_COMPAT_DIR.'is_a.php');
-       }
-
-       // G. Giunta 2005/01/29: declare global these variables,
-       // so that xmlrpc.inc will work even if included from within a function
-       // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used.
-       $GLOBALS['xmlrpcI4']='i4';
-       $GLOBALS['xmlrpcInt']='int';
-       $GLOBALS['xmlrpcBoolean']='boolean';
-       $GLOBALS['xmlrpcDouble']='double';
-       $GLOBALS['xmlrpcString']='string';
-       $GLOBALS['xmlrpcDateTime']='dateTime.iso8601';
-       $GLOBALS['xmlrpcBase64']='base64';
-       $GLOBALS['xmlrpcArray']='array';
-       $GLOBALS['xmlrpcStruct']='struct';
-       $GLOBALS['xmlrpcValue']='undefined';
-
-       $GLOBALS['xmlrpcTypes']=array(
-               $GLOBALS['xmlrpcI4']       => 1,
-               $GLOBALS['xmlrpcInt']      => 1,
-               $GLOBALS['xmlrpcBoolean']  => 1,
-               $GLOBALS['xmlrpcString']   => 1,
-               $GLOBALS['xmlrpcDouble']   => 1,
-               $GLOBALS['xmlrpcDateTime'] => 1,
-               $GLOBALS['xmlrpcBase64']   => 1,
-               $GLOBALS['xmlrpcArray']    => 2,
-               $GLOBALS['xmlrpcStruct']   => 3
-       );
-
-       $GLOBALS['xmlrpc_valid_parents'] = array(
-               'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
-               'BOOLEAN' => array('VALUE'),
-               'I4' => array('VALUE'),
-               'INT' => array('VALUE'),
-               'STRING' => array('VALUE'),
-               'DOUBLE' => array('VALUE'),
-               'DATETIME.ISO8601' => array('VALUE'),
-               'BASE64' => array('VALUE'),
-               'MEMBER' => array('STRUCT'),
-               'NAME' => array('MEMBER'),
-               'DATA' => array('ARRAY'),
-               'ARRAY' => array('VALUE'),
-               'STRUCT' => array('VALUE'),
-               'PARAM' => array('PARAMS'),
-               'METHODNAME' => array('METHODCALL'),
-               'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
-               'FAULT' => array('METHODRESPONSE'),
-               'NIL' => array('VALUE') // only used when extension activated
-       );
-
-       // define extra types for supporting NULL (useful for json or <NIL/>)
-       $GLOBALS['xmlrpcNull']='null';
-       $GLOBALS['xmlrpcTypes']['null']=1;
-
-       // Not in use anymore since 2.0. Shall we remove it?
-       /// @deprecated
-       $GLOBALS['xmlEntities']=array(
-               'amp'  => '&',
-               'quot' => '"',
-               'lt'   => '<',
-               'gt'   => '>',
-               'apos' => "'"
-       );
-
-       // tables used for transcoding different charsets into us-ascii xml
-
-       $GLOBALS['xml_iso88591_Entities']=array();
-       $GLOBALS['xml_iso88591_Entities']['in'] = array();
-       $GLOBALS['xml_iso88591_Entities']['out'] = array();
-       for ($i = 0; $i < 32; $i++)
-       {
-               $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
-               $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
-       }
-       for ($i = 160; $i < 256; $i++)
-       {
-               $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
-               $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
-       }
-
-       /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159.
-       /// These will NOT be present in true ISO-8859-1, but will save the unwary
-       /// windows user from sending junk.
+    if(!function_exists('xml_parser_create'))
+    {
+        // For PHP 4 onward, XML functionality is always compiled-in on windows:
+        // no more need to dl-open it. It might have been compiled out on *nix...
+        //if(strtoupper(substr(PHP_OS, 0, 3) != 'WIN'))
+        $phpver = phpversion();
+        if (!extension_loaded('xml') && version_compare($phpver,'5.3.0','<'))
+        {
+            dl('xml.so');
+        }
+    }
+
+    // Try to be backward compat with php < 4.2 (are we not being nice ?)
+    $phpversion = phpversion();
+    if($phpversion[0] == '4' && $phpversion[2] < 2)
+    {
+        // give an opportunity to user to specify where to include other files from
+        if(!defined('PHP_XMLRPC_COMPAT_DIR'))
+        {
+            define('PHP_XMLRPC_COMPAT_DIR',dirname(__FILE__).'/compat/');
+        }
+        if($phpversion[2] == '0')
+        {
+            if($phpversion[4] < 6)
+            {
+                include(PHP_XMLRPC_COMPAT_DIR.'is_callable.php');
+            }
+            include(PHP_XMLRPC_COMPAT_DIR.'is_scalar.php');
+            include(PHP_XMLRPC_COMPAT_DIR.'array_key_exists.php');
+            include(PHP_XMLRPC_COMPAT_DIR.'version_compare.php');
+        }
+        include(PHP_XMLRPC_COMPAT_DIR.'var_export.php');
+        include(PHP_XMLRPC_COMPAT_DIR.'is_a.php');
+    }
+
+    // G. Giunta 2005/01/29: declare global these variables,
+    // so that xmlrpc.inc will work even if included from within a function
+    // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used.
+    $GLOBALS['xmlrpcI4']='i4';
+    $GLOBALS['xmlrpcInt']='int';
+    $GLOBALS['xmlrpcBoolean']='boolean';
+    $GLOBALS['xmlrpcDouble']='double';
+    $GLOBALS['xmlrpcString']='string';
+    $GLOBALS['xmlrpcDateTime']='dateTime.iso8601';
+    $GLOBALS['xmlrpcBase64']='base64';
+    $GLOBALS['xmlrpcArray']='array';
+    $GLOBALS['xmlrpcStruct']='struct';
+    $GLOBALS['xmlrpcValue']='undefined';
+
+    $GLOBALS['xmlrpcTypes']=array(
+        $GLOBALS['xmlrpcI4']       => 1,
+        $GLOBALS['xmlrpcInt']      => 1,
+        $GLOBALS['xmlrpcBoolean']  => 1,
+        $GLOBALS['xmlrpcString']   => 1,
+        $GLOBALS['xmlrpcDouble']   => 1,
+        $GLOBALS['xmlrpcDateTime'] => 1,
+        $GLOBALS['xmlrpcBase64']   => 1,
+        $GLOBALS['xmlrpcArray']    => 2,
+        $GLOBALS['xmlrpcStruct']   => 3
+    );
+
+    $GLOBALS['xmlrpc_valid_parents'] = array(
+        'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
+        'BOOLEAN' => array('VALUE'),
+        'I4' => array('VALUE'),
+        'INT' => array('VALUE'),
+        'STRING' => array('VALUE'),
+        'DOUBLE' => array('VALUE'),
+        'DATETIME.ISO8601' => array('VALUE'),
+        'BASE64' => array('VALUE'),
+        'MEMBER' => array('STRUCT'),
+        'NAME' => array('MEMBER'),
+        'DATA' => array('ARRAY'),
+        'ARRAY' => array('VALUE'),
+        'STRUCT' => array('VALUE'),
+        'PARAM' => array('PARAMS'),
+        'METHODNAME' => array('METHODCALL'),
+        'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
+        'FAULT' => array('METHODRESPONSE'),
+        'NIL' => array('VALUE') // only used when extension activated
+    );
+
+    // define extra types for supporting NULL (useful for json or <NIL/>)
+    $GLOBALS['xmlrpcNull']='null';
+    $GLOBALS['xmlrpcTypes']['null']=1;
+
+    // Not in use anymore since 2.0. Shall we remove it?
+    /// @deprecated
+    $GLOBALS['xmlEntities']=array(
+        'amp'  => '&',
+        'quot' => '"',
+        'lt'   => '<',
+        'gt'   => '>',
+        'apos' => "'"
+    );
+
+    // tables used for transcoding different charsets into us-ascii xml
+
+    $GLOBALS['xml_iso88591_Entities']=array();
+    $GLOBALS['xml_iso88591_Entities']['in'] = array();
+    $GLOBALS['xml_iso88591_Entities']['out'] = array();
+    for ($i = 0; $i < 32; $i++)
+    {
+        $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
+        $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
+    }
+    for ($i = 160; $i < 256; $i++)
+    {
+        $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
+        $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
+    }
+
+    /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159.
+    /// These will NOT be present in true ISO-8859-1, but will save the unwary
+    /// windows user from sending junk.
 /*
 $cp1252_to_xmlent =
   array(
@@ -165,3479 +167,3480 @@ $cp1252_to_xmlent =
   );
 */
 
-       $GLOBALS['xmlrpcerr']['unknown_method']=1;
-       $GLOBALS['xmlrpcstr']['unknown_method']='Unknown method';
-       $GLOBALS['xmlrpcerr']['invalid_return']=2;
-       $GLOBALS['xmlrpcstr']['invalid_return']='Invalid return payload: enable debugging to examine incoming payload';
-       $GLOBALS['xmlrpcerr']['incorrect_params']=3;
-       $GLOBALS['xmlrpcstr']['incorrect_params']='Incorrect parameters passed to method';
-       $GLOBALS['xmlrpcerr']['introspect_unknown']=4;
-       $GLOBALS['xmlrpcstr']['introspect_unknown']="Can't introspect: method unknown";
-       $GLOBALS['xmlrpcerr']['http_error']=5;
-       $GLOBALS['xmlrpcstr']['http_error']="Didn't receive 200 OK from remote server.";
-       $GLOBALS['xmlrpcerr']['no_data']=6;
-       $GLOBALS['xmlrpcstr']['no_data']='No data received from server.';
-       $GLOBALS['xmlrpcerr']['no_ssl']=7;
-       $GLOBALS['xmlrpcstr']['no_ssl']='No SSL support compiled in.';
-       $GLOBALS['xmlrpcerr']['curl_fail']=8;
-       $GLOBALS['xmlrpcstr']['curl_fail']='CURL error';
-       $GLOBALS['xmlrpcerr']['invalid_request']=15;
-       $GLOBALS['xmlrpcstr']['invalid_request']='Invalid request payload';
-       $GLOBALS['xmlrpcerr']['no_curl']=16;
-       $GLOBALS['xmlrpcstr']['no_curl']='No CURL support compiled in.';
-       $GLOBALS['xmlrpcerr']['server_error']=17;
-       $GLOBALS['xmlrpcstr']['server_error']='Internal server error';
-       $GLOBALS['xmlrpcerr']['multicall_error']=18;
-       $GLOBALS['xmlrpcstr']['multicall_error']='Received from server invalid multicall response';
-
-       $GLOBALS['xmlrpcerr']['multicall_notstruct'] = 9;
-       $GLOBALS['xmlrpcstr']['multicall_notstruct'] = 'system.multicall expected struct';
-       $GLOBALS['xmlrpcerr']['multicall_nomethod']  = 10;
-       $GLOBALS['xmlrpcstr']['multicall_nomethod']  = 'missing methodName';
-       $GLOBALS['xmlrpcerr']['multicall_notstring'] = 11;
-       $GLOBALS['xmlrpcstr']['multicall_notstring'] = 'methodName is not a string';
-       $GLOBALS['xmlrpcerr']['multicall_recursion'] = 12;
-       $GLOBALS['xmlrpcstr']['multicall_recursion'] = 'recursive system.multicall forbidden';
-       $GLOBALS['xmlrpcerr']['multicall_noparams']  = 13;
-       $GLOBALS['xmlrpcstr']['multicall_noparams']  = 'missing params';
-       $GLOBALS['xmlrpcerr']['multicall_notarray']  = 14;
-       $GLOBALS['xmlrpcstr']['multicall_notarray']  = 'params is not an array';
-
-       $GLOBALS['xmlrpcerr']['cannot_decompress']=103;
-       $GLOBALS['xmlrpcstr']['cannot_decompress']='Received from server compressed HTTP and cannot decompress';
-       $GLOBALS['xmlrpcerr']['decompress_fail']=104;
-       $GLOBALS['xmlrpcstr']['decompress_fail']='Received from server invalid compressed HTTP';
-       $GLOBALS['xmlrpcerr']['dechunk_fail']=105;
-       $GLOBALS['xmlrpcstr']['dechunk_fail']='Received from server invalid chunked HTTP';
-       $GLOBALS['xmlrpcerr']['server_cannot_decompress']=106;
-       $GLOBALS['xmlrpcstr']['server_cannot_decompress']='Received from client compressed HTTP request and cannot decompress';
-       $GLOBALS['xmlrpcerr']['server_decompress_fail']=107;
-       $GLOBALS['xmlrpcstr']['server_decompress_fail']='Received from client invalid compressed HTTP request';
-
-       // The charset encoding used by the server for received messages and
-       // by the client for received responses when received charset cannot be determined
-       // or is not supported
-       $GLOBALS['xmlrpc_defencoding']='UTF-8';
-
-       // The encoding used internally by PHP.
-       // String values received as xml will be converted to this, and php strings will be converted to xml
-       // as if having been coded with this
-       $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';
-
-       $GLOBALS['xmlrpcName']='XML-RPC for PHP';
-       $GLOBALS['xmlrpcVersion']='2.2';
-
-       // let user errors start at 800
-       $GLOBALS['xmlrpcerruser']=800;
-       // let XML parse errors start at 100
-       $GLOBALS['xmlrpcerrxml']=100;
-
-       // formulate backslashes for escaping regexp
-       // Not in use anymore since 2.0. Shall we remove it?
-       /// @deprecated
-       $GLOBALS['xmlrpc_backslash']=chr(92).chr(92);
-
-       // set to TRUE to enable correct decoding of <NIL/> values
-       $GLOBALS['xmlrpc_null_extension']=false;
-
-       // used to store state during parsing
-       // quick explanation of components:
-       //   ac - used to accumulate values
-       //   isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1)
-       //   isf_reason - used for storing xmlrpcresp fault string
-       //   lv - used to indicate "looking for a value": implements
-       //        the logic to allow values with no types to be strings
-       //   params - used to store parameters in method calls
-       //   method - used to store method name
-       //   stack - array with genealogy of xml elements names:
-       //           used to validate nesting of xmlrpc elements
-       $GLOBALS['_xh']=null;
-
-       /**
-       * Convert a string to the correct XML representation in a target charset
-       * To help correct communication of non-ascii chars inside strings, regardless
-       * of the charset used when sending requests, parsing them, sending responses
-       * and parsing responses, an option is to convert all non-ascii chars present in the message
-       * into their equivalent 'charset entity'. Charset entities enumerated this way
-       * are independent of the charset encoding used to transmit them, and all XML
-       * parsers are bound to understand them.
-       * Note that in the std case we are not sending a charset encoding mime type
-       * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.
-       *
-       * @todo do a bit of basic benchmarking (strtr vs. str_replace)
-       * @todo make usage of iconv() or recode_string() or mb_string() where available
-       */
-       function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='')
-       {
-               if ($src_encoding == '')
-               {
-                       // lame, but we know no better...
-                       $src_encoding = $GLOBALS['xmlrpc_internalencoding'];
-               }
-
-               switch(strtoupper($src_encoding.'_'.$dest_encoding))
-               {
-                       case 'ISO-8859-1_':
-                       case 'ISO-8859-1_US-ASCII':
-                               $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
-                               $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);
-                               break;
-                       case 'ISO-8859-1_UTF-8':
-                               $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
-                               $escaped_data = utf8_encode($escaped_data);
-                               break;
-                       case 'ISO-8859-1_ISO-8859-1':
-                       case 'US-ASCII_US-ASCII':
-                       case 'US-ASCII_UTF-8':
-                       case 'US-ASCII_':
-                       case 'US-ASCII_ISO-8859-1':
-                       case 'UTF-8_UTF-8':
-                               $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
-                               break;
-                       case 'UTF-8_':
-                       case 'UTF-8_US-ASCII':
-                       case 'UTF-8_ISO-8859-1':
-       // NB: this will choke on invalid UTF-8, going most likely beyond EOF
-       $escaped_data = '';
-       // be kind to users creating string xmlrpcvals out of different php types
-       $data = (string) $data;
-       $ns = strlen ($data);
-       for ($nn = 0; $nn < $ns; $nn++)
-       {
-               $ch = $data[$nn];
-               $ii = ord($ch);
-               //1 7 0bbbbbbb (127)
-               if ($ii < 128)
-               {
-                       /// @todo shall we replace this with a (supposedly) faster str_replace?
-                       switch($ii){
-                               case 34:
-                                       $escaped_data .= '&quot;';
-                                       break;
-                               case 38:
-                                       $escaped_data .= '&amp;';
-                                       break;
-                               case 39:
-                                       $escaped_data .= '&apos;';
-                                       break;
-                               case 60:
-                                       $escaped_data .= '&lt;';
-                                       break;
-                               case 62:
-                                       $escaped_data .= '&gt;';
-                                       break;
-                               default:
-                                       $escaped_data .= $ch;
-                       } // switch
-               }
-               //2 11 110bbbbb 10bbbbbb (2047)
-               else if ($ii>>5 == 6)
-               {
-                       $b1 = ($ii & 31);
-                       $ii = ord($data[$nn+1]);
-                       $b2 = ($ii & 63);
-                       $ii = ($b1 * 64) + $b2;
-                       $ent = sprintf ('&#%d;', $ii);
-                       $escaped_data .= $ent;
-                       $nn += 1;
-               }
-               //3 16 1110bbbb 10bbbbbb 10bbbbbb
-               else if ($ii>>4 == 14)
-               {
-                       $b1 = ($ii & 31);
-                       $ii = ord($data[$nn+1]);
-                       $b2 = ($ii & 63);
-                       $ii = ord($data[$nn+2]);
-                       $b3 = ($ii & 63);
-                       $ii = ((($b1 * 64) + $b2) * 64) + $b3;
-                       $ent = sprintf ('&#%d;', $ii);
-                       $escaped_data .= $ent;
-                       $nn += 2;
-               }
-               //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
-               else if ($ii>>3 == 30)
-               {
-                       $b1 = ($ii & 31);
-                       $ii = ord($data[$nn+1]);
-                       $b2 = ($ii & 63);
-                       $ii = ord($data[$nn+2]);
-                       $b3 = ($ii & 63);
-                       $ii = ord($data[$nn+3]);
-                       $b4 = ($ii & 63);
-                       $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
-                       $ent = sprintf ('&#%d;', $ii);
-                       $escaped_data .= $ent;
-                       $nn += 3;
-               }
-       }
-                               break;
-                       default:
-                               $escaped_data = '';
-                               error_log("Converting from $src_encoding to $dest_encoding: not supported...");
-               }
-               return $escaped_data;
-       }
-
-       /// xml parser handler function for opening element tags
-       function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false)
-       {
-               // if invalid xmlrpc already detected, skip all processing
-               if ($GLOBALS['_xh']['isf'] < 2)
-               {
-                       // check for correct element nesting
-                       // top level element can only be of 2 types
-                       /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
-                       ///       there is only a single top level element in xml anyway
-                       if (count($GLOBALS['_xh']['stack']) == 0)
-                       {
-                               if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (
-                                       $name != 'VALUE' && !$accept_single_vals))
-                               {
-                                       $GLOBALS['_xh']['isf'] = 2;
-                                       $GLOBALS['_xh']['isf_reason'] = 'missing top level xmlrpc element';
-                                       return;
-                               }
-                               else
-                               {
-                                       $GLOBALS['_xh']['rt'] = strtolower($name);
-                               }
-                       }
-                       else
-                       {
-                               // not top level element: see if parent is OK
-                               $parent = end($GLOBALS['_xh']['stack']);
-                               if (!array_key_exists($name, $GLOBALS['xmlrpc_valid_parents']) || !in_array($parent, $GLOBALS['xmlrpc_valid_parents'][$name]))
-                               {
-                                       $GLOBALS['_xh']['isf'] = 2;
-                                       $GLOBALS['_xh']['isf_reason'] = "xmlrpc element $name cannot be child of $parent";
-                                       return;
-                               }
-                       }
-
-                       switch($name)
-                       {
-                               // optimize for speed switch cases: most common cases first
-                               case 'VALUE':
-                                       /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
-                                       $GLOBALS['_xh']['vt']='value'; // indicator: no value found yet
-                                       $GLOBALS['_xh']['ac']='';
-                                       $GLOBALS['_xh']['lv']=1;
-                                       $GLOBALS['_xh']['php_class']=null;
-                                       break;
-                               case 'I4':
-                               case 'INT':
-                               case 'STRING':
-                               case 'BOOLEAN':
-                               case 'DOUBLE':
-                               case 'DATETIME.ISO8601':
-                               case 'BASE64':
-                                       if ($GLOBALS['_xh']['vt']!='value')
-                                       {
-                                               //two data elements inside a value: an error occurred!
-                                               $GLOBALS['_xh']['isf'] = 2;
-                                               $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
-                                               return;
-                                       }
-                                       $GLOBALS['_xh']['ac']=''; // reset the accumulator
-                                       break;
-                               case 'STRUCT':
-                               case 'ARRAY':
-                                       if ($GLOBALS['_xh']['vt']!='value')
-                                       {
-                                               //two data elements inside a value: an error occurred!
-                                               $GLOBALS['_xh']['isf'] = 2;
-                                               $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
-                                               return;
-                                       }
-                                       // create an empty array to hold child values, and push it onto appropriate stack
-                                       $cur_val = array();
-                                       $cur_val['values'] = array();
-                                       $cur_val['type'] = $name;
-                                       // check for out-of-band information to rebuild php objs
-                                       // and in case it is found, save it
-                                       if (@isset($attrs['PHP_CLASS']))
-                                       {
-                                               $cur_val['php_class'] = $attrs['PHP_CLASS'];
-                                       }
-                                       $GLOBALS['_xh']['valuestack'][] = $cur_val;
-                                       $GLOBALS['_xh']['vt']='data'; // be prepared for a data element next
-                                       break;
-                               case 'DATA':
-                                       if ($GLOBALS['_xh']['vt']!='data')
-                                       {
-                                               //two data elements inside a value: an error occurred!
-                                               $GLOBALS['_xh']['isf'] = 2;
-                                               $GLOBALS['_xh']['isf_reason'] = "found two data elements inside an array element";
-                                               return;
-                                       }
-                               case 'METHODCALL':
-                               case 'METHODRESPONSE':
-                               case 'PARAMS':
-                                       // valid elements that add little to processing
-                                       break;
-                               case 'METHODNAME':
-                               case 'NAME':
-                                       /// @todo we could check for 2 NAME elements inside a MEMBER element
-                                       $GLOBALS['_xh']['ac']='';
-                                       break;
-                               case 'FAULT':
-                                       $GLOBALS['_xh']['isf']=1;
-                                       break;
-                               case 'MEMBER':
-                                       $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on
-                                       //$GLOBALS['_xh']['ac']='';
-                                       // Drop trough intentionally
-                               case 'PARAM':
-                                       // clear value type, so we can check later if no value has been passed for this param/member
-                                       $GLOBALS['_xh']['vt']=null;
-                                       break;
-                               case 'NIL':
-                                       if ($GLOBALS['xmlrpc_null_extension'])
-                                       {
-                                               if ($GLOBALS['_xh']['vt']!='value')
-                                               {
-                                                       //two data elements inside a value: an error occurred!
-                                                       $GLOBALS['_xh']['isf'] = 2;
-                                                       $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
-                                                       return;
-                                               }
-                                               $GLOBALS['_xh']['ac']=''; // reset the accumulator
-                                               break;
-                                       }
-                                       // we do not support the <NIL/> extension, so
-                                       // drop through intentionally
-                               default:
-                                       /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
-                                       $GLOBALS['_xh']['isf'] = 2;
-                                       $GLOBALS['_xh']['isf_reason'] = "found not-xmlrpc xml element $name";
-                                       break;
-                       }
-
-                       // Save current element name to stack, to validate nesting
-                       $GLOBALS['_xh']['stack'][] = $name;
-
-                       /// @todo optimization creep: move this inside the big switch() above
-                       if($name!='VALUE')
-                       {
-                               $GLOBALS['_xh']['lv']=0;
-                       }
-               }
-       }
-
-       /// Used in decoding xml chunks that might represent single xmlrpc values
-       function xmlrpc_se_any($parser, $name, $attrs)
-       {
-               xmlrpc_se($parser, $name, $attrs, true);
-       }
-
-       /// xml parser handler function for close element tags
-       function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true)
-       {
-               if ($GLOBALS['_xh']['isf'] < 2)
-               {
-                       // push this element name from stack
-                       // NB: if XML validates, correct opening/closing is guaranteed and
-                       // we do not have to check for $name == $curr_elem.
-                       // we also checked for proper nesting at start of elements...
-                       $curr_elem = array_pop($GLOBALS['_xh']['stack']);
-
-                       switch($name)
-                       {
-                               case 'VALUE':
-                                       // This if() detects if no scalar was inside <VALUE></VALUE>
-                                       if ($GLOBALS['_xh']['vt']=='value')
-                                       {
-                                               $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
-                                               $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcString'];
-                                       }
-
-                                       if ($rebuild_xmlrpcvals)
-                                       {
-                                               // build the xmlrpc val out of the data received, and substitute it
-                                               $temp =& new xmlrpcval($GLOBALS['_xh']['value'], $GLOBALS['_xh']['vt']);
-                                               // in case we got info about underlying php class, save it
-                                               // in the object we're rebuilding
-                                               if (isset($GLOBALS['_xh']['php_class']))
-                                                       $temp->_php_class = $GLOBALS['_xh']['php_class'];
-                                               // check if we are inside an array or struct:
-                                               // if value just built is inside an array, let's move it into array on the stack
-                                               $vscount = count($GLOBALS['_xh']['valuestack']);
-                                               if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
-                                               {
-                                                       $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $temp;
-                                               }
-                                               else
-                                               {
-                                                       $GLOBALS['_xh']['value'] = $temp;
-                                               }
-                                       }
-                                       else
-                                       {
-                                               /// @todo this needs to treat correctly php-serialized objects,
-                                               /// since std deserializing is done by php_xmlrpc_decode,
-                                               /// which we will not be calling...
-                                               if (isset($GLOBALS['_xh']['php_class']))
-                                               {
-                                               }
-
-                                               // check if we are inside an array or struct:
-                                               // if value just built is inside an array, let's move it into array on the stack
-                                               $vscount = count($GLOBALS['_xh']['valuestack']);
-                                               if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
-                                               {
-                                                       $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $GLOBALS['_xh']['value'];
-                                               }
-                                       }
-                                       break;
-                               case 'BOOLEAN':
-                               case 'I4':
-                               case 'INT':
-                               case 'STRING':
-                               case 'DOUBLE':
-                               case 'DATETIME.ISO8601':
-                               case 'BASE64':
-                                       $GLOBALS['_xh']['vt']=strtolower($name);
-                               /// @todo: optimization creep - remove the if/elseif cycle below
+    $GLOBALS['xmlrpcerr']['unknown_method']=1;
+    $GLOBALS['xmlrpcstr']['unknown_method']='Unknown method';
+    $GLOBALS['xmlrpcerr']['invalid_return']=2;
+    $GLOBALS['xmlrpcstr']['invalid_return']='Invalid return payload: enable debugging to examine incoming payload';
+    $GLOBALS['xmlrpcerr']['incorrect_params']=3;
+    $GLOBALS['xmlrpcstr']['incorrect_params']='Incorrect parameters passed to method';
+    $GLOBALS['xmlrpcerr']['introspect_unknown']=4;
+    $GLOBALS['xmlrpcstr']['introspect_unknown']="Can't introspect: method unknown";
+    $GLOBALS['xmlrpcerr']['http_error']=5;
+    $GLOBALS['xmlrpcstr']['http_error']="Didn't receive 200 OK from remote server.";
+    $GLOBALS['xmlrpcerr']['no_data']=6;
+    $GLOBALS['xmlrpcstr']['no_data']='No data received from server.';
+    $GLOBALS['xmlrpcerr']['no_ssl']=7;
+    $GLOBALS['xmlrpcstr']['no_ssl']='No SSL support compiled in.';
+    $GLOBALS['xmlrpcerr']['curl_fail']=8;
+    $GLOBALS['xmlrpcstr']['curl_fail']='CURL error';
+    $GLOBALS['xmlrpcerr']['invalid_request']=15;
+    $GLOBALS['xmlrpcstr']['invalid_request']='Invalid request payload';
+    $GLOBALS['xmlrpcerr']['no_curl']=16;
+    $GLOBALS['xmlrpcstr']['no_curl']='No CURL support compiled in.';
+    $GLOBALS['xmlrpcerr']['server_error']=17;
+    $GLOBALS['xmlrpcstr']['server_error']='Internal server error';
+    $GLOBALS['xmlrpcerr']['multicall_error']=18;
+    $GLOBALS['xmlrpcstr']['multicall_error']='Received from server invalid multicall response';
+
+    $GLOBALS['xmlrpcerr']['multicall_notstruct'] = 9;
+    $GLOBALS['xmlrpcstr']['multicall_notstruct'] = 'system.multicall expected struct';
+    $GLOBALS['xmlrpcerr']['multicall_nomethod']  = 10;
+    $GLOBALS['xmlrpcstr']['multicall_nomethod']  = 'missing methodName';
+    $GLOBALS['xmlrpcerr']['multicall_notstring'] = 11;
+    $GLOBALS['xmlrpcstr']['multicall_notstring'] = 'methodName is not a string';
+    $GLOBALS['xmlrpcerr']['multicall_recursion'] = 12;
+    $GLOBALS['xmlrpcstr']['multicall_recursion'] = 'recursive system.multicall forbidden';
+    $GLOBALS['xmlrpcerr']['multicall_noparams']  = 13;
+    $GLOBALS['xmlrpcstr']['multicall_noparams']  = 'missing params';
+    $GLOBALS['xmlrpcerr']['multicall_notarray']  = 14;
+    $GLOBALS['xmlrpcstr']['multicall_notarray']  = 'params is not an array';
+
+    $GLOBALS['xmlrpcerr']['cannot_decompress']=103;
+    $GLOBALS['xmlrpcstr']['cannot_decompress']='Received from server compressed HTTP and cannot decompress';
+    $GLOBALS['xmlrpcerr']['decompress_fail']=104;
+    $GLOBALS['xmlrpcstr']['decompress_fail']='Received from server invalid compressed HTTP';
+    $GLOBALS['xmlrpcerr']['dechunk_fail']=105;
+    $GLOBALS['xmlrpcstr']['dechunk_fail']='Received from server invalid chunked HTTP';
+    $GLOBALS['xmlrpcerr']['server_cannot_decompress']=106;
+    $GLOBALS['xmlrpcstr']['server_cannot_decompress']='Received from client compressed HTTP request and cannot decompress';
+    $GLOBALS['xmlrpcerr']['server_decompress_fail']=107;
+    $GLOBALS['xmlrpcstr']['server_decompress_fail']='Received from client invalid compressed HTTP request';
+
+    // The charset encoding used by the server for received messages and
+    // by the client for received responses when received charset cannot be determined
+    // or is not supported
+    $GLOBALS['xmlrpc_defencoding']='UTF-8';
+
+    // The encoding used internally by PHP.
+    // String values received as xml will be converted to this, and php strings will be converted to xml
+    // as if having been coded with this
+    $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';
+
+    $GLOBALS['xmlrpcName']='XML-RPC for PHP';
+    $GLOBALS['xmlrpcVersion']='2.2';
+
+    // let user errors start at 800
+    $GLOBALS['xmlrpcerruser']=800;
+    // let XML parse errors start at 100
+    $GLOBALS['xmlrpcerrxml']=100;
+
+    // formulate backslashes for escaping regexp
+    // Not in use anymore since 2.0. Shall we remove it?
+    /// @deprecated
+    $GLOBALS['xmlrpc_backslash']=chr(92).chr(92);
+
+    // set to TRUE to enable correct decoding of <NIL/> values
+    $GLOBALS['xmlrpc_null_extension']=false;
+
+    // used to store state during parsing
+    // quick explanation of components:
+    //   ac - used to accumulate values
+    //   isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1)
+    //   isf_reason - used for storing xmlrpcresp fault string
+    //   lv - used to indicate "looking for a value": implements
+    //        the logic to allow values with no types to be strings
+    //   params - used to store parameters in method calls
+    //   method - used to store method name
+    //   stack - array with genealogy of xml elements names:
+    //           used to validate nesting of xmlrpc elements
+    $GLOBALS['_xh']=null;
+
+    /**
+    * Convert a string to the correct XML representation in a target charset
+    * To help correct communication of non-ascii chars inside strings, regardless
+    * of the charset used when sending requests, parsing them, sending responses
+    * and parsing responses, an option is to convert all non-ascii chars present in the message
+    * into their equivalent 'charset entity'. Charset entities enumerated this way
+    * are independent of the charset encoding used to transmit them, and all XML
+    * parsers are bound to understand them.
+    * Note that in the std case we are not sending a charset encoding mime type
+    * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.
+    *
+    * @todo do a bit of basic benchmarking (strtr vs. str_replace)
+    * @todo make usage of iconv() or recode_string() or mb_string() where available
+    */
+    function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='')
+    {
+        if ($src_encoding == '')
+        {
+            // lame, but we know no better...
+            $src_encoding = $GLOBALS['xmlrpc_internalencoding'];
+        }
+
+        switch(strtoupper($src_encoding.'_'.$dest_encoding))
+        {
+            case 'ISO-8859-1_':
+            case 'ISO-8859-1_US-ASCII':
+                $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
+                $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);
+                break;
+            case 'ISO-8859-1_UTF-8':
+                $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
+                $escaped_data = utf8_encode($escaped_data);
+                break;
+            case 'ISO-8859-1_ISO-8859-1':
+            case 'US-ASCII_US-ASCII':
+            case 'US-ASCII_UTF-8':
+            case 'US-ASCII_':
+            case 'US-ASCII_ISO-8859-1':
+            case 'UTF-8_UTF-8':
+                $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
+                break;
+            case 'UTF-8_':
+            case 'UTF-8_US-ASCII':
+            case 'UTF-8_ISO-8859-1':
+    // NB: this will choke on invalid UTF-8, going most likely beyond EOF
+    $escaped_data = '';
+    // be kind to users creating string xmlrpcvals out of different php types
+    $data = (string) $data;
+    $ns = strlen ($data);
+    for ($nn = 0; $nn < $ns; $nn++)
+    {
+        $ch = $data[$nn];
+        $ii = ord($ch);
+        //1 7 0bbbbbbb (127)
+        if ($ii < 128)
+        {
+            /// @todo shall we replace this with a (supposedly) faster str_replace?
+            switch($ii){
+                case 34:
+                    $escaped_data .= '&quot;';
+                    break;
+                case 38:
+                    $escaped_data .= '&amp;';
+                    break;
+                case 39:
+                    $escaped_data .= '&apos;';
+                    break;
+                case 60:
+                    $escaped_data .= '&lt;';
+                    break;
+                case 62:
+                    $escaped_data .= '&gt;';
+                    break;
+                default:
+                    $escaped_data .= $ch;
+            } // switch
+        }
+        //2 11 110bbbbb 10bbbbbb (2047)
+        else if ($ii>>5 == 6)
+        {
+            $b1 = ($ii & 31);
+            $ii = ord($data[$nn+1]);
+            $b2 = ($ii & 63);
+            $ii = ($b1 * 64) + $b2;
+            $ent = sprintf ('&#%d;', $ii);
+            $escaped_data .= $ent;
+            $nn += 1;
+        }
+        //3 16 1110bbbb 10bbbbbb 10bbbbbb
+        else if ($ii>>4 == 14)
+        {
+            $b1 = ($ii & 31);
+            $ii = ord($data[$nn+1]);
+            $b2 = ($ii & 63);
+            $ii = ord($data[$nn+2]);
+            $b3 = ($ii & 63);
+            $ii = ((($b1 * 64) + $b2) * 64) + $b3;
+            $ent = sprintf ('&#%d;', $ii);
+            $escaped_data .= $ent;
+            $nn += 2;
+        }
+        //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
+        else if ($ii>>3 == 30)
+        {
+            $b1 = ($ii & 31);
+            $ii = ord($data[$nn+1]);
+            $b2 = ($ii & 63);
+            $ii = ord($data[$nn+2]);
+            $b3 = ($ii & 63);
+            $ii = ord($data[$nn+3]);
+            $b4 = ($ii & 63);
+            $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
+            $ent = sprintf ('&#%d;', $ii);
+            $escaped_data .= $ent;
+            $nn += 3;
+        }
+    }
+                break;
+            default:
+                $escaped_data = '';
+                error_log("Converting from $src_encoding to $dest_encoding: not supported...");
+        }
+        return $escaped_data;
+    }
+
+    /// xml parser handler function for opening element tags
+    function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false)
+    {
+        // if invalid xmlrpc already detected, skip all processing
+        if ($GLOBALS['_xh']['isf'] < 2)
+        {
+            // check for correct element nesting
+            // top level element can only be of 2 types
+            /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
+            ///       there is only a single top level element in xml anyway
+            if (count($GLOBALS['_xh']['stack']) == 0)
+            {
+                if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (
+                    $name != 'VALUE' && !$accept_single_vals))
+                {
+                    $GLOBALS['_xh']['isf'] = 2;
+                    $GLOBALS['_xh']['isf_reason'] = 'missing top level xmlrpc element';
+                    return;
+                }
+                else
+                {
+                    $GLOBALS['_xh']['rt'] = strtolower($name);
+                }
+            }
+            else
+            {
+                // not top level element: see if parent is OK
+                $parent = end($GLOBALS['_xh']['stack']);
+                if (!array_key_exists($name, $GLOBALS['xmlrpc_valid_parents']) || !in_array($parent, $GLOBALS['xmlrpc_valid_parents'][$name]))
+                {
+                    $GLOBALS['_xh']['isf'] = 2;
+                    $GLOBALS['_xh']['isf_reason'] = "xmlrpc element $name cannot be child of $parent";
+                    return;
+                }
+            }
+
+            switch($name)
+            {
+                // optimize for speed switch cases: most common cases first
+                case 'VALUE':
+                    /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
+                    $GLOBALS['_xh']['vt']='value'; // indicator: no value found yet
+                    $GLOBALS['_xh']['ac']='';
+                    $GLOBALS['_xh']['lv']=1;
+                    $GLOBALS['_xh']['php_class']=null;
+                    break;
+                case 'I4':
+                case 'INT':
+                case 'STRING':
+                case 'BOOLEAN':
+                case 'DOUBLE':
+                case 'DATETIME.ISO8601':
+                case 'BASE64':
+                    if ($GLOBALS['_xh']['vt']!='value')
+                    {
+                        //two data elements inside a value: an error occurred!
+                        $GLOBALS['_xh']['isf'] = 2;
+                        $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
+                        return;
+                    }
+                    $GLOBALS['_xh']['ac']=''; // reset the accumulator
+                    break;
+                case 'STRUCT':
+                case 'ARRAY':
+                    if ($GLOBALS['_xh']['vt']!='value')
+                    {
+                        //two data elements inside a value: an error occurred!
+                        $GLOBALS['_xh']['isf'] = 2;
+                        $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
+                        return;
+                    }
+                    // create an empty array to hold child values, and push it onto appropriate stack
+                    $cur_val = array();
+                    $cur_val['values'] = array();
+                    $cur_val['type'] = $name;
+                    // check for out-of-band information to rebuild php objs
+                    // and in case it is found, save it
+                    if (@isset($attrs['PHP_CLASS']))
+                    {
+                        $cur_val['php_class'] = $attrs['PHP_CLASS'];
+                    }
+                    $GLOBALS['_xh']['valuestack'][] = $cur_val;
+                    $GLOBALS['_xh']['vt']='data'; // be prepared for a data element next
+                    break;
+                case 'DATA':
+                    if ($GLOBALS['_xh']['vt']!='data')
+                    {
+                        //two data elements inside a value: an error occurred!
+                        $GLOBALS['_xh']['isf'] = 2;
+                        $GLOBALS['_xh']['isf_reason'] = "found two data elements inside an array element";
+                        return;
+                    }
+                case 'METHODCALL':
+                case 'METHODRESPONSE':
+                case 'PARAMS':
+                    // valid elements that add little to processing
+                    break;
+                case 'METHODNAME':
+                case 'NAME':
+                    /// @todo we could check for 2 NAME elements inside a MEMBER element
+                    $GLOBALS['_xh']['ac']='';
+                    break;
+                case 'FAULT':
+                    $GLOBALS['_xh']['isf']=1;
+                    break;
+                case 'MEMBER':
+                    $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on
+                    //$GLOBALS['_xh']['ac']='';
+                    // Drop trough intentionally
+                case 'PARAM':
+                    // clear value type, so we can check later if no value has been passed for this param/member
+                    $GLOBALS['_xh']['vt']=null;
+                    break;
+                case 'NIL':
+                    if ($GLOBALS['xmlrpc_null_extension'])
+                    {
+                        if ($GLOBALS['_xh']['vt']!='value')
+                        {
+                            //two data elements inside a value: an error occurred!
+                            $GLOBALS['_xh']['isf'] = 2;
+                            $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
+                            return;
+                        }
+                        $GLOBALS['_xh']['ac']=''; // reset the accumulator
+                        break;
+                    }
+                    // we do not support the <NIL/> extension, so
+                    // drop through intentionally
+                default:
+                    /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!