OSDN Git Service

Add some codes from 3.61. Currently files under /nucleus/libs and /nucleus/libs/sql...
authorsakamocchi <sakamocchi@1ca29b6e-896d-4ea0-84a5-967f57386b96>
Fri, 31 Dec 2010 17:48:22 +0000 (17:48 +0000)
committersakamocchi <sakamocchi@1ca29b6e-896d-4ea0-84a5-967f57386b96>
Fri, 31 Dec 2010 17:48:22 +0000 (17:48 +0000)
git-svn-id: https://svn.sourceforge.jp/svnroot/nucleus-jp/nucleus-jp/trunk@1081 1ca29b6e-896d-4ea0-84a5-967f57386b96

31 files changed:
utf8/install/index.php
utf8/nucleus/libs/ACTION.php
utf8/nucleus/libs/ACTIONLOG.php
utf8/nucleus/libs/ACTIONS.php
utf8/nucleus/libs/ADMIN.php
utf8/nucleus/libs/BAN.php
utf8/nucleus/libs/BLOG.php
utf8/nucleus/libs/BODYACTIONS.php
utf8/nucleus/libs/COMMENT.php
utf8/nucleus/libs/COMMENTACTIONS.php
utf8/nucleus/libs/COMMENTS.php
utf8/nucleus/libs/ITEM.php
utf8/nucleus/libs/ITEMACTIONS.php
utf8/nucleus/libs/KARMA.php
utf8/nucleus/libs/MANAGER.php
utf8/nucleus/libs/MEDIA.php
utf8/nucleus/libs/MEMBER.php
utf8/nucleus/libs/PAGEFACTORY.php
utf8/nucleus/libs/PLUGIN.php
utf8/nucleus/libs/PLUGINADMIN.php
utf8/nucleus/libs/SEARCH.php
utf8/nucleus/libs/SKIN.php
utf8/nucleus/libs/TEMPLATE.php
utf8/nucleus/libs/backup.php
utf8/nucleus/libs/globalfunctions.php
utf8/nucleus/libs/mysql.php
utf8/nucleus/libs/showlist.php
utf8/nucleus/libs/sql/mysql.php
utf8/nucleus/upgrades/upgrade1.5.php
utf8/nucleus/upgrades/upgrade2.0.php
utf8/nucleus/upgrades/upgrade2.5.php

index 57fc872..b1c60a1 100755 (executable)
@@ -737,11 +737,11 @@ function doInstall() {
 \r
        // 7. update GOD member\r
        $query = 'UPDATE ' . tableName('nucleus_member')\r
-                  . " SET mname         = '" . addslashes($user_name) . "',"\r
-                  . " mrealname         = '" . addslashes($user_realname) . "',"\r
-                  . " mpassword         = '" . md5(addslashes($user_password) ) . "',"\r
-                  . " murl               = '" . addslashes($config_indexurl) . "',"\r
-                  . " memail           = '" . addslashes($user_email) . "',"\r
+                  . " SET mname         = '" . sql_real_escape_string($user_name) . "',"\r
+                  . " mrealname         = '" . sql_real_escape_string($user_realname) . "',"\r
+                  . " mpassword         = '" . md5(sql_real_escape_string($user_password) ) . "',"\r
+                  . " murl               = '" . sql_real_escape_string($config_indexurl) . "',"\r
+                  . " memail           = '" . sql_real_escape_string($user_email) . "',"\r
                   . " madmin           = 1,"\r
                   . " mcanlogin         = 1"\r
                   . " WHERE"\r
@@ -751,9 +751,9 @@ function doInstall() {
 \r
        // 8. update weblog settings\r
        $query = 'UPDATE ' . tableName('nucleus_blog')\r
-                  . " SET bname  = '" . addslashes($blog_name) . "',"\r
-                  . " bshortname = '" . addslashes($blog_shortname) . "',"\r
-                  . " burl        = '" . addslashes($config_indexurl) . "'"\r
+                  . " SET bname  = '" . sql_real_escape_string($blog_name) . "',"\r
+                  . " bshortname = '" . sql_real_escape_string($blog_shortname) . "',"\r
+                  . " burl        = '" . sql_real_escape_string($config_indexurl) . "'"\r
                   . " WHERE"\r
                   . " bnumber  = 1";\r
 \r
@@ -996,7 +996,7 @@ function installCustomPlugs(&$manager) {
 \r
        foreach ($aConfPlugsToInstall as $plugName) {\r
                // do this before calling getPlugin (in case the plugin id is used there)\r
-               $query = 'INSERT INTO ' . sql_table('plugin') . ' (porder, pfile) VALUES (' . (++$numCurrent) . ', "' . addslashes($plugName) . '")';\r
+               $query = 'INSERT INTO ' . sql_table('plugin') . ' (porder, pfile) VALUES (' . (++$numCurrent) . ', "' . sql_real_escape_string($plugName) . '")';\r
                sql_query($query);\r
 \r
                // get and install the plugin\r
@@ -1005,7 +1005,7 @@ function installCustomPlugs(&$manager) {
                $plugin->plugid = $numCurrent;\r
 \r
                if (!$plugin) {\r
-                       sql_query('DELETE FROM ' . sql_table('plugin') . ' WHERE pfile=\'' . addslashes($plugName) . '\'');\r
+                       sql_query('DELETE FROM ' . sql_table('plugin') . ' WHERE pfile=\'' . sql_real_escape_string($plugName) . '\'');\r
                        $numCurrent--;\r
                        array_push($aErrors, _ERROR22 . $plugName);\r
                        continue;\r
@@ -1124,8 +1124,8 @@ function doCheckFiles() {
 \r
 function updateConfig($name, $val) {\r
        global $MYSQL_CONN;\r
-       $name = addslashes($name);\r
-       $val  = trim(addslashes($val) );\r
+       $name = sql_real_escape_string($name);\r
+       $val  = trim(sql_real_escape_string($val) );\r
 \r
        $query = 'UPDATE ' . tableName('nucleus_config')\r
                   . " SET   value = '$val'"\r
index b8c8732..ea5c3c8 100755 (executable)
  */
 class ACTION
 {
-    /**
-     *  Constructor for an new ACTION object
-     */
-    function ACTION()
-    {
-        // do nothing
-    }
-
-    /**
-     *  Calls functions that handle an action called from action.php
-     */
-    function doAction($action)
-    {
-        switch($action) {
-            case 'autodraft':
-                return $this->autoDraft();
-                break;
-            case 'updateticket':
-                return $this->updateTicket();
-                break;
-            case 'addcomment':
-                return $this->addComment();
-                break;
-            case 'sendmessage':
-                return $this->sendMessage();
-                break;
-            case 'createaccount':
-                return $this->createAccount();
-                break;
-            case 'forgotpassword':
-                return $this->forgotPassword();
-                break;
-            case 'votepositive':
-                return $this->doKarma('pos');
-                break;
-            case 'votenegative':
-                return $this->doKarma('neg');
-                break;
-            case 'plugin':
-                return $this->callPlugin();
-                break;
-            default:
-                doError(_ERROR_BADACTION);
-        }
-    }
-
-    /**
-     *  Adds a new comment to an item (if IP isn't banned)
-     */
-    function addComment() {
-        global $CONF, $errormessage, $manager;
-
-        $post['itemid'] =   intPostVar('itemid');
-        $post['user'] =     postVar('user');
-        $post['userid'] =   postVar('userid');
-        $post['email'] =   postVar('email');
-        $post['body'] =     postVar('body');
-
-        // set cookies when required
-        $remember = intPostVar('remember');
-        if ($remember == 1) {
-            $lifetime = time()+2592000;
-            setcookie($CONF['CookiePrefix'] . 'comment_user',$post['user'],$lifetime,'/','',0);
-            setcookie($CONF['CookiePrefix'] . 'comment_userid', $post['userid'],$lifetime,'/','',0);
-            setcookie($CONF['CookiePrefix'] . 'comment_email',  $post['email'], $lifetime,'/','',0);
-        }
-
-        $comments = new COMMENTS($post['itemid']);
-
-        $blogid = getBlogIDFromItemID($post['itemid']);
-        $this->checkban($blogid);
-        $blog =& $manager->getBlog($blogid);
-
-        // note: PreAddComment and PostAddComment gets called somewhere inside addComment
-        $errormessage = $comments->addComment($blog->getCorrectTime(),$post);
-
-        if ($errormessage == '1') {
-            // redirect when adding comments succeeded
-            if (postVar('url')) {
-                redirect(postVar('url'));
-            } else {
-                $url = createItemLink($post['itemid']);
-                redirect($url);
-            }
-        } else {
-            // else, show error message using default skin for blog
-            return array(
-                'message' => $errormessage,
-                'skinid' => $blog->getDefaultSkin()
-            );
-        }
-
-        exit;
-    }
-
-    /**
-     *  Sends a message from the current member to the member given as argument
-     */
-    function sendMessage() {
-        global $CONF, $member;
-
-        $error = $this->validateMessage();
-        if ($error != '')
-            return array('message' => $error);
-
-        if (!$member->isLoggedIn()) {
-            $fromMail = postVar('frommail');
-            $fromName = _MMAIL_FROMANON;
-        } else {
-            $fromMail = $member->getEmail();
-            $fromName = $member->getDisplayName();
-        }
-
-        $tomem = new MEMBER();
-        $tomem->readFromId(postVar('memberid'));
-
-        $message  = _MMAIL_MSG . ' ' . $fromName . "\n"
-              . '(' . _MMAIL_FROMNUC. ' ' . $CONF['IndexURL'] .") \n\n"
-              . _MMAIL_MAIL . " \n\n"
-              . postVar('message');
-        $message .= getMailFooter();
-
-        $title = _MMAIL_TITLE . ' ' . $fromName;
-        mb_language('ja');
-        mb_internal_encoding(_CHARSET);
-        @mb_send_mail($tomem->getEmail(), $title, $message, "From: ". $fromMail);
-
-        if (postVar('url')) {
-            redirect(postVar('url'));
-        } else {
-            $CONF['MemberURL'] = $CONF['IndexURL'];
-            if ($CONF['URLMode'] == 'pathinfo')
-            {
-                $url = createLink('member', array('memberid' => $tomem->getID(), 'name' => $tomem->getDisplayName()));
-            }
-            else
-            {
-                $url = $CONF['IndexURL'] . createMemberLink($tomem->getID());
-            }
-            redirect($url);
-        }
-        exit;
-    }
-
-    /**
-     *  Checks if a mail to a member is allowed
-     *  Returns a string with the error message if the mail is disallowed
-     */
-    function validateMessage() {
-        global $CONF, $member, $manager;
-
-        if (!$CONF['AllowMemberMail'])
-            return _ERROR_MEMBERMAILDISABLED;
-
-        if (!$member->isLoggedIn() && !$CONF['NonmemberMail'])
-            return _ERROR_DISALLOWED;
-
-        if (!$member->isLoggedIn() && (!isValidMailAddress(postVar('frommail'))))
-            return _ERROR_BADMAILADDRESS;
-
-        // let plugins do verification (any plugin which thinks the comment is invalid
-        // can change 'error' to something other than '')
-        $result = '';
-        $manager->notify('ValidateForm', array('type' => 'membermail', 'error' => &$result));
-
-        return $result;
-
-    }
-
-    /**
-     *  Creates a new user account
-     */
-    function createAccount() {
-        global $CONF, $manager;
-
-        if (!$CONF['AllowMemberCreate'])
-            doError(_ERROR_MEMBERCREATEDISABLED);
-
-        // evaluate content from FormExtra
-        $result = 1;
-        $data = array('type' => 'membermail', 'error' => &$result);
-        $manager->notify('ValidateForm', &$data);
-
-        if ($result!=1) {
-            return $result;
-        }
-        else {
-
-            // even though the member can not log in, set some random initial password. One never knows.
-            srand((double)microtime()*1000000);
-            $initialPwd = md5(uniqid(rand(), true));
-
-            // create member (non admin/can not login/no notes/random string as password)
-            $name = shorten(postVar('name'), 32, '');
-            $r = MEMBER::create($name, postVar('realname'), $initialPwd, postVar('email'), postVar('url'), 0, 0, '');
-
-            if ($r != 1) {
-                return $r;
-            }
-
-            // send message containing password.
-            $newmem = new MEMBER();
-            $newmem->readFromName($name);
-            $newmem->sendActivationLink('register');
-
-            $manager->notify('PostRegister',array('member' => &$newmem));
-
-            if (postVar('desturl')) {
-                redirect(postVar('desturl'));
-            } else {
-                // header has been already sent, so deleted the line below
-                //header ("Content-Type: text/html; charset="._CHARSET);
-                echo _MSG_ACTIVATION_SENT;
-                echo '<br /><br />Return to <a href="'.$CONF['IndexURL'].'" title="'.$CONF['SiteName'].'">'.$CONF['SiteName'].'</a>';
-                echo "\n</body>\n</html>";
-            }
-            exit;
-        }
-    }
-
-    /**
-     *  Sends a new password
-     */
-    function forgotPassword() {
-        $membername = trim(postVar('name'));
-
-        if (!MEMBER::exists($membername))
-            doError(_ERROR_NOSUCHMEMBER);
-        $mem = MEMBER::createFromName($membername);
-
-        /* below keeps regular users from resetting passwords using forgot password feature
-             Removing for now until clear why it is required.*/
-        /*if (!$mem->canLogin())
-            doError(_ERROR_NOLOGON_NOACTIVATE);*/
-
-        // check if e-mail address is correct
-        if (!($mem->getEmail() == postVar('email')))
-            doError(_ERROR_INCORRECTEMAIL);
-
-        // send activation link
-        $mem->sendActivationLink('forgot');
-
-        if (postVar('url')) {
-            redirect(postVar('url'));
-        } else {
-            header ("Content-Type: text/html; charset="._CHARSET);
-            echo _MSG_ACTIVATION_SENT;
-            echo '<br /><br />Return to <a href="'.$CONF['IndexURL'].'" title="'.$CONF['SiteName'].'">'.$CONF['SiteName'].'</a>';
-        }
-        exit;
-    }
-
-    /**
-     *  Handle karma votes
-     */
-    function doKarma($type) {
-        global $itemid, $member, $CONF, $manager;
-
-        // check if itemid exists
-        if (!$manager->existsItem($itemid,0,0))
-            doError(_ERROR_NOSUCHITEM);
-
-        $blogid = getBlogIDFromItemID($itemid);
-        $this->checkban($blogid);
-
-        $karma =& $manager->getKarma($itemid);
-
-        // check if not already voted
-        if (!$karma->isVoteAllowed(serverVar('REMOTE_ADDR')))
-            doError(_ERROR_VOTEDBEFORE);
-
-        // check if item does allow voting
-        $item =& $manager->getItem($itemid,0,0);
-        if ($item['closed'])
-            doError(_ERROR_ITEMCLOSED);
-
-        switch($type) {
-            case 'pos':
-                $karma->votePositive();
-                break;
-            case 'neg':
-                $karma->voteNegative();
-                break;
-        }
+       /**
+        *  Constructor for an new ACTION object
+        */
+       function ACTION()
+       {
+               // do nothing
+       }
+
+       /**
+        *  Calls functions that handle an action called from action.php
+        */
+       function doAction($action)
+       {
+               switch($action) {
+                       case 'autodraft':
+                               return $this->autoDraft();
+                               break;
+                       case 'updateticket':
+                               return $this->updateTicket();
+                               break;
+                       case 'addcomment':
+                               return $this->addComment();
+                               break;
+                       case 'sendmessage':
+                               return $this->sendMessage();
+                               break;
+                       case 'createaccount':
+                               return $this->createAccount();
+                               break;
+                       case 'forgotpassword':
+                               return $this->forgotPassword();
+                               break;
+                       case 'votepositive':
+                               return $this->doKarma('pos');
+                               break;
+                       case 'votenegative':
+                               return $this->doKarma('neg');
+                               break;
+                       case 'plugin':
+                               return $this->callPlugin();
+                               break;
+                       default:
+                               doError(_ERROR_BADACTION);
+               }
+       }
+
+       /**
+        *  Adds a new comment to an item (if IP isn't banned)
+        */
+       function addComment() {
+               global $CONF, $errormessage, $manager;
+
+               $post['itemid'] =   intPostVar('itemid');
+               $post['user'] =  postVar('user');
+               $post['userid'] =   postVar('userid');
+               $post['email'] =   postVar('email');
+               $post['body'] =  postVar('body');
+
+               // set cookies when required
+               $remember = intPostVar('remember');
+               if ($remember == 1) {
+                       $lifetime = time()+2592000;
+                       setcookie($CONF['CookiePrefix'] . 'comment_user',$post['user'],$lifetime,'/','',0);
+                       setcookie($CONF['CookiePrefix'] . 'comment_userid', $post['userid'],$lifetime,'/','',0);
+                       setcookie($CONF['CookiePrefix'] . 'comment_email',  $post['email'], $lifetime,'/','',0);
+               }
+
+               $comments = new COMMENTS($post['itemid']);
+
+               $blogid = getBlogIDFromItemID($post['itemid']);
+               $this->checkban($blogid);
+               $blog =& $manager->getBlog($blogid);
+
+               // note: PreAddComment and PostAddComment gets called somewhere inside addComment
+               $errormessage = $comments->addComment($blog->getCorrectTime(),$post);
+
+               if ($errormessage == '1') {
+                       // redirect when adding comments succeeded
+                       if (postVar('url')) {
+                               redirect(postVar('url'));
+                       } else {
+                               $url = createItemLink($post['itemid']);
+                               redirect($url);
+                       }
+               } else {
+                       // else, show error message using default skin for blog
+                       return array(
+                               'message' => $errormessage,
+                               'skinid' => $blog->getDefaultSkin()
+                       );
+               }
+
+               exit;
+       }
+
+       /**
+        *  Sends a message from the current member to the member given as argument
+        */
+       function sendMessage() {
+               global $CONF, $member;
+
+               $error = $this->validateMessage();
+               if ($error != '')
+                       return array('message' => $error);
+
+               if (!$member->isLoggedIn()) {
+                       $fromMail = postVar('frommail');
+                       $fromName = _MMAIL_FROMANON;
+               } else {
+                       $fromMail = $member->getEmail();
+                       $fromName = $member->getDisplayName();
+               }
+
+               $tomem = new MEMBER();
+               $tomem->readFromId(postVar('memberid'));
+
+               $message  = _MMAIL_MSG . ' ' . $fromName . "\n"
+                         . '(' . _MMAIL_FROMNUC. ' ' . $CONF['IndexURL'] .") \n\n"
+                         . _MMAIL_MAIL . " \n\n"
+                         . postVar('message');
+               $message .= getMailFooter();
+
+               $title = _MMAIL_TITLE . ' ' . $fromName;
+               mb_language('ja');
+               mb_internal_encoding(_CHARSET);
+               @mb_send_mail($tomem->getEmail(), $title, $message, "From: ". $fromMail);
+
+               if (postVar('url')) {
+                       redirect(postVar('url'));
+               } else {
+                       $CONF['MemberURL'] = $CONF['IndexURL'];
+                       if ($CONF['URLMode'] == 'pathinfo')
+                       {
+                               $url = createLink('member', array('memberid' => $tomem->getID(), 'name' => $tomem->getDisplayName()));
+                       }
+                       else
+                       {
+                               $url = $CONF['IndexURL'] . createMemberLink($tomem->getID());
+                       }
+                       redirect($url);
+               }
+               exit;
+       }
+
+       /**
+        *  Checks if a mail to a member is allowed
+        *  Returns a string with the error message if the mail is disallowed
+        */
+       function validateMessage() {
+               global $CONF, $member, $manager;
+
+               if (!$CONF['AllowMemberMail'])
+                       return _ERROR_MEMBERMAILDISABLED;
+
+               if (!$member->isLoggedIn() && !$CONF['NonmemberMail'])
+                       return _ERROR_DISALLOWED;
+
+               if (!$member->isLoggedIn() && (!isValidMailAddress(postVar('frommail'))))
+                       return _ERROR_BADMAILADDRESS;
+
+               // let plugins do verification (any plugin which thinks the comment is invalid
+               // can change 'error' to something other than '')
+               $result = '';
+               $manager->notify('ValidateForm', array('type' => 'membermail', 'error' => &$result));
+
+               return $result;
+
+       }
+
+       /**
+        *  Creates a new user account
+        */
+       function createAccount() {
+               global $CONF, $manager;
+
+               if (!$CONF['AllowMemberCreate'])
+                       doError(_ERROR_MEMBERCREATEDISABLED);
+
+               // evaluate content from FormExtra
+               $result = 1;
+               $data = array('type' => 'membermail', 'error' => &$result);
+               $manager->notify('ValidateForm', &$data);
+
+               if ($result!=1) {
+                       return $result;
+               }
+               else {
+
+                       // even though the member can not log in, set some random initial password. One never knows.
+                       srand((double)microtime()*1000000);
+                       $initialPwd = md5(uniqid(rand(), true));
+
+                       // create member (non admin/can not login/no notes/random string as password)
+                       $name = shorten(postVar('name'), 32, '');
+                       $r = MEMBER::create($name, postVar('realname'), $initialPwd, postVar('email'), postVar('url'), 0, 0, '');
+
+                       if ($r != 1) {
+                               return $r;
+                       }
+
+                       // send message containing password.
+                       $newmem = new MEMBER();
+                       $newmem->readFromName($name);
+                       $newmem->sendActivationLink('register');
+
+                       $manager->notify('PostRegister',array('member' => &$newmem));
+
+                       if (postVar('desturl')) {
+                               redirect(postVar('desturl'));
+                       } else {
+                               // header has been already sent, so deleted the line below
+                               //header ("Content-Type: text/html; charset="._CHARSET);
+                               echo _MSG_ACTIVATION_SENT;
+                               echo '<br /><br />Return to <a href="'.$CONF['IndexURL'].'" title="'.$CONF['SiteName'].'">'.$CONF['SiteName'].'</a>';
+                               echo "\n</body>\n</html>";
+                       }
+                       exit;
+               }
+       }
+
+       /**
+        *  Sends a new password
+        */
+       function forgotPassword() {
+               $membername = trim(postVar('name'));
+
+               if (!MEMBER::exists($membername))
+                       doError(_ERROR_NOSUCHMEMBER);
+               $mem = MEMBER::createFromName($membername);
+
+               /* below keeps regular users from resetting passwords using forgot password feature
+                        Removing for now until clear why it is required.*/
+               /*if (!$mem->canLogin())
+                       doError(_ERROR_NOLOGON_NOACTIVATE);*/
+
+               // check if e-mail address is correct
+               if (!($mem->getEmail() == postVar('email')))
+                       doError(_ERROR_INCORRECTEMAIL);
+
+               // send activation link
+               $mem->sendActivationLink('forgot');
+
+               if (postVar('url')) {
+                       redirect(postVar('url'));
+               } else {
+                       header ("Content-Type: text/html; charset="._CHARSET);
+                       echo _MSG_ACTIVATION_SENT;
+                       echo '<br /><br />Return to <a href="'.$CONF['IndexURL'].'" title="'.$CONF['SiteName'].'">'.$CONF['SiteName'].'</a>';
+               }
+               exit;
+       }
+
+       /**
+        *  Handle karma votes
+        */
+       function doKarma($type) {
+               global $itemid, $member, $CONF, $manager;
+
+               // check if itemid exists
+               if (!$manager->existsItem($itemid,0,0))
+                       doError(_ERROR_NOSUCHITEM);
+
+               $blogid = getBlogIDFromItemID($itemid);
+               $this->checkban($blogid);
+
+               $karma =& $manager->getKarma($itemid);
+
+               // check if not already voted
+               if (!$karma->isVoteAllowed(serverVar('REMOTE_ADDR')))
+                       doError(_ERROR_VOTEDBEFORE);
+
+               // check if item does allow voting
+               $item =& $manager->getItem($itemid,0,0);
+               if ($item['closed'])
+                       doError(_ERROR_ITEMCLOSED);
+
+               switch($type) {
+                       case 'pos':
+                               $karma->votePositive();
+                               break;
+                       case 'neg':
+                               $karma->voteNegative();
+                               break;
+               }
 
 //             $blogid = getBlogIDFromItemID($itemid);
-        $blog =& $manager->getBlog($blogid);
-
-        // send email to notification address, if any
-        if ($blog->getNotifyAddress() && $blog->notifyOnVote()) {
-
-            $mailto_msg = _NOTIFY_KV_MSG . ' ' . $itemid . "\n";
-            $itemLink = createItemLink(intval($itemid));
-            $temp = parse_url($itemLink);
-            if (!$temp['scheme']) {
-                $itemLink = $CONF['IndexURL'] . $itemLink;
-            }
-            $mailto_msg .= $itemLink . "\n\n";
-            if ($member->isLoggedIn()) {
-                $mailto_msg .= _NOTIFY_MEMBER . ' ' . $member->getDisplayName() . ' (ID=' . $member->getID() . ")\n";
-            }
-            $mailto_msg .= _NOTIFY_IP . ' ' . serverVar('REMOTE_ADDR') . "\n";
-            $mailto_msg .= _NOTIFY_HOST . ' ' .  gethostbyaddr(serverVar('REMOTE_ADDR'))  . "\n";
-            $mailto_msg .= _NOTIFY_VOTE . "\n " . $type . "\n";
-            $mailto_msg .= getMailFooter();
-
-            $mailto_title = _NOTIFY_KV_TITLE . ' ' . strip_tags($item['title']) . ' (' . $itemid . ')';
-
-            $frommail = $member->getNotifyFromMailAddress();
-
-            $notify = new NOTIFICATION($blog->getNotifyAddress());
-            $notify->notify($mailto_title, $mailto_msg , $frommail);
-        }
-
-
-        $refererUrl = serverVar('HTTP_REFERER');
-        if ($refererUrl) {
-            $url = $refererUrl;
-        } else {
+               $blog =& $manager->getBlog($blogid);
+
+               // send email to notification address, if any
+               if ($blog->getNotifyAddress() && $blog->notifyOnVote()) {
+
+                       $mailto_msg = _NOTIFY_KV_MSG . ' ' . $itemid . "\n";
+                       $itemLink = createItemLink(intval($itemid));
+                       $temp = parse_url($itemLink);
+                       if (!$temp['scheme']) {
+                               $itemLink = $CONF['IndexURL'] . $itemLink;
+                       }
+                       $mailto_msg .= $itemLink . "\n\n";
+                       if ($member->isLoggedIn()) {
+                               $mailto_msg .= _NOTIFY_MEMBER . ' ' . $member->getDisplayName() . ' (ID=' . $member->getID() . ")\n";
+                       }
+                       $mailto_msg .= _NOTIFY_IP . ' ' . serverVar('REMOTE_ADDR') . "\n";
+                       $mailto_msg .= _NOTIFY_HOST . ' ' .  gethostbyaddr(serverVar('REMOTE_ADDR'))  . "\n";
+                       $mailto_msg .= _NOTIFY_VOTE . "\n " . $type . "\n";
+                       $mailto_msg .= getMailFooter();
+
+                       $mailto_title = _NOTIFY_KV_TITLE . ' ' . strip_tags($item['title']) . ' (' . $itemid . ')';
+
+                       $frommail = $member->getNotifyFromMailAddress();
+
+                       $notify = new NOTIFICATION($blog->getNotifyAddress());
+                       $notify->notify($mailto_title, $mailto_msg , $frommail);
+               }
+
+
+               $refererUrl = serverVar('HTTP_REFERER');
+               if ($refererUrl) {
+                       $url = $refererUrl;
+               } else {
 //                     $url = $CONF['IndexURL'] . 'index.php?itemid=' . $itemid;
-            $url = $itemLink;
-        }
-
-        redirect($url);
-        exit;
-    }
-
-    /**
-      * Calls a plugin action
-      */
-    function callPlugin() {
-        global $manager;
-
-        $pluginName = 'NP_' . requestVar('name');
-        $actionType = requestVar('type');
-
-        // 1: check if plugin is installed
-        if (!$manager->pluginInstalled($pluginName))
-            doError(_ERROR_NOSUCHPLUGIN);
-
-        // 2: call plugin
-        $pluginObject =& $manager->getPlugin($pluginName);
-        if ($pluginObject)
-            $error = $pluginObject->doAction($actionType);
-        else
-            $error = 'Could not load plugin (see actionlog)';
-
-        // doAction returns error when:
-        // - an error occurred (duh)
-        // - no actions are allowed (doAction is not implemented)
-        if ($error)
-            doError($error);
-
-        exit;
-
-    }
-
-    /**
-     *  Checks if an IP or IP range is banned
-     */
-    function checkban($blogid) {
-        // check if banned
-        $ban = BAN::isBanned($blogid, serverVar('REMOTE_ADDR'));
-        if ($ban != 0) {
-            doError(_ERROR_BANNED1 . $ban->iprange . _ERROR_BANNED2 . $ban->message . _ERROR_BANNED3);
-        }
-
-    }
-
-    /**
-     * Gets a new ticket
-     */
-    function updateTicket() {
-        global $manager;
-        if ($manager->checkTicket()) {
-            echo $manager->getNewTicket();
-        }
-        else {
-            echo _ERROR . ':' . _ERROR_BADTICKET;
-        }
-        return false;
-    }
-
-    /**
-     * Handles AutoSaveDraft
-     */
-    function autoDraft() {
-        global $manager;
-        if ($manager->checkTicket()) {
-            $manager->loadClass('ITEM');
-            $info = ITEM::createDraftFromRequest();
-            if ($info['status'] == 'error') {
-                echo $info['message'];
-            }
-            else {
-                echo $info['draftid'];
-            }
-        }
-        else {
-            echo _ERROR . ':' . _ERROR_BADTICKET;
-        }
-        return false;
-    }
-
-
+                       $url = $itemLink;
+               }
+
+               redirect($url);
+               exit;
+       }
+
+       /**
+         * Calls a plugin action
+         */
+       function callPlugin() {
+               global $manager;
+
+               $pluginName = 'NP_' . requestVar('name');
+               $actionType = requestVar('type');
+
+               // 1: check if plugin is installed
+               if (!$manager->pluginInstalled($pluginName))
+                       doError(_ERROR_NOSUCHPLUGIN);
+
+               // 2: call plugin
+               $pluginObject =& $manager->getPlugin($pluginName);
+               if ($pluginObject)
+                       $error = $pluginObject->doAction($actionType);
+               else
+                       $error = 'Could not load plugin (see actionlog)';
+
+               // doAction returns error when:
+               // - an error occurred (duh)
+               // - no actions are allowed (doAction is not implemented)
+               if ($error)
+                       doError($error);
+
+               exit;
+
+       }
+
+       /**
+        *  Checks if an IP or IP range is banned
+        */
+       function checkban($blogid) {
+               // check if banned
+               $ban = BAN::isBanned($blogid, serverVar('REMOTE_ADDR'));
+               if ($ban != 0) {
+                       doError(_ERROR_BANNED1 . $ban->iprange . _ERROR_BANNED2 . $ban->message . _ERROR_BANNED3);
+               }
+
+       }
+
+       /**
+        * Gets a new ticket
+        */
+       function updateTicket() {
+               global $manager;
+               if ($manager->checkTicket()) {
+                       echo $manager->getNewTicket();
+               }
+               else {
+                       echo _ERROR . ':' . _ERROR_BADTICKET;
+               }
+               return false;
+       }
+
+       /**
+        * Handles AutoSaveDraft
+        */
+       function autoDraft() {
+               global $manager;
+               if ($manager->checkTicket()) {
+                       $manager->loadClass('ITEM');
+                       $info = ITEM::createDraftFromRequest();
+                       if ($info['status'] == 'error') {
+                               echo $info['message'];
+                       }
+                       else {
+                               echo $info['draftid'];
+                       }
+               }
+               else {
+                       echo _ERROR . ':' . _ERROR_BADTICKET;
+               }
+               return false;
+       }
 }
-
 ?>
\ No newline at end of file
index bbe318e..56c7d7a 100755 (executable)
@@ -37,7 +37,7 @@ class ACTIONLOG {
                if ($member && $member->isLoggedIn())
                        $message = "[" . $member->getDisplayName() . "] " . $message;
 
-               $message = addslashes($message);                // add slashes
+               $message = sql_real_escape_string($message);            // add slashes
                $timestamp = date("Y-m-d H:i:s",time());        // format timestamp
                $query = "INSERT INTO " . sql_table('actionlog') . " (timestamp, message) VALUES ('$timestamp', '$message')";
 
index afe58bf..2d713b0 100644 (file)
@@ -283,24 +283,45 @@ class ACTIONS extends BaseActions {
         *              When present, the output will be a full <a href...> link. When empty,
         *              only a raw link will be outputted
         */
-       function _searchlink($maxresults, $startpos, $direction, $linktext = '') {
+       function _searchlink($maxresults, $startpos, $direction, $linktext = '', $recount = '') {
                global $CONF, $blog, $query, $amount;
                // TODO: Move request uri to linkparams. this is ugly. sorry for that.
                $startpos       = intval($startpos);            // will be 0 when empty.
+               $path                   = $parsed['path'];
                $parsed         = parse_url(serverVar('REQUEST_URI'));
                $parsed         = $parsed['query'];
-               $url            = '';
+               $url                    = '';
 
                switch ($direction) {
                        case 'prev':
                                if ( intval($startpos) - intval($maxresults) >= 0) {
                                        $startpos       = intval($startpos) - intval($maxresults);
-                                       $url            = $CONF['SearchURL'].'?'.alterQueryStr($parsed,'startpos',$startpos);
+                                       //$url          = $CONF['SearchURL'].'?'.alterQueryStr($parsed,'startpos',$startpos);
+                                       switch ($this->skintype)
+                                       {
+                                               case 'index':
+                                                       $url = $path;
+                                                       break;
+                                               case 'search':
+                                                       $url = $CONF['SearchURL'];
+                                                       break;
+                                       }
+                                       $url .= '?'.alterQueryStr($parsed,'startpos',$startpos);
                                }
                                break;
                        case 'next':
-                               $iAmountOnPage = $this->amountfound;
-                               if ($iAmountOnPage == 0)
+                               global $navigationItems;
+                               if (!isset($navigationItems)) $navigationItems = 0;
+                               
+                               if ($recount)
+                                       $iAmountOnPage = 0;
+                               else 
+                                       $iAmountOnPage = $this->amountfound;
+                               
+                               if (intval($navigationItems) > 0) {
+                                       $iAmountOnPage = intval($navigationItems) - intval($startpos);
+                               }
+                               elseif ($iAmountOnPage == 0)
                                {
                                        // [%nextlink%] or [%prevlink%] probably called before [%blog%] or [%searchresults%]
                                        // try a count query
@@ -310,7 +331,9 @@ class ACTIONS extends BaseActions {
                                                        $sqlquery = $blog->getSqlBlog('', 'count');
                                                        break;
                                                case 'search':
+                                                       $unused_highlight = '';
                                                        $sqlquery = $blog->getSqlSearch($query, $amount, $unused_highlight, 'count');
+                                                       $url = $CONF['SearchURL'];
                                                        break;
                                        }
                                        if ($sqlquery)
@@ -318,8 +341,10 @@ class ACTIONS extends BaseActions {
                                }
                                if (intval($iAmountOnPage) >= intval($maxresults)) {
                                        $startpos       = intval($startpos) + intval($maxresults);
-                                       $url            = $CONF['SearchURL'].'?'.alterQueryStr($parsed,'startpos',$startpos);
+                                       //$url          = $CONF['SearchURL'].'?'.alterQueryStr($parsed,'startpos',$startpos);
+                                       $url            .= '?'.alterQueryStr($parsed,'startpos',$startpos);
                                }
+                               else $url       = '';
                                break;
                        default:
                                break;
@@ -602,7 +627,11 @@ class ACTIONS extends BaseActions {
         */
        function parse_categorylist($template, $blogname = '') {
                global $blog, $manager;
-
+               
+               // when no blog found
+               if (($blogName == '') && (!is_object($blog)))
+                       return 0;
+                       
                if ($blogname == '') {
                        $this->_preBlogContent('categorylist',$blog);
                        $blog->showCategoryList($template);
@@ -643,7 +672,12 @@ class ACTIONS extends BaseActions {
                        $this->doForm('commentform-closed');
                        return;
                }
-
+               
+               if (!$blog->isPublic() && !$member->isLoggedIn()) {
+                       $this->doForm('commentform-closedtopublic');
+                       return;
+               }
+               
                if (!$destinationurl)
                {
                        $destinationurl = createLink(
@@ -868,7 +902,7 @@ class ACTIONS extends BaseActions {
         * (includes a member info thingie)      
         */
        function parse_member($what) {
-               global $memberinfo, $member;
+               global $memberinfo, $member, $CONF;
 
                // 1. only allow the member-details-page specific variables on member pages
                if ($this->skintype == 'member') {
@@ -917,11 +951,16 @@ class ACTIONS extends BaseActions {
                                case 'yourid':
                                        echo $member->getID();
                                        break;
+                               case 'yourprofileurl':
+                                       if ($CONF['URLMode'] == 'pathinfo')
+                                               echo createMemberLink($member->getID());
+                                       else
+                                               echo $CONF['IndexURL'] . createMemberLink($member->getID());
+                                       break;
                        }
                }
-
        }
-
+       
        /**
         * Parse skinvar membermailform
         */
@@ -1000,12 +1039,12 @@ class ACTIONS extends BaseActions {
        /**
         * Parse skinvar nextlink
         */
-       function parse_nextlink($linktext = '', $amount = 10) {
+       function parse_nextlink($linktext = '', $amount = 10, $recount = '') {
                global $itemidnext, $archivenext, $startpos;
                if ($this->skintype == 'item')
                        $this->_itemlink($itemidnext, $linktext);
                else if ($this->skintype == 'search' || $this->skintype == 'index')
-                       $this->_searchlink($amount, $startpos, 'next', $linktext);
+                       $this->_searchlink($amount, $startpos, 'next', $linktext, $recount);
                else
                        $this->_archivelink($archivenext, $linktext);
        }
index 0ea39ce..6b6e536 100755 (executable)
@@ -346,7 +346,7 @@ class ADMIN {
                           . ' WHERE iblog=bnumber and iauthor=mnumber and icat=catid and iblog=' . $blogid;\r
 \r
                if ($search)\r
-                       $query .= ' and ((ititle LIKE "%' . addslashes($search) . '%") or (ibody LIKE "%' . addslashes($search) . '%") or (imore LIKE "%' . addslashes($search) . '%"))';\r
+                       $query .= ' and ((ititle LIKE "%' . sql_real_escape_string($search) . '%") or (ibody LIKE "%' . sql_real_escape_string($search) . '%") or (imore LIKE "%' . sql_real_escape_string($search) . '%"))';\r
 \r
                // non-blog-admins can only edit/delete their own items\r
                if (!$member->blogAdminRights($blogid))\r
@@ -913,7 +913,7 @@ class ADMIN {
                           . ' WHERE iauthor='. $member->getID() .' and iauthor=mnumber and iblog=bnumber and icat=catid';\r
 \r
                if ($search)\r
-                       $query .= ' and ((ititle LIKE "%' . addslashes($search) . '%") or (ibody LIKE "%' . addslashes($search) . '%") or (imore LIKE "%' . addslashes($search) . '%"))';\r
+                       $query .= ' and ((ititle LIKE "%' . sql_real_escape_string($search) . '%") or (ibody LIKE "%' . sql_real_escape_string($search) . '%") or (imore LIKE "%' . sql_real_escape_string($search) . '%"))';\r
 \r
                $query .= ' ORDER BY itime DESC'\r
                                . " LIMIT $start,$amount";\r
@@ -969,7 +969,7 @@ class ADMIN {
                $query = 'SELECT cbody, cuser, cmail, cemail, mname, ctime, chost, cnumber, cip, citem FROM ' . sql_table('comment') . ' LEFT OUTER JOIN ' . sql_table('member') . ' ON mnumber = cmember WHERE citem = ' . $itemid;\r
 \r
                if ($search)\r
-                       $query .= ' and cbody LIKE "%' . addslashes($search) . '%"';\r
+                       $query .= ' and cbody LIKE "%' . sql_real_escape_string($search) . '%"';\r
 \r
                $query .= ' ORDER BY ctime ASC'\r
                                . " LIMIT $start,$amount";\r
@@ -1011,7 +1011,7 @@ class ADMIN {
                $query =  'SELECT cbody, cuser, cmail, mname, ctime, chost, cnumber, cip, citem FROM '.sql_table('comment').' LEFT OUTER JOIN '.sql_table('member').' ON mnumber=cmember WHERE cmember=' . $member->getID();\r
 \r
                if ($search)\r
-                       $query .= ' and cbody LIKE "%' . addslashes($search) . '%"';\r
+                       $query .= ' and cbody LIKE "%' . sql_real_escape_string($search) . '%"';\r
 \r
                $query .= ' ORDER BY ctime DESC'\r
                                . " LIMIT $start,$amount";\r
@@ -1067,7 +1067,7 @@ class ADMIN {
                $query =  'SELECT cbody, cuser, cemail, cmail, mname, ctime, chost, cnumber, cip, citem FROM '.sql_table('comment').' LEFT OUTER JOIN '.sql_table('member').' ON mnumber=cmember WHERE cblog=' . intval($blogid);\r
 \r
                if ($search != '')\r
-                       $query .= ' and cbody LIKE "%' . addslashes($search) . '%"';\r
+                       $query .= ' and cbody LIKE "%' . sql_real_escape_string($search) . '%"';\r
 \r
 \r
                $query .= ' ORDER BY ctime DESC'\r
@@ -1469,9 +1469,11 @@ class ADMIN {
 \r
                // change <br /> to \n\r
                $comment['body'] = str_replace('<br />','',$comment['body']);\r
-\r
-               $comment['body'] = eregi_replace("<a href=['\"]([^'\"]+)['\"]( rel=\"nofollow\")?>[^<]*</a>","\\1",$comment['body']);\r
-\r
+               \r
+               // replaced eregi_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0\r
+               /* original eregi_replace: eregi_replace("<a href=['\"]([^'\"]+)['\"]( rel=\"nofollow\")?>[^<]*</a>", "\\1", $comment['body']) */\r
+               $comment['body'] = preg_replace("#<a href=['\"]([^'\"]+)['\"]( rel=\"nofollow\")?>[^<]*</a>#I", "\\1", $comment['body']);\r
+               \r
                $this->pagehead();\r
 \r
                ?>\r
@@ -1538,18 +1540,25 @@ class ADMIN {
                $url = postVar('url');\r
                $email = postVar('email');\r
                $body = postVar('body');\r
-\r
+               \r
+               # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
+               # original eregi: eregi("[a-zA-Z0-9|\.,;:!\?=\/\\]{90,90}", $body) != FALSE\r
+               # important note that '\' must be matched with '\\\\' in preg* expressions\r
                // intercept words that are too long\r
-               if (eregi("[a-zA-Z0-9|\.,;:!\?=\/\\]{90,90}",$body) != false)\r
+               if (preg_match('#[a-zA-Z0-9|\.,;:!\?=\/\\\\]{90,90}#', $body) != FALSE)\r
+               {\r
                        $this->error(_ERROR_COMMENT_LONGWORD);\r
-\r
+               }\r
+               \r
                // check length\r
-               if (strlen($body)<3)\r
+               if (strlen($body) < 3) {\r
                        $this->error(_ERROR_COMMENT_NOCOMMENT);\r
+               }\r
                if (strlen($body)>5000)\r
+               {\r
                        $this->error(_ERROR_COMMENT_TOOLONG);\r
-\r
-\r
+               }\r
+               \r
                // prepare body\r
                $body = COMMENT::prepareBody($body);\r
 \r
@@ -1557,7 +1566,7 @@ class ADMIN {
                $manager->notify('PreUpdateComment',array('body' => &$body));\r
 \r
                $query =  'UPDATE '.sql_table('comment')\r
-                          . " SET cmail = '" . addslashes($url) . "', cemail = '" . addslashes($email) . "', cbody = '" . addslashes($body) . "'"\r
+                          . " SET cmail = '" . sql_real_escape_string($url) . "', cemail = '" . sql_real_escape_string($email) . "', cbody = '" . sql_real_escape_string($body) . "'"\r
                           . " WHERE cnumber=" . $commentid;\r
                sql_query($query);\r
 \r
@@ -1833,17 +1842,23 @@ class ADMIN {
                                <?php                      // show a dropdown list of all available languages\r
                                global $DIR_LANG;\r
                                $dirhandle = opendir($DIR_LANG);\r
-                               while ($filename = readdir($dirhandle)) {\r
-                                       if (ereg("^(.*)\.php$",$filename,$matches)) {\r
+                               while ($filename = readdir($dirhandle))\r
+                               {\r
+                                       # replaced ereg() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
+                                       # original ereg: ereg("^(.*)\.php$", $filename, $matches)\r
+                                       if (preg_match('#^(.*)\.php$#', $filename, $matches) )\r
+                                       {\r
                                                $name = $matches[1];\r
-                                               echo "<option value='$name'";\r
-                                               if ($name == $mem->getLanguage())\r
-                                                       echo " selected='selected'";\r
+                                               echo "<option value=\"$name\"";\r
+                                               if ($name == $mem->getLanguage() )\r
+                                               {\r
+                                                       echo " selected=\"selected\"";\r
+                                               }\r
                                                echo ">$name</option>";\r
                                        }\r
                                }\r
                                closedir($dirhandle);\r
-\r
+                               \r
                                ?>\r
                                </select>\r
 \r
@@ -1897,10 +1912,13 @@ class ADMIN {
                $email            = strip_tags(postVar('email'));\r
                $url                    = strip_tags(postVar('url'));\r
 \r
-               // Sometimes user didn't prefix the URL with http://, this cause a malformed URL. Let's fix it.\r
-               if (!eregi("^https?://", $url))\r
-                       $url = "http://".$url;\r
-\r
+               # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
+               # original eregi: !eregi("^https?://", $url)\r
+               // begin if: sometimes user didn't prefix the URL with http:// or https://, this cause a malformed URL. Let's fix it.\r
+               if (!preg_match('#^https?://#', $url) )\r
+               {\r
+                       $url = "http://" . $url;\r
+               }\r
                $admin            = postVar('admin');\r
                $canlogin          = postVar('canlogin');\r
                $notes            = strip_tags(postVar('notes'));\r
@@ -2174,15 +2192,16 @@ class ADMIN {
 \r
                if ($password && (strlen($password) < 6))\r
                        return $this->_showActivationPage($key, _ERROR_PASSWORDTOOSHORT);\r
-\r
-               $pwdvalid = true;\r
-               $pwderror = '';\r
-               global $manager;\r
-               $manager->notify('PrePasswordSet',array('password' => $password, 'errormessage' => &$pwderror, 'valid' => &$pwdvalid));\r
-               if (!$pwdvalid) {\r
-                       return $this->_showActivationPage($key,$pwderror);\r
+               \r
+               if ($password) {\r
+                       $pwdvalid = true;\r
+                       $pwderror = '';\r
+                       global $manager;\r
+                       $manager->notify('PrePasswordSet',array('password' => $password, 'errormessage' => &$pwderror, 'valid' => &$pwdvalid));\r
+                       if (!$pwdvalid) {\r
+                               return $this->_showActivationPage($key,$pwderror);\r
+                       }\r
                }\r
-\r
                $error = '';\r
                $manager->notify('ValidateForm', array('type' => 'activation', 'member' => $mem, 'error' => &$error));\r
                if ($error != '')\r
@@ -2506,7 +2525,7 @@ class ADMIN {
                 <td><?php $this->input_yesno('reqemail',$blog->emailRequired(),72); ?></td>\r
          </tr><tr>\r
                        <td><?php echo _EBLOG_NOTIFY?> <?php help('blognotify'); ?></td>\r
-                       <td><input name="notify" tabindex="80" maxlength="60" size="40" value="<?php echo  htmlspecialchars($blog->getNotifyAddress()); ?>" /></td>\r
+                       <td><input name="notify" tabindex="80" maxlength="128" size="40" value="<?php echo  htmlspecialchars($blog->getNotifyAddress()); ?>" /></td>\r
                </tr><tr>\r
                        <td><?php echo _EBLOG_NOTIFY_ON?></td>\r
                        <td>\r
@@ -2629,7 +2648,7 @@ class ADMIN {
                if (!isValidCategoryName($cname))\r
                        $this->error(_ERROR_BADCATEGORYNAME);\r
 \r
-               $query = 'SELECT * FROM '.sql_table('category') . ' WHERE cname=\'' . addslashes($cname).'\' and cblog=' . intval($blogid);\r
+               $query = 'SELECT * FROM '.sql_table('category') . ' WHERE cname=\'' . sql_real_escape_string($cname).'\' and cblog=' . intval($blogid);\r
                $res = sql_query($query);\r
                if (sql_num_rows($res) > 0)\r
                        $this->error(_ERROR_DUPCATEGORYNAME);\r
@@ -2719,14 +2738,14 @@ class ADMIN {
                if (!isValidCategoryName($cname))\r
                        $this->error(_ERROR_BADCATEGORYNAME);\r
 \r
-               $query = 'SELECT * FROM '.sql_table('category').' WHERE cname=\'' . addslashes($cname).'\' and cblog=' . intval($blogid) . " and not(catid=$catid)";\r
+               $query = 'SELECT * FROM '.sql_table('category').' WHERE cname=\'' . sql_real_escape_string($cname).'\' and cblog=' . intval($blogid) . " and not(catid=$catid)";\r
                $res = sql_query($query);\r
                if (sql_num_rows($res) > 0)\r
                        $this->error(_ERROR_DUPCATEGORYNAME);\r
 \r
                $query =  'UPDATE '.sql_table('category').' SET'\r
-                          . " cname='" . addslashes($cname) . "',"\r
-                          . " cdesc='" . addslashes($cdesc) . "'"\r
+                          . " cname='" . sql_real_escape_string($cname) . "',"\r
+                          . " cdesc='" . sql_real_escape_string($cdesc) . "'"\r
                           . " WHERE catid=" . $catid;\r
 \r
                sql_query($query);\r
@@ -3155,7 +3174,7 @@ class ADMIN {
 \r
                /* unlink comments from memberid */\r
                if ($memberid) {\r
-                       $query = 'UPDATE ' . sql_table('comment') . ' SET cmember="0", cuser="'. addslashes($mem->getDisplayName())\r
+                       $query = 'UPDATE ' . sql_table('comment') . ' SET cmember="0", cuser="'. sql_real_escape_string($mem->getDisplayName())\r
                                   .'" WHERE cmember='.$memberid;\r
                        sql_query($query);\r
                }\r
@@ -3295,11 +3314,11 @@ class ADMIN {
 \r
 \r
                // add slashes for sql queries\r
-               $bname     = addslashes($bname);\r
-               $bshortname  = addslashes($bshortname);\r
-               $btimeoffset = addslashes($btimeoffset);\r
-               $bdesc     = addslashes($bdesc);\r
-               $bdefskin       = addslashes($bdefskin);\r
+               $bname     = sql_real_escape_string($bname);\r
+               $bshortname  = sql_real_escape_string($bshortname);\r
+               $btimeoffset = sql_real_escape_string($btimeoffset);\r
+               $bdesc     = sql_real_escape_string($bdesc);\r
+               $bdefskin       = sql_real_escape_string($bdefskin);\r
 \r
                // create blog\r
                $query = 'INSERT INTO '.sql_table('blog')." (bname, bshortname, bdesc, btimeoffset, bdefskin) VALUES ('$bname', '$bshortname', '$bdesc', '$btimeoffset', '$bdefskin')";\r
@@ -3308,11 +3327,10 @@ class ADMIN {
                $blog   =& $manager->getBlog($blogid);\r
 \r
                // create new category\r
-\r
-\r
+               $catdefname = (defined('_EBLOGDEFAULTCATEGORY_NAME') ? _EBLOGDEFAULTCATEGORY_NAME : 'General');\r
+               $catdefdesc = (defined('_EBLOGDEFAULTCATEGORY_DESC') ? _EBLOGDEFAULTCATEGORY_DESC : 'Items that do not fit in other categories');\r
                $sql = 'INSERT INTO %s (cblog, cname, cdesc) VALUES (%d, "%s", "%s")';\r
-               sql_query(sprintf($sql, sql_table('category'), $blogid, _EBLOGDEFAULTCATEGORY_NAME, _EBLOGDEFAULTCATEGORY_DESC));\r
-\r
+               sql_query(sprintf($sql, sql_table('category'), $blogid, $catdefname, $catdefdesc));\r
 //             sql_query('INSERT INTO '.sql_table('category')." (cblog, cname, cdesc) VALUES ($blogid, _EBLOGDEFAULTCATEGORY_NAME, _EBLOGDEFAULTCATEGORY_DESC)");\r
                $catid = sql_insert_id();\r
 \r
@@ -3324,15 +3342,15 @@ class ADMIN {
                $memberid = $member->getID();\r
                $query = 'INSERT INTO '.sql_table('team')." (tmember, tblog, tadmin) VALUES ($memberid, $blogid, 1)";\r
                sql_query($query);\r
-\r
-\r
-\r
-\r
-\r
-\r
-               $blog->additem($blog->getDefaultCategory(),_EBLOG_FIRSTITEM_TITLE,_EBLOG_FIRSTITEM_BODY,'',$blogid, $memberid,$blog->getCorrectTime(),0,0,0);\r
-\r
-\r
+               \r
+               $itemdeftitle = (defined('_EBLOG_FIRSTITEM_TITLE') ? _EBLOG_FIRSTITEM_TITLE : 'First Item');\r
+               $itemdefbody = (defined('_EBLOG_FIRSTITEM_BODY') ? _EBLOG_FIRSTITEM_BODY : 'This is the first item in your weblog. Feel free to delete it.');\r
+               \r
+               $blog->additem($blog->getDefaultCategory(),$itemdeftitle,$itemdefbody,'',$blogid, $memberid,$blog->getCorrectTime(),0,0,0);\r
+               //$blog->additem($blog->getDefaultCategory(),_EBLOG_FIRSTITEM_TITLE,_EBLOG_FIRSTITEM_BODY,'',$blogid, $memberid,$blog->getCorrectTime(),0,0,0);\r
+               \r
+               \r
+               \r
                $manager->notify(\r
                        'PostAddBlog',\r
                        array(\r
@@ -3762,7 +3780,7 @@ selector();
                $member->isAdmin() or $this->disallow();\r
 \r
                $extrahead = '<script type="text/javascript" src="javascript/templateEdit.js"></script>';\r
-               $extrahead .= '<script type="text/javascript">setTemplateEditText("'.addslashes(_EDITTEMPLATE_EMPTY).'");</script>';\r
+               $extrahead .= '<script type="text/javascript">setTemplateEditText("'.sql_real_escape_string(_EDITTEMPLATE_EMPTY).'");</script>';\r
 \r
                $this->pagehead($extrahead);\r
 \r
@@ -3934,8 +3952,8 @@ selector();
                        $this->error(_ERROR_DUPTEMPLATENAME);\r
 \r
 \r
-               $name = addslashes($name);\r
-               $desc = addslashes($desc);\r
+               $name = sql_real_escape_string($name);\r
+               $desc = sql_real_escape_string($desc);\r
 \r
                // 1. Remove all template parts\r
                $query = 'DELETE FROM '.sql_table('template').' WHERE tdesc=' . $templateid;\r
@@ -4001,8 +4019,8 @@ selector();
         * @todo document this\r
         */\r
        function addToTemplate($id, $partname, $content) {\r
-               $partname = addslashes($partname);\r
-               $content = addslashes($content);\r
+               $partname = sql_real_escape_string($partname);\r
+               $content = sql_real_escape_string($content);\r
 \r
                $id = intval($id);\r
 \r
@@ -4638,7 +4656,7 @@ selector();
                $newid = intval($newid);\r
                $content = $skin->getContent($type);\r
                if ($content) {\r
-                       $query = 'INSERT INTO '.sql_table('skin')." (sdesc, scontent, stype) VALUES ($newid,'". addslashes($content)."', '". addslashes($type)."')";\r
+                       $query = 'INSERT INTO '.sql_table('skin')." (sdesc, scontent, stype) VALUES ($newid,'". sql_real_escape_string($content)."', '". sql_real_escape_string($type)."')";\r
                        sql_query($query);\r
                }\r
        }\r
@@ -4720,12 +4738,18 @@ selector();
                                <?php                      // show a dropdown list of all available languages\r
                                global $DIR_LANG;\r
                                $dirhandle = opendir($DIR_LANG);\r
-                               while ($filename = readdir($dirhandle)) {\r
-                                       if (ereg("^(.*)\.php$",$filename,$matches)) {\r
+                               while ($filename = readdir($dirhandle) )\r
+                               {\r
+                                       # replaced ereg() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
+                                       # original ereg: ereg("^(.*)\.php$",$filename,$matches)\r
+                                       if (preg_match('#^(.*)\.php$#', $filename, $matches) )\r
+                                       {\r
                                                $name = $matches[1];\r
-                                               echo "<option value='$name'";\r
+                                               echo "<option value=\"$name\"";\r
                                                if ($name == $CONF['Language'])\r
-                                                       echo " selected='selected'";\r
+                                               {\r
+                                                       echo " selected=\"selected\"";\r
+                                               }\r
                                                echo ">$name</option>";\r
                                        }\r
                                }\r
@@ -5129,8 +5153,8 @@ selector();
         * @todo document this\r
         */\r
        function updateConfig($name, $val) {\r
-               $name = addslashes($name);\r
-               $val = trim(addslashes($val));\r
+               $name = sql_real_escape_string($name);\r
+               $val = trim(sql_real_escape_string($val));\r
 \r
                $query = 'UPDATE '.sql_table('config')\r
                           . " SET value='$val'"\r
@@ -5180,7 +5204,8 @@ selector();
 \r
                $baseUrl = htmlspecialchars($CONF['AdminURL']);\r
 \r
-               ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\r
+               ?>\r
+               <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\r
                <html <?php echo _HTML_XML_NAME_SPACE_AND_LANG_CODE; ?>>\r
                <head>\r
                        <meta http-equiv="Content-Type" content="text/html; charset=<?php echo _CHARSET ?>" />\r
@@ -5901,23 +5926,31 @@ selector();
                        </div></form>\r
 \r
                        <h3><?php echo _PLUGS_TITLE_NEW?></h3>\r
-\r
-                       <?php                      // find a list of possibly non-installed plugins\r
+                       \r
+                       <?php\r
+                       // find a list of possibly non-installed plugins\r
                                $candidates = array();\r
                                global $DIR_PLUGINS;\r
                                $dirhandle = opendir($DIR_PLUGINS);\r
-                               while ($filename = readdir($dirhandle)) {\r
-                                       if (ereg('^NP_(.*)\.php$',$filename,$matches)) {\r
+                               while ($filename = readdir($dirhandle) )\r
+                               {\r
+                                       # replaced ereg() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
+                                       # original ereg: ereg('^NP_(.*)\.php$',$filename,$matches)\r
+                                       if (preg_match('#^NP_(.*)\.php$#', $filename, $matches) )\r
+                                       {\r
                                                $name = $matches[1];\r
                                                // only show in list when not yet installed\r
-                                               $res = sql_query('SELECT * FROM '.sql_table('plugin').' WHERE pfile="NP_'.addslashes($name).'"');\r
+                                               $res = sql_query('SELECT * FROM ' . sql_table('plugin') . ' WHERE `pfile` = "NP_' . sql_real_escape_string($name) . '"');\r
                                                if (sql_num_rows($res) == 0)\r
-                                                       array_push($candidates,$name);\r
+                                               {\r
+                                                       array_push($candidates, $name);\r
+                                               }\r
                                        }\r
                                }\r
                                closedir($dirhandle);\r
-\r
-                               if (sizeof($candidates) > 0) {\r
+                               \r
+                               if (sizeof($candidates) > 0)\r
+                               {\r
                        ?>\r
 \r
                        <p><?php echo _PLUGS_ADD_TEXT?></p>\r
@@ -5927,14 +5960,20 @@ selector();
                                <input type='hidden' name='action' value='pluginadd' />\r
                                <?php $manager->addTicketHidden() ?>\r
                                <select name="filename" tabindex="30">\r
-                               <?php                              foreach($candidates as $name)\r
-                                               echo '<option value="NP_',$name,'">',htmlspecialchars($name),'</option>';\r
+                               <?php   \r
+                               foreach($candidates as $name)\r
+                               {\r
+                                       echo '<option value="NP_',$name,'">',htmlspecialchars($name),'</option>';\r
+                               }\r
                                ?>\r
                                </select>\r
                                <input type='submit' tabindex="40" value='<?php echo _PLUGS_BTN_INSTALL?>' />\r
                        </div></form>\r
 \r
-               <?php              } else {     // sizeof(candidates) == 0\r
+               <?php\r
+                               }\r
+                               else\r
+                               {\r
                                echo '<p>',_PLUGS_NOCANDIDATES,'</p>';\r
                        }\r
 \r
@@ -5969,7 +6008,7 @@ selector();
                if (($plug->supportsFeature('HelpPage') > 0) && (@file_exists($helpFile))) {\r
                        @readfile($helpFile);\r
                } else {\r
-                       echo '<p>' . _ERROR .': ', _ERROR_PLUGNOHELPFILE,'</p>';\r
+                       echo '<p>Error: ', _ERROR_PLUGNOHELPFILE,'</p>';\r
                        echo '<p><a href="index.php?action=pluginlist">(',_BACK,')</a></p>';\r
                }\r
 \r
@@ -6008,7 +6047,7 @@ selector();
                );\r
 \r
                // do this before calling getPlugin (in case the plugin id is used there)\r
-               $query = 'INSERT INTO '.sql_table('plugin').' (porder, pfile) VALUES ('.$newOrder.',"'.addslashes($name).'")';\r
+               $query = 'INSERT INTO '.sql_table('plugin').' (porder, pfile) VALUES ('.$newOrder.',"'.sql_real_escape_string($name).'")';\r
                sql_query($query);\r
                $iPid = sql_insert_id();\r
 \r
@@ -6094,7 +6133,7 @@ selector();
                        {\r
                                $eventList = $plug->getEventList();\r
                                foreach ($eventList as $eventName)\r
-                                       sql_query('INSERT INTO '.sql_table('plugin_event').' (pid, event) VALUES ('.$pid.', \''.addslashes($eventName).'\')');\r
+                                       sql_query('INSERT INTO '.sql_table('plugin_event').' (pid, event) VALUES ('.$pid.', \''.sql_real_escape_string($eventName).'\')');\r
                        }\r
                }\r
 \r
@@ -6399,7 +6438,7 @@ selector();
 \r
                // get list of oids per pid\r
                $query = 'SELECT * FROM ' . sql_table('plugin_option_desc') . ',' . sql_table('plugin')\r
-                          . ' WHERE opid=pid and ocontext=\''.addslashes($context).'\' ORDER BY porder, oid ASC';\r
+                          . ' WHERE opid=pid and ocontext=\''.sql_real_escape_string($context).'\' ORDER BY porder, oid ASC';\r
                $res = sql_query($query);\r
                $aOptions = array();\r
                while ($o = sql_fetch_object($res)) {\r
@@ -6432,22 +6471,19 @@ selector();
                        // new plugin?\r
                        if ($iPrevPid != $aOption['pid']) {\r
                                $iPrevPid = $aOption['pid'];\r
-\r
-\r
-\r
+                               if (!defined('_PLUGIN_OPTIONS_TITLE')) {\r
+                                       define('_PLUGIN_OPTIONS_TITLE', 'Options for %s');\r
+                               }\r
                                echo '<tr><th colspan="2">'.sprintf(_PLUGIN_OPTIONS_TITLE, htmlspecialchars($aOption['pfile'], ENT_QUOTES)).'</th></tr>';\r
                        }\r
-\r
+                       \r
                        $meta = NucleusPlugin::getOptionMeta($aOption['typeinfo']);\r
                        if (@$meta['access'] != 'hidden') {\r
                                echo '<tr>';\r
                                listplug_plugOptionRow($aOption);\r
                                echo '</tr>';\r
                        }\r
-\r
                }\r
-\r
-\r
        }\r
 \r
        /**\r
index d7271b0..972f33b 100755 (executable)
@@ -57,7 +57,7 @@ class BAN {
                );
 
                $query = 'INSERT INTO '.sql_table('ban')." (blogid, iprange, reason) VALUES "
-                          . "($blogid,'".addslashes($iprange)."','".addslashes($reason)."')";
+                          . "($blogid,'".sql_real_escape_string($iprange)."','".sql_real_escape_string($reason)."')";
                $res = sql_query($query);
 
                $manager->notify(
@@ -82,7 +82,7 @@ class BAN {
 
                $manager->notify('PreDeleteBan', array('blogid' => $blogid, 'range' => $iprange));
 
-               $query = 'DELETE FROM '.sql_table('ban')." WHERE blogid=$blogid and iprange='" .addslashes($iprange). "'";
+               $query = 'DELETE FROM '.sql_table('ban')." WHERE blogid=$blogid and iprange='" .sql_real_escape_string($iprange). "'";
                sql_query($query);
 
                $result = (sql_affected_rows() > 0);
index 18af84b..a922e1e 100755 (executable)
@@ -25,1273 +25,1285 @@ require_once dirname(__FILE__) . '/ITEMACTIONS.php';
 
 class BLOG {
 
-    // blog id
-    var $blogid;
-
-    // ID of currently selected category
-    var $selectedcatid;
-
-    // After creating an object of the blog class, contains true if the BLOG object is
-    // valid (the blog exists)
-    var $isValid;
-
-    // associative array, containing all blogsettings (use the get/set functions instead)
-    var $settings;
-
-    /**
-     * Creates a new BLOG object for the given blog
-     *
-     * @param $id blogid
-     */
-    function BLOG($id) {
-        $this->blogid = intval($id);
-        $this->readSettings();
-
-        // try to set catid
-        // (the parse functions in SKIN.php will override this, so it's mainly useless)
-        global $catid;
-        $this->setSelectedCategory($catid);
-    }
-
-    /**
-     * Shows the given amount of items for this blog
-     *
-     * @param $template
-     *      String representing the template _NAME_ (!)
-     * @param $amountEntries
-     *      amount of entries to show
-     * @param $startpos
-     *      offset from where items should be shown (e.g. 5 = start at fifth item)
-     * @returns int
-     *      amount of items shown
-     */
-    function readLog($template, $amountEntries, $offset = 0, $startpos = 0) {
-        return $this->readLogAmount($template,$amountEntries,'','',1,1,$offset, $startpos);
-    }
-
-    /**
-     * Shows an archive for a given month
-     *
-     * @param $year
-     *      year
-     * @param $month
-     *      month
-     * @param $template
-     *      String representing the template name to be used
-     */
-    function showArchive($templatename, $year, $month = 0, $day = 0) {
-
-        // create extra where clause for select query
-        if ($day == 0 && $month != 0) {
-            $timestamp_start = mktime(0,0,0,$month,1,$year);
-            $timestamp_end = mktime(0,0,0,$month+1,1,$year);  // also works when $month==12
-        } elseif ($month == 0) {
-            $timestamp_start = mktime(0,0,0,1,1,$year);
-            $timestamp_end = mktime(0,0,0,12,31,$year);  // also works when $month==12
-        } else {
-            $timestamp_start = mktime(0,0,0,$month,$day,$year);
-            $timestamp_end = mktime(0,0,0,$month,$day+1,$year);
-        }
-        $extra_query = ' and i.itime>=' . mysqldate($timestamp_start)
-                     . ' and i.itime<' . mysqldate($timestamp_end);
-
-
-        $this->readLogAmount($templatename,0,$extra_query,'',1,1);
-
-    }
-
-
-    // sets/gets current category (only when category exists)
-    function setSelectedCategory($catid) {
-        if ($this->isValidCategory($catid) || (intval($catid) == 0))
-            $this->selectedcatid = intval($catid);
-    }
-
-    function setSelectedCategoryByName($catname) {
-        $this->setSelectedCategory($this->getCategoryIdFromName($catname));
-    }
-
-    function getSelectedCategory() {
-        return $this->selectedcatid;
-    }
-
-    /**
-     * Shows the given amount of items for this blog
-     *
-     * @param $template
-     *      String representing the template _NAME_ (!)
-     * @param $amountEntries
-     *      amount of entries to show (0 = no limit)
-     * @param $extraQuery
-     *      extra conditions to be added to the query
-     * @param $highlight
-     *      contains a query that should be highlighted
-     * @param $comments
-     *      1=show comments 0=don't show comments
-     * @param $dateheads
-     *      1=show dateheads 0=don't show dateheads
-     * @param $offset
-     *      offset
-     * @returns int
-     *      amount of items shown
-     */
-    function readLogAmount($template, $amountEntries, $extraQuery, $highlight, $comments, $dateheads, $offset = 0, $startpos = 0) {
-
-        $query = $this->getSqlBlog($extraQuery);
-
-        if ($amountEntries > 0) {
-                // $offset zou moeten worden:
-                // (($startpos / $amountentries) + 1) * $offset ... later testen ...
-               $query .= ' LIMIT ' . intval($startpos + $offset).',' . intval($amountEntries);
-        }
-        return $this->showUsingQuery($template, $query, $highlight, $comments, $dateheads);
-    }
-
-    function showUsingQuery($templateName, $query, $highlight = '', $comments = 0, $dateheads = 1) {
-        global $CONF, $manager;
-
-        $lastVisit = cookieVar($CONF['CookiePrefix'] .'lastVisit');
-        if ($lastVisit != 0)
-            $lastVisit = $this->getCorrectTime($lastVisit);
-
-        // set templatename as global variable (so plugins can access it)
-        global $currentTemplateName;
-        $currentTemplateName = $templateName;
-
-        $template =& $manager->getTemplate($templateName);
-
-        // create parser object & action handler
-        $actions =& new ITEMACTIONS($this);
-        $parser =& new PARSER($actions->getDefinedActions(),$actions);
-        $actions->setTemplate($template);
-        $actions->setHighlight($highlight);
-        $actions->setLastVisit($lastVisit);
-        $actions->setParser($parser);
-        $actions->setShowComments($comments);
-
-        // execute query
-        $items = sql_query($query);
-
-        // loop over all items
-        $old_date = 0;
-        while ($item = sql_fetch_object($items)) {
-
-            $item->timestamp = strtotime($item->itime); // string timestamp -> unix timestamp
-
-            // action handler needs to know the item we're handling
-            $actions->setCurrentItem($item);
-
-            // add date header if needed
-            if ($dateheads) {
-                $new_date = date('dFY',$item->timestamp);
-                if ($new_date != $old_date) {
-                    // unless this is the first time, write date footer
-                    $timestamp = $item->timestamp;
-                    if ($old_date != 0) {
-                        $oldTS = strtotime($old_date);
-                        $manager->notify('PreDateFoot',array('blog' => &$this, 'timestamp' => $oldTS));
-                        $tmp_footer = strftime(isset($template['DATE_FOOTER'])?$template['DATE_FOOTER']:'', $oldTS);
-                        $parser->parse($tmp_footer);
-                        $manager->notify('PostDateFoot',array('blog' => &$this, 'timestamp' => $oldTS));
-                    }
-                    $manager->notify('PreDateHead',array('blog' => &$this, 'timestamp' => $timestamp));
-                    // note, to use templatvars in the dateheader, the %-characters need to be doubled in
-                    // order to be preserved by strftime
-                    $tmp_header = strftime((isset($template['DATE_HEADER']) ? $template['DATE_HEADER'] : null), $timestamp);
-                    $parser->parse($tmp_header);
-                    $manager->notify('PostDateHead',array('blog' => &$this, 'timestamp' => $timestamp));
-                }
-                $old_date = $new_date;
-            }
-
-            // parse item
-            $parser->parse($template['ITEM_HEADER']);
-            $manager->notify('PreItem', array('blog' => &$this, 'item' => &$item));
-            $parser->parse($template['ITEM']);
-            $manager->notify('PostItem', array('blog' => &$this, 'item' => &$item));
-            $parser->parse($template['ITEM_FOOTER']);
-
-        }
-
-        $numrows = sql_num_rows($items);
-
-        // add another date footer if there was at least one item
-        if (($numrows > 0) && $dateheads) {
-            $manager->notify('PreDateFoot',array('blog' => &$this, 'timestamp' => strtotime($old_date)));
-            $parser->parse($template['DATE_FOOTER']);
-            $manager->notify('PostDateFoot',array('blog' => &$this, 'timestamp' => strtotime($old_date)));
-        }
-
-        sql_free_result($items);    // free memory
-
-        return $numrows;
-
-    }
-
-    function showOneitem($itemid, $template, $highlight) {
-        $extraQuery = ' and inumber=' . intval($itemid);
-
-        return $this->readLogAmount($template, 1, $extraQuery, $highlight, 0, 0);
-    }
-
-
-    /**
-      * Adds an item to this blog
-      */
-    function additem($catid, $title, $body, $more, $blogid, $authorid, $timestamp, $closed, $draft, $posted='1') {
-        global $manager;
-
-        $blogid     = intval($blogid);
-        $authorid   = intval($authorid);
-        $title      = $title;
-        $body       = $body;
-        $more       = $more;
-        $catid      = intval($catid);
-
-        // convert newlines to <br />
-        if ($this->convertBreaks()) {
-            $body = addBreaks($body);
-            $more = addBreaks($more);
-        }
+       // blog id
+       var $blogid;
+
+       // ID of currently selected category
+       var $selectedcatid;
+
+       // After creating an object of the blog class, contains true if the BLOG object is
+       // valid (the blog exists)
+       var $isValid;
+
+       // associative array, containing all blogsettings (use the get/set functions instead)
+       var $settings;
+
+       /**
+        * Creates a new BLOG object for the given blog
+        *
+        * @param $id blogid
+        */
+       function BLOG($id) {
+               $this->blogid = intval($id);
+               $this->readSettings();
+
+               // try to set catid
+               // (the parse functions in SKIN.php will override this, so it's mainly useless)
+               global $catid;
+               $this->setSelectedCategory($catid);
+       }
+
+       /**
+        * Shows the given amount of items for this blog
+        *
+        * @param $template
+        *        String representing the template _NAME_ (!)
+        * @param $amountEntries
+        *        amount of entries to show
+        * @param $startpos
+        *        offset from where items should be shown (e.g. 5 = start at fifth item)
+        * @returns int
+        *        amount of items shown
+        */
+       function readLog($template, $amountEntries, $offset = 0, $startpos = 0) {
+               return $this->readLogAmount($template,$amountEntries,'','',1,1,$offset, $startpos);
+       }
+
+       /**
+        * Shows an archive for a given month
+        *
+        * @param $year
+        *        year
+        * @param $month
+        *        month
+        * @param $template
+        *        String representing the template name to be used
+        */
+       function showArchive($templatename, $year, $month = 0, $day = 0) {
+
+               // create extra where clause for select query
+               if ($day == 0 && $month != 0) {
+                       $timestamp_start = mktime(0,0,0,$month,1,$year);
+                       $timestamp_end = mktime(0,0,0,$month+1,1,$year);  // also works when $month==12
+               } elseif ($month == 0) {
+                       $timestamp_start = mktime(0,0,0,1,1,$year);
+                       $timestamp_end = mktime(0,0,0,12,31,$year);  // also works when $month==12
+               } else {
+                       $timestamp_start = mktime(0,0,0,$month,$day,$year);
+                       $timestamp_end = mktime(0,0,0,$month,$day+1,$year);
+               }
+               $extra_query = ' and i.itime>=' . mysqldate($timestamp_start)
+                                        . ' and i.itime<' . mysqldate($timestamp_end);
+
+
+               $this->readLogAmount($templatename,0,$extra_query,'',1,1);
+
+       }
+
+
+       // sets/gets current category (only when category exists)
+       function setSelectedCategory($catid) {
+               if ($this->isValidCategory($catid) || (intval($catid) == 0))
+                       $this->selectedcatid = intval($catid);
+       }
+
+       function setSelectedCategoryByName($catname) {
+               $this->setSelectedCategory($this->getCategoryIdFromName($catname));
+       }
+
+       function getSelectedCategory() {
+               return $this->selectedcatid;
+       }
+
+       /**
+        * Shows the given amount of items for this blog
+        *
+        * @param $template
+        *        String representing the template _NAME_ (!)
+        * @param $amountEntries
+        *        amount of entries to show (0 = no limit)
+        * @param $extraQuery
+        *        extra conditions to be added to the query
+        * @param $highlight
+        *        contains a query that should be highlighted
+        * @param $comments
+        *        1=show comments 0=don't show comments
+        * @param $dateheads
+        *        1=show dateheads 0=don't show dateheads
+        * @param $offset
+        *        offset
+        * @returns int
+        *        amount of items shown
+        */
+       function readLogAmount($template, $amountEntries, $extraQuery, $highlight, $comments, $dateheads, $offset = 0, $startpos = 0) {
+
+               $query = $this->getSqlBlog($extraQuery);
+
+               if ($amountEntries > 0) {
+                               // $offset zou moeten worden:
+                               // (($startpos / $amountentries) + 1) * $offset ... later testen ...
+                          $query .= ' LIMIT ' . intval($startpos + $offset).',' . intval($amountEntries);
+               }
+               return $this->showUsingQuery($template, $query, $highlight, $comments, $dateheads);
+       }
+
+       function showUsingQuery($templateName, $query, $highlight = '', $comments = 0, $dateheads = 1) {
+               global $CONF, $manager;
+
+               $lastVisit = cookieVar($CONF['CookiePrefix'] .'lastVisit');
+               if ($lastVisit != 0)
+                       $lastVisit = $this->getCorrectTime($lastVisit);
+
+               // set templatename as global variable (so plugins can access it)
+               global $currentTemplateName;
+               $currentTemplateName = $templateName;
+
+               $template =& $manager->getTemplate($templateName);
+
+               // create parser object & action handler
+               $actions =& new ITEMACTIONS($this);
+               $parser =& new PARSER($actions->getDefinedActions(),$actions);
+               $actions->setTemplate($template);
+               $actions->setHighlight($highlight);
+               $actions->setLastVisit($lastVisit);
+               $actions->setParser($parser);
+               $actions->setShowComments($comments);
+
+               // execute query
+               $items = sql_query($query);
+
+               // loop over all items
+               $old_date = 0;
+               while ($item = sql_fetch_object($items)) {
+
+                       $item->timestamp = strtotime($item->itime); // string timestamp -> unix timestamp
+
+                       // action handler needs to know the item we're handling
+                       $actions->setCurrentItem($item);
+
+                       // add date header if needed
+                       if ($dateheads) {
+                               $new_date = date('dFY',$item->timestamp);
+                               if ($new_date != $old_date) {
+                                       // unless this is the first time, write date footer
+                                       $timestamp = $item->timestamp;
+                                       if ($old_date != 0) {
+                                               $oldTS = strtotime($old_date);
+                                               $manager->notify('PreDateFoot',array('blog' => &$this, 'timestamp' => $oldTS));
+                                               $tmp_footer = strftime(isset($template['DATE_FOOTER'])?$template['DATE_FOOTER']:'', $oldTS);
+                                               $parser->parse($tmp_footer);
+                                               $manager->notify('PostDateFoot',array('blog' => &$this, 'timestamp' => $oldTS));
+                                       }
+                                       $manager->notify('PreDateHead',array('blog' => &$this, 'timestamp' => $timestamp));
+                                       // note, to use templatvars in the dateheader, the %-characters need to be doubled in
+                                       // order to be preserved by strftime
+                                       $tmp_header = strftime((isset($template['DATE_HEADER']) ? $template['DATE_HEADER'] : null), $timestamp);
+                                       $parser->parse($tmp_header);
+                                       $manager->notify('PostDateHead',array('blog' => &$this, 'timestamp' => $timestamp));
+                               }
+                               $old_date = $new_date;
+                       }
+
+                       // parse item
+                       $parser->parse($template['ITEM_HEADER']);
+                       $manager->notify('PreItem', array('blog' => &$this, 'item' => &$item));
+                       $parser->parse($template['ITEM']);
+                       $manager->notify('PostItem', array('blog' => &$this, 'item' => &$item));
+                       $parser->parse($template['ITEM_FOOTER']);
+
+               }
+
+               $numrows = sql_num_rows($items);
+
+               // add another date footer if there was at least one item
+               if (($numrows > 0) && $dateheads) {
+                       $manager->notify('PreDateFoot',array('blog' => &$this, 'timestamp' => strtotime($old_date)));
+                       $parser->parse($template['DATE_FOOTER']);
+                       $manager->notify('PostDateFoot',array('blog' => &$this, 'timestamp' => strtotime($old_date)));
+               }
+
+               sql_free_result($items);        // free memory
+
+               return $numrows;
+
+       }
+
+       function showOneitem($itemid, $template, $highlight) {
+               $extraQuery = ' and inumber=' . intval($itemid);
+
+               return $this->readLogAmount($template, 1, $extraQuery, $highlight, 0, 0);
+       }
+
+
+       /**
+         * Adds an item to this blog
+         */
+       function additem($catid, $title, $body, $more, $blogid, $authorid, $timestamp, $closed, $draft, $posted='1') {
+               global $manager;
+
+               $blogid  = intval($blogid);
+               $authorid   = intval($authorid);
+               $title    = $title;
+               $body      = $body;
+               $more      = $more;
+               $catid    = intval($catid);
+
+               // convert newlines to <br />
+               if ($this->convertBreaks()) {
+                       $body = addBreaks($body);
+                       $more = addBreaks($more);
+               }
 
-        if ($closed != '1') $closed = '0';
-        if ($draft != '0') $draft = '1';
+               if ($closed != '1') $closed = '0';
+               if ($draft != '0') $draft = '1';
 
-        if (!$this->isValidCategory($catid))
-            $catid = $this->getDefaultCategory();
-
-        if ($timestamp > $this->getCorrectTime())
-            $isFuture = 1;
-
-        $timestamp = date('Y-m-d H:i:s',$timestamp);
+               if (!$this->isValidCategory($catid))
+                       $catid = $this->getDefaultCategory();
+
+               if ($timestamp > $this->getCorrectTime())
+                       $isFuture = 1;
+
+               $timestamp = date('Y-m-d H:i:s',$timestamp);
 
-        $manager->notify('PreAddItem',array('title' => &$title, 'body' => &$body, 'more' => &$more, 'blog' => &$this, 'authorid' => &$authorid, 'timestamp' => &$timestamp, 'closed' => &$closed, 'draft' => &$draft, 'catid' => &$catid));
+               $manager->notify('PreAddItem',array('title' => &$title, 'body' => &$body, 'more' => &$more, 'blog' => &$this, 'authorid' => &$authorid, 'timestamp' => &$timestamp, 'closed' => &$closed, 'draft' => &$draft, 'catid' => &$catid));
 
-        $title = addslashes($title);
-        $body = addslashes($body);
-        $more = addslashes($more);
+               $title = sql_real_escape_string($title);
+               $body = sql_real_escape_string($body);
+               $more = sql_real_escape_string($more);
 
-        $query = 'INSERT INTO '.sql_table('item').' (ITITLE, IBODY, IMORE, IBLOG, IAUTHOR, ITIME, ICLOSED, IDRAFT, ICAT, IPOSTED) '
-               . "VALUES ('$title', '$body', '$more', $blogid, $authorid, '$timestamp', $closed, $draft, $catid, $posted)";
-        sql_query($query);
-        $itemid = sql_insert_id();
+               $query = 'INSERT INTO '.sql_table('item').' (ITITLE, IBODY, IMORE, IBLOG, IAUTHOR, ITIME, ICLOSED, IDRAFT, ICAT, IPOSTED) '
+                          . "VALUES ('$title', '$body', '$more', $blogid, $authorid, '$timestamp', $closed, $draft, $catid, $posted)";
+               sql_query($query);
+               $itemid = sql_insert_id();
 
-        $manager->notify('PostAddItem',array('itemid' => $itemid));
+               $manager->notify('PostAddItem',array('itemid' => $itemid));
 
-        if (!$draft)
-            $this->updateUpdateFile();
+               if (!$draft)
+                       $this->updateUpdateFile();
 
-        // send notification mail
-        if (!$draft && !$isFuture && $this->getNotifyAddress() && $this->notifyOnNewItem())
-            $this->sendNewItemNotification($itemid, stripslashes($title), stripslashes($body));
+               // send notification mail
+               if (!$draft && !$isFuture && $this->getNotifyAddress() && $this->notifyOnNewItem())
+                       $this->sendNewItemNotification($itemid, stripslashes($title), stripslashes($body));
 
-        return $itemid;
-    }
+               return $itemid;
+       }
 
-    function sendNewItemNotification($itemid, $title, $body) {
-        global $CONF, $member;
+       function sendNewItemNotification($itemid, $title, $body) {
+               global $CONF, $member;
 
-        // create text version of html post
-        $ascii = toAscii($body);
+               // create text version of html post
+               $ascii = toAscii($body);
 
-        $mailto_msg = _NOTIFY_NI_MSG . " \n";
+               $mailto_msg = _NOTIFY_NI_MSG . " \n";
 //             $mailto_msg .= $CONF['IndexURL'] . 'index.php?itemid=' . $itemid . "\n\n";
-        $temp = parse_url($CONF['Self']);
-        if ($temp['scheme']) {
-            $mailto_msg .= createItemLink($itemid) . "\n\n";
-        } else {
-            $tempurl = $this->getURL();
-            if (substr($tempurl, -1) == '/' || substr($tempurl, -4) == '.php') {
-                $mailto_msg .= $tempurl . '?itemid=' . $itemid . "\n\n";
-            } else {
-                $mailto_msg .= $tempurl . '/?itemid=' . $itemid . "\n\n";
-            }
-        }
-        $mailto_msg .= _NOTIFY_TITLE . ' ' . strip_tags($title) . "\n";
-        $mailto_msg .= _NOTIFY_CONTENTS . "\n " . $ascii . "\n";
-        $mailto_msg .= getMailFooter();
-
-        $mailto_title = $this->getName() . ': ' . _NOTIFY_NI_TITLE;
-
-        $frommail = $member->getNotifyFromMailAddress();
-
-        $notify =& new NOTIFICATION($this->getNotifyAddress());
-        $notify->notify($mailto_title, $mailto_msg , $frommail);
-
-
-
-    }
-
-
-    /**
-      * Creates a new category for this blog
-      *
-      * @param $catName
-      *     name of the new category. When empty, a name is generated automatically
-      *     (starting with newcat)
-      * @param $catDescription
-      *     description of the new category. Defaults to 'New Category'
-      *
-      * @returns
-      *     the new category-id in case of success.
-      *     0 on failure
-      */
-    function createNewCategory($catName = '', $catDescription = _CREATED_NEW_CATEGORY_DESC) {
-        global $member, $manager;
-
-        if ($member->blogAdminRights($this->getID())) {
-            // generate
-            if ($catName == '')
-            {
-                $catName = _CREATED_NEW_CATEGORY_NAME;
-                $i = 1;
-
-                $res = sql_query('SELECT * FROM '.sql_table('category')." WHERE cname='".$catName.$i."' and cblog=".$this->getID());
-                while (sql_num_rows($res) > 0)
-                {
-                    $i++;
-                    $res = sql_query('SELECT * FROM '.sql_table('category')." WHERE cname='".$catName.$i."' and cblog=".$this->getID());
-                }
-
-                $catName = $catName . $i;
-            }
-
-            $manager->notify(
-                'PreAddCategory',
-                array(
-                    'blog' => &$this,
-                    'name' => &$catName,
-                    'description' => $catDescription
-                )
-            );
-
-            $query = 'INSERT INTO '.sql_table('category').' (cblog, cname, cdesc) VALUES (' . $this->getID() . ", '" . addslashes($catName) . "', '" . addslashes($catDescription) . "')";
-            sql_query($query);
-            $catid = sql_insert_id();
-
-            $manager->notify(
-                'PostAddCategory',
-                array(
-                    'blog' => &$this,
-                    'name' => $catName,
-                    'description' => $catDescription,
-                    'catid' => $catid
-                )
-            );
-
-            return $catid;
-        } else {
-            return 0;
-        }
-
-    }
-
-
-    /**
-     * Searches all months of this blog for the given query
-     *
-     * @param $query
-     *      search query
-     * @param $template
-     *      template to be used (__NAME__ of the template)
-     * @param $amountMonths
-     *      max amount of months to be search (0 = all)
-     * @param $maxresults
-     *      max number of results to show
-     * @param $startpos
-     *      offset
-     * @returns
-     *      amount of hits found
-     */
-    function search($query, $template, $amountMonths, $maxresults, $startpos) {
-        global $CONF, $manager;
-
-        $highlight  = '';
-        $sqlquery   = $this->getSqlSearch($query, $amountMonths, $highlight);
-
-        if ($sqlquery == '')
-        {
-            // no query -> show everything
-            $extraquery = '';
-            $amountfound = $this->readLogAmount($template, $maxresults, $extraQuery, $query, 1, 1);
-        } else {
-
-            // add LIMIT to query (to split search results into pages)
-            if (intval($maxresults > 0))
-                $sqlquery .= ' LIMIT ' . intval($startpos).',' . intval($maxresults);
-
-            // show results
-            $amountfound = $this->showUsingQuery($template, $sqlquery, $highlight, 1, 1);
-
-            // when no results were found, show a message
-            if ($amountfound == 0)
-            {
-                $template =& $manager->getTemplate($template);
-                $vars = array(
-                    'query'     => htmlspecialchars($query),
-                    'blogid'    => $this->getID()
-                );
-                echo TEMPLATE::fill($template['SEARCH_NOTHINGFOUND'],$vars);
-            }
-        }
-
-        return $amountfound;
-    }
-
-    /**
-     * Returns an SQL query to use for a search query
-     *
-     * @param $query
-     *      search query
-     * @param $amountMonths
-     *      amount of months to search back. Default = 0 = unlimited
-     * @param $mode
-     *      either empty, or 'count'. In this case, the query will be a SELECT COUNT(*) query
-     * @returns $highlight
-     *      words to highlight (out parameter)
-     * @returns
-     *      either a full SQL query, or an empty string (if querystring empty)
-     * @note
-     *      No LIMIT clause is added. (caller should add this if multiple pages are requested)
-     */
-    function getSqlSearch($query, $amountMonths = 0, &$highlight, $mode = '')
-    {
-        $searchclass =& new SEARCH($query);
-
-        $highlight    = $searchclass->inclusive;
-
-        // if querystring is empty, return empty string
-        if ($searchclass->inclusive == '')
-            return '';
-
-
-        $where  = $searchclass->boolean_sql_where('ititle,ibody,imore');
-        $select = $searchclass->boolean_sql_select('ititle,ibody,imore');
-
-        // get list of blogs to search
-        $blogs      = $searchclass->blogs;      // array containing blogs that always need to be included
-        $blogs[]    = $this->getID();           // also search current blog (duh)
-        $blogs      = array_unique($blogs);     // remove duplicates
-        $selectblogs = '';
-        if (count($blogs) > 0)
-            $selectblogs = ' and i.iblog in (' . implode(',', $blogs) . ')';
-
-        if ($mode == '')
-        {
-            $query = 'SELECT i.inumber as itemid, i.ititle as title, i.ibody as body, m.mname as author, m.mrealname as authorname, i.itime, i.imore as more, m.mnumber as authorid, m.memail as authormail, m.murl as authorurl, c.cname as category, i.icat as catid, i.iclosed as closed';
-            if ($select)
-                $query .= ', '.$select. ' as score ';
-        } else {
-            $query = 'SELECT COUNT(*) as result ';
-        }
-
-        $query .= ' FROM '.sql_table('item').' as i, '.sql_table('member').' as m, '.sql_table('category').' as c'
-               . ' WHERE i.iauthor=m.mnumber'
-               . ' and i.icat=c.catid'
-               . ' and i.idraft=0'  // exclude drafts
-               . $selectblogs
-                    // don't show future items
-               . ' and i.itime<=' . mysqldate($this->getCorrectTime())
-               . ' and '.$where;
-
-        // take into account amount of months to search
-        if ($amountMonths > 0)
-        {
-            $localtime = getdate($this->getCorrectTime());
-            $timestamp_start = mktime(0,0,0,$localtime['mon'] - $amountMonths,1,$localtime['year']);
-            $query .= ' and i.itime>' . mysqldate($timestamp_start);
-        }
-
-        if ($mode == '')
-        {
-            if ($select)
-                $query .= ' ORDER BY score DESC';
-            else
-                $query .= ' ORDER BY i.itime DESC ';
-        }
-
-        return $query;
-    }
-
-    /**
-     * Returns the SQL query that's normally used to display the blog items on the index type skins
-     *
-     * @param $mode
-     *      either empty, or 'count'. In this case, the query will be a SELECT COUNT(*) query
-     * @returns
-     *      either a full SQL query, or an empty string
-     * @note
-     *      No LIMIT clause is added. (caller should add this if multiple pages are requested)
-     */
-    function getSqlBlog($extraQuery, $mode = '')
-    {
-        if ($mode == '')
-            $query = 'SELECT i.inumber as itemid, i.ititle as title, i.ibody as body, m.mname as author, m.mrealname as authorname, i.itime, i.imore as more, m.mnumber as authorid, m.memail as authormail, m.murl as authorurl, c.cname as category, i.icat as catid, i.iclosed as closed';
-        else
-            $query = 'SELECT COUNT(*) as result ';
-
-        $query .= ' FROM '.sql_table('item').' as i, '.sql_table('member').' as m, '.sql_table('category').' as c'
-               . ' WHERE i.iblog='.$this->blogid
-               . ' and i.iauthor=m.mnumber'
-               . ' and i.icat=c.catid'
-               . ' and i.idraft=0'  // exclude drafts
-                    // don't show future items
-               . ' and i.itime<=' . mysqldate($this->getCorrectTime());
-
-        if ($this->getSelectedCategory())
-            $query .= ' and i.icat=' . $this->getSelectedCategory() . ' ';
-
-
-        $query .= $extraQuery;
-
-        if ($mode == '')
-            $query .= ' ORDER BY i.itime DESC';
-
-        return $query;
-    }
-
-    /**
-      * Shows the archivelist using the given template
-      */
-    function showArchiveList($template, $mode = 'month', $limit = 0) {
-        global $CONF, $catid, $manager;
-
-        if (!isset ($linkparams)) {
-        $linkparams = array();
-        }
-
-        if ($catid) {
-            $linkparams = array('catid' => $catid);
-        }
-
-        $template =& $manager->getTemplate($template);
-        $data['blogid'] = $this->getID();
-
-        $tplt = isset($template['ARCHIVELIST_HEADER']) ? $template['ARCHIVELIST_HEADER']
-                                                       : '';
-        echo TEMPLATE::fill($tplt, $data);
-
-        $query = 'SELECT itime, SUBSTRING(itime,1,4) AS Year, SUBSTRING(itime,6,2) AS Month, SUBSTRING(itime,9,2) as Day FROM '.sql_table('item')
-        . ' WHERE iblog=' . $this->getID()
-        . ' and itime <=' . mysqldate($this->getCorrectTime())  // don't show future items!
-        . ' and idraft=0'; // don't show draft items
-
-        if ($catid)
-            $query .= ' and icat=' . intval($catid);
-
-        $query .= ' GROUP BY Year';
-        if ($mode == 'month' || $mode == 'day')
-            $query .= ', Month';
-        if ($mode == 'day')
-            $query .= ', Day';
-
-        $query .= ' ORDER BY itime DESC';
-
-        if ($limit > 0)
-            $query .= ' LIMIT ' . intval($limit);
-
-        $res = sql_query($query);
-
-        while ($current = sql_fetch_object($res)) {
-            $current->itime = strtotime($current->itime);   // string time -> unix timestamp
-
-            if ($mode == 'day') {
-                $archivedate      = date('Y-m-d',$current->itime);
-                $archive['day']   = date('d',$current->itime);
-                $data['day']      = date('d',$current->itime);
-                $data['month']    = date('m',$current->itime);
-                $archive['month'] = $data['month'];
-            } elseif ($mode == 'year') {
-                $archivedate      = date('Y',$current->itime);
-                $data['day']      = '';
-                $data['month']    = '';
-                $archive['day']   = '';
-                $archive['month'] = '';
-            } else {
-                $archivedate = date('Y-m',$current->itime);
-                $data['month'] = date('m',$current->itime);
-                $archive['month'] = $data['month'];
-                $data['day'] = '';
-                $archive['day'] = '';
-            }
-
-            $data['year'] = date('Y',$current->itime);
-            $archive['year'] = $data['year'];
-            $data['archivelink'] = createArchiveLink($this->getID(),$archivedate,$linkparams);
-
-            $manager->notify(
-                'PreArchiveListItem',
-                array(
-                    'listitem' => &$data
-                )
-            );
-
-            $temp = TEMPLATE::fill($template['ARCHIVELIST_LISTITEM'],$data);
-            echo strftime($temp,$current->itime);
-
-        }
-
-        sql_free_result($res);
-
-        $tplt = isset($template['ARCHIVELIST_FOOTER']) ? $template['ARCHIVELIST_FOOTER']
-                                                       : '';
-        echo TEMPLATE::fill($tplt, $data);
-    }
-
-
-    /**
-      * Shows the list of categories using a given template
-      */
-    function showCategoryList($template) {
-        global $CONF, $manager;
-
-        // determine arguments next to catids
-        // I guess this can be done in a better way, but it works
-        global $archive, $archivelist;
-
-        $linkparams = array();
-        if ($archive) {
-            $blogurl = createArchiveLink($this->getID(), $archive, '');
-            $linkparams['blogid'] = $this->getID();
-            $linkparams['archive'] = $archive;
-        } else if ($archivelist) {
-            $blogurl = createArchiveListLink($this->getID(), '');
-            $linkparams['archivelist'] = $archivelist;
-        } else {
-            $blogurl = createBlogidLink($this->getID(), '');
-            $linkparams['blogid'] = $this->getID();
-        }
-
-        //$blogurl = $this->getURL() . $qargs;
-        //$blogurl = createBlogLink($this->getURL(), $linkparams);
-
-        $template =& $manager->getTemplate($template);
-
-        echo TEMPLATE::fill((isset($template['CATLIST_HEADER']) ? $template['CATLIST_HEADER'] : null),
-                            array(
-                                'blogid' => $this->getID(),
-                                'blogurl' => $blogurl,
-                                'self' => $CONF['Self']
-                            ));
-
-        $query = 'SELECT catid, cdesc as catdesc, cname as catname FROM '.sql_table('category').' WHERE cblog=' . $this->getID() . ' ORDER BY cname ASC';
-        $res = sql_query($query);
-
-
-        while ($data = sql_fetch_assoc($res)) {
-            $data['blogid'] = $this->getID();
-            $data['blogurl'] = $blogurl;
-            $data['catlink'] = createLink(
-                                'category',
-                                array(
-                                    'catid' => $data['catid'],
-                                    'name' => $data['catname'],
-                                    'extra' => $linkparams
-                                )
-                               );
-            $data['self'] = $CONF['Self'];
-            
-            //catiscurrent
-            if ($this->getSelectedCategory()) {
-                if ($this->getSelectedCategory() == $data['catid']) {
-                    $data['catiscurrent'] = 'yes';
-                    $data['currentcat'] = 'yes';
-                }
-                else {
-                    $data['catiscurrent'] = 'no';
-                    $data['currentcat'] = 'no';
-                }
-            }
-            else {
-                global $itemid;
-                if (intval($itemid) && $manager->existsItem(intval($itemid),0,0)) {
-                    $iobj =& $manager->getItem(intval($itemid),0,0);
-                    $cid = $iobj['catid'];
-                    if ($cid == $data['catid']) {
-                        $data['catiscurrent'] = 'yes';
-                        $data['currentcat'] = 'yes';
-                    }
-                    else {
-                        $data['catiscurrent'] = 'no';
-                        $data['currentcat'] = 'no';
-                    }
-                }
-            }
-
-            $manager->notify(
-                'PreCategoryListItem',
-                array(
-                    'listitem' => &$data
-                )
-            );
-
-            echo TEMPLATE::fill((isset($template['CATLIST_LISTITEM']) ? $template['CATLIST_LISTITEM'] : null), $data);
-            //$temp = TEMPLATE::fill((isset($template['CATLIST_LISTITEM']) ? $template['CATLIST_LISTITEM'] : null), $data);
-            //echo strftime($temp, $current->itime);
-
-        }
-
-        sql_free_result($res);
-
-        echo TEMPLATE::fill((isset($template['CATLIST_FOOTER']) ? $template['CATLIST_FOOTER'] : null),
-                            array(
-                                'blogid' => $this->getID(),
-                                'blogurl' => $blogurl,
-                                'self' => $CONF['Self']
-                            ));
-    }
-
-    /**
-      * Shows a list of all blogs in the system using a given template
-      * ordered by  number, name, shortname or description
-      * in ascending or descending order
-      */
-    function showBlogList($template, $bnametype, $orderby, $direction) {
-        global $CONF, $manager;
-
-        switch ($orderby) {
-            case 'number':
-                $orderby='bnumber';
-                break;
-            case 'name':
-                $orderby='bname';
-                break;
-            case 'shortname':
-                $orderby='bshortname';
-                break;
-            case 'description':
-                $orderby='bdesc';
-                break;
-            default:
-                $orderby='bnumber';
-                break;
-        }
-
-        $direction=strtolower($direction);
-        switch ($direction) {
-            case 'asc':
-                $direction='ASC';
-                break;
-            case 'desc':
-                $direction='DESC';
-                break;
-            default:
-                $direction='ASC';
-                break;
-        }
-
-        $template =& $manager->getTemplate($template);
-
-        echo TEMPLATE::fill((isset($template['BLOGLIST_HEADER']) ? $template['BLOGLIST_HEADER'] : null),
-                            array(
-                                'sitename' => $CONF['SiteName'],
-                                'siteurl' => $CONF['IndexURL']
-                            ));
-
-        $query = 'SELECT bnumber, bname, bshortname, bdesc, burl FROM '.sql_table('blog').' ORDER BY '.$orderby.' '.$direction;
-        $res = sql_query($query);
-
-        while ($data = sql_fetch_assoc($res)) {
-
-            $list = array();
+               $temp = parse_url($CONF['Self']);
+               if ($temp['scheme']) {
+                       $mailto_msg .= createItemLink($itemid) . "\n\n";
+               } else {
+                       $tempurl = $this->getURL();
+                       if (substr($tempurl, -1) == '/' || substr($tempurl, -4) == '.php') {
+                               $mailto_msg .= $tempurl . '?itemid=' . $itemid . "\n\n";
+                       } else {
+                               $mailto_msg .= $tempurl . '/?itemid=' . $itemid . "\n\n";
+                       }
+               }
+               $mailto_msg .= _NOTIFY_TITLE . ' ' . strip_tags($title) . "\n";
+               $mailto_msg .= _NOTIFY_CONTENTS . "\n " . $ascii . "\n";
+               $mailto_msg .= getMailFooter();
+
+               $mailto_title = $this->getName() . ': ' . _NOTIFY_NI_TITLE;
+
+               $frommail = $member->getNotifyFromMailAddress();
+
+               $notify =& new NOTIFICATION($this->getNotifyAddress());
+               $notify->notify($mailto_title, $mailto_msg , $frommail);
+
+
+
+       }
+
+
+       /**
+         * Creates a new category for this blog
+         *
+         * @param $catName
+         *      name of the new category. When empty, a name is generated automatically
+         *      (starting with newcat)
+         * @param $catDescription
+         *      description of the new category. Defaults to 'New Category'
+         *
+         * @returns
+         *      the new category-id in case of success.
+         *      0 on failure
+         */
+       function createNewCategory($catName = '', $catDescription = _CREATED_NEW_CATEGORY_DESC) {
+               global $member, $manager;
+
+               if ($member->blogAdminRights($this->getID())) {
+                       // generate
+                       if ($catName == '')
+                       {
+                               $catName = _CREATED_NEW_CATEGORY_NAME;
+                               $i = 1;
+
+                               $res = sql_query('SELECT * FROM '.sql_table('category')." WHERE cname='".$catName.$i."' and cblog=".$this->getID());
+                               while (sql_num_rows($res) > 0)
+                               {
+                                       $i++;
+                                       $res = sql_query('SELECT * FROM '.sql_table('category')." WHERE cname='".$catName.$i."' and cblog=".$this->getID());
+                               }
+
+                               $catName = $catName . $i;
+                       }
+
+                       $manager->notify(
+                               'PreAddCategory',
+                               array(
+                                       'blog' => &$this,
+                                       'name' => &$catName,
+                                       'description' => $catDescription
+                               )
+                       );
+
+                       $query = 'INSERT INTO '.sql_table('category').' (cblog, cname, cdesc) VALUES (' . $this->getID() . ", '" . sql_real_escape_string($catName) . "', '" . sql_real_escape_string($catDescription) . "')";
+                       sql_query($query);
+                       $catid = sql_insert_id();
+
+                       $manager->notify(
+                               'PostAddCategory',
+                               array(
+                                       'blog' => &$this,
+                                       'name' => $catName,
+                                       'description' => $catDescription,
+                                       'catid' => $catid
+                               )
+                       );
+
+                       return $catid;
+               } else {
+                       return 0;
+               }
+
+       }
+
+
+       /**
+        * Searches all months of this blog for the given query
+        *
+        * @param $query
+        *        search query
+        * @param $template
+        *        template to be used (__NAME__ of the template)
+        * @param $amountMonths
+        *        max amount of months to be search (0 = all)
+        * @param $maxresults
+        *        max number of results to show
+        * @param $startpos
+        *        offset
+        * @returns
+        *        amount of hits found
+        */
+       function search($query, $template, $amountMonths, $maxresults, $startpos) {
+               global $CONF, $manager;
+
+               $highlight  = '';
+               $sqlquery   = $this->getSqlSearch($query, $amountMonths, $highlight);
+
+               if ($sqlquery == '')
+               {
+                       // no query -> show everything
+                       $extraquery = '';
+                       $amountfound = $this->readLogAmount($template, $maxresults, $extraQuery, $query, 1, 1);
+               } else {
+
+                       // add LIMIT to query (to split search results into pages)
+                       if (intval($maxresults > 0))
+                               $sqlquery .= ' LIMIT ' . intval($startpos).',' . intval($maxresults);
+
+                       // show results
+                       $amountfound = $this->showUsingQuery($template, $sqlquery, $highlight, 1, 1);
+
+                       // when no results were found, show a message
+                       if ($amountfound == 0)
+                       {
+                               $template =& $manager->getTemplate($template);
+                               $vars = array(
+                                       'query'  => htmlspecialchars($query),
+                                       'blogid'        => $this->getID()
+                               );
+                               echo TEMPLATE::fill($template['SEARCH_NOTHINGFOUND'],$vars);
+                       }
+               }
+
+               return $amountfound;
+       }
+
+       /**
+        * Returns an SQL query to use for a search query
+        *
+        * @param $query
+        *        search query
+        * @param $amountMonths
+        *        amount of months to search back. Default = 0 = unlimited
+        * @param $mode
+        *        either empty, or 'count'. In this case, the query will be a SELECT COUNT(*) query
+        * @returns $highlight
+        *        words to highlight (out parameter)
+        * @returns
+        *        either a full SQL query, or an empty string (if querystring empty)
+        * @note
+        *        No LIMIT clause is added. (caller should add this if multiple pages are requested)
+        */
+       function getSqlSearch($query, $amountMonths = 0, &$highlight, $mode = '')
+       {
+               $searchclass =& new SEARCH($query);
+
+               $highlight      = $searchclass->inclusive;
+
+               // if querystring is empty, return empty string
+               if ($searchclass->inclusive == '')
+                       return '';
+
+
+               $where  = $searchclass->boolean_sql_where('ititle,ibody,imore');
+               $select = $searchclass->boolean_sql_select('ititle,ibody,imore');
+
+               // get list of blogs to search
+               $blogs    = $searchclass->blogs;          // array containing blogs that always need to be included
+               $blogs[]        = $this->getID();                  // also search current blog (duh)
+               $blogs    = array_unique($blogs);        // remove duplicates
+               $selectblogs = '';
+               if (count($blogs) > 0)
+                       $selectblogs = ' and i.iblog in (' . implode(',', $blogs) . ')';
+
+               if ($mode == '')
+               {
+                       $query = 'SELECT i.inumber as itemid, i.ititle as title, i.ibody as body, m.mname as author, m.mrealname as authorname, i.itime, i.imore as more, m.mnumber as authorid, m.memail as authormail, m.murl as authorurl, c.cname as category, i.icat as catid, i.iclosed as closed';
+                       if ($select)
+                               $query .= ', '.$select. ' as score ';
+               } else {
+                       $query = 'SELECT COUNT(*) as result ';
+               }
+
+               $query .= ' FROM '.sql_table('item').' as i, '.sql_table('member').' as m, '.sql_table('category').' as c'
+                          . ' WHERE i.iauthor=m.mnumber'
+                          . ' and i.icat=c.catid'
+                          . ' and i.idraft=0'  // exclude drafts
+                          . $selectblogs
+                                       // don't show future items
+                          . ' and i.itime<=' . mysqldate($this->getCorrectTime())
+                          . ' and '.$where;
+
+               // take into account amount of months to search
+               if ($amountMonths > 0)
+               {
+                       $localtime = getdate($this->getCorrectTime());
+                       $timestamp_start = mktime(0,0,0,$localtime['mon'] - $amountMonths,1,$localtime['year']);
+                       $query .= ' and i.itime>' . mysqldate($timestamp_start);
+               }
+
+               if ($mode == '')
+               {
+                       if ($select)
+                               $query .= ' ORDER BY score DESC';
+                       else
+                               $query .= ' ORDER BY i.itime DESC ';
+               }
+
+               return $query;
+       }
+
+       /**
+        * Returns the SQL query that's normally used to display the blog items on the index type skins
+        *
+        * @param $mode
+        *        either empty, or 'count'. In this case, the query will be a SELECT COUNT(*) query
+        * @returns
+        *        either a full SQL query, or an empty string
+        * @note
+        *        No LIMIT clause is added. (caller should add this if multiple pages are requested)
+        */
+       function getSqlBlog($extraQuery, $mode = '')
+       {
+               if ($mode == '')
+                       $query = 'SELECT i.inumber as itemid, i.ititle as title, i.ibody as body, m.mname as author, m.mrealname as authorname, i.itime, i.imore as more, m.mnumber as authorid, m.memail as authormail, m.murl as authorurl, c.cname as category, i.icat as catid, i.iclosed as closed';
+               else
+                       $query = 'SELECT COUNT(*) as result ';
+
+               $query .= ' FROM '.sql_table('item').' as i, '.sql_table('member').' as m, '.sql_table('category').' as c'
+                          . ' WHERE i.iblog='.$this->blogid
+                          . ' and i.iauthor=m.mnumber'
+                          . ' and i.icat=c.catid'
+                          . ' and i.idraft=0'  // exclude drafts
+                                       // don't show future items
+                          . ' and i.itime<=' . mysqldate($this->getCorrectTime());
+
+               if ($this->getSelectedCategory())
+                       $query .= ' and i.icat=' . $this->getSelectedCategory() . ' ';
+
+
+               $query .= $extraQuery;
+
+               if ($mode == '')
+                       $query .= ' ORDER BY i.itime DESC';
+
+               return $query;
+       }
+
+       /**
+         * Shows the archivelist using the given template
+         */
+       function showArchiveList($template, $mode = 'month', $limit = 0) {
+               global $CONF, $catid, $manager;
+
+               if (!isset ($linkparams)) {
+               $linkparams = array();
+               }
+
+               if ($catid) {
+                       $linkparams = array('catid' => $catid);
+               }
+
+               $template =& $manager->getTemplate($template);
+               $data['blogid'] = $this->getID();
+
+               $tplt = isset($template['ARCHIVELIST_HEADER']) ? $template['ARCHIVELIST_HEADER']
+                                                                                                          : '';
+               echo TEMPLATE::fill($tplt, $data);
+
+               $query = 'SELECT itime, SUBSTRING(itime,1,4) AS Year, SUBSTRING(itime,6,2) AS Month, SUBSTRING(itime,9,2) as Day FROM '.sql_table('item')
+               . ' WHERE iblog=' . $this->getID()
+               . ' and itime <=' . mysqldate($this->getCorrectTime())  // don't show future items!
+               . ' and idraft=0'; // don't show draft items
+
+               if ($catid)
+                       $query .= ' and icat=' . intval($catid);
+
+               $query .= ' GROUP BY Year';
+               if ($mode == 'month' || $mode == 'day')
+                       $query .= ', Month';
+               if ($mode == 'day')
+                       $query .= ', Day';
+
+               $query .= ' ORDER BY itime DESC';
+
+               if ($limit > 0)
+                       $query .= ' LIMIT ' . intval($limit);
+
+               $res = sql_query($query);
+
+               while ($current = sql_fetch_object($res)) {
+                       $current->itime = strtotime($current->itime);   // string time -> unix timestamp
+
+                       if ($mode == 'day') {
+                               $archivedate      = date('Y-m-d',$current->itime);
+                               $archive['day']   = date('d',$current->itime);
+                               $data['day']      = date('d',$current->itime);
+                               $data['month']  = date('m',$current->itime);
+                               $archive['month'] = $data['month'];
+                       } elseif ($mode == 'year') {
+                               $archivedate      = date('Y',$current->itime);
+                               $data['day']      = '';
+                               $data['month']  = '';
+                               $archive['day']   = '';
+                               $archive['month'] = '';
+                       } else {
+                               $archivedate = date('Y-m',$current->itime);
+                               $data['month'] = date('m',$current->itime);
+                               $archive['month'] = $data['month'];
+                               $data['day'] = '';
+                               $archive['day'] = '';
+                       }
+
+                       $data['year'] = date('Y',$current->itime);
+                       $archive['year'] = $data['year'];
+                       $data['archivelink'] = createArchiveLink($this->getID(),$archivedate,$linkparams);
+
+                       $manager->notify(
+                               'PreArchiveListItem',
+                               array(
+                                       'listitem' => &$data
+                               )
+                       );
+
+                       $temp = TEMPLATE::fill($template['ARCHIVELIST_LISTITEM'],$data);
+                       echo strftime($temp,$current->itime);
+
+               }
+
+               sql_free_result($res);
+
+               $tplt = isset($template['ARCHIVELIST_FOOTER']) ? $template['ARCHIVELIST_FOOTER']
+                                                                                                          : '';
+               echo TEMPLATE::fill($tplt, $data);
+       }
+
+
+       /**
+         * Shows the list of categories using a given template
+         */
+       function showCategoryList($template) {
+               global $CONF, $manager;
+
+               // determine arguments next to catids
+               // I guess this can be done in a better way, but it works
+               global $archive, $archivelist;
+
+               $linkparams = array();
+               if ($archive) {
+                       $blogurl = createArchiveLink($this->getID(), $archive, '');
+                       $linkparams['blogid'] = $this->getID();
+                       $linkparams['archive'] = $archive;
+               } else if ($archivelist) {
+                       $blogurl = createArchiveListLink($this->getID(), '');
+                       $linkparams['archivelist'] = $archivelist;
+               } else {
+                       $blogurl = createBlogidLink($this->getID(), '');
+                       $linkparams['blogid'] = $this->getID();
+               }
+
+               //$blogurl = $this->getURL() . $qargs;
+               //$blogurl = createBlogLink($this->getURL(), $linkparams);
+
+               $template =& $manager->getTemplate($template);
+
+               echo TEMPLATE::fill((isset($template['CATLIST_HEADER']) ? $template['CATLIST_HEADER'] : null),
+                                                       array(
+                                                               'blogid' => $this->getID(),
+                                                               'blogurl' => $blogurl,
+                                                               'self' => $CONF['Self']
+                                                       ));
+
+               $query = 'SELECT catid, cdesc as catdesc, cname as catname FROM '.sql_table('category').' WHERE cblog=' . $this->getID() . ' ORDER BY cname ASC';
+               $res = sql_query($query);
+
+
+               while ($data = sql_fetch_assoc($res)) {
+                       $data['blogid'] = $this->getID();
+                       $data['blogurl'] = $blogurl;
+                       $data['catlink'] = createLink(
+                                                               'category',
+                                                               array(
+                                                                       'catid' => $data['catid'],
+                                                                       'name' => $data['catname'],
+                                                                       'extra' => $linkparams
+                                                               )
+                                                          );
+                       $data['self'] = $CONF['Self'];
+                       
+                       //catiscurrent
+                       if ($this->getSelectedCategory()) {
+                               if ($this->getSelectedCategory() == $data['catid']) {
+                                       $data['catiscurrent'] = 'yes';
+                                       $data['currentcat'] = 'yes';
+                               }
+                               else {
+                                       $data['catiscurrent'] = 'no';
+                                       $data['currentcat'] = 'no';
+                               }
+                       }
+                       else {
+                               global $itemid;
+                               if (intval($itemid) && $manager->existsItem(intval($itemid),0,0)) {
+                                       $iobj =& $manager->getItem(intval($itemid),0,0);
+                                       $cid = $iobj['catid'];
+                                       if ($cid == $data['catid']) {
+                                               $data['catiscurrent'] = 'yes';
+                                               $data['currentcat'] = 'yes';
+                                       }
+                                       else {
+                                               $data['catiscurrent'] = 'no';
+                                               $data['currentcat'] = 'no';
+                                       }
+                               }
+                       }
+
+                       $manager->notify(
+                               'PreCategoryListItem',
+                               array(
+                                       'listitem' => &$data
+                               )
+                       );
+
+                       echo TEMPLATE::fill((isset($template['CATLIST_LISTITEM']) ? $template['CATLIST_LISTITEM'] : null), $data);
+                       //$temp = TEMPLATE::fill((isset($template['CATLIST_LISTITEM']) ? $template['CATLIST_LISTITEM'] : null), $data);
+                       //echo strftime($temp, $current->itime);
+
+               }
+
+               sql_free_result($res);
+
+               echo TEMPLATE::fill((isset($template['CATLIST_FOOTER']) ? $template['CATLIST_FOOTER'] : null),
+                                                       array(
+                                                               'blogid' => $this->getID(),
+                                                               'blogurl' => $blogurl,
+                                                               'self' => $CONF['Self']
+                                                       ));
+       }
+
+       /**
+         * Shows a list of all blogs in the system using a given template
+         * ordered by  number, name, shortname or description
+         * in ascending or descending order
+         */
+       function showBlogList($template, $bnametype, $orderby, $direction) {
+               global $CONF, $manager;
+
+               switch ($orderby) {
+                       case 'number':
+                               $orderby='bnumber';
+                               break;
+                       case 'name':
+                               $orderby='bname';
+                               break;
+                       case 'shortname':
+                               $orderby='bshortname';
+                               break;
+                       case 'description':
+                               $orderby='bdesc';
+                               break;
+                       default:
+                               $orderby='bnumber';
+                               break;
+               }
+
+               $direction=strtolower($direction);
+               switch ($direction) {
+                       case 'asc':
+                               $direction='ASC';
+                               break;
+                       case 'desc':
+                               $direction='DESC';
+                               break;
+                       default:
+                               $direction='ASC';
+                               break;
+               }
+
+               $template =& $manager->getTemplate($template);
+
+               echo TEMPLATE::fill((isset($template['BLOGLIST_HEADER']) ? $template['BLOGLIST_HEADER'] : null),
+                                                       array(
+                                                               'sitename' => $CONF['SiteName'],
+                                                               'siteurl' => $CONF['IndexURL']
+                                                       ));
+
+               $query = 'SELECT bnumber, bname, bshortname, bdesc, burl FROM '.sql_table('blog').' ORDER BY '.$orderby.' '.$direction;
+               $res = sql_query($query);
+
+               while ($data = sql_fetch_assoc($res)) {
+
+                       $list = array();
 
 //                     $list['bloglink'] = createLink('blog', array('blogid' => $data['bnumber']));
-            $list['bloglink'] = createBlogidLink($data['bnumber']);
-
-            $list['blogdesc'] = $data['bdesc'];
-
-            $list['blogurl'] = $data['burl'];
-
-            if ($bnametype=='shortname') {
-                $list['blogname'] = $data['bshortname'];
-            }
-            else { // all other cases
-                $list['blogname'] = $data['bname'];
-            }
-
-            $manager->notify(
-                'PreBlogListItem',
-                array(
-                    'listitem' => &$list
-                )
-            );
-
-            echo TEMPLATE::fill((isset($template['BLOGLIST_LISTITEM']) ? $template['BLOGLIST_LISTITEM'] : null), $list);
-
-        }
-
-        sql_free_result($res);
-
-        echo TEMPLATE::fill((isset($template['BLOGLIST_FOOTER']) ? $template['BLOGLIST_FOOTER'] : null),
-                            array(
-                                'sitename' => $CONF['SiteName'],
-                                'siteurl' => $CONF['IndexURL']
-                            ));
-
-    }
-
-    /**
-      * Blogsettings functions
-      */
-
-    function readSettings() {
-        $query =  'SELECT *'
-               . ' FROM '.sql_table('blog')
-               . ' WHERE bnumber=' . $this->blogid;
-        $res = sql_query($query);
-
-        $this->isValid = (sql_num_rows($res) > 0);
-        if (!$this->isValid)
-            return;
-
-        $this->settings = sql_fetch_assoc($res);
-    }
-
-    function writeSettings() {
-
-        // (can't use floatval since not available prior to PHP 4.2)
-        $offset = $this->getTimeOffset();
-        if (!is_float($offset))
-            $offset = intval($offset);
-
-        $query =  'UPDATE '.sql_table('blog')
-               . " SET bname='" . addslashes($this->getName()) . "',"
-               . "     bshortname='". addslashes($this->getShortName()) . "',"
-               . "     bcomments=". intval($this->commentsEnabled()) . ","
-               . "     bmaxcomments=" . intval($this->getMaxComments()) . ","
-               . "     btimeoffset=" . $offset . ","
-               . "     bpublic=" . intval($this->isPublic()) . ","
-               . "     breqemail=" . intval($this->emailRequired()) . ","
-               . "     bconvertbreaks=" . intval($this->convertBreaks()) . ","
-               . "     ballowpast=" . intval($this->allowPastPosting()) . ","
-               . "     bnotify='" . addslashes($this->getNotifyAddress()) . "',"
-               . "     bnotifytype=" . intval($this->getNotifyType()) . ","
-               . "     burl='" . addslashes($this->getURL()) . "',"
-               . "     bupdate='" . addslashes($this->getUpdateFile()) . "',"
-               . "     bdesc='" . addslashes($this->getDescription()) . "',"
-               . "     bdefcat=" . intval($this->getDefaultCategory()) . ","
-               . "     bdefskin=" . intval($this->getDefaultSkin()) . ","
-               . "     bincludesearch=" . intval($this->getSearchable())
-               . " WHERE bnumber=" . intval($this->getID());
-        sql_query($query);
-
-    }
-
-
-
-    // update update file if requested
-    function updateUpdatefile() {
-         if ($this->getUpdateFile()) {
-            $f_update = fopen($this->getUpdateFile(),'w');
-            fputs($f_update,$this->getCorrectTime());
-            fclose($f_update);
-         }
-
-    }
-
-    function isValidCategory($catid) {
-        $query = 'SELECT * FROM '.sql_table('category').' WHERE cblog=' . $this->getID() . ' and catid=' . intval($catid);
-        $res = sql_query($query);
-        return (sql_num_rows($res) != 0);
-    }
-
-    function getCategoryName($catid) {
-        $res = sql_query('SELECT cname FROM '.sql_table('category').' WHERE cblog='.$this->getID().' and catid=' . intval($catid));
-        $o = sql_fetch_object($res);
-        return $o->cname;
-    }
-
-    function getCategoryDesc($catid) {
-        $res = sql_query('SELECT cdesc FROM '.sql_table('category').' WHERE cblog='.$this->getID().' and catid=' . intval($catid));
-        $o = sql_fetch_object($res);
-        return $o->cdesc;
-    }
-
-    function getCategoryIdFromName($name) {
-        $res = sql_query('SELECT catid FROM '.sql_table('category').' WHERE cblog='.$this->getID().' and cname="' . addslashes($name) . '"');
-        if (sql_num_rows($res) > 0) {
-            $o = sql_fetch_object($res);
-            return $o->catid;
-        } else {
-            return $this->getDefaultCategory();
-        }
-    }
-
-    function convertBreaks() {
-        return $this->getSetting('bconvertbreaks');
-    }
-
-    function insertJavaScriptInfo($authorid = '') {
-        global $member, $CONF;
-
-        if ($authorid == '')
-            $authorid = $member->getID();
-
-        ?>
-        <script type="text/javascript">
-            setConvertBreaks(<?php echo  $this->convertBreaks() ? 'true' : 'false' ?>);
-            setMediaUrl("<?php echo $CONF['MediaURL']?>");
-            setAuthorId(<?php echo $authorid?>);
-        </script><?php  }
-
-    function setConvertBreaks($val) {
-        $this->setSetting('bconvertbreaks',$val);
-    }
-    function setAllowPastPosting($val) {
-        $this->setSetting('ballowpast',$val);
-    }
-    function allowPastPosting() {
-        return $this->getSetting('ballowpast');
-    }
-
-    function getCorrectTime($t=0) {
-        if ($t == 0) $t = time();
-        return ($t + 3600 * $this->getTimeOffset());
-    }
-
-    function getName() {
-        return $this->getSetting('bname');
-    }
-
-    function getShortName() {
-        return $this->getSetting('bshortname');
-    }
-
-    function getMaxComments() {
-        return $this->getSetting('bmaxcomments');
-    }
-
-    function getNotifyAddress() {
-        return $this->getSetting('bnotify');
-    }
-
-    function getNotifyType() {
-        return $this->getSetting('bnotifytype');
-    }
-
-    function notifyOnComment() {
-        $n = $this->getNotifyType();
-        return (($n != 0) && (($n % 3) == 0));
-    }
-
-    function notifyOnVote() {
-        $n = $this->getNotifyType();
-        return (($n != 0) && (($n % 5) == 0));
-    }
-
-    function notifyOnNewItem() {
-        $n = $this->getNotifyType();
-        return (($n != 0) && (($n % 7) == 0));
-    }
-
-    function setNotifyType($val) {
-        $this->setSetting('bnotifytype',$val);
-    }
-
-
-    function getTimeOffset() {
-        return $this->getSetting('btimeoffset');
-    }
-
-    function commentsEnabled() {
-        return $this->getSetting('bcomments');
-    }
-
-    function getURL() {
-        return $this->getSetting('burl');
-    }
-
-    function getDefaultSkin() {
-        return $this->getSetting('bdefskin');
-    }
-
-    function getUpdateFile() {
-        return $this->getSetting('bupdate');
-    }
-
-    function getDescription() {
-        return $this->getSetting('bdesc');
-    }
-
-    function isPublic() {
-        return $this->getSetting('bpublic');
-    }
-
-    function emailRequired() {
-        return $this->getSetting('breqemail');
-    }
-
-    function getSearchable() {
-        return $this->getSetting('bincludesearch');
-    }
-
-    function getDefaultCategory() {
-        return $this->getSetting('bdefcat');
-    }
-
-    function setPublic($val) {
-        $this->setSetting('bpublic',$val);
-    }
-
-    function setSearchable($val) {
-        $this->setSetting('bincludesearch',$val);
-    }
-
-    function setDescription($val) {
-        $this->setSetting('bdesc',$val);
-    }
-
-    function setUpdateFile($val) {
-        $this->setSetting('bupdate',$val);
-    }
-
-    function setDefaultSkin($val) {
-        $this->setSetting('bdefskin',$val);
-    }
-
-    function setURL($val) {
-        $this->setSetting('burl',$val);
-    }
-
-    function setName($val) {
-        $this->setSetting('bname',$val);
-    }
-
-    function setShortName($val) {
-        $this->setSetting('bshortname',$val);
-    }
-
-    function setCommentsEnabled($val) {
-        $this->setSetting('bcomments',$val);
-    }
-
-    function setMaxComments($val) {
-        $this->setSetting('bmaxcomments',$val);
-    }
-
-    function setNotifyAddress($val) {
-        $this->setSetting('bnotify',$val);
-    }
-
-    function setEmailRequired($val) {
-        $this->setSetting('breqemail',$val);
-    }
-
-    function setTimeOffset($val) {
-        // check validity of value
-        // 1. replace , by . (common mistake)
-        $val = str_replace(',','.',$val);
-        // 2. cast to float or int
-        if (is_numeric($val) && strstr($val,'.5')) {
-            $val = (float) $val;
-        } else {
-            $val = intval($val);
-        }
-
-        $this->setSetting('btimeoffset',$val);
-    }
-
-    function setDefaultCategory($val) {
-        $this->setSetting('bdefcat',$val);
-    }
-
-    function getSetting($key) {
-        return $this->settings[$key];
-    }
-
-    function setSetting($key,$value) {
-        $this->settings[$key] = $value;
-    }
-
-
-    // tries to add a member to the team. Returns false if the member was already on
-    // the team
-    function addTeamMember($memberid, $admin) {
-        global $manager;
-
-        $memberid = intval($memberid);
-        $admin = intval($admin);
-
-        // check if member is already a member
-        $tmem = MEMBER::createFromID($memberid);
-
-        if ($tmem->isTeamMember($this->getID()))
-            return 0;
-
-        $manager->notify(
-            'PreAddTeamMember',
-            array(
-                'blog' => &$this,
-                'member' => &$tmem,
-                'admin' => &$admin
-            )
-        );
-
-        // add to team
-        $query = 'INSERT INTO '.sql_table('team').' (TMEMBER, TBLOG, TADMIN) '
-               . 'VALUES (' . $memberid .', '.$this->getID().', "'.$admin.'")';
-        sql_query($query);
-
-        $manager->notify(
-            'PostAddTeamMember',
-            array(
-                'blog' => &$this,
-                'member' => &$tmem,
-                'admin' => $admin
-            )
-
-        );
-
-        $logMsg = sprintf(_TEAM_ADD_NEWTEAMMEMBER, $tmem->getDisplayName(), $memberid, $this->getName());
-        ACTIONLOG::add(INFO, $logMsg);
-
-        return 1;
-    }
-
-    function getID() {
-        return intVal($this->blogid);
-    }
-
-    // returns true if there is a blog with the given shortname (static)
-    function exists($name) {
-        $r = sql_query('select * FROM '.sql_table('blog').' WHERE bshortname="'.addslashes($name).'"');
-        return (sql_num_rows($r) != 0);
-    }
-
-    // returns true if there is a blog with the given ID (static)
-    function existsID($id) {
-        $r = sql_query('select * FROM '.sql_table('blog').' WHERE bnumber='.intval($id));
-        return (sql_num_rows($r) != 0);
-    }
-
-        // flag there is a future post pending
-        function setFuturePost() {
-        $query =  'UPDATE '.sql_table('blog')
-               . " SET bfuturepost='1' WHERE bnumber=" . $this->getID();
-        sql_query($query);
-        }
-
-    // clear there is a future post pending
-    function clearFuturePost() {
-        $query =  'UPDATE '.sql_table('blog')
-               . " SET bfuturepost='0' WHERE bnumber=" . $this->getID();
-        sql_query($query);
-    }
-
-    // check if we should throw justPosted event
-    function checkJustPosted() {
-        global $manager;
-
-        if ($this->settings['bfuturepost'] == 1) {
-            $blogid = $this->getID();
-            $result = sql_query("SELECT * FROM " . sql_table('item')
-                      . " WHERE iposted=0 AND iblog=" . $blogid . " AND itime<NOW()");
-            if (sql_num_rows($result) > 0) {
-                // This $pinged is allow a plugin to tell other hook to the event that a ping is sent already
-                // Note that the plugins's calling order is subject to thri order in the plugin list
-                $pinged = false;
-                $manager->notify(
-                        'JustPosted',
-                        array('blogid' => $blogid,
-                        'pinged' => &$pinged
-                        )
-                );
-
-                // clear all expired future posts
-                sql_query("UPDATE " . sql_table('item') . " SET iposted='1' WHERE iblog=" . $blogid . " AND itime<NOW()");
-
-                // check to see any pending future post, clear the flag is none
-                $result = sql_query("SELECT * FROM " . sql_table('item')
-                          . " WHERE iposted=0 AND iblog=" . $blogid);
-                if (sql_num_rows($result) == 0) {
-                    $this->clearFuturePost();
-                }
-            }
-        }
-    }
-
-    /**
-     * Shows the given list of items for this blog
-     *
-     * @param $itemarray
-     *      array of item numbers to be displayed
-     * @param $template
-     *      String representing the template _NAME_ (!)
-     * @param $highlight
-     *      contains a query that should be highlighted
-     * @param $comments
-     *      1=show comments 0=don't show comments
-     * @param $dateheads
-     *      1=show dateheads 0=don't show dateheads
-     * @returns int
-     *      amount of items shown
-     */
-    function readLogFromList($itemarray, $template, $highlight = '', $comments = 1, $dateheads = 1) {
-
-        $query = $this->getSqlItemList($itemarray);
-
-        return $this->showUsingQuery($template, $query, $highlight, $comments, $dateheads);
-    }
-
-    /**
-     * Returns the SQL query used to fill out templates for a list of items
-     *
-     * @param $itemarray
-     *      an array holding the item numbers of the items to be displayed
-     * @returns
-     *      either a full SQL query, or an empty string
-     * @note
-     *      No LIMIT clause is added. (caller should add this if multiple pages are requested)
-     */
-    function getSqlItemList($itemarray)
-    {
-        if (!is_array($itemarray)) return '';
-        $items = array();
-        foreach ($itemarray as $value) {
-            if (intval($value)) $items[] = intval($value);
-        }
-        if (!count($items)) return '';
-        //$itemlist = implode(',',$items);
-        $i = count($items);
-        $query = '';
-        foreach ($items as $value) {
-            $query .= '('
-                    .   'SELECT'
-                    .   ' i.inumber as itemid,'
-                    .   ' i.ititle as title,'
-                    .   ' i.ibody as body,'
-                    .   ' m.mname as author,'
-                    .   ' m.mrealname as authorname,'
-                    .   ' i.itime,'
-                    .   ' i.imore as more,'
-                    .   ' m.mnumber as authorid,'
-                    .   ' m.memail as authormail,'
-                    .   ' m.murl as authorurl,'
-                    .   ' c.cname as category,'
-                    .   ' i.icat as catid,'
-                    .   ' i.iclosed as closed';
-
-            $query .= ' FROM '
-                    . sql_table('item') . ' as i, '
-                    . sql_table('member') . ' as m, '
-                    . sql_table('category').' as c'
-                    . ' WHERE'
-                    .     ' i.iblog   = ' . $this->blogid
-                    . ' and i.iauthor = m.mnumber'
-                    . ' and i.icat    = c.catid'
-                    . ' and i.idraft  = 0'  // exclude drafts
-                        // don't show future items
-                    . ' and i.itime  <= ' . mysqldate($this->getCorrectTime());
-
-            //$query .= ' and i.inumber IN ('.$itemlist.')';
-            $query .= ' and i.inumber = '.intval($value);
-            $query .= ')';
-            $i--;
-            if ($i) $query .= ' UNION ';
-        }
-
-        return $query;
-    }
+                       $list['bloglink'] = createBlogidLink($data['bnumber']);
+
+                       $list['blogdesc'] = $data['bdesc'];
+
+                       $list['blogurl'] = $data['burl'];
+
+                       if ($bnametype=='shortname') {
+                               $list['blogname'] = $data['bshortname'];
+                       }
+                       else { // all other cases
+                               $list['blogname'] = $data['bname'];
+                       }
+
+                       $manager->notify(
+                               'PreBlogListItem',
+                               array(
+                                       'listitem' => &$list
+                               )
+                       );
+
+                       echo TEMPLATE::fill((isset($template['BLOGLIST_LISTITEM']) ? $template['BLOGLIST_LISTITEM'] : null), $list);
+
+               }
+
+               sql_free_result($res);
+
+               echo TEMPLATE::fill((isset($template['BLOGLIST_FOOTER']) ? $template['BLOGLIST_FOOTER'] : null),
+                                                       array(
+                                                               'sitename' => $CONF['SiteName'],
+                                                               'siteurl' => $CONF['IndexURL']
+                                                       ));
+
+       }
+
+       /**
+         * Blogsettings functions
+         */
+
+       function readSettings() {
+               $query =  'SELECT *'
+                          . ' FROM '.sql_table('blog')
+                          . ' WHERE bnumber=' . $this->blogid;
+               $res = sql_query($query);
+
+               $this->isValid = (sql_num_rows($res) > 0);
+               if (!$this->isValid)
+                       return;
+
+               $this->settings = sql_fetch_assoc($res);
+       }
+
+       function writeSettings() {
+
+               // (can't use floatval since not available prior to PHP 4.2)
+               $offset = $this->getTimeOffset();
+               if (!is_float($offset))
+                       $offset = intval($offset);
+
+               $query =  'UPDATE '.sql_table('blog')
+                          . " SET bname='" . sql_real_escape_string($this->getName()) . "',"
+                          . "   bshortname='". sql_real_escape_string($this->getShortName()) . "',"
+                          . "   bcomments=". intval($this->commentsEnabled()) . ","
+                          . "   bmaxcomments=" . intval($this->getMaxComments()) . ","
+                          . "   btimeoffset=" . $offset . ","
+                          . "   bpublic=" . intval($this->isPublic()) . ","
+                          . "   breqemail=" . intval($this->emailRequired()) . ","
+                          . "   bconvertbreaks=" . intval($this->convertBreaks()) . ","
+                          . "   ballowpast=" . intval($this->allowPastPosting()) . ","
+                          . "   bnotify='" . sql_real_escape_string($this->getNotifyAddress()) . "',"
+                          . "   bnotifytype=" . intval($this->getNotifyType()) . ","
+                          . "   burl='" . sql_real_escape_string($this->getURL()) . "',"
+                          . "   bupdate='" . sql_real_escape_string($this->getUpdateFile()) . "',"
+                          . "   bdesc='" . sql_real_escape_string($this->getDescription()) . "',"
+                          . "   bdefcat=" . intval($this->getDefaultCategory()) . ","
+                          . "   bdefskin=" . intval($this->getDefaultSkin()) . ","
+                          . "   bincludesearch=" . intval($this->getSearchable())
+                          . " WHERE bnumber=" . intval($this->getID());
+               sql_query($query);
+
+       }
+
+
+
+       // update update file if requested
+       function updateUpdatefile() {
+                if ($this->getUpdateFile()) {
+                       $f_update = fopen($this->getUpdateFile(),'w');
+                       fputs($f_update,$this->getCorrectTime());
+                       fclose($f_update);
+                }
+
+       }
+
+       function isValidCategory($catid) {
+               $query = 'SELECT * FROM '.sql_table('category').' WHERE cblog=' . $this->getID() . ' and catid=' . intval($catid);
+               $res = sql_query($query);
+               return (sql_num_rows($res) != 0);
+       }
+
+       function getCategoryName($catid) {
+               $res = sql_query('SELECT cname FROM '.sql_table('category').' WHERE cblog='.$this->getID().' and catid=' . intval($catid));
+               $o = sql_fetch_object($res);
+               return $o->cname;
+       }
+
+       function getCategoryDesc($catid) {
+               $res = sql_query('SELECT cdesc FROM '.sql_table('category').' WHERE cblog='.$this->getID().' and catid=' . intval($catid));
+               $o = sql_fetch_object($res);
+               return $o->cdesc;
+       }
+
+       function getCategoryIdFromName($name) {
+               $res = sql_query('SELECT catid FROM '.sql_table('category').' WHERE cblog='.$this->getID().' and cname="' . sql_real_escape_string($name) . '"');
+               if (sql_num_rows($res) > 0) {
+                       $o = sql_fetch_object($res);
+                       return $o->catid;
+               } else {
+                       return $this->getDefaultCategory();
+               }
+       }
+
+       function convertBreaks() {
+               return $this->getSetting('bconvertbreaks');
+       }
+
+       function insertJavaScriptInfo($authorid = '') {
+               global $member, $CONF;
+
+               if ($authorid == '')
+                       $authorid = $member->getID();
+
+               ?>
+               <script type="text/javascript">
+                       setConvertBreaks(<?php echo  $this->convertBreaks() ? 'true' : 'false' ?>);
+                       setMediaUrl("<?php echo $CONF['MediaURL']?>");
+                       setAuthorId(<?php echo $authorid?>);
+               </script><?php  }
+
+       function setConvertBreaks($val) {
+               $this->setSetting('bconvertbreaks',$val);
+       }
+       function setAllowPastPosting($val) {
+               $this->setSetting('ballowpast',$val);
+       }
+       function allowPastPosting() {
+               return $this->getSetting('ballowpast');
+       }
+
+       function getCorrectTime($t=0) {
+               if ($t == 0) $t = time();
+               return ($t + 3600 * $this->getTimeOffset());
+       }
+
+       function getName() {
+               return $this->getSetting('bname');
+       }
+
+       function getShortName() {
+               return $this->getSetting('bshortname');
+       }
+
+       function getMaxComments() {
+               return $this->getSetting('bmaxcomments');
+       }
+
+       function getNotifyAddress() {
+               return $this->getSetting('bnotify');
+       }
+
+       function getNotifyType() {
+               return $this->getSetting('bnotifytype');
+       }
+
+       function notifyOnComment() {
+               $n = $this->getNotifyType();
+               return (($n != 0) && (($n % 3) == 0));
+       }
+
+       function notifyOnVote() {
+               $n = $this->getNotifyType();
+               return (($n != 0) && (($n % 5) == 0));
+       }
+
+       function notifyOnNewItem() {
+               $n = $this->getNotifyType();
+               return (($n != 0) && (($n % 7) == 0));
+       }
+
+       function setNotifyType($val) {
+               $this->setSetting('bnotifytype',$val);
+       }
+
+
+       function getTimeOffset() {
+               return $this->getSetting('btimeoffset');
+       }
+
+       function commentsEnabled() {
+               return $this->getSetting('bcomments');
+       }
+
+       function getURL() {
+               return $this->getSetting('burl');
+       }
+
+       function getDefaultSkin() {
+               return $this->getSetting('bdefskin');
+       }
+
+       function getUpdateFile() {
+               return $this->getSetting('bupdate');
+       }
+
+       function getDescription() {
+               return $this->getSetting('bdesc');
+       }
+
+       function isPublic() {
+               return $this->getSetting('bpublic');
+       }
+
+       function emailRequired() {
+               return $this->getSetting('breqemail');
+       }
+
+       function getSearchable() {
+               return $this->getSetting('bincludesearch');
+       }
+
+       function getDefaultCategory() {
+               return $this->getSetting('bdefcat');
+       }
+
+       function setPublic($val) {
+               $this->setSetting('bpublic',$val);
+       }
+
+       function setSearchable($val) {
+               $this->setSetting('bincludesearch',$val);
+       }
+
+       function setDescription($val) {
+               $this->setSetting('bdesc',$val);
+       }
+
+       function setUpdateFile($val) {
+               $this->setSetting('bupdate',$val);
+       }
+
+       function setDefaultSkin($val) {
+               $this->setSetting('bdefskin',$val);
+       }
+
+       function setURL($val) {
+               $this->setSetting('burl',$val);
+       }
+
+       function setName($val) {
+               $this->setSetting('bname',$val);
+       }
+
+       function setShortName($val) {
+               $this->setSetting('bshortname',$val);
+       }
+
+       function setCommentsEnabled($val) {
+               $this->setSetting('bcomments',$val);
+       }
+
+       function setMaxComments($val) {
+               $this->setSetting('bmaxcomments',$val);
+       }
+
+       function setNotifyAddress($val) {
+               $this->setSetting('bnotify',$val);
+       }
+
+       function setEmailRequired($val) {
+               $this->setSetting('breqemail',$val);
+       }
+
+       function setTimeOffset($val) {
+               // check validity of value
+               // 1. replace , by . (common mistake)
+               $val = str_replace(',','.',$val);
+               // 2. cast to float or int
+               if (is_numeric($val) && strstr($val,'.5')) {
+                       $val = (float) $val;
+               } else {
+                       $val = intval($val);
+               }
+
+               $this->setSetting('btimeoffset',$val);
+       }
+
+       function setDefaultCategory($val) {
+               $this->setSetting('bdefcat',$val);
+       }
+
+       function getSetting($key) {
+               return $this->settings[$key];
+       }
+
+       function setSetting($key,$value) {
+               $this->settings[$key] = $value;
+       }
+
+
+       // tries to add a member to the team. Returns false if the member was already on
+       // the team
+       function addTeamMember($memberid, $admin) {
+               global $manager;
+
+               $memberid = intval($memberid);
+               $admin = intval($admin);
+
+               // check if member is already a member
+               $tmem = MEMBER::createFromID($memberid);
+
+               if ($tmem->isTeamMember($this->getID()))
+                       return 0;
+
+               $manager->notify(
+                       'PreAddTeamMember',
+                       array(
+                               'blog' => &$this,
+                               'member' => &$tmem,
+                               'admin' => &$admin
+                       )
+               );
+
+               // add to team
+               $query = 'INSERT INTO '.sql_table('team').' (TMEMBER, TBLOG, TADMIN) '
+                          . 'VALUES (' . $memberid .', '.$this->getID().', "'.$admin.'")';
+               sql_query($query);
+
+               $manager->notify(
+                       'PostAddTeamMember',
+                       array(
+                               'blog' => &$this,
+                               'member' => &$tmem,
+                               'admin' => $admin
+                       )
+
+               );
+
+               $logMsg = sprintf(_TEAM_ADD_NEWTEAMMEMBER, $tmem->getDisplayName(), $memberid, $this->getName());
+               ACTIONLOG::add(INFO, $logMsg);
+
+               return 1;
+       }
+
+       function getID() {
+               return intVal($this->blogid);
+       }
+
+       // returns true if there is a blog with the given shortname (static)
+       function exists($name) {
+               $r = sql_query('select * FROM '.sql_table('blog').' WHERE bshortname="'.sql_real_escape_string($name).'"');
+               return (sql_num_rows($r) != 0);
+       }
+
+       // returns true if there is a blog with the given ID (static)
+       function existsID($id) {
+               $r = sql_query('select * FROM '.sql_table('blog').' WHERE bnumber='.intval($id));
+               return (sql_num_rows($r) != 0);
+       }
+
+               // flag there is a future post pending
+               function setFuturePost() {
+               $query =  'UPDATE '.sql_table('blog')
+                          . " SET bfuturepost='1' WHERE bnumber=" . $this->getID();
+               sql_query($query);
+               }
+
+       // clear there is a future post pending
+       function clearFuturePost() {
+               $query =  'UPDATE '.sql_table('blog')
+                          . " SET bfuturepost='0' WHERE bnumber=" . $this->getID();
+               sql_query($query);
+       }
+
+       // check if we should throw justPosted event
+       function checkJustPosted() {
+               global $manager;
+
+               if ($this->settings['bfuturepost'] == 1) {
+                       $blogid = $this->getID();
+                       $result = sql_query("SELECT * FROM " . sql_table('item')
+                                         . " WHERE iposted=0 AND iblog=" . $blogid . " AND itime<NOW()");
+                       if (sql_num_rows($result) > 0) {
+                               // This $pinged is allow a plugin to tell other hook to the event that a ping is sent already
+                               // Note that the plugins's calling order is subject to thri order in the plugin list
+                               $pinged = false;
+                               $manager->notify(
+                                               'JustPosted',
+                                               array('blogid' => $blogid,
+                                               'pinged' => &$pinged
+                                               )
+                               );
+
+                               // clear all expired future posts
+                               sql_query("UPDATE " . sql_table('item') . " SET iposted='1' WHERE iblog=" . $blogid . " AND itime<NOW()");
+
+                               // check to see any pending future post, clear the flag is none
+                               $result = sql_query("SELECT * FROM " . sql_table('item')
+                                                 . " WHERE iposted=0 AND iblog=" . $blogid);
+                               if (sql_num_rows($result) == 0) {
+                                       $this->clearFuturePost();
+                               }
+                       }
+               }
+       }
+
+       /**
+        * Shows the given list of items for this blog
+        *
+        * @param $itemarray
+        *        array of item numbers to be displayed
+        * @param $template
+        *        String representing the template _NAME_ (!)
+        * @param $highlight
+        *        contains a query that should be highlighted
+        * @param $comments
+        *        1=show comments 0=don't show comments
+        * @param $dateheads
+        *        1=show dateheads 0=don't show dateheads
+        * @param $showDrafts
+        *              0=do not show drafts 1=show drafts
+        * @param $showFuture
+        *              0=do not show future posts 1=show future posts
+        * @returns int
+        *        amount of items shown
+        */
+       function readLogFromList($itemarray, $template, $highlight = '', $comments = 1, $dateheads = 1,$showDrafts = 0, $showFuture = 0) {
+               
+               $query = $this->getSqlItemList($itemarray,$showDrafts,$showFuture);
+               
+               return $this->showUsingQuery($template, $query, $highlight, $comments, $dateheads);
+       }
+
+       /**
+        * Returns the SQL query used to fill out templates for a list of items
+        *
+        * @param $itemarray
+        *        an array holding the item numbers of the items to be displayed
+        * @param $showDrafts
+        *              0=do not show drafts 1=show drafts
+        * @param $showFuture
+        *              0=do not show future posts 1=show future posts
+        * @returns
+        *        either a full SQL query, or an empty string
+        * @note
+        *        No LIMIT clause is added. (caller should add this if multiple pages are requested)
+        */
+       function getSqlItemList($itemarray,$showDrafts = 0,$showFuture = 0)
+       {
+               if (!is_array($itemarray)) return '';
+               $showDrafts = intval($showDrafts);
+               $showFuture = intval($showFuture);
+               $items = array();
+               foreach ($itemarray as $value) {
+                       if (intval($value)) $items[] = intval($value);
+               }
+               if (!count($items)) return '';
+               //$itemlist = implode(',',$items);
+               $i = count($items);
+               $query = '';
+               foreach ($items as $value) {
+                       $query .= '('
+                                       .   'SELECT'
+                                       .   ' i.inumber as itemid,'
+                                       .   ' i.ititle as title,'
+                                       .   ' i.ibody as body,'
+                                       .   ' m.mname as author,'
+                                       .   ' m.mrealname as authorname,'
+                                       .   ' i.itime,'
+                                       .   ' i.imore as more,'
+                                       .   ' m.mnumber as authorid,'
+                                       .   ' m.memail as authormail,'
+                                       .   ' m.murl as authorurl,'
+                                       .   ' c.cname as category,'
+                                       .   ' i.icat as catid,'
+                                       .   ' i.iclosed as closed';
+
+                       $query .= ' FROM '
+                                       . sql_table('item') . ' as i, '
+                                       . sql_table('member') . ' as m, '
+                                       . sql_table('category').' as c'
+                                       . ' WHERE'
+                                       .        ' i.iblog   = ' . $this->blogid
+                                       . ' and i.iauthor = m.mnumber'
+                                       . ' and i.icat  = c.catid'
+                                       . ' and i.idraft  = 0'  // exclude drafts
+                                               // don't show future items
+                                       . ' and i.itime  <= ' . mysqldate($this->getCorrectTime());
+                       if (!$showDrafts) $query .= ' and i.idraft=0';  // exclude drafts                                               
+                       if (!$showFuture) $query .= ' and i.itime<=' . mysqldate($this->getCorrectTime()); // don't show future items
+                       
+                       //$query .= ' and i.inumber IN ('.$itemlist.')';
+                       $query .= ' and i.inumber = '.intval($value);
+                       $query .= ')';
+                       $i--;
+                       if ($i) $query .= ' UNION ';
+               }
+
+               return $query;
+       }
 
 }
 
index 059a317..ddbbe04 100644 (file)
@@ -31,6 +31,8 @@ class BODYACTIONS extends BaseActions {
        
        function setCurrentItem(&$item) {
                $this->currentItem =& $item;
+               global $currentitemid;
+               $currentitemid = $this->currentItem->itemid;
        }
        
        function setTemplate($template) {
@@ -38,7 +40,7 @@ class BODYACTIONS extends BaseActions {
        }
 
        function getDefinedActions() {
-               return array('image', 'media', 'popup', 'plugin');
+               return array('image', 'media', 'popup', 'plugin', 'if', 'else', 'endif', 'elseif', 'ifnot', 'elseifnot');
        }
 
        function parse_plugin($pluginName) {
@@ -148,6 +150,247 @@ class BODYACTIONS extends BaseActions {
 
                echo TEMPLATE::fill($this->template['POPUP_CODE'],$vars);
        }
+       
+       
+       // function to enable if-else-elseif-elseifnot-ifnot-endif to item template fields
+       
+       /**
+        * Checks conditions for if statements
+        *
+        * @param string $field type of <%if%>
+        * @param string $name property of field
+        * @param string $value value of property
+        */
+       function checkCondition($field, $name='', $value = '') {
+               global $catid, $blog, $member, $itemidnext, $itemidprev, $manager, $archiveprevexists, $archivenextexists;
+
+               $condition = 0;
+               switch($field) {
+                       case 'category':
+                               $condition = ($blog && $this->_ifCategory($name,$value));
+                               break;
+                       case 'itemcategory':
+                               $condition = ($this->_ifItemCategory($name,$value));
+                               break;
+                       case 'blogsetting':
+                               $condition = ($blog && ($blog->getSetting($name) == $value));
+                               break;
+                       case 'itemblogsetting':
+                               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentItem->itemid));
+                               $condition = ($b && ($b->getSetting($name) == $value));
+                               break;
+                       case 'loggedin':
+                               $condition = $member->isLoggedIn();
+                               break;
+                       case 'onteam':
+                               $condition = $member->isLoggedIn() && $this->_ifOnTeam($name);
+                               break;
+                       case 'admin':
+                               $condition = $member->isLoggedIn() && $this->_ifAdmin($name);
+                               break;
+                       case 'author':
+                               $condition = ($this->_ifAuthor($name,$value));
+                               break;
+/*                     case 'nextitem':
+                               $condition = ($itemidnext != '');
+                               break;
+                       case 'previtem':
+                               $condition = ($itemidprev != '');
+                               break;
+                       case 'archiveprevexists':
+                               $condition = ($archiveprevexists == true);
+                               break;
+                       case 'archivenextexists':
+                               $condition = ($archivenextexists == true);
+                               break; 
+                       case 'skintype':
+                               $condition = ($name == $this->skintype);
+                               break; */
+                       case 'hasplugin':
+                               $condition = $this->_ifHasPlugin($name, $value);
+                               break;
+                       default:
+                               $condition = $manager->pluginInstalled('NP_' . $field) && $this->_ifPlugin($field, $name, $value);
+                               break;
+               }
+               return $condition;
+       }       
+       
+       /**
+        *  Different checks for a category
+        */
+       function _ifCategory($name = '', $value='') {
+               global $blog, $catid;
+
+               // when no parameter is defined, just check if a category is selected
+               if (($name != 'catname' && $name != 'catid') || ($value == ''))
+                       return $blog->isValidCategory($catid);
+
+               // check category name
+               if ($name == 'catname') {
+                       $value = $blog->getCategoryIdFromName($value);
+                       if ($value == $catid)
+                               return $blog->isValidCategory($catid);
+               }
+
+               // check category id
+               if (($name == 'catid') && ($value == $catid))
+                       return $blog->isValidCategory($catid);
+
+               return false;
+       }
+       
+               
+       /**
+        *  Different checks for an author
+        */
+       function _ifAuthor($name = '', $value='') {
+               global $member, $manager;
+               
+               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentItem->itemid));
+
+               // when no parameter is defined, just check if author is current visitor
+               if (($name != 'isadmin' && $name != 'name') || ($name == 'name' && $value == '')) {
+                       return (intval($member->getID()) > 0 && intval($member->getID()) == intval($this->currentItem->authorid));
+               }
+
+               // check author name
+               if ($name == 'name') {
+                       $value = strtolower($value);
+                       if ($value == strtolower($this->currentItem->author))
+                               return true;
+               }
+
+               // check if author is admin
+               if (($name == 'isadmin')) {                     
+                       $aid = intval($this->currentItem->authorid);
+                       $blogid = intval($b->getID());                  
+                       $amember =& $manager->getMember($aid);
+                       if ($amember->isAdmin())
+                               return true;
+                               
+                       return $amember->isBlogAdmin($blogid);
+               }
+
+               return false;
+       }
+       
+       /**
+        *  Different checks for a category
+        */
+       function _ifItemCategory($name = '', $value='') {
+               global $catid, $manager;
+               
+               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentItem->itemid));
+
+               // when no parameter is defined, just check if a category is selected
+               if (($name != 'catname' && $name != 'catid') || ($value == ''))
+                       return $b->isValidCategory($catid);
+                       
+               $icatid = $this->currentItem->catid;
+               //$icategory = $this->currentItem->category;
+
+               // check category name
+               if ($name == 'catname') {
+                       $value = $b->getCategoryIdFromName($value);
+                       if ($value == $icatid)
+                               return $b->isValidCategory($icatid);
+               }
 
+               // check category id
+               if (($name == 'catid') && ($value == $icatid))
+                       return $b->isValidCategory($icatid);
+
+               return false;
+       }
+
+       
+       /**
+        *  Checks if a member is on the team of a blog and return his rights
+        */
+       function _ifOnTeam($blogName = '') {
+               global $blog, $member, $manager;
+
+               // when no blog found
+               if (($blogName == '') && (!is_object($blog)))
+                       return 0;
+
+               // explicit blog selection
+               if ($blogName != '')
+                       $blogid = getBlogIDFromName($blogName);
+
+               if (($blogName == '') || !$manager->existsBlogID($blogid))
+                       // use current blog
+                       $blogid = $blog->getID();
+
+               return $member->teamRights($blogid);
+       }
+
+       /**
+        *  Checks if a member is admin of a blog
+        */
+       function _ifAdmin($blogName = '') {
+               global $blog, $member, $manager;
+
+               // when no blog found
+               if (($blogName == '') && (!is_object($blog)))
+                       return 0;
+
+               // explicit blog selection
+               if ($blogName != '')
+                       $blogid = getBlogIDFromName($blogName);
+                       
+               if (($blogName == '') || !$manager->existsBlogID($blogid))
+                       // use current blog
+                       $blogid = $blog->getID();
+               
+               return $member->isBlogAdmin($blogid);
+       }
+
+       
+       /**
+        *      hasplugin,PlugName
+        *         -> checks if plugin exists
+        *      hasplugin,PlugName,OptionName
+        *         -> checks if the option OptionName from plugin PlugName is not set to 'no'
+        *      hasplugin,PlugName,OptionName=value
+        *         -> checks if the option OptionName from plugin PlugName is set to value
+        */
+       function _ifHasPlugin($name, $value) {
+               global $manager;
+               $condition = false;
+               // (pluginInstalled method won't write a message in the actionlog on failure)
+               if ($manager->pluginInstalled('NP_'.$name)) {
+                       $plugin =& $manager->getPlugin('NP_' . $name);
+                       if ($plugin != NULL) {
+                               if ($value == "") {
+                                       $condition = true;
+                               } else {
+                                       list($name2, $value2) = explode('=', $value, 2);
+                                       if ($value2 == "" && $plugin->getOption($name2) != 'no') {
+                                               $condition = true;
+                                       } else if ($plugin->getOption($name2) == $value2) {
+                                               $condition = true;
+                                       }
+                               }
+                       }
+               }
+               return $condition;
+       }
+       
+       /**
+        * Checks if a plugin exists and call its doIf function
+        */
+       function _ifPlugin($name, $key = '', $value = '') {
+               global $manager;
+               
+               $plugin =& $manager->getPlugin('NP_' . $name);
+               if (!$plugin) return;
+               
+               $params = func_get_args();
+               array_shift($params);
+               
+               return call_user_func_array(array(&$plugin, 'doIf'), $params);
+       }
 }
 ?>
index 39c83c4..6bdd43f 100755 (executable)
@@ -26,14 +26,13 @@ class COMMENT {
          * @static
          */
        function getComment($commentid) {
-               $query =  'SELECT cnumber as commentid, cbody as body, cuser as user, cmail as userid, cemail as email, cmember as memberid, ctime, chost as host, mname as member, cip as ip, cblog as blogid'
-                          . ' FROM '.sql_table('comment').' left outer join '.sql_table('member').' on cmember=mnumber'
-                          . ' WHERE cnumber=' . intval($commentid);
+               $query = 'SELECT `cnumber` AS commentid, `cbody` AS body, `cuser` AS user, `cmail` AS userid, `cemail` AS email, `cmember` AS memberid, `ctime`, `chost` AS host, `mname` AS member, `cip` AS ip, `cblog` AS blogid'
+                                       . ' FROM ' . sql_table('comment') . ' LEFT OUTER JOIN ' . sql_table('member') . ' ON `cmember` = `mnumber`'
+                                       . ' WHERE `cnumber` = ' . intval($commentid);
                $comments = sql_query($query);
 
                $aCommentInfo = sql_fetch_assoc($comments);
-               if ($aCommentInfo)
-               {
+               if ($aCommentInfo) {
                        $aCommentInfo['timestamp'] = strtotime($aCommentInfo['ctime']);
                }
                return $aCommentInfo;
@@ -49,13 +48,18 @@ class COMMENT {
                $comment['userid'] = strip_tags($comment['userid']);
                $comment['email'] = strip_tags($comment['email']);
 
-               // remove quotes and newlines from user and userid
-               $comment['user'] = strtr($comment['user'], "\'\"\n",'-- ');
-               $comment['userid'] = strtr($comment['userid'], "\'\"\n",'-- ');
-               $comment['email'] = strtr($comment['email'], "\'\"\n",'-- ');
-
+               // remove newlines from user; remove quotes and newlines from userid and email; trim whitespace from beginning and end
+               $comment['user'] = trim(strtr($comment['user'], "\n", ' ') );
+               $comment['userid'] = trim(strtr($comment['userid'], "\'\"\n", '-- ') );
+               $comment['email'] = trim(strtr($comment['email'], "\'\"\n", '-- ') );
+               
+               // begin if: a comment userid is supplied, but does not have an "http://" or "https://" at the beginning - prepend an "http://"
+               if ( !empty($comment['userid']) && (strpos($comment['userid'], 'http://') !== 0) && (strpos($comment['userid'], 'https://') !== 0) ) {
+                       $comment['userid'] = 'http://' . $comment['userid'];
+               } // end if
+               
                $comment['body'] = COMMENT::prepareBody($comment['body']);
-
+               
                return $comment;
        }
 
@@ -65,10 +69,12 @@ class COMMENT {
         * @ static
         */             
        function prepareBody($body) {
-
-               // remove newlines when too many in a row
-               $body = ereg_replace("\n.\n.\n","\n",$body);
-
+               # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
+               # original ereg_replace: ereg_replace("\n.\n.\n", "\n", $body);
+               // remove newlines when too many in a row               
+               $body = preg_replace("/\r\n/", "\n", $body);
+               $body = preg_replace("/\n+/", "\n", $body);
+               
                // encode special characters as entities
                $body = htmlspecialchars($body);
 
@@ -109,11 +115,9 @@ class COMMENT {
                // since htmlspecialchars is applied _before_ URL linking
                // move the part of URL, starting from the disallowed entity to the 'post' link part
                $aBadEntities = array('&quot;', '&gt;', '&lt;');
-               foreach ($aBadEntities as $entity)
-               {
+               foreach ($aBadEntities as $entity) {
                        $pos = strpos($url, $entity);
-                       if ($pos)
-                       {
+                       if ($pos) {
                                $post = substr($url, $pos) . $post;
                                $url = substr($url, 0, $pos);
 
@@ -127,25 +131,28 @@ class COMMENT {
                }
 
                // move ending comma from url to 'post' part
-               if (substr($url, strlen($url) - 1) == ',')
-               {
+               if (substr($url, strlen($url) - 1) == ',') {
                        $url = substr($url, 0, strlen($url) - 1);
                        $post = ',' . $post;
                }
 
-               if (!ereg('^'.$protocol.'://',$url))
+               # replaced ereg() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
+               # original ereg: ereg('^' . $protocol . '://', $url)
+               if (!preg_match('#^' . $protocol . '://#', $url) )
+               {
                        $linkedUrl = $protocol . (($protocol == 'mailto') ? ':' : '://') . $url;
+               }
                else
+               {
                        $linkedUrl = $url;
-
-
-               if ($protocol != 'mailto')
+               }
+               
+               if ($protocol != 'mailto') {
                        $displayedUrl = $linkedUrl;
-               else
+               } else {
                        $displayedUrl = $url;
+               }
                return $pre . '<a href="'.$linkedUrl.'" rel="nofollow">'.shorten($displayedUrl,30,'...').'</a>' . $post;
        }
-
 }
-
 ?>
\ No newline at end of file
index 351e2c3..b7d7c85 100644 (file)
@@ -71,7 +71,13 @@ class COMMENTACTIONS extends BaseActions {
                        'plugin',
                        'include',
                        'phpinclude',
-                       'parsedinclude'
+                       'parsedinclude',
+                       'if',
+                       'else',
+                       'endif',
+                       'elseif',
+                       'ifnot',
+                       'elseifnot'
                );
        }
 
@@ -89,16 +95,25 @@ class COMMENTACTIONS extends BaseActions {
        
        function setCurrentComment(&$comment) {
                global $manager;
-               if ($comment['memberid'] != 0) {
+               // begin if: member comment
+               if ($comment['memberid'] != 0)
+               {
                        $comment['authtext'] = $template['COMMENTS_AUTH'];
 
                        $mem =& $manager->getMember($comment['memberid']);
                        $comment['user'] = $mem->getDisplayName();
+                       
+                       // begin if: member URL exists, set it as the userid
                        if ($mem->getURL())
+                       {
                                $comment['userid'] = $mem->getURL();
+                       }
+                       // else: set the email as the userid
                        else
+                       {
                                $comment['userid'] = $mem->getEmail();
-
+                       } // end if
+                       
                        $comment['userlinkraw'] = createLink(
                                                                                'member',
                                                                                array(
@@ -107,27 +122,40 @@ class COMMENTACTIONS extends BaseActions {
                                                                                        'extra' => $this->commentsObj->itemActions->linkparams
                                                                                )
                                                                          );
-
-               } else {
-
-                       // create smart links
-/*                     if (isValidMailAddress($comment['userid']))
-                               $comment['userlinkraw'] = 'mailto:'.$comment['userid'];
-                       elseif (strstr($comment['userid'],'http://') != false)
-                               $comment['userlinkraw'] = $comment['userid'];
-                       elseif (strstr($comment['userid'],'www') != false)
-                               $comment['userlinkraw'] = 'http://'.$comment['userid'];*/
-                       if (strstr($comment['userid'],'http://') != false)
-                               $comment['userlinkraw'] = $comment['userid'];
-                       elseif (strstr($comment['userid'],'www') != false)
-                               $comment['userlinkraw'] = 'http://'.$comment['userid'];
-                       elseif (isValidMailAddress($comment['email']))
-                               $comment['userlinkraw'] = 'mailto:'.$comment['email'];
-                       elseif (isValidMailAddress($comment['userid']))
-                               $comment['userlinkraw'] = 'mailto:'.$comment['userid'];
+               // else: non-member comment
                }
-
+               else
+               {
+                       // create smart links
+                       // begin if: comment userid is not empty
+                       if (!empty($comment['userid']) )
+                       {
+                               // begin if: comment userid has either "http://" or "https://" at the beginning
+                               if ( (strpos($comment['userid'], 'http://') === 0) || (strpos($comment['userid'], 'https://') === 0) )
+                               {
+                                       $comment['userlinkraw'] = $comment['userid'];
+                               }
+                               // else: prepend the "http://" (backwards compatibility before rev 1471)
+                               else
+                               {
+                                       $comment['userlinkraw'] = 'http://' . $comment['userid'];
+                               } // end if
+                       }
+                       // else if: comment email is valid
+                       else if (isValidMailAddress($comment['email']) )
+                       {
+                               $comment['userlinkraw'] = 'mailto:' . $comment['email'];
+                       }
+                       // else if: comment userid is a valid email
+                       else if (isValidMailAddress($comment['userid']) )
+                       {
+                               $comment['userlinkraw'] = 'mailto:' . $comment['userid'];
+                       } // end if
+               } // end if
                $this->currentComment =& $comment;
+               global $currentcommentid, $currentcommentarray;
+               $currentcommentid = $comment['commentid'];
+               $currentcommentarray = $comment;
        }
 
        /**
@@ -401,6 +429,263 @@ class COMMENTACTIONS extends BaseActions {
                        echo $this->currentComment['user'];
                }
        }
+       
+       // function to enable if-else-elseif-elseifnot-ifnot-endif to comment template fields
+       
+       /**
+        * Checks conditions for if statements
+        *
+        * @param string $field type of <%if%>
+        * @param string $name property of field
+        * @param string $value value of property
+        */
+       function checkCondition($field, $name='', $value = '') {
+               global $catid, $blog, $member, $itemidnext, $itemidprev, $manager, $archiveprevexists, $archivenextexists;
+
+               $condition = 0;
+               switch($field) {
+                       case 'category':
+                               $condition = ($blog && $this->_ifCategory($name,$value));
+                               break;
+                       case 'itemcategory':
+                               $condition = ($this->_ifItemCategory($name,$value));
+                               break;
+                       case 'blogsetting':
+                               $condition = ($blog && ($blog->getSetting($name) == $value));
+                               break;
+                       case 'itemblogsetting':
+                               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentComment['itemid']));
+                               $condition = ($b && ($b->getSetting($name) == $value));
+                               break;
+                       case 'loggedin':
+                               $condition = $member->isLoggedIn();
+                               break;
+                       case 'onteam':
+                               $condition = $member->isLoggedIn() && $this->_ifOnTeam($name);
+                               break;
+                       case 'admin':
+                               $condition = $member->isLoggedIn() && $this->_ifAdmin($name);
+                               break;
+                       case 'author':
+                               $condition = ($this->_ifAuthor($name,$value));
+                               break;
+/*                     case 'nextitem':
+                               $condition = ($itemidnext != '');
+                               break;
+                       case 'previtem':
+                               $condition = ($itemidprev != '');
+                               break;
+                       case 'archiveprevexists':
+                               $condition = ($archiveprevexists == true);
+                               break;
+                       case 'archivenextexists':
+                               $condition = ($archivenextexists == true);
+                               break; 
+                       case 'skintype':
+                               $condition = ($name == $this->skintype);
+                               break; */
+                       case 'hasplugin':
+                               $condition = $this->_ifHasPlugin($name, $value);
+                               break;
+                       default:
+                               $condition = $manager->pluginInstalled('NP_' . $field) && $this->_ifPlugin($field, $name, $value);
+                               break;
+               }
+               return $condition;
+       }       
+       
+       /**
+        *  Different checks for a category
+        */
+       function _ifCategory($name = '', $value='') {
+               global $blog, $catid;
+
+               // when no parameter is defined, just check if a category is selected
+               if (($name != 'catname' && $name != 'catid') || ($value == ''))
+                       return $blog->isValidCategory($catid);
+
+               // check category name
+               if ($name == 'catname') {
+                       $value = $blog->getCategoryIdFromName($value);
+                       if ($value == $catid)
+                               return $blog->isValidCategory($catid);
+               }
+
+               // check category id
+               if (($name == 'catid') && ($value == $catid))
+                       return $blog->isValidCategory($catid);
+
+               return false;
+       }
+       
+               
+       /**
+        *  Different checks for an author
+        */
+       function _ifAuthor($name = '', $value='') {
+               global $member, $manager;
+               
+               if ($this->currentComment['memberid'] == 0) return false;
+               
+               $mem =& $manager->getMember($this->currentComment['memberid']);
+               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentComment['itemid']));
+               $citem =& $manager->getItem($this->currentComment['itemid'],1,1);
+
+               // when no parameter is defined, just check if item author is current visitor
+               if (($name != 'isadmin' && $name != 'name' && $name != 'isauthor' && $name != 'isonteam')) {
+                       return (intval($member->getID()) > 0 && intval($member->getID()) == intval($citem['authorid']));
+               }
+
+               // check comment author name
+               if ($name == 'name') {
+                       $value = trim(strtolower($value));
+                       if ($value == '') 
+                               return false;
+                       if ($value == strtolower($mem->getDisplayName()))
+                               return true;
+               }
+
+               // check if comment author is admin
+               if ($name == 'isadmin') {                       
+                       $blogid = intval($b->getID());                  
+                       if ($mem->isAdmin())
+                               return true;
+                               
+                       return $mem->isBlogAdmin($blogid);
+               }
+               
+               // check if comment author is item author
+               if ($name == 'isauthor') {                      
+                       return (intval($citem['authorid']) == intval($this->currentComment['memberid']));
+               }
+               
+               // check if comment author is on team
+               if ($name == 'isonteam') {
+                       return $mem->teamRights(intval($b->getID()));
+               }
+
+               return false;
+       }
+       
+       /**
+        *  Different checks for a category
+        */
+       function _ifItemCategory($name = '', $value='') {
+               global $catid, $manager;
+               
+               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentComment['itemid']));
+               $citem =& $manager->getItem($this->currentComment['itemid'],1,1);
+               $icatid = $citem['catid'];
+
+               // when no parameter is defined, just check if a category is selected
+               if (($name != 'catname' && $name != 'catid') || ($value == ''))
+                       return $b->isValidCategory($icatid);
+                       
+               // check category name
+               if ($name == 'catname') {
+                       $value = $b->getCategoryIdFromName($value);
+                       if ($value == $icatid)
+                               return $b->isValidCategory($icatid);
+               }
+
+               // check category id
+               if (($name == 'catid') && ($value == $icatid))
+                       return $b->isValidCategory($icatid);
+
+               return false;
+       }
+
+       
+       /**
+        *  Checks if a member is on the team of a blog and return his rights
+        */
+       function _ifOnTeam($blogName = '') {
+               global $blog, $member, $manager;
+               
+               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentComment['itemid']));
+               
+               // when no blog found
+               if (($blogName == '') && (!is_object($b)))
+                       return 0;
+
+               // explicit blog selection
+               if ($blogName != '')
+                       $blogid = getBlogIDFromName($blogName);
+
+               if (($blogName == '') || !$manager->existsBlogID($blogid))
+                       // use current blog
+                       $blogid = $b->getID();
 
+               return $member->teamRights($blogid);
+       }
+
+       /**
+        *  Checks if a member is admin of a blog
+        */
+       function _ifAdmin($blogName = '') {
+               global $blog, $member, $manager;
+
+               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentComment['itemid']));
+               
+               // when no blog found
+               if (($blogName == '') && (!is_object($b)))
+                       return 0;
+
+               // explicit blog selection
+               if ($blogName != '')
+                       $blogid = getBlogIDFromName($blogName);
+
+               if (($blogName == '') || !$manager->existsBlogID($blogid))
+                       // use current blog
+                       $blogid = $b->getID();
+
+               return $member->isBlogAdmin($blogid);
+       }
+
+       
+       /**
+        *      hasplugin,PlugName
+        *         -> checks if plugin exists
+        *      hasplugin,PlugName,OptionName
+        *         -> checks if the option OptionName from plugin PlugName is not set to 'no'
+        *      hasplugin,PlugName,OptionName=value
+        *         -> checks if the option OptionName from plugin PlugName is set to value
+        */
+       function _ifHasPlugin($name, $value) {
+               global $manager;
+               $condition = false;
+               // (pluginInstalled method won't write a message in the actionlog on failure)
+               if ($manager->pluginInstalled('NP_'.$name)) {
+                       $plugin =& $manager->getPlugin('NP_' . $name);
+                       if ($plugin != NULL) {
+                               if ($value == "") {
+                                       $condition = true;
+                               } else {
+                                       list($name2, $value2) = explode('=', $value, 2);
+                                       if ($value2 == "" && $plugin->getOption($name2) != 'no') {
+                                               $condition = true;
+                                       } else if ($plugin->getOption($name2) == $value2) {
+                                               $condition = true;
+                                       }
+                               }
+                       }
+               }
+               return $condition;
+       }
+
+       /**
+        * Checks if a plugin exists and call its doIf function
+        */
+       function _ifPlugin($name, $key = '', $value = '') {
+               global $manager;
+
+               $plugin =& $manager->getPlugin('NP_' . $name);
+               if (!$plugin) return;
+
+               $params = func_get_args();
+               array_shift($params);
+
+               return call_user_func_array(array(&$plugin, 'doIf'), $params);
+       }
 }
 ?>
\ No newline at end of file
index 9796773..d49f655 100755 (executable)
@@ -259,12 +259,12 @@ class COMMENTS {
 
                $manager->notify('PreAddComment',array('comment' => &$comment, 'spamcheck' => &$spamcheck));
 
-               $name           = addslashes($comment['user']);
-               $url            = addslashes($comment['userid']);
-               $email      = addslashes($comment['email']);
-               $body           = addslashes($comment['body']);
-               $host           = addslashes($comment['host']);
-               $ip                     = addslashes($comment['ip']);
+               $name           = sql_real_escape_string($comment['user']);
+               $url            = sql_real_escape_string($comment['userid']);
+               $email      = sql_real_escape_string($comment['email']);
+               $body           = sql_real_escape_string($comment['body']);
+               $host           = sql_real_escape_string($comment['host']);
+               $ip                     = sql_real_escape_string($comment['ip']);
                $memberid       = intval($comment['memberid']);
                $timestamp      = date('Y-m-d H:i:s', $comment['timestamp']);
                $itemid         = $this->itemid;
@@ -301,36 +301,46 @@ class COMMENTS {
         */
        function isValidComment(&$comment, & $spamcheck) {
                global $member, $manager;
-
+               
                // check if there exists a item for this date
                $item =& $manager->getItem($this->itemid,0,0);
-
-               if (!$item)
+               
+               if (!$item) {
                        return _ERROR_NOSUCHITEM;
-
-               if ($item['closed'])
+               }
+               
+               if ($item['closed']) {
                        return _ERROR_ITEMCLOSED;
-
+               }
+               
+               # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
+               # original eregi comparison: eregi('[a-zA-Z0-9|\.,;:!\?=\/\\]{90,90}', $comment['body']) != FALSE
+               
                // don't allow words that are too long
-               if (eregi('[a-zA-Z0-9|\.,;:!\?=\/\\]{90,90}',$comment['body']) != false)
+               if (preg_match('/[a-zA-Z0-9|\.,;:!\?=\/\\\\]{90,90}/', $comment['body']) != 0)
+               {
                        return _ERROR_COMMENT_LONGWORD;
-
+               }
+               
                // check lengths of comment
-               if (strlen($comment['body'])<3)
+               if (strlen($comment['body'])<3) {
                        return _ERROR_COMMENT_NOCOMMENT;
-
-               if (strlen($comment['body'])>5000)
+               }
+               
+               if (strlen($comment['body'])>5000) {
                        return _ERROR_COMMENT_TOOLONG;
-
+               }
+               
                // only check username if no member logged in
-               if (!$member->isLoggedIn())
+               if (!$member->isLoggedIn()) {
                        if (strlen($comment['user'])<2)
                                return _ERROR_COMMENT_NOUSERNAME;
-
-               if ((strlen($comment['email']) != 0) && !(isValidMailAddress($comment['email']))) {
+               }
+               
+               if ((strlen($comment['email']) != 0) && !(isValidMailAddress(trim($comment['email']) ) ) )
                        return _ERROR_BADMAILADDRESS;
                }
-
+               
                // let plugins do verification (any plugin which thinks the comment is invalid
                // can change 'error' to something other than '1')
                $result = 1;
index 139484d..e773c70 100755 (executable)
@@ -213,9 +213,9 @@ class ITEM {
                // update item itsself\r
                $query =  'UPDATE '.sql_table('item')\r
                           . ' SET'\r
-                          . " ibody='". addslashes($body) ."',"\r
-                          . " ititle='" . addslashes($title) . "',"\r
-                          . " imore='" . addslashes($more) . "',"\r
+                          . " ibody='". sql_real_escape_string($body) ."',"\r
+                          . " ititle='" . sql_real_escape_string($title) . "',"\r
+                          . " imore='" . sql_real_escape_string($more) . "',"\r
                           . " iclosed=" . intval($closed) . ","\r
                           . " icat=" . intval($catid);\r
 \r
index fb87f00..8f85186 100644 (file)
@@ -102,13 +102,13 @@ class ITEMACTIONS extends BaseActions {
                        'editlink',\r
                        'editpopupcode',\r
                        'comments',\r
-                       'relevance'/*,\r
+                       'relevance',\r
                        'if',\r
                        'else',\r
                        'endif',\r
                        'elseif',\r
                        'ifnot',\r
-                       'elseifnot'*/\r
+                       'elseifnot'\r
                );\r
        }\r
 \r
@@ -119,11 +119,13 @@ class ITEMACTIONS extends BaseActions {
        function setParser(&$parser) {\r
                $this->parser =& $parser;\r
        }\r
-\r
-       function setCurrentItem(&$item) {\r
-               $this->currentItem =& $item;\r
-       }\r
-\r
+       \r
+       function setCurrentItem(&$item) {
+               $this->currentItem =& $item;
+               global $currentitemid;
+               $currentitemid = $this->currentItem->itemid;
+       }
+       
        function setBlog(&$blog) {\r
                $this->blog =& $blog;\r
        }\r
@@ -540,7 +542,246 @@ class ITEMACTIONS extends BaseActions {
                $this->parser->actions = $this->getDefinedActions();\r
        }\r
        */\r
-\r
+       \r
+       // function to enable if-else-elseif-elseifnot-ifnot-endif to item template fields
+       
+               /**
+        * Checks conditions for if statements
+        *
+        * @param string $field type of <%if%>
+        * @param string $name property of field
+        * @param string $value value of property
+        */
+       function checkCondition($field, $name='', $value = '') {
+               global $catid, $blog, $member, $itemidnext, $itemidprev, $manager, $archiveprevexists, $archivenextexists;
+
+               $condition = 0;
+               switch($field) {
+                       case 'category':
+                               $condition = ($blog && $this->_ifCategory($name,$value));
+                               break;
+                       case 'itemcategory':
+                               $condition = ($this->_ifItemCategory($name,$value));
+                               break;
+                       case 'blogsetting':
+                               $condition = ($blog && ($blog->getSetting($name) == $value));
+                               break;
+                       case 'itemblogsetting':
+                               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentItem->itemid));
+                               $condition = ($b && ($b->getSetting($name) == $value));
+                               break;
+                       case 'loggedin':
+                               $condition = $member->isLoggedIn();
+                               break;
+                       case 'onteam':
+                               $condition = $member->isLoggedIn() && $this->_ifOnTeam($name);
+                               break;
+                       case 'admin':
+                               $condition = $member->isLoggedIn() && $this->_ifAdmin($name);
+                               break;
+                       case 'author':
+                               $condition = ($this->_ifAuthor($name,$value));
+                               break;
+/*                     case 'nextitem':
+                               $condition = ($itemidnext != '');
+                               break;
+                       case 'previtem':
+                               $condition = ($itemidprev != '');
+                               break;
+                       case 'archiveprevexists':
+                               $condition = ($archiveprevexists == true);
+                               break;
+                       case 'archivenextexists':
+                               $condition = ($archivenextexists == true);
+                               break; 
+                       case 'skintype':
+                               $condition = ($name == $this->skintype);
+                               break; */
+                       case 'hasplugin':
+                               $condition = $this->_ifHasPlugin($name, $value);
+                               break;
+                       default:
+                               $condition = $manager->pluginInstalled('NP_' . $field) && $this->_ifPlugin($field, $name, $value);
+                               break;
+               }
+               return $condition;
+       }       
+       
+       /**
+        *  Different checks for a category
+        */
+       function _ifCategory($name = '', $value='') {
+               global $blog, $catid;
+
+               // when no parameter is defined, just check if a category is selected
+               if (($name != 'catname' && $name != 'catid') || ($value == ''))
+                       return $blog->isValidCategory($catid);
+
+               // check category name
+               if ($name == 'catname') {
+                       $value = $blog->getCategoryIdFromName($value);
+                       if ($value == $catid)
+                               return $blog->isValidCategory($catid);
+               }
+
+               // check category id
+               if (($name == 'catid') && ($value == $catid))
+                       return $blog->isValidCategory($catid);
+
+               return false;
+       }
+       
+               
+       /**
+        *  Different checks for an author
+        */
+       function _ifAuthor($name = '', $value='') {
+               global $member, $manager;
+               
+               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentItem->itemid));
+
+               // when no parameter is defined, just check if author is current visitor
+               if (($name != 'isadmin' && $name != 'name') || ($name == 'name' && $value == '')) {
+                       return (intval($member->getID()) > 0 && intval($member->getID()) == intval($this->currentItem->authorid));
+               }
+
+               // check author name
+               if ($name == 'name') {
+                       $value = strtolower($value);
+                       if ($value == strtolower($this->currentItem->author))
+                               return true;
+               }
+
+               // check if author is admin
+               if (($name == 'isadmin')) {                     
+                       $aid = intval($this->currentItem->authorid);
+                       $blogid = intval($b->getID());                  
+                       $amember =& $manager->getMember($aid);
+                       if ($amember->isAdmin())
+                               return true;
+                               
+                       return $amember->isBlogAdmin($blogid);
+               }
+
+               return false;
+       }
+       
+       /**
+        *  Different checks for a category
+        */
+       function _ifItemCategory($name = '', $value='') {
+               global $catid, $manager;
+               
+               $b =& $manager->getBlog(getBlogIDFromItemID($this->currentItem->itemid));
+
+               // when no parameter is defined, just check if a category is selected
+               if (($name != 'catname' && $name != 'catid') || ($value == ''))
+                       return $b->isValidCategory($catid);
+                       
+               $icatid = $this->currentItem->catid;
+               //$icategory = $this->currentItem->category;
+
+               // check category name
+               if ($name == 'catname') {
+                       $value = $b->getCategoryIdFromName($value);
+                       if ($value == $icatid)
+                               return $b->isValidCategory($icatid);
+               }
+
+               // check category id
+               if (($name == 'catid') && ($value == $icatid))
+                       return $b->isValidCategory($icatid);
+
+               return false;
+       }
+
+       
+       /**
+        *  Checks if a member is on the team of a blog and return his rights
+        */
+       function _ifOnTeam($blogName = '') {
+               global $blog, $member, $manager;
+
+               // when no blog found
+               if (($blogName == '') && (!is_object($blog)))
+                       return 0;
+
+               // explicit blog selection
+               if ($blogName != '')
+                       $blogid = getBlogIDFromName($blogName);
+
+               if (($blogName == '') || !$manager->existsBlogID($blogid))
+                       // use current blog
+                       $blogid = $blog->getID();
+
+               return $member->teamRights($blogid);
+       }
+
+       /**
+        *  Checks if a member is admin of a blog
+        */
+       function _ifAdmin($blogName = '') {
+               global $blog, $member, $manager;
+
+               // when no blog found
+               if (($blogName == '') && (!is_object($blog)))
+                       return 0;
+
+               // explicit blog selection
+               if ($blogName != '')
+                       $blogid = getBlogIDFromName($blogName);
+
+               if (($blogName == '') || !$manager->existsBlogID($blogid))
+                       // use current blog
+                       $blogid = $blog->getID();
+
+               return $member->isBlogAdmin($blogid);
+       }
+
+       
+       /**
+        *      hasplugin,PlugName
+        *         -> checks if plugin exists
+        *      hasplugin,PlugName,OptionName
+        *         -> checks if the option OptionName from plugin PlugName is not set to 'no'
+        *      hasplugin,PlugName,OptionName=value
+        *         -> checks if the option OptionName from plugin PlugName is set to value
+        */
+       function _ifHasPlugin($name, $value) {
+               global $manager;
+               $condition = false;
+               // (pluginInstalled method won't write a message in the actionlog on failure)
+               if ($manager->pluginInstalled('NP_'.$name)) {
+                       $plugin =& $manager->getPlugin('NP_' . $name);
+                       if ($plugin != NULL) {
+                               if ($value == "") {
+                                       $condition = true;
+                               } else {
+                                       list($name2, $value2) = explode('=', $value, 2);
+                                       if ($value2 == "" && $plugin->getOption($name2) != 'no') {
+                                               $condition = true;
+                                       } else if ($plugin->getOption($name2) == $value2) {
+                                               $condition = true;
+                                       }
+                               }
+                       }
+               }
+               return $condition;
+       }
+
+       /**
+        * Checks if a plugin exists and call its doIf function
+        */
+       function _ifPlugin($name, $key = '', $value = '') {
+               global $manager;
+
+               $plugin =& $manager->getPlugin('NP_' . $name);
+               if (!$plugin) return;
+
+               $params = func_get_args();
+               array_shift($params);
+
+               return call_user_func_array(array(&$plugin, 'doIf'), $params);
+       }
 }\r
-\r
 ?>
\ No newline at end of file
index c1139ef..a0337af 100755 (executable)
@@ -103,14 +103,14 @@ class KARMA {
 
        // checks if a vote is still allowed for an IP
        function isVoteAllowed($ip) {
-               $query = 'SELECT * FROM '.sql_table('karma')." WHERE itemid=$this->itemid and ip='".addslashes($ip)."'";
+               $query = 'SELECT * FROM '.sql_table('karma')." WHERE itemid=$this->itemid and ip='".sql_real_escape_string($ip)."'";
                $res = sql_query($query);
                return (sql_num_rows($res) == 0);
        }
 
        // save IP in database so no multiple votes are possible
        function saveIP() {
-               $query = 'INSERT INTO '.sql_table('karma').' (itemid, ip) VALUES ('.$this->itemid.",'".addslashes(serverVar('REMOTE_ADDR'))."')";
+               $query = 'INSERT INTO '.sql_table('karma').' (itemid, ip) VALUES ('.$this->itemid.",'".sql_real_escape_string(serverVar('REMOTE_ADDR'))."')";
                sql_query($query);
        }
 }
index 06826c7..4e67cda 100755 (executable)
@@ -511,7 +511,7 @@ class MANAGER {
             $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).'\'';
+        $query = 'SELECT COUNT(*) as result FROM ' . sql_table('tickets') . ' WHERE member=' . intval($memberId). ' and ticket=\''.sql_real_escape_string($ticket).'\'';
         if (quickQuery($query) == 1)
         {
             // [in the original implementation, the checked ticket was deleted. This would lead to invalid
@@ -519,7 +519,7 @@ class MANAGER {
             //  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).'\'');
+            // sql_query('DELETE FROM '.sql_table('tickets').' WHERE member=' . intval($memberId). ' and ticket=\''.sql_real_escape_string($ticket).'\'');
             return true;
         } else {
             // not a valid ticket
@@ -564,7 +564,7 @@ class MANAGER {
 
                 // 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()) . '\')';
+                $query .= 'VALUES (\'' . sql_real_escape_string($ticket). '\', \'' . intval($memberId). '\', \'' . date('Y-m-d H:i:s',time()) . '\')';
                 if (sql_query($query))
                     $ok = true;
             }
index b61a537..2cb70e7 100755 (executable)
@@ -142,9 +142,15 @@ class MEDIA {
          */
        function addMediaObject($collection, $uploadfile, $filename) {
                global $DIR_MEDIA, $manager;
-
+               
+               // clean filename of characters that may cause trouble in a filename using cleanFileName() function from globalfunctions.php
+               $filename = cleanFileName($filename);
+               // should already have tested for allowable types before calling this method. This will only catch files with no extension at all
+               if ($filename === false) 
+                       return _ERROR_BADFILETYPE;
+               
                $manager->notify('PreMediaUpload',array('collection' => &$collection, 'uploadfile' => $uploadfile, 'filename' => &$filename));
-
+               
                // don't allow uploads to unknown or forbidden collections
                $exceptReadOnly = true;
                if (!MEDIA::isValidCollection($collection,$exceptReadOnly))
index b6296a0..5ed9bd6 100755 (executable)
@@ -68,7 +68,7 @@ class MEMBER {
        }
 
        function readFromName($displayname) {
-               return $this->read("mname='".addslashes($displayname)."'");
+               return $this->read("mname='".sql_real_escape_string($displayname)."'");
        }
 
        function readFromID($id) {
@@ -335,7 +335,9 @@ class MEMBER {
        function sendActivationLink($type, $extra='')
        {
                global $CONF;
-
+               
+               if (!isset($CONF['ActivationDays'])) $CONF['ActivationDays'] = 2;
+               
                // generate key and URL
                $key = $this->generateActivationEntry($type, $extra);
                $url = $CONF['AdminURL'] . 'index.php?action=activate&key=' . $key;
@@ -364,7 +366,8 @@ class MEMBER {
                        'siteName' => $CONF['SiteName'],
                        'siteUrl' => $CONF['IndexURL'],
                        'memberName' => $this->getDisplayName(),
-                       'activationUrl' => $url
+                       'activationUrl' => $url,
+                       'activationDays' => $CONF['ActivationDays']
                );
 
                $message = TEMPLATE::fill($message, $aVars);
@@ -445,16 +448,16 @@ class MEMBER {
        function write() {
 
                $query =  'UPDATE '.sql_table('member')
-                          . " SET mname='" . addslashes($this->getDisplayName()) . "',"
-                          . "     mrealname='". addslashes($this->getRealName()) . "',"
-                          . "     mpassword='". addslashes($this->getPassword()) . "',"
-                          . "     mcookiekey='". addslashes($this->getCookieKey()) . "',"
-                          . "     murl='" . addslashes($this->getURL()) . "',"
-                          . "     memail='" . addslashes($this->getEmail()) . "',"
+                          . " SET mname='" . sql_real_escape_string($this->getDisplayName()) . "',"
+                          . "     mrealname='". sql_real_escape_string($this->getRealName()) . "',"
+                          . "     mpassword='". sql_real_escape_string($this->getPassword()) . "',"
+                          . "     mcookiekey='". sql_real_escape_string($this->getCookieKey()) . "',"
+                          . "     murl='" . sql_real_escape_string($this->getURL()) . "',"
+                          . "     memail='" . sql_real_escape_string($this->getEmail()) . "',"
                           . "     madmin=" . $this->isAdmin() . ","
-                          . "     mnotes='" . addslashes($this->getNotes()) . "',"
+                          . "     mnotes='" . sql_real_escape_string($this->getNotes()) . "',"
                           . "     mcanlogin=" . $this->canLogin() . ","
-                          . "     deflang='" . addslashes($this->getLanguage()) . "',"
+                          . "     deflang='" . sql_real_escape_string($this->getLanguage()) . "',"
                           . "     mautosave=" . intval($this->getAutosave()) . ""
                           . " WHERE mnumber=" . $this->getID();
                sql_query($query);
@@ -576,7 +579,7 @@ class MEMBER {
         * @static
         */
        function exists($name) {
-               $r = sql_query('select * FROM '.sql_table('member')." WHERE mname='".addslashes($name)."'");
+               $r = sql_query('select * FROM '.sql_table('member')." WHERE mname='".sql_real_escape_string($name)."'");
                return (sql_num_rows($r) != 0);
        }
 
@@ -613,32 +616,43 @@ class MEMBER {
                        return _ERROR_BADMAILADDRESS;
 
                if (!isValidDisplayName($name))
+               {
                        return _ERROR_BADNAME;
-
+               }
                if (MEMBER::exists($name))
+               {
                        return _ERROR_NICKNAMEINUSE;
-
+               }
                if (!$realname)
+               {
                        return _ERROR_REALNAMEMISSING;
-
+               }
                if (!$password)
+               {
                        return _ERROR_PASSWORDMISSING;
-
-               // Sometimes user didn't prefix the URL with http://, this cause a malformed URL. Let's fix it.
-               if (!eregi("^https?://", $url))
-                       $url = "http://".$url;
-
-               $name = addslashes($name);
-               $realname = addslashes($realname);
-               $password = addslashes(md5($password));
-               $email = addslashes($email);
-               $url = addslashes($url);
+               }
+               
+               # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
+               # original eregi: !eregi("^https?://", $url)
+               // begin if: sometimes user didn't prefix the URL with http:// or https://, this cause a malformed URL. Let's fix it.
+               if (!preg_match('#^https?://#', $url) )
+               {
+                       $url = 'http://' . $url;
+               } // end if
+               
+               $name = sql_real_escape_string($name);
+               $realname = sql_real_escape_string($realname);
+               $password = sql_real_escape_string(md5($password));
+               $email = sql_real_escape_string($email);
+               $url = sql_real_escape_string($url);
                $admin = intval($admin);
                $canlogin = intval($canlogin);
-               $notes = addslashes($notes);
-
-               if (($admin) && !($canlogin)) {return _ERROR;}
-
+               $notes = sql_real_escape_string($notes);
+               
+               if (($admin) && !($canlogin)) {
+                       return _ERROR;
+               }
+               
                $query = 'INSERT INTO '.sql_table('member')." (MNAME,MREALNAME,MPASSWORD,MEMAIL,MURL, MADMIN, MCANLOGIN, MNOTES) "
                           . "VALUES ('$name','$realname','$password','$email','$url',$admin, $canlogin, '$notes')";
                sql_query($query);
@@ -656,7 +670,7 @@ class MEMBER {
         */
        function getActivationInfo($key)
        {
-               $query = 'SELECT * FROM ' . sql_table('activation') . ' WHERE vkey=\'' . addslashes($key). '\'';
+               $query = 'SELECT * FROM ' . sql_table('activation') . ' WHERE vkey=\'' . sql_real_escape_string($key). '\'';
                $res = sql_query($query);
 
                if (!$res || (sql_num_rows($res) == 0))
@@ -708,7 +722,7 @@ class MEMBER {
                        // attempt to add entry in database
                        // add in database as non-active
                        $query = 'INSERT INTO ' . sql_table('activation'). ' (vkey, vtime, vmember, vtype, vextra) ';
-                       $query .= 'VALUES (\'' . addslashes($key). '\', \'' . date('Y-m-d H:i:s',time()) . '\', \'' . intval($this->getID()). '\', \'' . addslashes($type). '\', \'' . addslashes($extra). '\')';
+                       $query .= 'VALUES (\'' . sql_real_escape_string($key). '\', \'' . date('Y-m-d H:i:s',time()) . '\', \'' . intval($this->getID()). '\', \'' . sql_real_escape_string($type). '\', \'' . sql_real_escape_string($extra). '\')';
                        if (sql_query($query))
                                $ok = true;
                }
@@ -756,7 +770,7 @@ class MEMBER {
                }
 
                // delete from activation table
-               sql_query('DELETE FROM ' . sql_table('activation') . ' WHERE vkey=\'' . addslashes($key) . '\'');
+               sql_query('DELETE FROM ' . sql_table('activation') . ' WHERE vkey=\'' . sql_real_escape_string($key) . '\'');
 
                // success!
                return true;
@@ -774,6 +788,9 @@ class MEMBER {
                if (isset($CONF['ActivationDays']) && intval($CONF['ActivationDays']) > 0) {
                    $actdays = intval($CONF['ActivationDays']);
                }
+               else {
+                       $CONF['ActivationDays'] = 2;
+               }
                $boundary = time() - (60 * 60 * 24 * $actdays);
 
                // 1. walk over all entries, and see if special actions need to be performed
@@ -792,7 +809,7 @@ class MEMBER {
                                case 'addresschange':
                                        // revert the e-mail address of the member back to old address
                                        list($oldEmail, $oldCanLogin) = explode('/', $o->vextra);
-                                       sql_query('UPDATE ' . sql_table('member') . ' SET mcanlogin=' . intval($oldCanLogin). ', memail=\'' . addslashes($oldEmail). '\' WHERE mnumber=' . intval($o->vmember));
+                                       sql_query('UPDATE ' . sql_table('member') . ' SET mcanlogin=' . intval($oldCanLogin). ', memail=\'' . sql_real_escape_string($oldEmail). '\' WHERE mnumber=' . intval($o->vmember));
                                        break;
                                case 'forgot':
                                        // delete the activation link and ignore. member can request a new password using the
index 55c9d6f..aa9409e 100755 (executable)
@@ -80,8 +80,7 @@ class PAGEFACTORY extends BaseActions {
                        'ticket',\r
                        'autosave',\r
                        'autosaveinfo',\r
-                       'ifautosave',\r
-                       'xmldeclaration'\r
+                       'ifautosave'\r
                );\r
 \r
                // TODO: maybe add 'skin' later on?\r
@@ -174,13 +173,6 @@ class PAGEFACTORY extends BaseActions {
                        ADMIN::selectBlogCategory('catid',$catid,$startidx,1,$this->blog->getID());\r
        }\r
 \r
-       function parse_xmldeclaration() {\r
-               $ua = serverVar('HTTP_USER_AGENT');\r
-               if (!(ereg("Windows", $ua) && ereg("MSIE", $ua)) || ereg("MSIE 7", $ua)) {\r
-                       echo '<' . '?xml version="1.0" encoding="' . _CHARSET .'"?' . '>' . "\n";\r
-               }\r
-       }\r
-\r
        function parse_blogid() {\r
                echo $this->blog->getID();\r
        }\r
@@ -288,17 +280,29 @@ class PAGEFACTORY extends BaseActions {
        // extra javascript for input and textarea fields\r
        function parse_jsinput($which) {\r
                global $CONF;\r
-               $out = 'name="' . $which . '" id="input' . $which . '"';\r
+       ?>\r
+                       name="<?php echo $which?>"\r
+                       id="input<?php echo $which?>"\r
+       <?php\r
                if ($CONF['DisableJsTools'] != 1) {\r
-                       $out .= 'onkeyup="storeCaret(this); updPreview(' . $which . '); doMonitor();"'\r
-                                 . 'onclick="storeCaret(this);"'\r
-                                 . 'onselect="storeCaret(this);"';\r
-               } elseif ($CONF['DisableJsTools'] == 0) {\r
-                       $out .= ' onkeyup="doMonitor();" onkeypress="shortCuts();"';\r
-               } else {\r
-                       $out .= ' onkeyup="doMonitor();"';\r
+       ?>\r
+                       onkeyup="storeCaret(this); updPreview('<?php echo $which?>'); doMonitor();"\r
+                       onclick="storeCaret(this);"\r
+                       onselect="storeCaret(this);"\r
+\r
+       <?php\r
+               }\r
+               else if ($CONF['DisableJsTools'] == 0) {\r
+       ?>\r
+                       onkeyup="doMonitor();"\r
+                       onkeypress="shortCuts();"\r
+       <?php\r
+               }\r
+               else {\r
+       ?>\r
+                       onkeyup="doMonitor();"\r
+       <?php\r
                }\r
-               echo $out;\r
        }\r
 \r
        // shows the javascript button bar\r
@@ -420,14 +424,15 @@ class PAGEFACTORY extends BaseActions {
         * convenience method\r
         */\r
        function _jsbutton($type, $code ,$tooltip) {\r
-               echo <<<__JSBUTTON__\r
-                       <span class="jsbutton" onmouseover="BtnHighlight(this);" onmouseout="BtnNormal(this);" onclick="{$code}">\r
-                               <img src="images/button-{$type}.gif" title="{$tooltip}" alt="{$tooltip}" width="16" height="16" />\r
+       ?>\r
+                       <span class="jsbutton"\r
+                               onmouseover="BtnHighlight(this);"\r
+                               onmouseout="BtnNormal(this);"\r
+                               onclick="<?php echo $code?>" >\r
+                               <img src="images/button-<?php echo $type?>.gif" alt="<?php echo $tooltip?>" title="<?php echo $tooltip?>" width="16" height="16"/>\r
                        </span>\r
-\r
-__JSBUTTON__;\r
-       }\r
-\r
+       <?php   }\r
+       \r
        function _jsbuttonspacer() {\r
                echo '<span class="jsbuttonspacer">&nbsp;</span>';\r
        }\r
index 8f4d72e..c07aa26 100755 (executable)
                        $query = 'INSERT INTO ' . sql_table('plugin_option_desc')
                                   .' (opid, oname, ocontext, odesc, otype, odef, oextra)'
                                   .' VALUES ('.intval($this->plugid)
-                                                        .', \''.addslashes($name).'\''
-                                                        .', \''.addslashes($context).'\''
-                                                        .', \''.addslashes($desc).'\''
-                                                        .', \''.addslashes($type).'\''
-                                                        .', \''.addslashes($defValue).'\''
-                                                        .', \''.addslashes($typeExtras).'\')';
+                                                        .', \''.sql_real_escape_string($name).'\''
+                                                        .', \''.sql_real_escape_string($context).'\''
+                                                        .', \''.sql_real_escape_string($desc).'\''
+                                                        .', \''.sql_real_escape_string($type).'\''
+                                                        .', \''.sql_real_escape_string($defValue).'\''
+                                                        .', \''.sql_real_escape_string($typeExtras).'\')';
                        sql_query($query);
                        $oid = sql_insert_id();
 
 
                        // update plugin_option
                        sql_query('DELETE FROM ' . sql_table('plugin_option') . ' WHERE oid='.intval($oid) . ' and ocontextid='. intval($contextid));
-                       sql_query('INSERT INTO ' . sql_table('plugin_option') . ' (ovalue, oid, ocontextid) VALUES (\''.addslashes($value).'\', '. intval($oid) . ', ' . intval($contextid) . ')');
+                       sql_query('INSERT INTO ' . sql_table('plugin_option') . ' (ovalue, oid, ocontextid) VALUES (\''.sql_real_escape_string($value).'\', '. intval($oid) . ', ' . intval($contextid) . ')');
 
                        // update cache
                        $this->_aOptionValues[$oid . '_' . $contextid] = $value;
 
                                // fill DB with default value
                                $query = 'INSERT INTO ' . sql_table('plugin_option') . ' (oid,ocontextid,ovalue)'
-                                          .' VALUES ('.intval($oid).', '.intval($contextid).', \''.addslashes($defVal).'\')';
+                                          .' VALUES ('.intval($oid).', '.intval($contextid).', \''.sql_real_escape_string($defVal).'\')';
                                sql_query($query);
                        }
                        else {
                 */
                function _getOID($context, $name) {
                        $key = $context . '_' . $name;
-                       $info = @$this->_aOptionToInfo[$key];
+                       $info = $this->_aOptionToInfo[$key];
                        if (is_array($info)) return $info['oid'];
 
                        // load all OIDs for this plugin from the database
                        }
                        sql_free_result($res);
 
-                       return @$this->_aOptionToInfo[$key]['oid'];
+                       return $this->_aOptionToInfo[$key]['oid'];
                }
                function _getDefVal($context, $name) {
                        $key = $context . '_' . $name;
                        // delete all associated plugin options
                        $aOIDs = array();
                                // find ids
-                       $query = 'SELECT oid FROM '.sql_table('plugin_option_desc') . ' WHERE ocontext=\''.addslashes($context).'\'';
+                       $query = 'SELECT oid FROM '.sql_table('plugin_option_desc') . ' WHERE ocontext=\''.sql_real_escape_string($context).'\'';
                        $res = sql_query($query);
                        while ($o = sql_fetch_object($res))
                                array_push($aOIDs, $o->oid);
                                                $meta = NucleusPlugin::getOptionMeta($o->oextra);
 
                                                // if the option is readonly or hidden it may not be saved
-                                               if ((@$meta['access'] != 'readonly') && (@$meta['access'] != 'hidden')) {
+                                               if (($meta['access'] != 'readonly') && ($meta['access'] != 'hidden')) {
 
                                                        $value = undoMagic($value);     // value comes from request
 
                                                        }
 
                                                        // check the validity of numerical options
-                                                       if ((@$meta['datatype'] == 'numerical') && (!is_numeric($value))) {
+                                                       if (($meta['datatype'] == 'numerical') && (!is_numeric($value))) {
                                                                //the option must be numeric, but the it isn't
                                                                //use the default for this option
                                                                $value = $o->odef;
 
                                                        // delete the old value for the option
                                                        sql_query('DELETE FROM '.sql_table('plugin_option').' WHERE oid='.intval($oid).' AND ocontextid='.intval($contextid));
-                                                       sql_query('INSERT INTO '.sql_table('plugin_option')." (oid, ocontextid, ovalue) VALUES (".intval($oid).",".intval($contextid).",'" . addslashes($value) . "')");
+                                                       sql_query('INSERT INTO '.sql_table('plugin_option')." (oid, ocontextid, ovalue) VALUES (".intval($oid).",".intval($contextid).",'" . sql_real_escape_string($value) . "')");
                                                }
                                        }
                                }
index c2efc14..1111d71 100755 (executable)
  * $NucleusJP: PLUGINADMIN.php,v 1.8.2.2 2007/10/23 22:48:56 kmorimatsu Exp $
  */
 
-global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;\r
-$aVarsToCheck = array('HTTP_GET_VARS', 'HTTP_POST_VARS', 'HTTP_COOKIE_VARS', 'HTTP_ENV_VARS', 'HTTP_SESSION_VARS', 'HTTP_POST_FILES', 'HTTP_SERVER_VARS', 'GLOBALS', 'argv', 'argc', '_GET', '_POST', '_COOKIE', '_ENV', '_SESSION', '_SERVER', '_FILES', 'DIR_LIBS');\r
-\r
-foreach ($aVarsToCheck 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
-       } else {\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
-if (!isset($DIR_LIBS)) {\r
-       die('Sorry.');\r
-}\r
-\r
-include($DIR_LIBS . 'ADMIN.php');\r
-\r
 class PluginAdmin {\r
 \r
        var $strFullName;               // NP_SomeThing\r
@@ -64,7 +29,8 @@ class PluginAdmin {
        function PluginAdmin($pluginName)\r
        {\r
                global $manager;\r
-\r
+               include_once($DIR_LIBS . 'ADMIN.php');
+               \r
                $this->strFullName = 'NP_' . $pluginName;\r
 \r
                // check if plugin exists and is installed\r
index 209a278..baad7a2 100755 (executable)
  * @version $NucleusJP: SEARCH.php,v 1.7 2006/07/20 08:01:52 kimitake Exp $
  */
 
-class SEARCH
-{
+class SEARCH {
 
-    var $querystring;
-    var $marked;
-    var $inclusive;
-    var $blogs;
+       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 (!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);
-*/
-        $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)
-    {
+               /* * * 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 = sql_real_escape_string($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);
+               
+               # replaced eregi_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
+               # just added delimiters to regex and the 'i' for case-insensitive matching
+               
+               /* convert normal boolean operators to shortened syntax */
+               $result = preg_replace('# not #i', ' -', $result);
+               $result = preg_replace('# and #i', ' ', $result);
+               $result = preg_replace('# or #i', ',', $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]|$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 = $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(" . sql_real_escape_string($match_a[$ith]) . ") -
+                                                       LENGTH(REPLACE(LOWER(" . sql_real_escape_string($match_a[$ith]) . "),LOWER('" . sql_real_escape_string($string) . "'),'')))
+                                                       /LENGTH('" . sql_real_escape_string($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++) {
-//                     $temp_a[$ith] = "(i.$match_a[$ith] LIKE '%" . addslashes($key_a[0]) . "%') ";
-            $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 " . $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 " . $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 " . $binKey . " '%" . addslashes(substr($key_a[$kn], 1)) . "%') ";
-                }
-                $like .=' AND ('. implode(' and ', $temp_a).')';
-            }
-        }
-        
-        $like = '('.$like.')';
-        return $like;
-    }
-
-/***********************************************/
+       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 '%" . sql_real_escape_string($key_a[0]) . "%') ";
+                       $binKey    = preg_match('/[a-zA-Z]/', $key_a[0]) ? '' : 'BINARY';
+                       $temp_a[$ith] = "(i.$match_a[$ith] LIKE " . $binKey . " '%" . sql_real_escape_string($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 '%" . sql_real_escape_string(substr($key_a[$kn],1)) . "%') ";
+                                       $temp_a[$ith] = " (i.$match_a[$ith] LIKE " . $binKey . " '%" . sql_real_escape_string(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 '%" . sql_real_escape_string($key_a[$kn]) . "%') ";
+                                       $temp_a[$ith] = " (i.$match_a[$ith] LIKE " . $binKey . " '%" . sql_real_escape_string($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 '%" . sql_real_escape_string(substr($key_a[$kn],1)) . "%') ";
+                                       $temp_a[$ith] = " NOT(i.$match_a[$ith] LIKE " . $binKey . " '%" . sql_real_escape_string(substr($key_a[$kn], 1)) . "%') ";
+                               }
+                               $like .=' AND ('. implode(' and ', $temp_a).')';
+                       }
+               }
+               
+               $like = '('.$like.')';
+               return $like;
+       }
 }
 ?>
\ No newline at end of file
index 522a25a..7a48b60 100755 (executable)
@@ -66,7 +66,7 @@ class SKIN {
         * @static
         */
        function exists($name) {
-               return quickQuery('select count(*) as result FROM '.sql_table('skin_desc').' WHERE sdname="'.addslashes($name).'"') > 0;
+               return quickQuery('select count(*) as result FROM '.sql_table('skin_desc').' WHERE sdname="'.sql_real_escape_string($name).'"') > 0;
        }
 
        /**
@@ -98,7 +98,7 @@ class SKIN {
        function getIdFromName($name) {
                $query =  'SELECT sdnumber'
                           . ' FROM '.sql_table('skin_desc')
-                          . ' WHERE sdname="'.addslashes($name).'"';
+                          . ' WHERE sdname="'.sql_real_escape_string($name).'"';
                $res = sql_query($query);
                $obj = sql_fetch_object($res);
                return $obj->sdnumber;
@@ -133,7 +133,7 @@ class SKIN {
                        )
                );
 
-               sql_query('INSERT INTO '.sql_table('skin_desc')." (sdname, sddesc, sdtype, sdincmode, sdincpref) VALUES ('" . addslashes($name) . "','" . addslashes($desc) . "','".addslashes($type)."','".addslashes($includeMode)."','".addslashes($includePrefix)."')");
+               sql_query('INSERT INTO '.sql_table('skin_desc')." (sdname, sddesc, sdtype, sdincmode, sdincpref) VALUES ('" . sql_real_escape_string($name) . "','" . sql_real_escape_string($desc) . "','".sql_real_escape_string($type)."','".sql_real_escape_string($includeMode)."','".sql_real_escape_string($includePrefix)."')");
                $newid = sql_insert_id();
 
                $manager->notify(
@@ -153,19 +153,19 @@ class SKIN {
 
        function parse($type) {
                global $manager, $CONF, $skinid;
-
+               
                $manager->notify('InitSkinParse',array('skin' => &$this, 'type' => $type));
-        $skinid = $this->id;
-
+               $skinid = $this->id;
+               
                // set output type
                sendContentType($this->getContentType(), 'skin', _CHARSET);
-
+               
                // set skin name as global var (so plugins can access it)
                global $currentSkinName;
                $currentSkinName = $this->getName();
-
+               
                $contents = $this->getContent($type);
-
+               
                if (!$contents) {
                        // use base skin if this skin does not have contents
                        $defskin =& new SKIN($CONF['BaseSkin']);
@@ -175,30 +175,30 @@ class SKIN {
                                return;
                        }
                }
-
+               
                $actions = $this->getAllowedActionsForType($type);
-
+               
                $manager->notify('PreSkinParse',array('skin' => &$this, 'type' => $type, 'contents' => &$contents));
-        $skinid = $this->id;
-
+               $skinid = $this->id;
+               
                // set IncludeMode properties of parser
                PARSER::setProperty('IncludeMode',$this->getIncludeMode());
                PARSER::setProperty('IncludePrefix',$this->getIncludePrefix());
-
+               
                $handler =& new ACTIONS($type, $this);
                $parser =& new PARSER($actions, $handler);
                $handler->setParser($parser);
                $handler->setSkin($this);
                $parser->parse($contents);
-
+               
                $manager->notify('PostSkinParse',array('skin' => &$this, 'type' => $type));
-        $skinid = $this->id;
+               $skinid = $this->id;
 
 
        }
 
        function getContent($type) {
-               $query = 'SELECT scontent FROM '.sql_table('skin')." WHERE sdesc=$this->id and stype='". addslashes($type) ."'";
+               $query = 'SELECT scontent FROM '.sql_table('skin')." WHERE sdesc=$this->id and stype='". sql_real_escape_string($type) ."'";
                $res = sql_query($query);
 
                if (sql_num_rows($res) == 0)
@@ -214,11 +214,11 @@ class SKIN {
                $skinid = $this->id;
 
                // delete old thingie
-               sql_query('DELETE FROM '.sql_table('skin')." WHERE stype='".addslashes($type)."' and sdesc=" . intval($skinid));
+               sql_query('DELETE FROM '.sql_table('skin')." WHERE stype='".sql_real_escape_string($type)."' and sdesc=" . intval($skinid));
 
                // write new thingie
                if ($content) {
-                       sql_query('INSERT INTO '.sql_table('skin')." SET scontent='" . addslashes($content) . "', stype='" . addslashes($type) . "', sdesc=" . intval($skinid));
+                       sql_query('INSERT INTO '.sql_table('skin')." SET scontent='" . sql_real_escape_string($content) . "', stype='" . sql_real_escape_string($type) . "', sdesc=" . intval($skinid));
                }
        }
 
@@ -234,11 +234,11 @@ class SKIN {
         */
        function updateGeneralInfo($name, $desc, $type = 'text/html', $includeMode = 'normal', $includePrefix = '') {
                $query =  'UPDATE '.sql_table('skin_desc').' SET'
-                          . " sdname='" . addslashes($name) . "',"
-                          . " sddesc='" . addslashes($desc) . "',"
-                          . " sdtype='" . addslashes($type) . "',"
-                          . " sdincmode='" . addslashes($includeMode) . "',"
-                          . " sdincpref='" . addslashes($includePrefix) . "'"
+                          . " sdname='" . sql_real_escape_string($name) . "',"
+                          . " sddesc='" . sql_real_escape_string($desc) . "',"
+                          . " sdtype='" . sql_real_escape_string($type) . "',"
+                          . " sdincmode='" . sql_real_escape_string($includeMode) . "',"
+                          . " sdincpref='" . sql_real_escape_string($includePrefix) . "'"
                           . " WHERE sdnumber=" . $this->getID();
                sql_query($query);
        }
@@ -375,6 +375,7 @@ class SKIN {
                                                                'membermailform',
                                                                'blogsetting',
 //                                                             'nucleusbutton'
+                                                               'categorylist'
                                );
                                break;
                        case 'item':
@@ -401,7 +402,8 @@ class SKIN {
                                break;
                        case 'error':
                                $extraActions = array(
-                                                               'errormessage'
+                                                               'errormessage',
+                                                               'categorylist'
                                );
                                break;
                        default:
@@ -419,6 +421,7 @@ class SKIN {
                                                'prevlink',
                                                'membermailform',
 //                                             'nucleusbutton'
+                                               'categorylist'
                                        );
                                }
                                break;
index 08df604..624b4af 100755 (executable)
@@ -39,7 +39,7 @@ class TEMPLATE {
        function getIdFromName($name) {
                $query =  'SELECT tdnumber'
                           . ' FROM '.sql_table('template_desc')
-                          . ' WHERE tdname="'.addslashes($name).'"';
+                          . ' WHERE tdname="'.sql_real_escape_string($name).'"';
                $res = sql_query($query);
                $obj = sql_fetch_object($res);
                return $obj->tdnumber;
@@ -50,8 +50,8 @@ class TEMPLATE {
         */
        function updateGeneralInfo($name, $desc) {
                $query =  'UPDATE '.sql_table('template_desc').' SET'
-                          . " tdname='" . addslashes($name) . "',"
-                          . " tddesc='" . addslashes($desc) . "'"
+                          . " tdname='" . sql_real_escape_string($name) . "',"
+                          . " tddesc='" . sql_real_escape_string($desc) . "'"
                           . " WHERE tdnumber=" . $this->getID();
                sql_query($query);
        }
@@ -63,11 +63,11 @@ class TEMPLATE {
                $id = $this->getID();
 
                // delete old thingie
-               sql_query('DELETE FROM '.sql_table('template')." WHERE tpartname='". addslashes($type) ."' and tdesc=" . intval($id));
+               sql_query('DELETE FROM '.sql_table('template')." WHERE tpartname='". sql_real_escape_string($type) ."' and tdesc=" . intval($id));
 
                // write new thingie
                if ($content) {
-                       sql_query('INSERT INTO '.sql_table('template')." SET tcontent='" . addslashes($content) . "', tpartname='" . addslashes($type) . "', tdesc=" . intval($id));
+                       sql_query('INSERT INTO '.sql_table('template')." SET tcontent='" . sql_real_escape_string($content) . "', tpartname='" . sql_real_escape_string($type) . "', tdesc=" . intval($id));
                }
        }
 
@@ -95,7 +95,7 @@ class TEMPLATE {
                        )
                );
 
-               sql_query('INSERT INTO '.sql_table('template_desc')." (tdname, tddesc) VALUES ('" . addslashes($name) . "','" . addslashes($desc) . "')");
+               sql_query('INSERT INTO '.sql_table('template_desc')." (tdname, tddesc) VALUES ('" . sql_real_escape_string($name) . "','" . sql_real_escape_string($desc) . "')");
                $newId = sql_insert_id();
 
                $manager->notify(
@@ -129,7 +129,7 @@ class TEMPLATE {
 
                $query = 'SELECT tpartname, tcontent'
                           . ' FROM '.sql_table('template_desc').', '.sql_table('template')
-                          . ' WHERE tdesc=tdnumber and tdname="' . addslashes($name) . '"';
+                          . ' WHERE tdesc=tdnumber and tdname="' . sql_real_escape_string($name) . '"';
                $res = sql_query($query);
                while ($obj = sql_fetch_object($res))
                        $template[$obj->tpartname] = $obj->tcontent;
@@ -168,7 +168,7 @@ class TEMPLATE {
        // returns true if there is a template with the given shortname
        // (static)
        function exists($name) {
-               $r = sql_query('select * FROM '.sql_table('template_desc').' WHERE tdname="'.addslashes($name).'"');
+               $r = sql_query('select * FROM '.sql_table('template_desc').' WHERE tdname="'.sql_real_escape_string($name).'"');
                return (sql_num_rows($r) != 0);
        }
 
index 50fd091..f13edec 100755 (executable)
@@ -298,7 +298,7 @@ class Backup
                                        echo ' NULL';\r
                                } elseif ($row[$j] != '') {\r
                                        // data\r
-                                       echo " '" . addslashes($row[$j]) . "'";\r
+                                       echo " '" . sql_real_escape_string($row[$j]) . "'";\r
                                } else {\r
                                        // empty column (!= no data!)\r
                                        echo "''";\r
index d78a923..eac38fe 100755 (executable)
 // needed if we include globalfunctions from install.php\r
 global $nucleus, $CONF, $DIR_LIBS, $DIR_LANG, $manager, $member;\r
 \r
-$nucleus['version'] = 'v3.51';\r
+$nucleus['version'] = 'v3.61';\r
 $nucleus['codename'] = '';\r
 \r
+// check and die if someone is trying to override internal globals (when register_globals turn on)\r
 checkVars(array('nucleus', 'CONF', 'DIR_LIBS', 'MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE', 'DIR_LANG', 'DIR_PLUGINS', 'HTTP_GET_VARS', 'HTTP_POST_VARS', 'HTTP_COOKIE_VARS', 'HTTP_ENV_VARS', 'HTTP_SESSION_VARS', 'HTTP_POST_FILES', 'HTTP_SERVER_VARS', 'GLOBALS', 'argv', 'argc', '_GET', '_POST', '_COOKIE', '_ENV', '_SESSION', '_SERVER', '_FILES'));\r
 \r
 $CONF['debug'] = 0;\r
 if ($CONF['debug']) {\r
-    error_reporting(E_ALL); // report all errors!\r
+       error_reporting(E_ALL); // report all errors!\r
 } else {\r
-    ini_set('display_errors','0');\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['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['ItemURL']                = $CONF['Self'];\r
+$CONF['ArchiveURL']              = $CONF['Self'];\r
+$CONF['ArchiveListURL']          = $CONF['Self'];\r
+$CONF['MemberURL']                = $CONF['Self'];\r
+$CONF['SearchURL']                = $CONF['Self'];\r
+$CONF['BlogURL']                        = $CONF['Self'];\r
+$CONF['CategoryURL']            = $CONF['Self'];\r
 \r
 // switch URLMode back to normal when $CONF['Self'] ends in .php\r
 // this avoids urls like index.php/item/13/index.php/item/15\r
 if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {\r
-    $CONF['URLMode'] = 'normal';\r
+       $CONF['URLMode'] = 'normal';\r
 }*/\r
 \r
+/*\r
+       Set these to 1 to allow viewing of future items or draft items\r
+       Should really never do this, but can be useful for some plugins that might need to\r
+       Could cause some other issues if you use future posts otr drafts\r
+       So use with care\r
+*/\r
+$CONF['allowDrafts'] = 0;\r
+$CONF['allowFuture'] = 0;\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
@@ -90,40 +100,40 @@ $orgRequestURI = serverVar('REQUEST_URI');
 sanitizeParams();\r
 \r
 // get all variables that can come from the request and put them in the global scope\r
-$blogid       = requestVar('blogid');\r
-$itemid       = intRequestVar('itemid');\r
-$catid        = intRequestVar('catid');\r
-$skinid       = requestVar('skinid');\r
-$memberid     = requestVar('memberid');\r
+$blogid           = requestVar('blogid');\r
+$itemid           = intRequestVar('itemid');\r
+$catid         = intRequestVar('catid');\r
+$skinid           = requestVar('skinid');\r
+$memberid       = requestVar('memberid');\r
 $archivelist  = requestVar('archivelist');\r
 $imagepopup   = requestVar('imagepopup');\r
-$archive      = requestVar('archive');\r
-$query        = requestVar('query');\r
-$highlight    = requestVar('highlight');\r
-$amount       = requestVar('amount');\r
-$action       = requestVar('action');\r
+$archive         = requestVar('archive');\r
+$query         = requestVar('query');\r
+$highlight     = requestVar('highlight');\r
+$amount           = requestVar('amount');\r
+$action           = requestVar('action');\r
 $nextaction   = requestVar('nextaction');\r
 $maxresults   = requestVar('maxresults');\r
-$startpos     = intRequestVar('startpos');\r
+$startpos       = intRequestVar('startpos');\r
 $errormessage = '';\r
-$error        = '';\r
-$special      = requestVar('special');\r
+$error         = '';\r
+$special         = requestVar('special');\r
 $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
+include_once($DIR_LIBS . 'mysql.php');\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
 include($DIR_LIBS . 'MEMBER.php');\r
 include($DIR_LIBS . 'ACTIONLOG.php');\r
 include($DIR_LIBS . 'MANAGER.php');\r
@@ -134,18 +144,18 @@ $manager =& MANAGER::instance();
 // make sure there's no unnecessary escaping:\r
 //set_magic_quotes_runtime(0);\r
 if (version_compare(PHP_VERSION, '5.3.0', '<')) {\r
-    ini_set('magic_quotes_runtime', '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
@@ -154,14 +164,14 @@ $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
-    if ($bLoggingSanitizedResult) {\r
-        addToLog(WARNING, $msg);\r
-    }\r
-    if (!$bSanitizeAndContinue) {\r
-        die("");\r
-    }\r
+       $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";\r
+       $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');\r
+       if ($bLoggingSanitizedResult) {\r
+               addToLog(WARNING, $msg);\r
+       }\r
+       if (!$bSanitizeAndContinue) {\r
+               die("");\r
+       }\r
 }\r
 \r
 // makes sure database connection gets closed on script termination\r
@@ -172,19 +182,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['ItemURL']                = $CONF['Self'];\r
+       $CONF['ArchiveURL']      = $CONF['Self'];\r
+       $CONF['ArchiveListURL'] = $CONF['Self'];\r
+       $CONF['MemberURL']        = $CONF['Self'];\r
+       $CONF['SearchURL']        = $CONF['Self'];\r
+       $CONF['BlogURL']                = $CONF['Self'];\r
+       $CONF['CategoryURL']    = $CONF['Self'];*/\r
 }\r
 \r
 $CONF['ItemURL'] = $CONF['Self'];\r
@@ -198,12 +208,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
@@ -213,99 +223,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
+       // 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
+       // 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
@@ -314,8 +324,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
@@ -336,183 +346,218 @@ 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 . preg_replace( '@\\|/@', '', $language) . '.php');\r
+\r
+# replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0\r
+# original ereg_replace: ereg_replace( '[\\|/]', '', $language) . '.php')\r
+# important note that '\' must be matched with '\\\\' in preg* expressions\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
+if (!defined('_ARCHIVETYPE_MONTH') )\r
+{\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
-\r
-                case $CONF['SpecialskinKey']:\r
-                    $i++;\r
-\r
-                    if ($i < sizeof($data) ) {\r
-                        $_REQUEST['special'] = $data[$i];\r
-                    }\r
-                    break;\r
-\r
-                default:\r
-                    // skip...\r
-            }\r
-        }\r
-    }\r
+       // initialize keywords if this hasn't been done before\r
+       if (!isset($CONF['ItemKey']) || $CONF['ItemKey'] == '') {\r
+               $CONF['ItemKey'] = 'item';\r
+       }\r
+\r
+       if (!isset($CONF['ArchiveKey']) || $CONF['ArchiveKey'] == '') {\r
+               $CONF['ArchiveKey'] = 'archive';\r
+       }\r
+\r
+       if (!isset($CONF['ArchivesKey']) || $CONF['ArchivesKey'] == '') {\r
+               $CONF['ArchivesKey'] = 'archives';\r
+       }\r
+\r
+       if (!isset($CONF['MemberKey']) || $CONF['MemberKey'] == '') {\r
+               $CONF['MemberKey'] = 'member';\r
+       }\r
+\r
+       if (!isset($CONF['BlogKey']) || $CONF['BlogKey'] == '') {\r
+               $CONF['BlogKey'] = 'blog';\r
+       }\r
+\r
+       if (!isset($CONF['CategoryKey']) || $CONF['CategoryKey'] == '') {\r
+               $CONF['CategoryKey'] = 'category';\r
+       }\r
+\r
+       if (!isset($CONF['SpecialskinKey']) || $CONF['SpecialskinKey'] == '') {\r
+               $CONF['SpecialskinKey'] = 'special';\r
+       }\r
+\r
+       $parsed = false;\r
+       $manager->notify(\r
+               'ParseURL',\r
+               array(\r
+                       'type' => basename(serverVar('SCRIPT_NAME') ), // e.g. item, blog, ...\r
+                       'info' => $virtualpath,\r
+                       'complete' => &$parsed\r
+               )\r
+       );\r
+\r
+       if (!$parsed) {\r
+               // default implementation\r
+               $data = explode("/", $virtualpath );\r
+               for ($i = 0; $i < sizeof($data); $i++) {\r
+                       switch ($data[$i]) {\r
+                               case $CONF['ItemKey']: // item/1 (blogid)\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $itemid = intval($data[$i]);\r
+                                       }\r
+                                       break;\r
+\r
+                               case $CONF['ArchivesKey']: // archives/1 (blogid)\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $archivelist = intval($data[$i]);\r
+                                       }\r
+                                       break;\r
+\r
+                               case $CONF['ArchiveKey']: // two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid)\r
+                                       if ((($i + 1) < sizeof($data) ) && (!strstr($data[$i + 1], '-') ) ) {\r
+                                               $blogid = intval($data[++$i]);\r
+                                       }\r
+\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $archive = $data[$i];\r
+                                       }\r
+                                       break;\r
+\r
+                               case 'blogid': // blogid/1\r
+                               case $CONF['BlogKey']: // blog/1\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $blogid = intval($data[$i]);\r
+                                       }\r
+                                       break;\r
+\r
+                               case $CONF['CategoryKey']: // category/1 (catid)\r
+                               case 'catid':\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $catid = intval($data[$i]);\r
+                                       }\r
+                                       break;\r
+\r
+                               case $CONF['MemberKey']:\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $memberid = intval($data[$i]);\r
+                                       }\r
+                                       break;\r
+\r
+                               case $CONF['SpecialskinKey']:\r
+                                       $i++;\r
+\r
+                                       if ($i < sizeof($data) ) {\r
+                                               $_REQUEST['special'] = $data[$i];\r
+                                       }\r
+                                       break;\r
+\r
+                               default:\r
+                                       // skip...\r
+                       }\r
+               }\r
+       }\r
+}\r
+/*     PostParseURL is a place to cleanup any of the path-related global variables before the selector function is run.\r
+       It has 2 values in the data in case the original virtualpath is needed, but most the use will be in tweaking\r
+       global variables to clean up (scrub out catid or add catid) or to set someother global variable based on\r
+       the values of something like catid or itemid\r
+       New in 3.60\r
+*/\r
+$manager->notify(\r
+       'PostParseURL',\r
+       array(\r
+               'type' => basename(serverVar('SCRIPT_NAME') ), // e.g. item, blog, ...\r
+               'info' => $virtualpath\r
+       )\r
+);\r
+\r
+function include_libs($file,$once=true,$require=true){\r
+       global $DIR_LIBS;\r
+       if (!is_dir($DIR_LIBS)) exit;\r
+       if ($once && $require) require_once($DIR_LIBS.$file);\r
+       elseif ($once && !$require) include_once($DIR_LIBS.$file);\r
+       elseif ($require) require($DIR_LIBS.$file);\r
+       else include($DIR_LIBS.$file);\r
+}\r
+\r
+function include_plugins($file,$once=true,$require=true){\r
+       global $DIR_PLUGINS;\r
+       if (!is_dir($DIR_PLUGINS)) exit;\r
+       if ($once && $require) require_once($DIR_PLUGINS.$file);\r
+       elseif ($once && !$require) include_once($DIR_PLUGINS.$file);\r
+       elseif ($require) require($DIR_PLUGINS.$file);\r
+       else include($DIR_PLUGINS.$file);\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 351;\r
+       return 361;\r
 }\r
 \r
 /**\r
@@ -521,7 +566,7 @@ function getNucleusVersion() {
  * be tested without having to install CVS.\r
  */\r
 function getNucleusPatchLevel() {\r
-    return 0;\r
+       return 0;\r
 }\r
 \r
 /**\r
@@ -531,15 +576,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
@@ -548,86 +593,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
@@ -635,18 +680,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
@@ -654,7 +699,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
@@ -662,555 +707,569 @@ 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
 /**\r
  * Highlights a specific query in a given HTML text (not within HTML tags) and returns it\r
- *\r
- * @param $text\r
- *             text to be highlighted\r
- * @param $expression\r
- *             regular expression to be matched (can be an array of expressions as well)\r
- * @param $highlight\r
- *             highlight to be used (use \\0 to indicate the matched expression)\r
- *\r
- */\r
+ * @param string $text text to be highlighted\r
+ * @param string $expression regular expression to be matched (can be an array of expressions as well)\r
+ * @param string $highlight highlight to be used (use \\0 to indicate the matched expression)\r
+ * @return string\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
+       {\r
+               return $text;\r
+       }\r
+\r
+       if (is_array($expression) && (count($expression) == 0) )\r
+       {\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
+       $count_matches = count($matches[2]);\r
+       for ($i = 0; $i < $count_matches; $i++) {\r
+               if ($i != 0)\r
+               {\r
+                       $result .= $matches[1][$i];\r
+               }\r
+\r
+               if (is_array($expression) )\r
+               {\r
+                       foreach ($expression as $regex)\r
+                       {\r
+                               if ($regex)\r
+                               {\r
+                                       $matches[2][$i] = @eregi_replace($regex, $highlight, $matches[2][$i]);\r
+                               }\r
+                       }\r
+\r
+                       $result .= $matches[2][$i];\r
+               }\r
+               else\r
+               {\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
+       // enhancement made in 3.6x based on code by Quandary.\r
+       if (preg_match('/^(?!\\.)(?:\\.?[-a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~]+)+@(?!\\.)(?:\\.?(?!-)[-a-zA-Z0-9]+(?<!-)){2,}$/', $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="' . sql_real_escape_string($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="' . sql_real_escape_string($name) . '"');\r
 }\r
 \r
 function quickQuery($q) {\r
-    $res = sql_query($q);\r
-    $obj = sql_fetch_object($res);\r
-    return isset($obj->result) ? $obj->result : false;\r
+       $res = sql_query($q);\r
+       $obj = sql_fetch_object($res);\r
+       return $obj->result;\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 isset($obj->pfile) ? $obj->pfile : false;\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
 }\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
-//             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
+       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 = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';\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,intval($CONF['allowFuture']),intval($CONF['allowDrafts']) ) {\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
+               \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
+       // set global skinpart variable so can determine quickly what is being parsed from any plugin or phpinclude\r
+       global $skinpart;\r
+       $skinpart = $type;\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
+       global $errormessage, $CONF, $skinid, $blogid, $manager;\r
 \r
-    if ($skin == '') {\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
+               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
+       # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
+       # original eregi: eregi('^[a-z0-9]+$', $name)\r
+       return preg_match('#^[a-z0-9]+$#i', $name);\r
 }\r
 \r
 function isValidDisplayName($name) {\r
-    return eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name);\r
+       # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
+       # original eregi: eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name)\r
+       return preg_match('#^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$#i', $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
+       # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
+       # original eregi: eregi('^[a-z0-9/]+$', $name)\r
+       return preg_match('#^[a-z0-9/]+$#i', $name);\r
 }\r
 \r
 function isValidSkinName($name) {\r
-    return eregi('^[a-z0-9/]+$', $name);\r
+       # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0\r
+       # original eregi: eregi('^[a-z0-9/]+$', $name);\r
+       return preg_match('#^[a-z0-9/]+$#i', $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
+               $text = mb_strimwidth($text, 0, $maxlength, $toadd, _CHARSET); // for Japanese\r
+       }\r
 \r
-    return $text;\r
+       return $text;\r
 }\r
 \r
 /**\r
@@ -1218,25 +1277,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
@@ -1244,86 +1303,92 @@ 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
-    include($DIR_LANG . preg_replace( '@\\|/@', '', $language) . '.php');\r
+\r
+       global $DIR_LANG;\r
+\r
+       # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0\r
+       # original ereg_replace: preg_replace( '@\\|/@', '', $language) . '.php')\r
+       # important note that '\' must be matched with '\\\\' in preg* expressions\r
+\r
+       include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');\r
+\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
@@ -1334,214 +1399,229 @@ 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
+       // 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
+       // 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
+       // 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
+       // 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
+       if (@file_exists($filename) ) {\r
+               include($filename);\r
+       }\r
 }\r
 \r
 /**\r
-  * Checks if a certain language/plugin exists\r
-  */\r
+ * Checks if a certain language exists\r
+ * @param string $lang\r
+ * @return bool\r
+ **/\r
 function checkLanguage($lang) {\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
+       global $DIR_LANG;\r
+       # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0\r
+       # original ereg_replace: ereg_replace( '[\\|/]', '', $lang) . '.php')\r
+       # important note that '\' must be matched with '\\\\' in preg* expressions\r
+       return file_exists($DIR_LANG . preg_replace('#[\\\\|/]#', '', $lang) . '.php');\r
 }\r
 \r
+/**\r
+ * Checks if a certain plugin exists\r
+ * @param string $plug\r
+ * @return bool\r
+ **/\r
 function checkPlugin($plug) {\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
+       global $DIR_PLUGINS;\r
+\r
+       # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0\r
+       # original ereg_replace: ereg_replace( '[\\|/]', '', $plug) . '.php')\r
+       # important note that '\' must be matched with '\\\\' in preg* expressions\r
+\r
+       return file_exists($DIR_PLUGINS . preg_replace('#[\\\\|/]#', '', $plug) . '.php');\r
+\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
-    global $CONF;\r
-    if ($CONF['URLMode'] == 'normal') {\r
-        if (strpos($url, '?') === FALSE && is_array($params)) {\r
-            $fParam = reset($params);\r
-            $fKey   = key($params);\r
-            array_shift($params);\r
-            $url .= '?' . $fKey . '=' . $fParam;\r
-        }\r
-    } elseif ($CONF['URLMode'] == 'pathinfo' && substr($url, -1) == '/') {\r
-        $url = substr($url, 0, -1);\r
-    }\r
-    return addLinkParams($url, $params);\r
+       global $CONF;\r
+       if ($CONF['URLMode'] == 'normal') {\r
+               if (strpos($url, '?') === FALSE && is_array($params)) {\r
+                       $fParam = reset($params);\r
+                       $fKey   = key($params);\r
+                       array_shift($params);\r
+                       $url .= '?' . $fKey . '=' . $fParam;\r
+               }\r
+       } elseif ($CONF['URLMode'] == 'pathinfo' && substr($url, -1) == '/') {\r
+               $url = substr($url, 0, -1);\r
+       }\r
+       return addLinkParams($url, $params);\r
 }\r
 \r
 function addLinkParams($link, $params) {\r
-    global $CONF;\r
+       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
@@ -1555,185 +1635,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
+       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
+       foreach ($aVars as $varName) {\r
 \r
-        if (phpversion() >= '4.1.0') {\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
+                       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
+               } 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
+                       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
@@ -1743,47 +1823,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
@@ -1792,139 +1872,180 @@ 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_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
+       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
+       {\r
+               if (!file_exists($p_translated) )\r
+               {\r
+                       $p_translated = '';\r
+               }\r
+       }\r
+       \r
+       if (!$p_translated)\r
+       {\r
+               $p_translated = serverVar('SCRIPT_FILENAME');\r
+               if (!file_exists($p_translated) )\r
+               {\r
+                       header("HTTP/1.0 404 Not Found");\r
+                       exit('');\r
+               }\r
+       }\r
+       \r
+       $p_translated=str_replace('\\','/',$p_translated);\r
+       $d_plugins=str_replace('\\','/',$DIR_PLUGINS);\r
+       \r
+       if (strpos($p_translated, $d_plugins) !== 0)\r
+       {\r
+               return;// This isn't plugin php file.\r
+       }\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
+       {\r
+               $name=substr($row[0],3);\r
+               $plugins[strtolower($name)]=$name;\r
+       }\r
+       sql_free_result($res);\r
+       \r
+       if ($plugins[$path])\r
+       {\r
+               $plugin_name = $plugins[$path];\r
+       }\r
+       else if (in_array($path, $plugins))\r
+       {\r
+               $plugin_name = $path;\r
+       }\r
+       else\r
+       {\r
+               header("HTTP/1.0 404 Not Found");\r
+               exit('');\r
+       }\r
+       \r
+       /* Return if not index.php */\r
+       if ( $phppath!=strtolower($plugin_name).'/' && $phppath!=strtolower($plugin_name).'/index.php' ) {\r
+               return;\r
+       }\r
+\r
+       /* Exit if not logged in. */\r
+       if ( !$member->isLoggedIn() ) {\r
+               exit(_GFUNCTIONS_YOU_AERNT_LOGGEDIN);\r
+       }\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'))) {\r
+               $p_translated=serverVar('SCRIPT_FILENAME');\r
+       }\r
+       if ($file=@file($p_translated))\r
+       {\r
+               $prevline='';\r
+               foreach($file as $line)\r
+               {\r
+                       if (preg_match('/[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]/i',$prevline.$line)) {\r
+                               return;\r
+                       }\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
+               {\r
+                       $language = getLanguageName();\r
+                       \r
+                       # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0\r
+                       # original ereg_replace: ereg_replace( '[\\|/]', '', $language) . '.php')\r
+                       # important note that '\' must be matched with '\\\\' in preg* expressions\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
+               {\r
+                       if (file_exists($DIR_LIBS.'mb_emulator/mb-emulator.php'))\r
+                       {\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
+               {\r
+                       list($uri,$qstring)=explode('?',$uri);\r
+               } else {\r
+                       if ( !($uri=serverVar('PHP_SELF')) ) {\r
+                               $uri=serverVar('SCRIPT_NAME');\r
+                       }\r
+                       $qstring=serverVar('QUERY_STRING');\r
+               }\r
+               if ($qstring) {\r
+                       $qstring='?'.$qstring;\r
+               }\r
+               echo '<p>'._SETTINGS_UPDATE.' : '._QMENU_PLUGINS.' <span style="color:red;">'.htmlspecialchars($plugin_name)."</span> ?</p>\n";\r
+               switch(strtoupper(serverVar('REQUEST_METHOD')))\r
+               {\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
@@ -1933,26 +2054,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
@@ -1961,14 +2082,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
@@ -1979,45 +2100,47 @@ 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
+               // note that we must use addslashes here because this function is called before the db connection is made\r
+               // and sql_real_escape_string needs a db connection\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
@@ -2025,12 +2148,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
@@ -2038,10 +2161,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
@@ -2050,9 +2173,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
@@ -2062,15 +2185,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
@@ -2078,17 +2201,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
@@ -2097,28 +2220,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
@@ -2137,8 +2260,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
@@ -2151,13 +2274,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
@@ -2166,15 +2289,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=710,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=710,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
@@ -2185,11 +2308,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
@@ -2199,15 +2322,47 @@ 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
+/**\r
+ * sets $special global variable for use in index.php before selector()\r
+ *\r
+ * @param String id\r
+ * @return nothing\r
+ */\r
 function selectSpecialSkinType($id) {\r
-    global $special;\r
-    $special = strtolower($id);\r
+       global $special;\r
+       $special = strtolower($id);\r
 }\r
 \r
+/**\r
+ * cleans filename of uploaded file for writing to file system\r
+ *\r
+ * @param String str\r
+ * @return String cleaned filename ready for use\r
+ */\r
+function cleanFileName($str) {\r
+       $cleaner = array();\r
+       $cleaner[] = array('expression'=>"/[àáäãâª]/",'replace'=>"a");\r
+       $cleaner[] = array('expression'=>"/[èéêë]/",'replace'=>"e");\r
+       $cleaner[] = array('expression'=>"/[ìíîï]/",'replace'=>"i");\r
+       $cleaner[] = array('expression'=>"/[òóõôö]/",'replace'=>"o");\r
+       $cleaner[] = array('expression'=>"/[ùúûü]/",'replace'=>"u");\r
+       $cleaner[] = array('expression'=>"/[ñ]/",'replace'=>"n");\r
+       $cleaner[] = array('expression'=>"/[ç]/",'replace'=>"c");\r
+       \r
+       $str = strtolower($str);\r
+       $ext_point = strripos($str,".");\r
+       if ($ext_point===false) return false;\r
+       $ext = substr($str,$ext_point,strlen($str));\r
+       $str = substr($str,0,$ext_point);\r
+       \r
+       foreach( $cleaner as $cv ) $str = preg_replace($cv["expression"],$cv["replace"],$str);\r
+       \r
+       return preg_replace("/[^a-z0-9-]/","_",$str).$ext;\r
+}\r
 ?>
\ No newline at end of file
index 2b0d4dc..abbdb1b 100644 (file)
@@ -115,8 +115,11 @@ if (!function_exists('mysql_query'))
                global $MYSQL_CONN;
                return mysqli_affected_rows($MYSQL_CONN);
        }
-}
-
-
 
+       function mysql_real_escape_string($val)
+       {
+               global $MYSQL_CONN;
+               return mysqli_real_escape_string($MYSQL_CONN,$val);
+       }
+}
 ?>
\ No newline at end of file
index ff351f9..a0d1304 100644 (file)
@@ -186,7 +186,6 @@ function listplug_table_pluginlist($template, $type) {
                                        echo _LIST_PLUGS_VER, ' ' , htmlspecialchars($plug->getVersion()) , '<br />';
                                        if ($plug->getURL())
                                        echo '<a href="',htmlspecialchars($plug->getURL()),'" tabindex="'.$template['tabindex'].'">',_LIST_PLUGS_SITE,'</a><br />';
-//                                     echo '<a href="',htmlspecialchars($plug->getURL()),'" tabindex="'.$template['tabindex'].'">'.htmlspecialchars(shorten($plug->getURL(), 25, '...')),'</a><br />';
                                echo '</td>';
                                echo '<td>';
                                        echo _LIST_PLUGS_DESC .'<br/>'. encode_desc($plug->getDescription());
@@ -273,7 +272,7 @@ function listplug_plugOptionRow($current) {
        $meta = NucleusPlugin::getOptionMeta($current['typeinfo']);
 
        // only if it is not a hidden option write the controls to the page
-       if (@$meta['access'] != 'hidden') {
+       if ($meta['access'] != 'hidden') {
                echo '<td>',htmlspecialchars($current['description']?$current['description']:$current['name']),'</td>';
                echo '<td>';
                switch($current['type']) {
@@ -298,7 +297,7 @@ function listplug_plugOptionRow($current) {
                        case 'textarea':
                                //$meta = NucleusPlugin::getOptionMeta($current['typeinfo']);
                                echo '<textarea class="pluginoption" cols="30" rows="5" name="',htmlspecialchars($varname),'"';
-                               if (@$meta['access'] == 'readonly') {
+                               if ($meta['access'] == 'readonly') {
                                        echo ' readonly="readonly"';
                                }
                                echo '>',htmlspecialchars($current['value']),'</textarea>';
@@ -308,15 +307,15 @@ function listplug_plugOptionRow($current) {
                                //$meta = NucleusPlugin::getOptionMeta($current['typeinfo']);
 
                                echo '<input type="text" size="40" maxlength="128" name="',htmlspecialchars($varname),'" value="',htmlspecialchars($current['value']),'"';
-                               if (@$meta['datatype'] == 'numerical') {
+                               if ($meta['datatype'] == 'numerical') {
                                        echo ' onkeyup="checkNumeric(this)" onblur="checkNumeric(this)"';
                                }
-                               if (@$meta['access'] == 'readonly') {
+                               if ($meta['access'] == 'readonly') {
                                        echo ' readonly="readonly"';
                                }
                                echo ' />';
                }
-               echo @$current['extra'];
+               echo $current['extra'];
                echo '</td>';
        }
 }
@@ -371,8 +370,7 @@ function listplug_table_itemlist($template, $type) {
                        echo " / <a href='index.php?action=itemdelete&amp;itemid={$current->inumber}'>" . _LISTS_DELETE . "</a><br />";
                        // evaluate amount of comments for the item
                        $camount = $COMMENTS->amountComments();
-                       if ($camount>0)
-                       {
+                       if ($camount>0) {
                                echo "<a href='index.php?action=itemcommentlist&amp;itemid=$current->inumber'>";
                                echo "( " . sprintf(_LIST_ITEM_COMMENTS, $COMMENTS->amountComments())." )</a>";
                        }
index bd29881..a9fdc4c 100755 (executable)
@@ -27,287 +27,288 @@ $MYSQL_CONN = 0;
 
 if (function_exists('mysql_query') && !function_exists('sql_fetch_assoc'))
 {
-    /**
-     *Errors before the database connection has been made
-     */
-    function startUpError($msg, $title) {
-        ?>
+       /**
+        *Errors before the database connection has been made
+        */
+       function startUpError($msg, $title) {
+               ?>
 <html xmlns="http://www.w3.org/1999/xhtml">
-    <head><title><?php echo htmlspecialchars($title)?></title></head>
-    <body>
-        <h1><?php echo htmlspecialchars($title)?></h1>
-        <?php echo $msg?>
-    </body>
+       <head><title><?php echo htmlspecialchars($title)?></title></head>
+       <body>
+               <h1><?php echo htmlspecialchars($title)?></h1>
+               <?php echo $msg?>
+       </body>
 </html>
 <?php
-        exit;
-    }
+               exit;
+       }
 
-    /**
-      * Connects to mysql server with arguments
-      */
-    function sql_connect_args($mysql_host = 'localhost', $mysql_user = '', $mysql_password = '', $mysql_database = '') {
-        
-        $CONN = @mysql_connect($mysql_host, $mysql_user, $mysql_password);
-        if ($mysql_database) mysql_select_db($mysql_database,$CONN);
+       /**
+         * Connects to mysql server with arguments
+         */
+       function sql_connect_args($mysql_host = 'localhost', $mysql_user = '', $mysql_password = '', $mysql_database = '') {
+               
+               $CONN = @mysql_connect($mysql_host, $mysql_user, $mysql_password);
+               if ($mysql_database) mysql_select_db($mysql_database,$CONN);
 
-        return $CONN;
-    }
-    
-    /**
-      * Connects to mysql server
-      */
-    function sql_connect() {
-        global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_CONN;
+               return $CONN;
+       }
+       
+       /**
+         * Connects to mysql server
+         */
+       function sql_connect() {
+               global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_CONN;
 
-        $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');
+               $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>
-        $resource = sql_query("show variables LIKE 'character_set_database'");
-        $fetchDat = sql_fetch_assoc($resource);
-        $charset  = $fetchDat['Value'];
-        $mySqlVer = implode('.', array_map('intval', explode('.', sql_get_server_info($MYSQL_CONN))));
-        if ($mySqlVer >= '5.0.7' && phpversion() >= '5.2.3') {
-            mysql_set_charset($charset);
-        } elseif ($mySqlVer >= '4.1.0') {
-            sql_query("SET CHARACTER SET " . $charset);
-        }
+               $resource = sql_query("show variables LIKE 'character_set_database'");
+               $fetchDat = sql_fetch_assoc($resource);
+               $charset  = $fetchDat['Value'];
+               $mySqlVer = implode('.', array_map('intval', explode('.', sql_get_server_info($MYSQL_CONN))));
+               if ($mySqlVer >= '5.0.7' && phpversion() >= '5.2.3') {
+                       mysql_set_charset($charset);
+               } elseif ($mySqlVer >= '4.1.0') {
+                       sql_query("SET CHARACTER SET " . $charset);
+               }
 // </add for garble measure>*/
 
-        return $MYSQL_CONN;
-    }
+               return $MYSQL_CONN;
+       }
 
-    /**
-      * disconnects from SQL server
-      */
-    function sql_disconnect($conn = false) {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        @mysql_close($conn);
-    }
-    
-    function sql_close($conn = false) {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        @mysql_close($conn);
-    }
-    
-    /**
-      * executes an SQL query
-      */
-    function sql_query($query, $conn = false) {
-        global $SQLCount,$MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        $SQLCount++;
-        $res = mysql_query($query,$conn) or print("mySQL error with query $query: " . mysql_error($conn) . '<p />');
-        return $res;
-    }
-    
-    /**
-      * executes an SQL error
-      */
-    function sql_error($conn = false)
-    {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        return mysql_error($conn);
-    }
-    
-    /**
-      * executes an SQL db select
-      */
-    function sql_select_db($db,$conn = false)
-    {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        return mysql_select_db($db,$conn);
-    }
-    
-    /**
-      * executes an SQL real escape 
-      */
-    function sql_real_escape_string($val,$conn = false)
-    {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        return mysql_real_escape_string($val,$conn);
-    }
-    
-    /**
-      * executes an PDO::quote() like escape, ie adds quotes arround the string and escapes chars as needed 
-      */
-    function sql_quote_string($val,$conn = false) {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        return "'".mysql_real_escape_string($val,$conn)."'";
-    }
-    
-    /**
-      * executes an SQL insert id
-      */
-    function sql_insert_id($conn = false)
-    {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        return mysql_insert_id($conn);
-    }
-    
-    /**
-      * executes an SQL result request
-      */
-    function sql_result($res, $row, $col)
-    {
-        return mysql_result($res,$row,$col);
-    }
-    
-    /**
-      * frees sql result resources
-      */
-    function sql_free_result($res)
-    {
-        return mysql_free_result($res);
-    }
-    
-    /**
-      * returns number of rows in SQL result
-      */
-    function sql_num_rows($res)
-    {
-        return mysql_num_rows($res);
-    }
-    
-    /**
-      * returns number of rows affected by SQL query
-      */
-    function sql_affected_rows($res)
-    {
-        return mysql_affected_rows($res);
-    }
-    
-    /**
-      * Get number of fields in result
-      */
-    function sql_num_fields($res)
-    {
-        return mysql_num_fields($res);
-    }
-    
-    /**
-      * fetches next row of SQL result as an associative array
-      */
-    function sql_fetch_assoc($res)
-    {
-        return mysql_fetch_assoc($res);
-    }
-    
-    /**
-      * Fetch a result row as an associative array, a numeric array, or both
-      */
-    function sql_fetch_array($res)
-    {
-        return mysql_fetch_array($res);
-    }
-    
-    /**
-      * fetches next row of SQL result as an object
-      */
-    function sql_fetch_object($res)
-    {
-        return mysql_fetch_object($res);
-    }
-    
-    /**
-      * Get a result row as an enumerated array
-      */
-    function sql_fetch_row($res)
-    {
-        return mysql_fetch_row($res);
-    }
-    
-    /**
-      * Get column information from a result and return as an object
-      */
-    function sql_fetch_field($res,$offset = 0)
-    {
-        return mysql_fetch_field($res,$offset);
-    }
-    
-    /**
-      * Get current system status (returns string)
-      */
-    function sql_stat($conn=false)
-    {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        return mysql_stat($conn);
-    }
-    
-    /**
-      * Returns the name of the character set
-      */
-    function sql_client_encoding($conn=false)
-    {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        return mysql_client_encoding($conn);
-    }
-    
-    /**
-      * Get SQL client version
-      */
-    function sql_get_client_info()
-    {
-        return mysql_get_client_info();
-    }
-    
-    /**
-      * Get SQL server version
-      */
-    function sql_get_server_info($conn=false)
-    {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        return mysql_get_server_info($conn);
-    }
-    
-    /**
-      * Returns a string describing the type of SQL connection in use for the connection or FALSE on failure
-      */
-    function sql_get_host_info($conn=false)
-    {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        return mysql_get_host_info($conn);
-    }
-    
-    /**
-      * Returns the SQL protocol on success, or FALSE on failure. 
-      */
-    function sql_get_proto_info($conn=false)
-    {
-        global $MYSQL_CONN;
-        if (!$conn) $conn = $MYSQL_CONN;
-        return mysql_get_proto_info($conn);
-    }
+       /**
+         * disconnects from SQL server
+         */
+       function sql_disconnect($conn = false) {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               @mysql_close($conn);
+       }
+       
+       function sql_close($conn = false) {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               @mysql_close($conn);
+       }
+       
+       /**
+         * executes an SQL query
+         */
+       function sql_query($query, $conn = false) {
+               global $SQLCount,$MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               $SQLCount++;
+               $res = mysql_query($query,$conn) or print("mySQL error with query $query: " . mysql_error($conn) . '<p />');
+               return $res;
+       }
+       
+       /**
+         * executes an SQL error
+         */
+       function sql_error($conn = false)
+       {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return mysql_error($conn);
+       }
+       
+       /**
+         * executes an SQL db select
+         */
+       function sql_select_db($db,$conn = false)
+       {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return mysql_select_db($db,$conn);
+       }
+       
+       /**
+         * executes an SQL real escape 
+         */
+       function sql_real_escape_string($val,$conn = false)
+       {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return mysql_real_escape_string($val,$conn);
+       }
+       
+       /**
+         * executes an PDO::quote() like escape, ie adds quotes arround the string and escapes chars as needed 
+         */
+       function sql_quote_string($val,$conn = false) {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return "'".mysql_real_escape_string($val,$conn)."'";
+       }
+       
+       /**
+         * executes an SQL insert id
+         */
+       function sql_insert_id($conn = false)
+       {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return mysql_insert_id($conn);
+       }
+       
+       /**
+         * executes an SQL result request
+         */
+       function sql_result($res, $row, $col)
+       {
+               return mysql_result($res,$row,$col);
+       }
+       
+       /**
+         * frees sql result resources
+         */
+       function sql_free_result($res)
+       {
+               return mysql_free_result($res);
+       }
+       
+       /**
+        * returns number of rows in SQL result
+        */
+       function sql_num_rows($res)
+       {
+               return mysql_num_rows($res);
+       }
+       
+       /**
+        * returns number of rows affected by SQL query
+        */
+       function sql_affected_rows($conn = false)
+       {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return mysql_affected_rows($conn);
+       }
+       
+       /**
+         * Get number of fields in result
+         */
+       function sql_num_fields($res)
+       {
+               return mysql_num_fields($res);
+       }
+       
+       /**
+         * fetches next row of SQL result as an associative array
+         */
+       function sql_fetch_assoc($res)
+       {
+               return mysql_fetch_assoc($res);
+       }
+       
+       /**
+         * Fetch a result row as an associative array, a numeric array, or both
+         */
+       function sql_fetch_array($res)
+       {
+               return mysql_fetch_array($res);
+       }
+       
+       /**
+         * fetches next row of SQL result as an object
+         */
+       function sql_fetch_object($res)
+       {
+               return mysql_fetch_object($res);
+       }
+       
+       /**
+         * Get a result row as an enumerated array
+         */
+       function sql_fetch_row($res)
+       {
+               return mysql_fetch_row($res);
+       }
+       
+       /**
+         * Get column information from a result and return as an object
+         */
+       function sql_fetch_field($res,$offset = 0)
+       {
+               return mysql_fetch_field($res,$offset);
+       }
+       
+       /**
+         * Get current system status (returns string)
+         */
+       function sql_stat($conn=false)
+       {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return mysql_stat($conn);
+       }
+       
+       /**
+         * Returns the name of the character set
+         */
+       function sql_client_encoding($conn=false)
+       {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return mysql_client_encoding($conn);
+       }
+       
+       /**
+         * Get SQL client version
+         */
+       function sql_get_client_info()
+       {
+               return mysql_get_client_info();
+       }
+       
+       /**
+         * Get SQL server version
+         */
+       function sql_get_server_info($conn=false)
+       {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return mysql_get_server_info($conn);
+       }
+       
+       /**
+         * Returns a string describing the type of SQL connection in use for the connection or FALSE on failure
+         */
+       function sql_get_host_info($conn=false)
+       {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return mysql_get_host_info($conn);
+       }
+       
+       /**
+         * Returns the SQL protocol on success, or FALSE on failure. 
+         */
+       function sql_get_proto_info($conn=false)
+       {
+               global $MYSQL_CONN;
+               if (!$conn) $conn = $MYSQL_CONN;
+               return mysql_get_proto_info($conn);
+       }
 
-    /**
-     * Get the name of the specified field in a result
-     */
-    function sql_field_name($res, $offset = 0)
-    {
-        return mysql_field_name($res, $offset);
-    }
+       /**
+        * Get the name of the specified field in a result
+        */
+       function sql_field_name($res, $offset = 0)
+       {
+               return mysql_field_name($res, $offset);
+       }
 
 /**************************************************************************
-    Unimplemented mysql_* functions
-    
+       Unimplemented mysql_* functions
+       
 # mysql_ data_ seek (maybe useful)
 # mysql_ errno (maybe useful)
 # mysql_ fetch_ lengths (maybe useful)
 # mysql_ field_ flags (maybe useful)
 # mysql_ field_ len (maybe useful)
-# mysql_ field_ name (maybe useful)
 # mysql_ field_ seek (maybe useful)
 # mysql_ field_ table (maybe useful)
 # mysql_ field_ type (maybe useful)
index 3040d2f..a9450aa 100755 (executable)
@@ -87,7 +87,7 @@ function upgrade_do150() {
     $res = sql_query('SELECT * FROM '.sql_table('template').' WHERE tpartname=\'DATE_HEADER\'');
     while ($o = mysql_fetch_object($res)) {
         $newval = str_replace('<%daylink%>','<%%daylink%%>',$o->tcontent);
-        $query = 'UPDATE '.sql_table('template').' SET tcontent=\''. addslashes($newval).'\' WHERE tdesc=' . $o->tdesc . ' AND tpartname=\'DATE_HEADER\'';
+        $query = 'UPDATE '.sql_table('template').' SET tcontent=\''. sql_real_escape_string($newval).'\' WHERE tdesc=' . $o->tdesc . ' AND tpartname=\'DATE_HEADER\'';
         upgrade_query('Updating DATE_HEADER part in template ' . $o->tdesc, $query);
     }
     
@@ -96,7 +96,7 @@ function upgrade_do150() {
     while ($o = mysql_fetch_object($res)) {
         if (!strstr($o->tcontent,'<%comments%>')) {
             $newval = $o->tcontent . '<%comments%>';
-            $query = 'UPDATE '.sql_table('template').' SET tcontent=\''. addslashes($newval).'\' WHERE tdesc=' . $o->tdesc . ' AND tpartname=\'ITEM\'';
+            $query = 'UPDATE '.sql_table('template').' SET tcontent=\''. sql_real_escape_string($newval).'\' WHERE tdesc=' . $o->tdesc . ' AND tpartname=\'ITEM\'';
             upgrade_query('Updating ITEM part in template ' . $o->tdesc, $query);
         }
     }
index 04739b7..8a2576d 100755 (executable)
@@ -57,14 +57,14 @@ function upgrade_do200() {
     // add SkinsURL setting
     if (!upgrade_checkIfCVExists('SkinsURL')) {
         $skinsurl = str_replace('/media/','/skins/',$CONF['MediaURL']);
-        $query = 'INSERT INTO '.sql_table('config')." VALUES ('SkinsURL', '".addslashes($skinsurl)."');";
+        $query = 'INSERT INTO '.sql_table('config')." VALUES ('SkinsURL', '".sql_real_escape_string($skinsurl)."');";
         upgrade_query("Adding setting SkinsURL",$query);
     }
 
     // add ActionURL setting
     if (!upgrade_checkIfCVExists('ActionURL')) {
         $actionurl = str_replace('/media/','/action.php',$CONF['MediaURL']);
-        $query = 'INSERT INTO '.sql_table('config')." VALUES ('ActionURL', '".addslashes($actionurl)."');";
+        $query = 'INSERT INTO '.sql_table('config')." VALUES ('ActionURL', '".sql_real_escape_string($actionurl)."');";
         upgrade_query("Adding setting ActionURL",$query);
     }
     
index 0a1d510..28947fe 100755 (executable)
@@ -55,11 +55,11 @@ function upgrade_do250() {
                                $query = 'INSERT INTO ' . sql_table('plugin_option_desc')
                                           .' (opid, oname, ocontext, odesc, otype)'
                                           ." VALUES ("
-                                                       ."'".addslashes($o->opid)."',"
-                                                       ."'".addslashes($o->oname) ."',"
+                                                       ."'".sql_real_escape_string($o->opid)."',"
+                                                       ."'".sql_real_escape_string($o->oname) ."',"
                                                        ."'global',"
-                                                       ."'".addslashes($o->odesc) ."',"
-                                                       ."'".addslashes($o->otype) ."')";
+                                                       ."'".sql_real_escape_string($o->odesc) ."',"
+                                                       ."'".sql_real_escape_string($o->otype) ."')";
                                upgrade_query('Moving option description for '.htmlspecialchars($o->oname).' to ' . sql_table('plugin_option_desc'), $query);
        
                                // store new id
@@ -92,7 +92,7 @@ function upgrade_do250() {
                                foreach ($aValues as $aInfo) {
                                        $query = 'INSERT INTO ' . sql_table('plugin_option') 
                                                   .' (oid, ocontextid, ovalue)'
-                                                  ." VALUES (".$aInfo['id'].",'0','".addslashes($aInfo['value'])."')";
+                                                  ." VALUES (".$aInfo['id'].",'0','".sql_real_escape_string($aInfo['value'])."')";
                                        upgrade_query('Re-filling ' . sql_table('plugin_option') . ' ('.$aInfo['id'].')', $query);
                                }
                        }