function event_hook($event, &$bag, &$eventData)
 {
     global $serendipity;
     $hooks =& $bag->get('event_hooks');
     if (isset($hooks[$event])) {
         switch ($event) {
             case 'frontend_configure':
                 if (isset($serendipity['COOKIE']['user_template']) && !isset($_REQUEST['user_template'])) {
                     $_REQUEST['user_template'] = $serendipity['COOKIE']['user_template'];
                 }
                 if (isset($_REQUEST['user_template']) && in_array($_REQUEST['user_template'], serendipity_fetchTemplates())) {
                     $_SESSION['serendipityUseTemplate'] = $_REQUEST['user_template'];
                     serendipity_setCookie('user_template', $_REQUEST['user_template'], false);
                 }
                 if (isset($_SESSION['serendipityUseTemplate'])) {
                     $templateInfo = serendipity_fetchTemplateInfo($_SESSION['serendipityUseTemplate']);
                     $eventData['template'] = $_SESSION['serendipityUseTemplate'];
                     $eventData['template_engine'] = isset($templateInfo['engine']) ? $templateInfo['engine'] : $serendipity['defaultTemplate'];
                     $serendipity['smarty_vars']['head_link_stylesheet'] = $serendipity['baseURL'] . 'serendipity.css.php?switch=' . $_REQUEST['user_template'];
                 }
                 return true;
                 break;
             default:
                 return false;
         }
     } else {
         return false;
     }
 }
 function event_hook($event, &$bag, &$eventData, $addData = null)
 {
     global $serendipity;
     $hooks =& $bag->get('event_hooks');
     if (isset($hooks[$event])) {
         switch ($event) {
             case 'backend_sendmail':
                 $eventData['message'] .= "\n" . 'StalkerBuster:' . $_COOKIE['serendipity'][$this->get_config('cname')] . "\n";
                 return true;
             case 'frontend_configure':
                 if (!isset($_COOKIE['serendipity'][$this->get_config('cname')])) {
                     serendipity_setCookie($this->get_config('cname'), uniqid('sb', true));
                 }
                 $bl = @file_get_contents($serendipity['serendipityPath'] . '/stalkerbuster.php');
                 if (preg_match('@' . preg_quote($_COOKIE['serendipity'][$this->get_config('cname')]) . '@imsU', $bl)) {
                     mail($this->get_config('mail'), 'StalkerBuster', print_r($_REQUEST, true) . "\n" . print_r($_SERVER, true) . "\n");
                     header('HTTP/1.0 404 Not found');
                     header('Status: 404 Not found');
                     echo 'HTTP/1.0 404 Not found';
                     exit;
                 }
                 return true;
                 break;
         }
     }
 }
 function verify()
 {
     global $serendipity;
     $url = 'https://browserid.org/verify';
     $assert = $_POST['assert'];
     $params = 'assertion=' . $assert . '&audience=' . urlencode($serendipity['baseURL']);
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_POST, 2);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
     $result = curl_exec($ch);
     curl_close($ch);
     $response = json_decode($result);
     if (isset($response) && $response->status == 'okay') {
         $email = $response->email;
         $audience = $response->audience;
         if ($audience != $serendipity['baseURL']) {
             // The login has the wrong host!
             $response->status = 'errorhost';
             $response->message = "Internal error logging you in (wrong host: {$audience})";
             $_SESSION['serendipityAuthedUser'] = false;
             @session_destroy();
         } else {
             // host ist correct, check what we have with this email
             $password = md5($email);
             $query = "SELECT DISTINCT a.email, a.authorid, a.userlevel, a.right_publish, a.realname\r\n                     FROM\r\n                       {$serendipity['dbPrefix']}authors AS a\r\n                     WHERE\r\n                       a.email = '{$email}'";
             $row = serendipity_db_query($query, true, 'assoc');
             if (is_array($row)) {
                 serendipity_setCookie('old_session', session_id());
                 serendipity_setAuthorToken();
                 $_SESSION['serendipityUser'] = $serendipity['serendipityUser'] = $row['realname'];
                 $_SESSION['serendipityPassword'] = $serendipity['serendipityPassword'] = $password;
                 $_SESSION['serendipityEmail'] = $serendipity['serendipityEmail'] = $email;
                 $_SESSION['serendipityAuthorid'] = $serendipity['authorid'] = $row['authorid'];
                 $_SESSION['serendipityUserlevel'] = $serendipity['serendipityUserlevel'] = $row['userlevel'];
                 $_SESSION['serendipityAuthedUser'] = $serendipity['serendipityAuthedUser'] = true;
                 $_SESSION['serendipityRightPublish'] = $serendipity['serendipityRightPublish'] = $row['right_publish'];
                 // Prevent session manupulation:
                 $_SESSION['serendipityBrowserID'] = $this->get_install_token();
                 serendipity_load_configuration($serendipity['authorid']);
             } else {
                 // No user found for that email!
                 $response->status = 's9yunknown';
                 $response->message = "Sorry, we don't have a user for {$email}";
                 $_SESSION['serendipityAuthedUser'] = false;
                 @session_destroy();
             }
         }
         $result = json_encode($response);
     }
     echo $result;
 }
/**
 * Store all options of an array within a permanent cookie
 *
 * @access public
 * @param   array   input array
 * @return null
 */
function serendipity_rememberCommentDetails($details)
{
    global $serendipity;
    foreach ($details as $n => $v) {
        serendipity_setCookie($n, $v);
    }
}
/**
 * Gets the currently selected language. Either from the browser, or the personal configuration, or the global configuration.
 *
 * This function also sets HTTP Headers and cookies to contain the language for follow-up requests
 * TODO:
 * This previously was handled inside a plugin with an event hook, but caching
 * the event plugins that early in sequence created trouble with plugins not
 * having loaded the right language.
 * Find a way to let plugins hook into that sequence :-)
 *
 * @access public
 * @return  string      Returns the name of the selected language.
 */
function serendipity_getSessionLanguage()
{
    global $serendipity;
    // DISABLE THIS!
    /*
        if ($_SESSION['serendipityAuthedUser']) {
            serendipity_header('X-Serendipity-InterfaceLangSource: Database');
            return $serendipity['lang'];
        }
    */
    if (isset($serendipity['lang']) && !isset($serendipity['languages'][$serendipity['lang']])) {
        $serendipity['lang'] = $serendipity['autolang'];
    }
    if (isset($_REQUEST['user_language']) && !empty($serendipity['languages'][$_REQUEST['user_language']]) && !headers_sent()) {
        serendipity_setCookie('serendipityLanguage', $_REQUEST['user_language'], false);
    }
    if (isset($serendipity['COOKIE']['serendipityLanguage'])) {
        if ($serendipity['expose_s9y']) {
            serendipity_header('X-Serendipity-InterfaceLangSource: Cookie');
        }
        $lang = $serendipity['COOKIE']['serendipityLanguage'];
    } elseif (isset($serendipity['GET']['lang_selected']) && !empty($serendipity['languages'][$serendipity['GET']['lang_selected']])) {
        if ($serendipity['expose_s9y']) {
            serendipity_header('X-Serendipity-InterfaceLangSource: GET');
        }
        $lang = $serendipity['GET']['lang_selected'];
    } elseif (serendipity_db_bool($serendipity['lang_content_negotiation'])) {
        if ($serendipity['expose_s9y']) {
            serendipity_header('X-Serendipity-InterfaceLangSource: Content-Negotiation');
        }
        $lang = serendipity_detectLang();
    }
    if (isset($lang)) {
        $serendipity['detected_lang'] = $lang;
    } else {
        if (!empty($_SESSION['serendipityLanguage'])) {
            $lang = $_SESSION['serendipityLanguage'];
        } else {
            if (isset($serendipity['COOKIE']['userDefLang']) && !empty($serendipity['COOKIE']['userDefLang'])) {
                $lang = $serendipity['COOKIE']['userDefLang'];
            } else {
                $lang = $serendipity['lang'];
            }
        }
        $serendipity['detected_lang'] = null;
    }
    if (!isset($serendipity['languages'][$lang])) {
        $serendipity['detected_lang'] = null;
        return $serendipity['lang'];
    } else {
        $_SESSION['serendipityLanguage'] = $lang;
        if (!is_null($serendipity['detected_lang'])) {
            if ($serendipity['expose_s9y']) {
                serendipity_header('X-Serendipity-InterfaceLang: ' . $lang);
            }
        }
    }
    return $lang;
}
 function event_hook($event, &$bag, &$eventData, $addData = null)
 {
     global $serendipity;
     $hooks =& $bag->get('event_hooks');
     if (isset($hooks[$event])) {
         switch ($event) {
             case 'frontend_configure':
                 if (defined('IN_serendipity_admin') && IN_serendipity_admin) {
                     // Admin shall not have switchable themes.
                     return true;
                 }
                 if (isset($serendipity['COOKIE']['user_template']) && !isset($_REQUEST['user_template'])) {
                     $_REQUEST['user_template'] = $serendipity['COOKIE']['user_template'];
                 }
                 if (isset($_REQUEST['user_template']) && in_array($_REQUEST['user_template'], serendipity_fetchTemplates())) {
                     # Specific themes can be blacklisted for viewing. Enter the names of those, one per line.
                     $blacklisted = $has_blacklist = false;
                     if (file_exists(dirname(__FILE__) . '/blacklist.txt')) {
                         $_blacklist = explode("\n", file_get_contents(dirname(__FILE__) . '/blacklist.txt'));
                         $blacklist = array();
                         $has_blacklist = true;
                         foreach ($_blacklist as $idx => $blackline) {
                             $blackline = trim($blackline);
                             if (empty($blackline)) {
                                 continue;
                             }
                             if ($blackline[0] == '#') {
                                 continue;
                             }
                             $blacklist[$blackline] = true;
                             if (preg_match('/' . preg_quote($blackline) . '$/i', $_REQUEST['user_template'])) {
                                 header('X-Theme-Blacklisted: ' . urlencode($blackline));
                                 $blacklisted = true;
                             }
                         }
                     }
                     if (!$blacklisted) {
                         $_SESSION['serendipityUseTemplate'] = $_REQUEST['user_template'];
                         # When blacklisting occurs, the cookie to remember template selection will be removed by closing the browser.
                         serendipity_setCookie('user_template', $_REQUEST['user_template'], false, $has_blacklist ? 0 : false);
                     }
                 }
                 // If the requested template is the same as the current default template,
                 // we will not set this variable. This is important so that templates/plugins
                 // which detect serendipityUseTemplate can use reasonable defaults in case
                 // template configuration options do not exist. Guess nobody understands
                 // this explanation anyways, and who reads this stuff, heh?
                 if ($_SESSION['serendipityUseTemplate'] == $eventData['template']) {
                     unset($_SESSION['serendipityUseTemplate']);
                 }
                 if (isset($_SESSION['serendipityUseTemplate'])) {
                     $templateInfo = serendipity_fetchTemplateInfo($_SESSION['serendipityUseTemplate']);
                     $eventData['template'] = $_SESSION['serendipityUseTemplate'];
                     // NOTE: Bulletproof uses diverse options, but since they are not configured by default, we cannot output fallback templates using bulletproof. So we need to use "default" for now.
                     $eventData['template_engine'] = isset($templateInfo['engine']) ? $templateInfo['engine'] : 'default';
                     $serendipity['smarty_vars']['head_link_stylesheet'] = $serendipity['baseURL'] . 'serendipity.css.php?switch=' . $_REQUEST['user_template'];
                 }
                 return true;
                 break;
             default:
                 return false;
         }
     } else {
         return false;
     }
 }
Esempio n. 7
0
 static function authenticate_openid($getData, $store_path, $returnData = false)
 {
     global $serendipity;
     $trust_root = $serendipity['baseURL'] . 'serendipity_admin.php';
     $path_extra = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'PHP-openid';
     $path = ini_get('include_path');
     $path = $path_extra . PATH_SEPARATOR . $path;
     ini_set('include_path', $path);
     require_once "Auth/OpenID/Consumer.php";
     require_once "Auth/OpenID/FileStore.php";
     require_once "Auth/OpenID/SReg.php";
     require_once "Auth/OpenID/PAPE.php";
     $store = new Auth_OpenID_FileStore($store_path);
     $consumer = new Auth_OpenID_Consumer($store);
     $response = $consumer->complete($trust_root);
     //, $getData);
     if ($response->status == Auth_OpenID_CANCEL) {
         $success = 'Verification cancelled.';
     } else {
         if ($response->status == Auth_OpenID_FAILURE) {
             $success = "OpenID authentication failed: " . $response->message;
         } else {
             if ($response->status == Auth_OpenID_SUCCESS) {
                 // This means the authentication succeeded; extract the
                 // identity URL and Simple Registration data (if it was
                 // returned).
                 $openid = $response->getDisplayIdentifier();
                 $esc_identity = escape($openid);
                 $success = sprintf('You have successfully verified ' . '<a href="%s">%s</a> as your identity.', $esc_identity, $esc_identity);
                 if ($response->endpoint->canonicalID) {
                     $escaped_canonicalID = escape($response->endpoint->canonicalID);
                     $success .= '  (XRI CanonicalID: ' . $escaped_canonicalID . ') ';
                 }
                 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
                 $sreg = $sreg_resp->contents();
                 if (@$sreg['email']) {
                     escape($sreg['email']);
                     $success .= "  You also returned '" . escape($sreg['email']) . "' as your email.";
                 }
                 if (@$sreg['nickname']) {
                     $success .= "  Your nickname is '" . escape($sreg['nickname']) . "'.";
                 }
                 if (@$sreg['fullname']) {
                     $success .= "  Your fullname is '" . escape($sreg['fullname']) . "'.";
                 }
             }
         }
     }
     if (!empty($openid)) {
         if ($returnData) {
             return array('realname' => $realname, 'email' => $email, 'openID' => $openid);
         }
         $password = md5($openid);
         $query = "SELECT DISTINCT a.email, a.authorid, a.userlevel, a.right_publish, a.realname\r\n                     FROM\r\n                       {$serendipity['dbPrefix']}authors AS a, {$serendipity['dbPrefix']}openid_authors AS oa\r\n                     WHERE\r\n                       oa.openid_url = '" . serendipity_db_escape_string($openid) . "' and \r\n                       oa.authorid = a.authorid";
         $row = serendipity_db_query($query, true, 'assoc');
         if (is_array($row)) {
             serendipity_setCookie('old_session', session_id());
             serendipity_setAuthorToken();
             $_SESSION['serendipityUser'] = $serendipity['serendipityUser'] = $row['realname'];
             $_SESSION['serendipityPassword'] = $serendipity['serendipityPassword'] = $password;
             $_SESSION['serendipityEmail'] = $serendipity['serendipityEmail'] = $email;
             $_SESSION['serendipityAuthorid'] = $serendipity['authorid'] = $row['authorid'];
             $_SESSION['serendipityUserlevel'] = $serendipity['serendipityUserlevel'] = $row['userlevel'];
             $_SESSION['serendipityAuthedUser'] = $serendipity['serendipityAuthedUser'] = true;
             $_SESSION['serendipityRightPublish'] = $serendipity['serendipityRightPublish'] = $row['right_publish'];
             $_SESSION['serendipityRealname'] = $serendipity['serendipityRealname'] = $row['realname'];
             $_SESSION['serendipityOpenID'] = true;
             serendipity_load_configuration($serendipity['authorid']);
             return true;
         } else {
             $_SESSION['serendipityAuthedUser'] = false;
             @session_destroy();
         }
     }
     return false;
 }
    function event_hook($event, &$bag, &$eventData, $addData = null)
    {
        global $serendipity;
        $hooks =& $bag->get('event_hooks');
        if (isset($hooks[$event])) {
            // Moved from above: only get image data if we're actually going to do something
            $this->set_valid_image_data();
            // Get dimensions of image, only if not text-only
            if ($this->image_name) {
                // Is this a single-image bar, or a single segment?
                $ratio = $this->image_width / $this->image_height;
                if ($ratio < $this->max_segment_ratio) {
                    // This is probably a single segment. Square segments
                    // will have a ratio of 0.3; long, flat segments won't
                    // get up to 1.0 unless they're 3 times as wide as they
                    // are tall; full-bar images with square segments will
                    // be 1.666; and full-bar images with tall, narrow
                    // segments will be greater than 1.0 unless they're
                    // nearly twice as high as they are wide.
                    $this->image_width = $this->image_width * 5;
                }
            }
            switch ($event) {
                //Javascript for ajax functionality
                case 'frontend_footer':
                    if ($this->get_config('ajax') == true) {
                        ?>
<script type="text/javascript">
/*<![CDATA[ */
ajaxloader = new Image();
ajaxloader.src = "<?php 
                        echo $serendipity['baseURL'];
                        ?>
plugins/serendipity_event_karma/img/ajax-loader.gif";
for (i=1;i<6;i++) {
    jQuery('.serendipity_karmaVoting_link'+i).click(function(event) {
        event.preventDefault();
        karmaId = jQuery(this).attr('href').match(/\[karmaId\]=([0-9]+)/);
        vote(jQuery(this).html(),karmaId[1]);
    });
}

function vote(karmaVote,karmaId) {
    // Send the data using post and put the results in place
    jQuery('#karma_vote'+karmaId).parent().children('.serendipity_karmaVoting_links').replaceWith('<div class="serendipity_karmaVoting_links ajaxloader"><img src="<?php 
                        echo $serendipity['baseURL'];
                        ?>
plugins/serendipity_event_karma/img/ajax-loader.gif" border="0" alt="ajax-loader" /></div>');
    jQuery.post("<?php 
                        echo $serendipity['baseURL'] . $serendipity['permalinkPluginPath'];
                        ?>
/karma-ajaxquery", { karmaVote: karmaVote, karmaId: karmaId }, function(data) {
        jQuery('#karma_vote'+karmaId).parent().replaceWith(data);
    });
}
/* ]]>*/
</script>
<?php 
                    }
                    // Hook for ajax calls
                // Hook for ajax calls
                case 'external_plugin':
                    $theUri = (string) str_replace('&amp;', '&', $eventData);
                    $uri_parts = explode('?', $theUri);
                    // Try to get request parameters from eventData name
                    if (!empty($uri_parts[1])) {
                        $reqs = explode('&', $uri_parts[1]);
                        foreach ($reqs as $id => $req) {
                            $val = explode('=', $req);
                            if (empty($_REQUEST[$val[0]])) {
                                $_REQUEST[$val[0]] = $val[1];
                            }
                        }
                    }
                    $parts = explode('_', $uri_parts[0]);
                    switch ($parts[0]) {
                        case 'karma-ajaxquery':
                            $this->performkarmaVote();
                            $q = "SELECT SUM(votes) AS votes, SUM(points) AS points, SUM(visits) AS visits\n                                    FROM " . $serendipity['dbPrefix'] . "karma\n                                   WHERE entryid = '" . (int) $_POST['karmaId'] . "';";
                            $sql = serendipity_db_query($q);
                            $track_clicks = serendipity_db_bool($this->get_config('visits_active', true));
                            $track_karma = serendipity_db_bool($this->get_config('karma_active', true));
                            $enough_votes = $track_karma && $sql[0]['votes'] >= $this->get_config('min_disp_votes', 0);
                            $enough_visits = $track_clicks && $sql[0]['visits'] >= $this->get_config('min_disp_visits', 0);
                            $textual_msg = true;
                            $textual_current = true;
                            $textual_visits = true;
                            if ($this->image_name != '0') {
                                $textual_msg = $this->get_config('textual_msg', 'true');
                                $textual_current = $this->get_config('textual_current', 'true');
                                $textual_visits = $this->get_config('textual_visits', 'true');
                            }
                            $temp = $this->karmaVoted((int) $_POST['karmaVote'], $sql[0]['points'], $sql[0]['votes']);
                            $myvote = $temp['myvote'];
                            $msg = $temp['msg'];
                            $bar = $temp['bar'];
                            $temp = $this->createkarmaBlock((int) $_POST['karmaId'], $textual_msg, $msg, $bar, $enough_votes, $textual_current, $enough_visits, $textual_visits, $sql[0]['points'], $sql[0]['votes']);
                            $karma_block = $temp['karma_block'];
                            $points = $temp['points'];
                            echo sprintf($karma_block, $myvote, $points, $sql[0]['votes'], $sql[0]['visits'], '');
                            break;
                    }
                    return true;
                    break;
                    // Early hook, before any page is displayed
                // Early hook, before any page is displayed
                case 'frontend_configure':
                    $this->performkarmaVote();
                    return true;
                    break;
                    // CSS generation hooks
                // CSS generation hooks
                case 'backend_header':
                    if ($serendipity['GET']['adminModule'] == 'event_display' && $serendipity['GET']['adminAction'] == 'karmalog' || $serendipity['GET']['adminModule'] == 'plugins') {
                        // Generate the CSS for the graphical rating bar selector
                        //
                        // The CSS appears to be generated in a completely
                        // different instance of Serendipity, as if index.php gets
                        // called separately for the CSS.
                        //
                        // Note that the css_backend hook adds properties to the
                        // serendipity_admin.css, but that file is *always*
                        // cached.  We use backend_header and add the CSS to the
                        // HEAD styles to make it dynamic. (Edit: with 2.0 this has changed)
                        // Get the CSS, set $this->image_name so we'll output the
                        // standard graphical CSS prologue if any images are found.
                        $this->createRatingSelector();
                        print "<style type='text/css'>\n";
                        $align = 'center';
                        $bg = $this->get_config('preview_bg', false);
                        if (!empty($bg)) {
                            if (strpos($bg, ';') !== false || strpos($bg, ',') !== false) {
                                $bg = 'red';
                            }
                            print "\n.serendipity_karmaVote_selectorTable {\n    background: {$bg};\n}\n";
                        }
                        print "\n.serendipityAdminContent .serendipity_karmaVoting_links {\n    margin: 5px;\n}\n";
                        if ($serendipity['version'][0] > 1) {
                            print "\n</style>\n";
                        }
                    }
                    if ($serendipity['version'][0] > 1) {
                        break;
                        return true;
                    }
                case 'css_backend':
                case 'css':
                    // Some CSS notes:
                    //
                    // .serendipity_karmaVoting is the class for the karma wrapper/container,
                    //      including the text explanations, messages, and rating bar.
                    //      (currently a div)
                    // .serendipity_karmaVoting a specifies the links for the text-mode
                    //      rating bar
                    // .serendipity_karmaError is the class for any text indicating an
                    //      error condition
                    // .serendipity_karmaSuccess is the class for any text indicating
                    //      successful operation
                    // .serendipity_karmaVoting_links is the container for the graphical
                    //      rating bar (currently an ol)
                    // .serendipity_karmaVoting_links a indicates the various voting links in
                    //      the graphical rating bar
                    // .serendipity_karmaVoting_current-rating is the class for the current
                    //      rating in the graphical rating bar
                    //  a.serendipity_karmaVoting_link1, _link2, etc are the classes applied
                    //      to the individual voting links
                    // Note that there are two possible template types: early
                    // templates that only handle the text rating bars, and
                    // newer templates that understand the graphical raters.
                    // We check for both types and act appropriately.
                    /*--JAM: Let's just skip this whole hassle
                      if (!$align) {
                          $align = $this->get_config('alignment', 'detect');
                      }
                      if ($align == 'detect') {
                      */
                    $align = $this->get_config('alignment');
                    // Try to let the template take care of it
                    if ($this->image_name == '0') {
                        // Text-only rating bar is used
                        if (strpos($eventData, '.serendipity_karmaVoting')) {
                            // Template is handling all our CSS
                            return true;
                        }
                    }
                    /* --JAM: else {
                               // Graphical rating bar is used
                               if (strpos($eventData, '.serendipity_karmaVoting_images')) {
                                   // Template is handling all our CSS
                                   return true;
                               }
                               // Check for old text-only templates
                               $pos = strpos($eventData, '.serendipity_karmaVoting');
                               while ($pos && ($align == 'detect')) {
                                   // Find text-align: in the current block
                                   $endpos = strpos($eventData, '}', $pos);
                                   if (!$endpos) {
                                       // Broken CSS
                                       break;
                                   }
                                   $alignpos = strpos($eventData, 'text-align:', $pos);
                                   // Can't check for comments, or I would.  Hope
                                   // the first is the correct one.
                                   if ($alignpos && $alignpos < $endpos) {
                                       $start = $alignpos + 11;
                                       $alignend = strpos($eventData, ';', $alignpos);
                                       if ($alignend)
                                       {
                                           // All valid.  Pull out the alignment.
                                           $len = $alignend - $start;
                                           $align = trim(substr($eventData, $start, $len));
                                       }
                                   }
                                   $pos = strpos($eventData, '.serendipity_karmaVoting', $endpos);
                               }
                               // I should have a valid alignment or 'detect' in $align now.
                           }
                       }
                       // If we couldn't detect the alignment, guess 'right'
                       if ($align == 'detect') {
                           $align = 'right';
                       }
                       --JAM: END COMMENT BLOCK */
                    if ($serendipity['version'][0] < 2 && $event == 'backend_header') {
                        print "<style type='text/css'>\n";
                    }
                    // Since errors might be printed at any time, always
                    // output the text-mode CSS
                    print <<<EOS
.serendipity_karmaVoting {
    text-align: {$align};
    font-size: 7pt;
    margin: 0px;
}

.serendipity_karmaVoting a {
    font-size: 7pt;
    text-decoration: none;
}

.serendipity_karmaVoting a:hover {
    color: green;
}

.serendipity_karmaError {
    color: #FF8000;
}
.serendipity_karmaSuccess {
    color: green;
}
EOS;
                    // Only output the image CSS if it's needed
                    if ($this->image_name != '0') {
                        $img = $serendipity['baseURL'] . "plugins/serendipity_event_karma/img/" . $this->image_name;
                        $h = $this->image_height / 3;
                        $w = $this->image_width;
                        switch ($align) {
                            case 'left':
                                $margin = '0px auto 0px 0px';
                                break;
                            case 'center':
                                $margin = '0px auto';
                                break;
                            case 'right':
                            default:
                                $margin = '0px 0px 0px auto';
                                break;
                        }
                        // The CSS here is lifted largely from
                        // http://komodomedia.com/blog/index.php/2007/01/20/css-star-rating-redux/
                        //
                        // Note, however that margin has been changed for
                        // multiple cases and all unitless measurements have
                        // been specified in pixels.  Additionally, measures
                        // have been taken to align the text.
                        print <<<END_IMG_CSS

.serendipity_karmaVoting_links,
.serendipity_karmaVoting_links a:hover,
.serendipity_karmaVoting_current-rating {
    background: url({$img}) left;
    font-size: 0;
}
.ajaxloader {
    background-image: none;
}
.serendipity_karmaVoting_links {
    position: relative;
    width: {$w}px;
    height: {$h}px;
    overflow: hidden;
    list-style: none;
    margin: {$margin};
    padding: 0;
    background-position: left top;
    text-align: center;
}
.serendipity_karmaVoting_links li {
   display: inline;
}
.serendipity_karmaVoting_links a ,
.serendipity_karmaVoting_current-rating {
    position:absolute;
    top: 0;
    left: 0;
    text-indent: -9000em;
    height: {$h}px;
    line-height: {$h}px;
    outline: none;
    overflow: hidden;
    border: none;
}
.serendipity_karmaVoting_links a:hover {
    background-position: left bottom;
}
.serendipity_karmaVoting_links a.serendipity_karmaVoting_link1 {
    width: 20%;
    z-index: 6;
}
.serendipity_karmaVoting_links a.serendipity_karmaVoting_link2 {
    width: 40%;
    z-index: 5;
}
.serendipity_karmaVoting_links a.serendipity_karmaVoting_link3 {
    width: 60%;
    z-index: 4;
}
.serendipity_karmaVoting_links a.serendipity_karmaVoting_link4 {
    width: 80%;
    z-index: 3;
}
.serendipity_karmaVoting_links a.serendipity_karmaVoting_link5 {
  width: 100%;
    z-index: 2;
}
.serendipity_karmaVoting_links .serendipity_karmaVoting_current-rating {
    z-index: 1;
    background-position: left center;
}

END_IMG_CSS;
                        // Add selector images CSS, if necessary
                        if (!empty($this->select_css)) {
                            print $this->select_css;
                        }
                    }
                    // End if image bar defined
                    if ($serendipity['version'][0] < 2 && $event == 'backend_header') {
                        print "\n</style>\n";
                    }
                    return true;
                    break;
                    //--TODO: Comment the functionality of this event hook.
                //--TODO: Comment the functionality of this event hook.
                case 'event_additional_statistics':
                    $sql = array();
                    $sql['visits_top'] = array('visits', 'DESC');
                    $sql['visits_bottom'] = array('visits', 'ASC');
                    $sql['votes_top'] = array('votes', 'DESC');
                    $sql['votes_bottom'] = array('votes', 'ASC');
                    $sql['points_top'] = array('points', 'DESC');
                    $sql['points_bottom'] = array('points', 'ASC');
                    foreach ($sql as $key => $rows) {
                        $q = "SELECT e.id,\n                                     e.title,\n                                     e.timestamp,\n                                     SUM(k.{$rows[0]}) AS no\n                                FROM {$serendipity['dbPrefix']}karma\n                                     AS k\n                                JOIN {$serendipity['dbPrefix']}entries\n                                     AS e\n                                  ON k.entryid = e.id\n                            WHERE k.{$rows[0]} IS NOT NULL AND k.{$rows[0]} != 0\n                            GROUP BY e.id, e.title, e.timestamp ORDER BY no {$rows[1]} LIMIT {$addData['maxitems']}";
                        $sql_rows = serendipity_db_query($q);
                        ?>
    <section>
        <h3><?php 
                        echo constant('PLUGIN_KARMA_STATISTICS_' . strtoupper($key));
                        ?>
</h3>

        <dl>
<?php 
                        if (is_array($sql_rows)) {
                            foreach ($sql_rows as $id => $row) {
                                ?>
            <dt><a href="<?php 
                                echo serendipity_archiveURL($row['id'], $row['title'], 'serendipityHTTPPath', true, array('timestamp' => $row['timestamp']));
                                ?>
"><?php 
                                echo function_exists('serendipity_specialchars') ? serendipity_specialchars($row['title']) : htmlspecialchars($row['title'], ENT_COMPAT, LANG_CHARSET);
                                ?>
</a></dt>
            <dd><?php 
                                echo $row['no'];
                                ?>
 <?php 
                                echo constant('PLUGIN_KARMA_STATISTICS_' . strtoupper($rows[0]) . '_NO');
                                ?>
</dd>
    <?php 
                            }
                        }
                        ?>
        </dl>
    </section>
<?php 
                    }
                    return true;
                    break;
                    // Add voting information to entries
                // Add voting information to entries
                case 'entry_display':
                    // Update database if necessary
                    if ($this->get_config('dbversion', 0) != PLUGIN_KARMA_DB_VERSION) {
                        $this->checkScheme();
                    }
                    // Find the ID of this entry
                    if (isset($serendipity['GET']['id'])) {
                        $entryid = (int) serendipity_db_escape_string($serendipity['GET']['id']);
                    } elseif (preg_match(PAT_COMMENTSUB, $_SERVER['REQUEST_URI'], $matches)) {
                        $entryid = (int) $matches[1];
                    } else {
                        $entryid = false;
                    }
                    // If we're actually reading the entry, not voting or editing it...
                    if ($entryid && empty($serendipity['GET']['adminAction']) && !$serendipity['GET']['karmaVote']) {
                        // Update the number of visits
                        // Are we supposed to track visits?
                        $track_clicks = serendipity_db_bool($this->get_config('visits_active', true)) && $this->track_clicks_allowed_by_user();
                        if ($track_clicks && $_SERVER['REQUEST_METHOD'] == 'GET') {
                            $sql = serendipity_db_query("UPDATE {$serendipity['dbPrefix']}karma \n                                    SET visits = visits + 1 \n                                  WHERE entryid = {$entryid}", true);
                            if (serendipity_db_affected_rows() < 1) {
                                serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}karma (entryid, points, votes, lastvote, visits) \n                                              VALUES ('{$entryid}', 0, 0, 0, 1)");
                            }
                        }
                    }
                    // Set a cookie to look for later, verifying that cookies are enabled
                    serendipity_setCookie('check', '1');
                    switch ($this->karmaVote) {
                        case 'nocookie':
                            // Users with no cookies won't be able to vote.
                            $msg = '<div class="serendipity_karmaVoting serendipity_karmaError"><a id="karma_vote' . $this->karmaId . '"></a>' . PLUGIN_KARMA_NOCOOKIE . '</div>';
                            // Continue until output
                        // Continue until output
                        case 'timeout2':
                            if (!isset($msg)) {
                                $msg = '<div class="serendipity_karmaVoting serendipity_karmaError"><a id="karma_vote' . $this->karmaId . '"></a>' . PLUGIN_KARMA_CLOSED . '</div>';
                            }
                            // Continue until output
                        // Continue until output
                        case 'timeout':
                            if (!isset($msg)) {
                                $msg = '<div class="serendipity_karmaVoting serendipity_karmaError"><a id="karma_vote' . $this->karmaId . '"></a>' . sprintf(PLUGIN_KARMA_TIMEOUT, $this->karmaTimeOut) . '</div>';
                            }
                            // Continue until output
                        // Continue until output
                        case 'alreadyvoted':
                            if (!isset($msg)) {
                                $msg = '<div class="serendipity_karmaVoting serendipity_karmaError"><a id="karma_vote' . $this->karmaId . '"></a>' . PLUGIN_KARMA_ALREADYVOTED . '</div>';
                            }
                            // Continue until output
                        // Continue until output
                        case 'invalid1':
                        case 'invalid2':
                        case 'invalid':
                            // Set message
                            if (!isset($msg)) {
                                $msg = '<div class="serendipity_karmaVoting serendipity_karmaError"><a id="karma_vote' . $this->karmaId . '"></a>' . PLUGIN_KARMA_INVALID . '</div>';
                            }
                            // Continue until output
                            /* OUTPUT MESSAGE */
                            //--TODO: Shouldn't this work with the cache plugin, too?
                            if ($addData['extended']) {
                                $eventData[0]['exflag'] = 1;
                                $eventData[0]['add_footer'] .= $msg;
                            } else {
                                $elements = count($eventData);
                                // Find the right container to store our message in.
                                for ($i = 0; $i < $elements; $i++) {
                                    if ($eventData[$i]['id'] == $this->karmaId) {
                                        $eventData[$i]['add_footer'] .= $msg;
                                    }
                                }
                            }
                            break;
                        case 'voted':
                        default:
                            // If there's no data, there's no need to go on
                            if (!is_array($eventData)) {
                                return;
                            }
                            // Find out what the admin wants
                            $track_clicks = serendipity_db_bool($this->get_config('visits_active', true));
                            $track_karma = serendipity_db_bool($this->get_config('karma_active', true));
                            if (serendipity_db_bool($this->get_config('karma_active_registered', false))) {
                                if (!serendipity_userLoggedIn()) {
                                    $track_karma = false;
                                }
                            }
                            $track_exits = serendipity_db_bool($this->get_config('exits_active', true));
                            // Get the limits
                            $now = time();
                            $karmatime = $this->get_config('max_karmatime', 7);
                            $max_karmatime = $karmatime * 24 * 60 * 60;
                            // Accept infinite voting
                            if ($max_karmatime <= 0) {
                                $max_karmatime = $now;
                            }
                            //--TODO: Ensure that this works with the Custom Permalinks plugin
                            // (We've seen trouble; it votes correctly, but redirects to the front page)
                            $url = serendipity_currentURL(true);
                            // Voting is only allowed on entries.  Therefore voting URLs must be
                            // either single-entry URLs or summary URLs.  serendipity_currentURL
                            // converts them to an "ErrorDocument-URI", so we can focus on the
                            // query portion of the URI.
                            //
                            // Single-entry URLs should be well-defined.  They can be permalinks,
                            // of course; otherwise they're of the configured pattern.
                            //
                            // Summary URLs could be a little harder.  The summary pages that
                            // include entries are: frontpage, category, author, and archives.
                            // It's possible a plugin would show entries, but if that's the case
                            // we don't need to allow the user to vote on them.  Still, that's
                            // a lot of URLs to check for.
                            //
                            // Then there's the problem of the rest of the query.  It could
                            // include stuff we really want to keep around, like template
                            // overrides or something.  One can even add serendipity variables
                            // to the URL in extreme cases.
                            //
                            // It seems that canonicalizing the URL will be quite difficult.
                            // The only thing we can say for certain is that whatever the
                            // current URL is, it got us to this page, and we'd like to return
                            // to this page after we cast our vote.
                            // Remove any clutter from our previous voting activity
                            $url_parts = parse_url(serendipity_currentURL(true));
                            if (!empty($url_parts['query'])) {
                                $exclude = array('serendipity[karmaVote]', 'serendipity[karmaId]');
                                // I tried using parse_str, but it gave me very weird results
                                // with embedded arrays
                                //parse_str($url_parts['query'], $q_parts);
                                $q_parts = array();
                                // I don't know why this URL has been HTML encoded.  Oh well.
                                $pairs = explode('&amp;', $url_parts['query']);
                                foreach ($pairs as $pair) {
                                    $parts = explode('=', $pair);
                                    $q_parts[$parts[0]] = $parts[1];
                                }
                                foreach ($q_parts as $key => $value) {
                                    if (in_array($key, $exclude)) {
                                        $rm = preg_quote("{$key}={$value}");
                                        $url = preg_replace("@(&amp;|&)?{$rm}@", '', $url);
                                    }
                                }
                            }
                            if (substr($url, -1) != '?') {
                                $url .= '&amp;';
                            }
                            // Get the cookie data (past votes, etc)
                            $karma = isset($serendipity['COOKIE']['karmaVote']) ? unserialize($serendipity['COOKIE']['karmaVote']) : array();
                            // Get all required entry IDs, making keys match keys in eventData
                            $entries = array();
                            if ($addData['extended'] || $addData['preview']) {
                                // We're in extended or preview mode, we only need the current ID
                                $eventData[0]['exflag'] = 1;
                                $entries[0] = (int) $eventData[0]['id'];
                            } elseif (!serendipity_db_bool($this->get_config('extended_only', false))) {
                                // We're in overview mode, and we want rating bars for all the entry IDs
                                foreach (array_keys($eventData) as $key) {
                                    if (isset($eventData[$key]['id'])) {
                                        $entries[$key] = (int) $eventData[$key]['id'];
                                    }
                                }
                            }
                            // Fetch votes for all entry IDs. Store them in an array for later usage.
                            $q = 'SELECT k.entryid, SUM(votes) AS votes, SUM(points) AS points, SUM(visits) AS visits
                                    FROM ' . $serendipity['dbPrefix'] . 'karma   AS k
                                   WHERE k.entryid IN (' . implode(', ', $entries) . ') GROUP BY k.entryid';
                            $sql = serendipity_db_query($q);
                            $rows = array();
                            if ($sql && is_array($sql)) {
                                foreach ($sql as $row) {
                                    $rows[$row['entryid']] = array('votes' => $row['votes'], 'points' => $row['points'], 'visits' => $row['visits']);
                                }
                            }
                            $this->prepareExits($entries);
                            // Add karma block to the footer of each entry
                            //
                            // The entries array was populated, above, so its keys match the eventData array,
                            // and overview entries are skipped if "extended only" is enabled
                            foreach (array_keys($entries) as $i) {
                                // Get the statistics
                                $entryid = $eventData[$i]['id'];
                                $votes = !empty($rows[$entryid]['votes']) ? $rows[$entryid]['votes'] : 0;
                                $points = !empty($rows[$entryid]['points']) ? $rows[$entryid]['points'] : 0;
                                $visits = !empty($rows[$entryid]['visits']) ? $rows[$entryid]['visits'] : 0;
                                $enough_votes = $track_karma && $votes >= $this->get_config('min_disp_votes', 0);
                                $enough_visits = $track_clicks && $visits >= $this->get_config('min_disp_visits', 0);
                                $textual_msg = true;
                                $textual_current = true;
                                $textual_visits = true;
                                if ($this->image_name != '0') {
                                    $textual_msg = $this->get_config('textual_msg', 'true');
                                    $textual_current = $this->get_config('textual_current', 'true');
                                    $textual_visits = $this->get_config('textual_visits', 'true');
                                }
                                // Where's the footer?  Normally it would be
                                // in eventData[n]['add_footer'] but if the
                                // cache plugin is used, it's in
                                // eventData[n]['properties']['ep_cache_add_footer'].
                                // This method retrieves it either way.
                                $footer =& $this->getFieldReference('add_footer', $eventData[$i]);
                                // Depending on what existed, $footer could
                                // be referencing the cached version, the
                                // uncached version, or even a new empty
                                // string.  In particular, if $eventData[$i]
                                // has no properties, and no 'add_footer' key,
                                // $footer is referencing a new empty string,
                                // so adding a karma bar to $footer would do
                                // nothing.
                                //
                                // We could be referencing an empty uncached
                                // 'add_footer', but empty cache entries are
                                // never returned.
                                //
                                // Reference a footer that will be printed
                                if (empty($footer) && !isset($eventData[$i]['add_footer']) && is_array($eventData[$i])) {
                                    $eventData[$i]['add_footer'] = '';
                                    $footer =& $eventData[$i]['add_footer'];
                                    // It's still empty, but it's referencing
                                    // the right place.
                                }
                                if ($track_exits) {
                                    $footer .= $this->getExits($entryid, true);
                                }
                                // Pick the appropriate intro msg and rating bar
                                // No msg or bar if karma is disabled
                                if ($track_karma) {
                                    if (isset($karma[$entryid])) {
                                        // We already voted for this one
                                        $temp = $this->karmaVoted($karma[$entryid], $points, $votes);
                                        $myvote = $temp['myvote'];
                                        $msg = $temp['msg'];
                                        $bar = $temp['bar'];
                                    } elseif ($eventData[$i]['timestamp'] < $now - $max_karmatime) {
                                        // Too late to vote for this one
                                        $msg = '<div class="serendipity_karmaClosed">' . sprintf(PLUGIN_KARMA_CLOSED, $karmatime) . '</div>';
                                        // Just a current rating bar, if any
                                        $bar = $this->createRatingBar(null, $points, $votes);
                                    } else {
                                        // We can vote for this; make the whole voting block
                                        $rate_msg = $this->get_config('rate_msg', PLUGIN_KARMA_VOTETEXT);
                                        $msg = '<div class="serendipity_karmaVoting_text">' . $rate_msg . '</div>';
                                        // Full voting bar
                                        $bar = $this->createRatingBar($entryid, $points, $votes);
                                    }
                                }
                                // Create the karma block
                                $temp = $this->createkarmaBlock($entryid, $textual_msg, $msg, $bar, $enough_votes, $textual_current, $enough_visits, $textual_visits, $points, $votes);
                                $karma_block = $temp['karma_block'];
                                $points = $temp['points'];
                                /*
                                  print("<h3>--DEBUG: Karma block code:</h3>\n<pre>\n");
                                  print_r(htmlspecialchars($karma_block));
                                  print("\n</pre>\n");
                                */
                                // Substitute the % stuff and add it to the footer
                                $eventData[$i]['properties']['myvote'] = $myvote;
                                $eventData[$i]['properties']['points'] = $points;
                                $eventData[$i]['properties']['votes'] = $votes;
                                $eventData[$i]['properties']['visits'] = $visits;
                                $footer .= sprintf($karma_block, $myvote, $points, $votes, $visits, $url);
                            }
                            // foreach key in entries
                    }
                    // End switch on karma voting status
                    return true;
                    break;
                    // Display the Karma Log link on the sidebar
                // Display the Karma Log link on the sidebar
                case 'backend_sidebar_admin_appearance':
                    ?>
<li><a href="?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=karmalog"><?php 
                    echo PLUGIN_KARMA_DISPLAY_LOG;
                    ?>
</a></li>
<?php 
                    return true;
                    break;
                    // Display the Karma Log!
                    //case 'external_plugin':
                // Display the Karma Log!
                //case 'external_plugin':
                case 'backend_sidebar_entries_event_display_karmalog':
                    // Print any stored messages
                    //foreach ($serendipity['karma_messages'] as $msg) {
                    //    print("<div class='serendipityAdminInfo'>$msg</div>\n");
                    //}
                    // Was I asked to process any votes?
                    if (($serendipity['POST']['delete_button'] || $serendipity['POST']['approve_button']) && sizeof($serendipity['POST']['delete']) != 0 && serendipity_checkFormToken()) {
                        foreach ($serendipity['POST']['delete'] as $d => $i) {
                            $kdata = $serendipity['POST']['karmalog' . $i];
                            // validate posted variables
                            // posted points
                            $ppoints = $kdata['points'];
                            if (!is_numeric($ppoints) || (int) $ppoints < -2 || (int) $ppoints > 2) {
                                print "<span class='msg_error'><span class='icon-attention-circled'></span> " . PLUGIN_KARMA_INVALID_INPUT . "</span>\n";
                                return false;
                            }
                            // posted id
                            $pid = $kdata['entryid'];
                            if (!is_numeric($pid)) {
                                print "<span class='msg_error'><span class='icon-attention-circled'></span> " . PLUGIN_KARMA_INVALID_INPUT . "</span>\n";
                                return false;
                            }
                            // posted IP
                            $pip = long2ip(ip2long($kdata['ip']));
                            if ($pip == -1 || $pip === FALSE) {
                                print "<span class='msg_error'><span class='icon-attention-circled'></span> " . PLUGIN_KARMA_INVALID_INPUT . "</span>\n";
                                return false;
                            }
                            // posted user agent (need a better validator, I think)
                            $puser_agent = $kdata['user_agent'];
                            if (serendipity_db_escape_string($puser_agent) != $puser_agent) {
                                print "<span class='msg_error'><span class='icon-attention-circled'></span> " . PLUGIN_KARMA_INVALID_INPUT . "</span>\n";
                                return false;
                            }
                            // posted vote time
                            $pvotetime = $kdata['votetime'];
                            $unixsecs = date('U', $kdata['votetime']);
                            if ($pvotetime != $unixsecs) {
                                print "<span class='msg_error'><span class='icon-attention-circled'></span> " . PLUGIN_KARMA_INVALID_INPUT . "</span>\n";
                                return false;
                            }
                            // Remove karma from entry?
                            if ($serendipity['POST']['delete_button']) {
                                // Fetch vote total for the entry IDs
                                $q = 'SELECT k.*
                                    FROM ' . $serendipity['dbPrefix'] . 'karma   AS k
                                    WHERE k.entryid IN (' . $pid . ') GROUP BY k.entryid';
                                $sql = serendipity_db_query($q);
                                if (is_array($sql)) {
                                    $karma = $sql[0];
                                    $update = sprintf("UPDATE {$serendipity['dbPrefix']}karma\n                                        SET points   = %s,\n                                        votes    = %s\n                                        WHERE entryid  = %s", serendipity_db_escape_string($karma['points'] - $ppoints), serendipity_db_escape_string($karma['votes'] - 1), serendipity_db_escape_string($pid));
                                    $updated = serendipity_db_query($update);
                                    if ($updated != 1) {
                                        printf("<span class='msg_error'><span class='icon-attention-circled'></span> " . PLUGIN_KARMA_REMOVE_ERROR . "</span>\n", $pid);
                                        // Don't delete from karma log if we couldn't take away the points
                                        continue;
                                    }
                                } else {
                                    // This will only happen if someone is messing with the karma table or submit data
                                    printf("<span class='msg_error'><span class='icon-attention-circled'></span> " . PLUGIN_KARMA_UPDATE_ERROR . "</span>", $pid);
                                    continue;
                                }
                            }
                            // Remove vote from log (approved or deleted, doesn't matter)
                            $del = sprintf("DELETE FROM {$serendipity['dbPrefix']}karmalog\n                                WHERE entryid = %s AND ip = '%s' AND user_agent LIKE '%%%s%%' AND votetime = %s LIMIT 1", serendipity_db_escape_string($pid), serendipity_db_escape_string($pip), serendipity_db_escape_string($puser_agent), serendipity_db_escape_string($pvotetime));
                            $deleted = serendipity_db_query($del);
                            // User feedback
                            if ($deleted == 1) {
                                if ($serendipity['POST']['delete_button']) {
                                    printf("<span class='msg_success'><span class='icon-ok-circled'></span> " . PLUGIN_KARMA_REMOVED_POINTS . "</span>\n", $ppoints, $pid);
                                } else {
                                    printf("<span class='msg_success'><span class='icon-ok-circled'></span> " . PLUGIN_KARMA_APPROVED_POINTS . "</span>\n", $ppoints, $pid);
                                }
                            } else {
                                printf("<span class='msg_error'><span class='icon-attention-circled'></span> " . PLUGIN_KARMA_REMOVE_ERROR . "</span>\n", $pid);
                            }
                        }
                    }
                    // URL; expected to be event_display and karmalog, respectively
                    $url = '?serendipity[adminModule]=' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['GET']['adminModule']) : htmlspecialchars($serendipity['GET']['adminModule'], ENT_COMPAT, LANG_CHARSET)) . '&serendipity[adminAction]=' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['GET']['adminAction']) : htmlspecialchars($serendipity['GET']['adminAction'], ENT_COMPAT, LANG_CHARSET));
                    // Filters
                    print "\n<h2>" . PLUGIN_KARMA_DISPLAY_LOG . "</h2>\n<form id='karmafilters' name='karmafilters' action='' method='get'>\n    <input name='serendipity[adminModule]' type='hidden' value='{$serendipity['GET']['adminModule']}'>\n    <input name='serendipity[adminAction]' type='hidden' value='{$serendipity['GET']['adminAction']}'>\n\n    <ul class='filters_toolbar clearfix plainList'>\n        <li><a class='button_link' href='#serendipity_admin_filters' title='" . FILTERS . "'><span class='icon-filter'></span><span class='visuallyhidden'> " . FILTERS . "</span></a></li>\n        <li><a class='button_link' href='#serendipity_admin_sort' title='" . SORT_ORDER . "'><span class='icon-sort'></span><span class='visuallyhidden'> " . SORT_ORDER . "</span></a></li>\n    </ul>\n\n    <fieldset id='serendipity_admin_filters' class='additional_info filter_pane'>\n        <legend><span class='visuallyhidden'>" . FILTERS . "</span></legend>\n\n        <div class='clearfix'>\n            <div class='form_field'>\n                <label for='serendipity_filter_useragent'>User Agent</label>\n                <input id='serendipity_filter_useragent' name='serendipity[filter][user_agent]' type='text' value='" . (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['GET']['filter']['user_agent']) : htmlspecialchars($serendipity['GET']['filter']['user_agent'], ENT_COMPAT, LANG_CHARSET)) . "'>\n            </div>\n\n            <div class='form_field'>\n                <label for='serendipity_filter_ip'>" . IP . "</label>\n                <input id='serendipity_filter_ip' name='serendipity[filter][ip]' type='text' value='" . (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['GET']['filter']['ip']) : htmlspecialchars($serendipity['GET']['filter']['ip'], ENT_COMPAT, LANG_CHARSET)) . "'>\n            </div>\n\n            <div class='form_field'>\n                <label for='serendipity_filter_entryid'>Entry ID</label>\n                <input id='serendipity_filter_entryid' name='serendipity[filter][entryid]' type='text' value='" . (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['GET']['filter']['entryid']) : htmlspecialchars($serendipity['GET']['filter']['entryid'], ENT_COMPAT, LANG_CHARSET)) . "'>\n            </div>\n\n            <div class='form_field'>\n                <label for='serendipity_filter_title'>Entry title</label>\n                <input id='serendipity_filter_title' name='serendipity[filter][title]' type='text' value='" . (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['GET']['filter']['title']) : htmlspecialchars($serendipity['GET']['filter']['title'], ENT_COMPAT, LANG_CHARSET)) . "'>\n            </div>\n        </div>\n\n        <div class='form_buttons'>\n            <input name='submit' type='submit' value='" . GO . "'>\n        </div>\n    </fieldset>\n";
                    // Set all filters into $and and $searchString
                    if (!empty($serendipity['GET']['filter']['entryid'])) {
                        $val = $serendipity['GET']['filter']['entryid'];
                        $and .= "AND l.entryid = '" . serendipity_db_escape_string($val) . "'";
                        $searchString .= "&amp;serendipity['filter']['entryid']=" . (function_exists('serendipity_specialchars') ? serendipity_specialchars($val) : htmlspecialchars($val, ENT_COMPAT, LANG_CHARSET));
                    }
                    if (!empty($serendipity['GET']['filter']['ip'])) {
                        $val = $serendipity['GET']['filter']['ip'];
                        $and .= "AND l.ip = '" . serendipity_db_escape_string($val) . "'";
                        $searchString .= "&amp;serendipity['filter']['ip']=" . (function_exists('serendipity_specialchars') ? serendipity_specialchars($val) : htmlspecialchars($val, ENT_COMPAT, LANG_CHARSET));
                    }
                    if (!empty($serendipity['GET']['filter']['user_agent'])) {
                        $val = $serendipity['GET']['filter']['user_agent'];
                        $and .= "AND l.user_agent LIKE '%" . serendipity_db_escape_string($val) . "%'";
                        $searchString .= "&amp;serendipity['filter']['user_agent']=" . (function_exists('serendipity_specialchars') ? serendipity_specialchars($val) : htmlspecialchars($val, ENT_COMPAT, LANG_CHARSET));
                    }
                    if (!empty($serendipity['GET']['filter']['title'])) {
                        $val = $serendipity['GET']['filter']['title'];
                        $and .= "AND e.title LIKE '%" . serendipity_db_escape_string($val) . "%'";
                        $searchString .= "&amp;serendipity['filter']['title']=" . (function_exists('serendipity_specialchars') ? serendipity_specialchars($val) : htmlspecialchars($val, ENT_COMPAT, LANG_CHARSET));
                    }
                    // Sorting (controls go after filtering controls in form above)
                    $sort_order = array('votetime' => DATE, 'user_agent' => USER_AGENT, 'title' => TITLE, 'entryid' => 'ID');
                    if (empty($serendipity['GET']['sort']['ordermode']) || $serendipity['GET']['sort']['ordermode'] != 'ASC') {
                        $desc = true;
                        $serendipity['GET']['sort']['ordermode'] = 'DESC';
                    }
                    if (!empty($serendipity['GET']['sort']['order']) && !empty($sort_order[$serendipity['GET']['sort']['order']])) {
                        $curr_order = $serendipity['GET']['sort']['order'];
                        $orderby = serendipity_db_escape_string($curr_order . ' ' . $serendipity['GET']['sort']['ordermode']);
                    } else {
                        $curr_order = 'votetime';
                        $orderby = 'votetime ' . serendipity_db_escape_string($serendipity['GET']['sort']['ordermode']);
                    }
                    print "\n    <fieldset id='serendipity_admin_sort' class='additional_info filter_pane'>\n        <legend><span class='visuallyhidden'>" . SORT_ORDER . "</span></legend>\n\n        <div class='clearfix'>\n            <div class='form_select'>\n                <label for='serendipity_sort_order'>" . SORT_BY . "</label>\n                <select id='serendipity_sort_order' name='serendipity[sort][order]'>\n";
                    foreach ($sort_order as $order => $val) {
                        print "\n  <option value='{$order}'" . ($curr_order == $order ? " selected='selected'" : '') . ">{$val}</option>\n";
                    }
                    print "\n                </select>\n            </div>\n            <div class='form_select'>\n                <label for='serendipity_sort_ordermode'>" . SORT_ORDER . "</label>\n                <select id='serendipity_sort_ordermode' name='serendipity[sort][ordermode]'>\n                    <option value='DESC'" . ($desc ? " selected='selected'" : '') . ">" . SORT_ORDER_DESC . "</option>\n                    <option value='ASC'" . ($desc ? '' : " selected='selected'") . ">" . SORT_ORDER_ASC . "</option>\n                </select>\n            </div>\n        </div>\n\n        <div class='form_buttons'>\n            <input name='submit' type='submit' value='" . GO . "'>\n        </div>\n    </fieldset>\n</form>\n";
                    // Paging (partly ripped from include/admin/comments.inc.php)
                    $commentsPerPage = (int) (!empty($serendipity['GET']['filter']['perpage']) ? $serendipity['GET']['filter']['perpage'] : 25);
                    $sql = serendipity_db_query("SELECT COUNT(*) AS total FROM {$serendipity['dbPrefix']}karmalog l WHERE 1 = 1 " . $and, true);
                    if (is_string($sql)) {
                        print "<span class='msg_error'><span class='icon-attention-circled'></span> " . $sql . "</span>\n";
                    }
                    $totalVotes = is_array($sql) && is_int($sql['total']) ? $sql['total'] : 0;
                    $pages = $commentsPerPage == COMMENTS_FILTER_ALL ? 1 : ceil($totalVotes / (int) $commentsPerPage);
                    $page = (int) $serendipity['GET']['page'];
                    if ($page == 0 || $page > $pages) {
                        $page = 1;
                    }
                    if ($page > 1) {
                        $linkPrevious = $url . '&amp;serendipity[page]=' . ($page - 1) . $searchString;
                    }
                    if ($pages > $page) {
                        $linkNext = $url . '&amp;serendipity[page]=' . ($page + 1) . $searchString;
                    }
                    if ($commentsPerPage == COMMENTS_FILTER_ALL) {
                        $limit = '';
                    } else {
                        $limit = serendipity_db_limit_sql(serendipity_db_limit(($page - 1) * (int) $commentsPerPage, (int) $commentsPerPage));
                    }
                    // Variables for display
                    if ($linkPrevious) {
                        $linkPrevious = '<a class="button_link" href="' . $linkPrevious . '" title="' . PREVIOUS . '"><span class="icon-left-dir"></span><span class="visuallyhidden"> ' . PREVIOUS . '</span></a>';
                    } else {
                        $linkPrevious = '<span class="visuallyhidden">' . NO_ENTRIES_TO_PRINT . '</span>';
                    }
                    if ($linkNext) {
                        $linkNext = '<a class="button_link" href="' . $linkNext . '" title="' . NEXT . '"><span class="visuallyhidden">' . NEXT . ' </span><span class="icon-right-dir"></span></a>';
                    } else {
                        $linkNext = '<span class="visuallyhidden">' . NO_ENTRIES_TO_PRINT . '</span>';
                    }
                    $paging = sprintf(PAGE_BROWSE_COMMENTS, $page, $pages, $totalVotes);
                    // Retrieve the next batch of karma votes
                    // [entryid, points, ip, user_agent, votetime]
                    $sql = serendipity_db_query("SELECT l.entryid AS entryid, l.points AS points, l.ip AS ip, l.user_agent AS user_agent, l.votetime AS votetime, e.title AS title FROM {$serendipity['dbPrefix']}karmalog l\n                        LEFT JOIN {$serendipity['dbPrefix']}entries e ON (e.id = l.entryid)\n                        WHERE 1 = 1 " . $and . "\n                        ORDER BY {$orderby} {$limit}");
                    // Start the form for display and deleting
                    if (is_array($sql)) {
                        print "<form action='' method='post' name='formMultiDelete' id='formMultiDelete'>\n" . serendipity_setFormToken();
                        // Start the vote table
                        print "\n<div class='clearfix karma_pane'>\n<ul id='karmalog' class='clearfix karmalog plainList zebra_list'>\n";
                        // Print each vote
                        $i = 0;
                        foreach ($sql as $vote) {
                            $i++;
                            // entryid, title, points, ip, user_agent, votetime
                            if (strlen($vote['title']) > 40) {
                                $votetitle = substr($vote['title'], 0, 40) . '&hellip;';
                            } else {
                                $votetitle = $vote['title'];
                            }
                            $entrylink = serendipity_archiveURL($vote['entryid'], $vote['title'], 'serendipityHTTPPath', true);
                            $entryFilterHtml = "<a class='button_link filter_karma' href='{$url}&serendipity[filter][entryid]={$vote['entryid']}' title='" . FILTERS . "'><span class='icon-filter'></span><span class='visuallyhidden'>" . FILTERS . "</span></a>";
                            $ipFilterHtml = "<a class='button_link filter_karma' href='{$url}&serendipity[filter][ip]={$vote['ip']}' title='" . FILTERS . "'><span class='icon-filter'></span><span class='visuallyhidden'>" . FILTERS . "</span></a>";
                            $timestr = strftime('%a %b %d %Y, %H:%M:%S', $vote['votetime']);
                            $cssClass = $i % 2 == 0 ? 'even' : 'odd';
                            $barClass = str_replace(array('.', ' '), array('_', '_'), $this->image_name);
                            $barHtml = $this->createRatingBar(null, $vote['points'], 1, $barClass);
                            $barHtml = sprintf($barHtml, 'what', $vote['points'], '1');
                            print "\n    <li id='karma_{$i}' class='{$cssClass} clearfix'>\n        <input type='hidden' name='serendipity[karmalog{$i}][points]' value='{$vote['points']}'>\n        <input type='hidden' name='serendipity[karmalog{$i}][entryid]' value='{$vote['entryid']}'>\n        <input type='hidden' name='serendipity[karmalog{$i}][votetime]' value='{$vote['votetime']}'>\n        <input type='hidden' name='serendipity[karmalog{$i}][ip]' value='{$vote['ip']}'>\n        <input type='hidden' name='serendipity[karmalog{$i}][user_agent]' value='{$vote['user_agent']}'>\n\n        <div class='form_check'>\n            <input id='multidelete_karma_{$i}' class='multidelete' type='checkbox' name='serendipity[delete][{$i}]' value='{$i}' data-multidelid='karma_{$i}'>\n            <label for='multidelete_karma_{$i}' class='visuallyhidden'>" . TOGGLE_SELECT . "</label>\n        </div>\n\n        <h4><a href='{$entrylink}' title='ID: {$vote['entryid']}'>{$votetitle}</a>\n            <button class='toggle_info button_link' type='button' data-href='#karma_data_{$i}'><span class='icon-info-circled'></span><span class='visuallyhidden'> " . MORE . "</span></button>\n            {$entryFilterHtml}\n        </h4>\n\n        {$barHtml}\n\n        <div id='karma_data_{$i}' class='additional_info'>\n            <dl class='clearfix comment_data'>\n                <dt>" . ON . "</dt>\n                <dd>{$timestr}</dd>\n                <dt>IP</dt>\n                <dd>{$vote['ip']} {$ipFilterHtml}</dd>\n                <dt><abbr title='User-Agent' lang='en'>UA</abbr></dt>\n                <dd>{$vote['user_agent']}</dd>\n            </dl>\n        </div>\n    </li>\n";
                        }
                        // End the vote table
                        print "\n                            </ul>\n                            ";
                        // Print the footer paging table
                        print "\n<nav class='pagination'>\n    <h3>{$paging}</h3>\n    <ul class='clearfix'>\n        <li class='prev'>{$linkPrevious}</li>\n        <li class='next'>{$linkNext}</li>\n    </ul>\n</nav>\n</div>\n";
                        if (is_array($sql)) {
                            print "\n<div class='form_buttons'>\n<input class='invert_selection' name='toggle' type='button' value='" . INVERT_SELECTIONS . "'> \n<input class='state_cancel' name='serendipity[delete_button]' type='submit' title='" . PLUGIN_KARMA_DELETE_VOTES . "' value='" . DELETE . "'>\n</div>\n</form>\n";
                        }
                    } else {
                        print "\n<span class='msg_notice'><span class='icon-info-circled'></span> No logs to display. You need to enable karma logging, if you want to see single votes displayed here.</span>\n";
                    }
                    return true;
                    break;
                default:
                    return false;
            }
            // End switch on event hooks
        } else {
            return false;
        }
    }
    function event_hook($event, &$bag, &$eventData, $addData = null)
    {
        global $serendipity;
        $hooks =& $bag->get('event_hooks');
        if (isset($hooks[$event])) {
            // Moved from above: only get image data if we're actually going to do something
            $this->set_valid_image_data();
            // Get dimensions of image, only if not text-only
            if ($this->image_name) {
                // Is this a single-image bar, or a single segment?
                $ratio = $this->image_width / $this->image_height;
                if ($ratio < $max_segment_ratio) {
                    // This is probably a single segment. Square segments
                    // will have a ratio of 0.3; long, flat segments won't
                    // get up to 1.0 unless they're 3 times as wide as they
                    // are tall; full-bar images with square segments will
                    // be 1.666; and full-bar images with tall, narrow
                    // segments will be greater than 1.0 unless they're
                    // nearly twice as high as they are wide.
                    $this->image_width = $this->image_width * 5;
                }
            }
            switch ($event) {
                // Early hook, before any page is displayed
                case 'frontend_configure':
                    // Make sure the karmaVote cookie is set, even if empty <a name="#1" />
                    if (!isset($serendipity['COOKIE']['karmaVote'])) {
                        serendipity_setCookie('karmaVote', serialize(array()));
                    }
                    // If user didn't vote, we're done.
                    if (!isset($serendipity['GET']['karmaId']) || !isset($serendipity['GET']['karmaVote'])) {
                        return;
                    }
                    // Get URL vote data
                    $this->karmaId = (int) $serendipity['GET']['karmaId'];
                    $this->karmaVoting = (int) $serendipity['GET']['karmaVote'];
                    // karmaVote cookie was just set (see name="#1"); this boils down to
                    // "if check cookie isn't 1, there's no real cookie".
                    // The check cookie gets set when a rater is displayed,
                    // so you've got no business voting if you haven't even
                    // seen the rater yet.
                    if (!isset($serendipity['COOKIE']['karmaVote']) or $serendipity['COOKIE']['check'] != '1') {
                        $this->karmaVote = 'nocookie';
                        return;
                    }
                    // Everything is ready.  Get the cookie vote data.
                    $karma = unserialize($serendipity['COOKIE']['karmaVote']);
                    // Stop on invalid votes (cookie invalid, or URL data incorrect)
                    if (!is_array($karma) || !is_numeric($this->karmaVoting) || !is_numeric($this->karmaId) || $this->karmaVoting > 2 || $this->karmaVoting < -2) {
                        $this->karmaVote = 'invalid1';
                        return;
                    }
                    // Stop if the cookie says we already voted
                    if (!empty($karma[$this->karmaId])) {
                        $this->karmaVote = 'alreadyvoted';
                        return;
                    }
                    // We don't want bots hitting the karma-voting
                    $agent = $_SERVER['HTTP_USER_AGENT'];
                    if (stristr($agent, 'google') || stristr($agent, 'LinkWalker') || stristr($agent, 'zermelo') || stristr($agent, 'NimbleCrawler')) {
                        $this->karmaVote = 'invalid1';
                        return;
                    }
                    // Voting takes place here.
                    //
                    // Get voting data from the database (keeps all entries,
                    // even if no karma match)
                    $q = 'SELECT *
                            FROM ' . $serendipity['dbPrefix'] . 'entries AS e
                 LEFT OUTER JOIN ' . $serendipity['dbPrefix'] . 'karma   AS k
                              ON e.id = k.entryid
                           WHERE e.id = ' . serendipity_db_escape_string($this->karmaId) . ' LIMIT 1';
                    $row = serendipity_db_query($q, true);
                    // If there's no entry with this ID, we're done
                    //
                    // --TODO: Modify the plugin to allow arbitrary voting with generated IDs
                    if (!isset($row) || !is_array($row)) {
                        $this->karmaVote = 'invalid2';
                        return;
                    }
                    $now = time();
                    if ($row['votes'] === '0' || $row['votes'] > 0) {
                        // Votes for this entry already exist. Do some checking.
                        $max_entrytime = $this->get_config('max_entrytime', 1440) * 60;
                        $max_votetime = $this->get_config('max_votetime', 5) * 60;
                        $max_karmatime = $this->get_config('max_karmatime', 7) * 24 * 60 * 60;
                        // Allow infinite voting when 0 or negative
                        if ($max_karmatime <= 0) {
                            $max_karmatime = $now;
                        }
                        // If the entry's timestamp is too old for voting,
                        // we're done.
                        if ($row['timestamp'] < $now - $max_karmatime) {
                            $this->karmaVote = 'timeout2';
                            return;
                        }
                        // If the entry is in the grace period, or votes
                        // aren't too close together, record the vote.
                        if ($row['timestamp'] > $now - $max_entrytime || $row['lastvote'] + $max_votetime < $now || $row['lastvote'] == 0) {
                            // Update votes
                            $q = sprintf("UPDATE {$serendipity['dbPrefix']}karma\n                                  SET points   = %s,\n                                      votes    = %s,\n                                      lastvote = %s\n                                WHERE entryid  = %s", $row['points'] + $this->karmaVoting, $row['votes'] + 1, $now, $this->karmaId);
                            serendipity_db_query($q);
                        } else {
                            // Entry was too recently voted upon.  Figure out
                            // how long until voting will be allowed (in minutes).
                            $this->karmaVote = 'timeout';
                            $this->karmaTimeOut = abs(ceil(($now - ($row['lastvote'] + $max_votetime)) / 60));
                            return;
                        }
                    } else {
                        // No row. Use INSERT instead of UPDATE.
                        $q = sprintf("INSERT INTO {$serendipity['dbPrefix']}karma\n                                       (entryid, points, votes, lastvote, visits)\n                                VALUES (%s,      %s,     %s,    %s,       %s)", $this->karmaId, $this->karmaVoting, 1, $now, 0);
                        $sql = serendipity_db_query($q);
                    }
                    // Log the vote
                    if (serendipity_db_bool($this->get_config('logging', false))) {
                        $q = sprintf("INSERT INTO {$serendipity['dbPrefix']}karmalog\n                                       (entryid, points, ip, user_agent, votetime)\n                                VALUES (%s, %s, '%s', '%s', %s)", $this->karmaId, $this->karmaVoting, serendipity_db_escape_string($_SERVER['REMOTE_ADDR']), substr(serendipity_db_escape_string($_SERVER['HTTP_USER_AGENT']), 0, 255), $now);
                        $sql = serendipity_db_query($q);
                        if (is_string($sql)) {
                            mail($serendipity['serendipityEmail'], 'KARMA ERROR', $q . '<br />' . $sql . '<br />');
                        }
                    }
                    // Set the cookie that we already voted for this entry
                    $karma[$this->karmaId] = $this->karmaVoting;
                    $this->karmaVote = 'voted';
                    serendipity_setCookie('karmaVote', serialize($karma));
                    return true;
                    break;
                    // CSS generation hooks
                // CSS generation hooks
                case 'backend_header':
                    // Generate the CSS for the graphical rating bar selector
                    //
                    // The CSS appears to be generated in a completely
                    // different instance of Serendipity, as if index.php gets
                    // called separately for the CSS.
                    //
                    // Note that the css_backend hook adds properties to the
                    // serendipity_admin.css, but that file is *always*
                    // cached.  We use backend_header and add the CSS to the
                    // HEAD styles to make it dynamic.
                    // Get the CSS, set $this->image_name so we'll output the
                    // standard graphical CSS prologue if any images are found.
                    $this->createRatingSelector();
                    print "<style type='text/css'>\n";
                    $align = 'center';
                    $bg = $this->get_config('preview_bg', false);
                    if (!empty($bg)) {
                        if (strpos($bg, ';') !== false || strpos($bg, ',') !== false) {
                            $bg = 'red';
                        }
                        print "\n.serendipity_karmaVote_selectorTable {\n    background: {$bg};\n}\n";
                    }
                    print "\n.serendipityAdminContent .serendipity_karmaVoting_links {\n    margin: 5px;\n}\n";
                case 'css':
                    // Some CSS notes:
                    //
                    // .serendipity_karmaVoting is the class for the karma wrapper/container,
                    //      including the text explanations, messages, and rating bar.
                    //      (currently a div)
                    // .serendipity_karmaVoting a specifies the links for the text-mode
                    //      rating bar
                    // .serendipity_karmaError is the class for any text indicating an
                    //      error condition
                    // .serendipity_karmaSuccess is the class for any text indicating
                    //      successful operation
                    // .serendipity_karmaVoting_links is the container for the graphical
                    //      rating bar (currently an ol)
                    // .serendipity_karmaVoting_links a indicates the various voting links in
                    //      the graphical rating bar
                    // .serendipity_karmaVoting_current-rating is the class for the current
                    //      rating in the graphical rating bar
                    //  a.serendipity_karmaVoting_link1, _link2, etc are the classes applied
                    //      to the individual voting links
                    // Note that there are two possible template types: early
                    // templates that only handle the text rating bars, and
                    // newer templates that understand the graphical raters.
                    // We check for both types and act appropriately.
                    /*--JAM: Let's just skip this whole hassle
                      if (!$align) {
                          $align = $this->get_config('alignment', 'detect');
                      }
                      if ($align == 'detect') {
                      */
                    $align = $this->get_config('alignment', 'center');
                    // Try to let the template take care of it
                    if ($this->image_name == '0') {
                        // Text-only rating bar is used
                        if (strpos($eventData, '.serendipity_karmaVoting')) {
                            // Template is handling all our CSS
                            return true;
                        }
                    }
                    /* --JAM: else {
                               // Graphical rating bar is used
                               if (strpos($eventData, '.serendipity_karmaVoting_images')) {
                                   // Template is handling all our CSS
                                   return true;
                               }
                               // Check for old text-only templates
                               $pos = strpos($eventData, '.serendipity_karmaVoting');
                               while ($pos && ($align == 'detect')) {
                                   // Find text-align: in the current block
                                   $endpos = strpos($eventData, '}', $pos);
                                   if (!$endpos) {
                                       // Broken CSS
                                       break;
                                   }
                                   $alignpos = strpos($eventData, 'text-align:', $pos);
                                   // Can't check for comments, or I would.  Hope
                                   // the first is the correct one.
                                   if ($alignpos && $alignpos < $endpos) {
                                       $start = $alignpos + 11;
                                       $alignend = strpos($eventData, ';', $alignpos);
                                       if ($alignend)
                                       {
                                           // All valid.  Pull out the alignment.
                                           $len = $alignend - $start;
                                           $align = trim(substr($eventData, $start, $len));
                                       }
                                   }
                                   $pos = strpos($eventData, '.serendipity_karmaVoting', $endpos);
                               }
                               // I should have a valid alignment or 'detect' in $align now. 
                           }
                       }
                       // If we couldn't detect the alignment, guess 'right'
                       if ($align == 'detect') {
                           $align = 'right';
                       }
                       --JAM: END COMMENT BLOCK */
                    // Since errors might be printed at any time, always
                    // output the text-mode CSS
                    print <<<EOS
.serendipity_karmaVoting {
    text-align: {$align};
    font-size: 7pt;
    margin: 0px;
}

.serendipity_karmaVoting a {
    font-size: 7pt;
    text-decoration: none;
}

.serendipity_karmaVoting a:hover {
    color: green;
}

.serendipity_karmaError {
    color: #FF8000;
}
.serendipity_karmaSuccess {
    color: green;
}
EOS;
                    // Only output the image CSS if it's needed
                    if ($this->image_name != '0') {
                        $img = $serendipity['baseURL'] . "plugins/serendipity_event_karma/img/" . $this->image_name;
                        $h = $this->image_height / 3;
                        $w = $this->image_width;
                        switch ($align) {
                            case 'left':
                                $margin = '0px auto 0px 0px';
                                break;
                            case 'center':
                                $margin = '0px auto';
                                break;
                            case 'right':
                            default:
                                $margin = '0px 0px 0px auto';
                                break;
                        }
                        // The CSS here is lifted largely from
                        // http://komodomedia.com/blog/index.php/2007/01/20/css-star-rating-redux/
                        //
                        // Note, however that margin has been changed for
                        // multiple cases and all unitless measurements have
                        // been specified in pixels.  Additionally, measures
                        // have been taken to align the text.
                        print <<<END_IMG_CSS

.serendipity_karmaVoting_links,
.serendipity_karmaVoting_links a:hover,
.serendipity_karmaVoting_current-rating {
    background: url({$img}) left;
    font-size: 0;
}
.serendipity_karmaVoting_links {
    position: relative;
    width: {$w}px;
    height: {$h}px;
    overflow: hidden;
    list-style: none;
    margin: {$margin};
    padding: 0px;
    background-position: left top;     
    text-align: center;
}
.serendipity_karmaVoting_links li {
   display: inline; 
}
.serendipity_karmaVoting_links a ,
.serendipity_karmaVoting_current-rating {
    position:absolute;
    top: 0px;
    left: 0px;
    text-indent: -9000em;
    height: {$h}px;
    line-height: {$h}px;
    outline: none;
    overflow: hidden;
    border: none;
}
.serendipity_karmaVoting_links a:hover {
    background-position: left bottom;
}
.serendipity_karmaVoting_links a.serendipity_karmaVoting_link1 {
    width: 20%;
    z-index: 6;
}
.serendipity_karmaVoting_links a.serendipity_karmaVoting_link2 {
    width: 40%;
    z-index: 5;
}
.serendipity_karmaVoting_links a.serendipity_karmaVoting_link3 {
    width: 60%;
    z-index: 4;
}
.serendipity_karmaVoting_links a.serendipity_karmaVoting_link4 {
    width: 80%;
    z-index: 3;
}
.serendipity_karmaVoting_links a.serendipity_karmaVoting_link5 {
  width: 100%;
    z-index: 2;
}
.serendipity_karmaVoting_links .serendipity_karmaVoting_current-rating {
    z-index: 1;
    background-position: left center;
}

END_IMG_CSS;
                        // Add selector images CSS, if necessary
                        if (!empty($this->select_css)) {
                            print $this->select_css;
                        }
                    }
                    // End if image bar defined
                    if ($event == 'backend_header') {
                        print "\n</style>\n";
                    }
                    return true;
                    break;
                    //--TODO: Comment the functionality of this event hook.
                //--TODO: Comment the functionality of this event hook.
                case 'event_additional_statistics':
                    $sql = array();
                    $sql['visits_top'] = array('visits', 'DESC');
                    $sql['visits_bottom'] = array('visits', 'ASC');
                    $sql['votes_top'] = array('votes', 'DESC');
                    $sql['votes_bottom'] = array('votes', 'ASC');
                    $sql['points_top'] = array('points', 'DESC');
                    $sql['points_bottom'] = array('points', 'ASC');
                    foreach ($sql as $key => $rows) {
                        $q = "SELECT e.id,\n                                     e.title,\n                                     e.timestamp,\n                                     SUM(k.{$rows[0]}) AS no\n                                FROM {$serendipity['dbPrefix']}karma\n                                     AS k\n                                JOIN {$serendipity['dbPrefix']}entries\n                                     AS e\n                                  ON k.entryid = e.id\n                            WHERE k.{$rows[0]} IS NOT NULL AND k.{$rows[0]} != 0\n                            GROUP BY e.id, e.title, e.timestamp ORDER BY no {$rows[1]} LIMIT {$addData['maxitems']}";
                        $sql_rows = serendipity_db_query($q);
                        ?>
    <dt><strong><?php 
                        echo constant('PLUGIN_KARMA_STATISTICS_' . strtoupper($key));
                        ?>
</strong></dt>
    <dl>
<?php 
                        if (is_array($sql_rows)) {
                            foreach ($sql_rows as $id => $row) {
                                ?>
        <dt><strong><a href="<?php 
                                echo serendipity_archiveURL($row['id'], $row['title'], 'serendipityHTTPPath', true, array('timestamp' => $row['timestamp']));
                                ?>
"><?php 
                                echo htmlspecialchars($row['title']);
                                ?>
</a></strong></dt>
        <dd><?php 
                                echo $row['no'];
                                ?>
 <?php 
                                echo constant('PLUGIN_KARMA_STATISTICS_' . strtoupper($rows[0]) . '_NO');
                                ?>
</dd>
    <?php 
                            }
                        }
                        ?>
    </dl>
<?php 
                    }
                    return true;
                    break;
                    // Add voting information to entries
                // Add voting information to entries
                case 'entry_display':
                    // Update database if necessary
                    if ($this->get_config('dbversion', 0) != PLUGIN_KARMA_DB_VERSION) {
                        $this->checkScheme();
                    }
                    // Find the ID of this entry
                    if (isset($serendipity['GET']['id'])) {
                        $entryid = (int) serendipity_db_escape_string($serendipity['GET']['id']);
                    } elseif (preg_match(PAT_COMMENTSUB, $_SERVER['REQUEST_URI'], $matches)) {
                        $entryid = (int) $matches[1];
                    } else {
                        $entryid = false;
                    }
                    // If we're actually reading the entry, not voting or editing it...
                    if ($entryid && empty($serendipity['GET']['adminAction']) && !$serendipity['GET']['karmaVote']) {
                        // Update the number of visits
                        // Are we supposed to track visits?
                        $track_clicks = serendipity_db_bool($this->get_config('visits_active', true)) && $this->track_clicks_allowed_by_user();
                        if ($track_clicks && $_SERVER['REQUEST_METHOD'] == 'GET') {
                            $sql = serendipity_db_query("UPDATE {$serendipity['dbPrefix']}karma \n                                    SET visits = visits + 1 \n                                  WHERE entryid = {$entryid}", true);
                            if (serendipity_db_affected_rows() < 1) {
                                serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}karma (entryid, points, votes, lastvote, visits) \n                                              VALUES ('{$entryid}', 0, 0, 0, 1)");
                            }
                        }
                    }
                    // Set a cookie to look for later, verifying that cookies are enabled
                    serendipity_setCookie('check', '1');
                    switch ($this->karmaVote) {
                        case 'nocookie':
                            // Users with no cookies won't be able to vote.
                            $msg = '<div class="serendipity_karmaVoting serendipity_karmaError"><a id="karma_vote' . $this->karmaId . '"></a>' . PLUGIN_KARMA_NOCOOKIE . '</div>';
                            // Continue until output
                        // Continue until output
                        case 'timeout2':
                            if (!isset($msg)) {
                                $msg = '<div class="serendipity_karmaVoting serendipity_karmaError"><a id="karma_vote' . $this->karmaId . '"></a>' . PLUGIN_KARMA_CLOSED . '</div>';
                            }
                            // Continue until output
                        // Continue until output
                        case 'timeout':
                            if (!isset($msg)) {
                                $msg = '<div class="serendipity_karmaVoting serendipity_karmaError"><a id="karma_vote' . $this->karmaId . '"></a>' . sprintf(PLUGIN_KARMA_TIMEOUT, $this->karmaTimeOut) . '</div>';
                            }
                            // Continue until output
                        // Continue until output
                        case 'alreadyvoted':
                            if (!isset($msg)) {
                                $msg = '<div class="serendipity_karmaVoting serendipity_karmaError"><a id="karma_vote' . $this->karmaId . '"></a>' . PLUGIN_KARMA_ALREADYVOTED . '</div>';
                            }
                            // Continue until output
                        // Continue until output
                        case 'invalid1':
                        case 'invalid2':
                        case 'invalid':
                            // Set message
                            if (!isset($msg)) {
                                $msg = '<div class="serendipity_karmaVoting serendipity_karmaError"><a id="karma_vote' . $this->karmaId . '"></a>' . PLUGIN_KARMA_INVALID . '</div>';
                            }
                            // Continue until output
                            /* OUTPUT MESSAGE */
                            //--TODO: Shouldn't this work with the cache plugin, too?
                            if ($addData['extended']) {
                                $eventData[0]['exflag'] = 1;
                                $eventData[0]['add_footer'] .= $msg;
                            } else {
                                $elements = count($eventData);
                                // Find the right container to store our message in.
                                for ($i = 0; $i < $elements; $i++) {
                                    if ($eventData[$i]['id'] == $this->karmaId) {
                                        $eventData[$i]['add_footer'] .= $msg;
                                    }
                                }
                            }
                            break;
                        case 'voted':
                        default:
                            // If there's no data, there's no need to go on
                            if (!is_array($eventData)) {
                                return;
                            }
                            // Find out what the admin wants
                            $track_clicks = serendipity_db_bool($this->get_config('visits_active', true));
                            $track_karma = serendipity_db_bool($this->get_config('karma_active', true));
                            if (serendipity_db_bool($this->get_config('karma_active_registered', false))) {
                                if (!serendipity_userLoggedIn()) {
                                    $track_karma = false;
                                }
                            }
                            $track_exits = serendipity_db_bool($this->get_config('exits_active', true));
                            // Get the limits
                            $now = time();
                            $karmatime = $this->get_config('max_karmatime', 7);
                            $max_karmatime = $karmatime * 24 * 60 * 60;
                            // Accept infinite voting
                            if ($max_karmatime <= 0) {
                                $max_karmatime = $now;
                            }
                            //--TODO: Ensure that this works with the Custom Permalinks plugin
                            // (We've seen trouble; it votes correctly, but redirects to the front page)
                            $url = serendipity_currentURL(true);
                            // Voting is only allowed on entries.  Therefore voting URLs must be
                            // either single-entry URLs or summary URLs.  serendipity_currentURL
                            // converts them to an "ErrorDocument-URI", so we can focus on the
                            // query portion of the URI.
                            //
                            // Single-entry URLs should be well-defined.  They can be permalinks,
                            // of course; otherwise they're of the configured pattern.
                            //
                            // Summary URLs could be a little harder.  The summary pages that
                            // include entries are: frontpage, category, author, and archives.
                            // It's possible a plugin would show entries, but if that's the case
                            // we don't need to allow the user to vote on them.  Still, that's
                            // a lot of URLs to check for.
                            //
                            // Then there's the problem of the rest of the query.  It could
                            // include stuff we really want to keep around, like template
                            // overrides or something.  One can even add serendipity variables
                            // to the URL in extreme cases.
                            //
                            // It seems that canonicalizing the URL will be quite difficult.
                            // The only thing we can say for certain is that whatever the
                            // current URL is, it got us to this page, and we'd like to return
                            // to this page after we cast our vote.
                            // Remove any clutter from our previous voting activity
                            $url_parts = parse_url(serendipity_currentURL(true));
                            if (!empty($url_parts['query'])) {
                                $exclude = array('serendipity[karmaVote]', 'serendipity[karmaId]');
                                // I tried using parse_str, but it gave me very weird results
                                // with embedded arrays
                                //parse_str($url_parts['query'], $q_parts);
                                $q_parts = array();
                                // I don't know why this URL has been HTML encoded.  Oh well.
                                $pairs = explode('&amp;', $url_parts['query']);
                                foreach ($pairs as $pair) {
                                    $parts = explode('=', $pair);
                                    $q_parts[$parts[0]] = $parts[1];
                                }
                                foreach ($q_parts as $key => $value) {
                                    if (in_array($key, $exclude)) {
                                        $rm = preg_quote("{$key}={$value}");
                                        $url = preg_replace("@(&amp;|&)?{$rm}@", '', $url);
                                    }
                                }
                            }
                            if (substr($url, -1) != '?') {
                                $url .= '&amp;';
                            }
                            // Get the cookie data (past votes, etc)
                            $karma = isset($serendipity['COOKIE']['karmaVote']) ? unserialize($serendipity['COOKIE']['karmaVote']) : array();
                            // Get all required entry IDs, making keys match keys in eventData
                            $entries = array();
                            if ($addData['extended'] || $addData['preview']) {
                                // We're in extended or preview mode, we only need the current ID
                                $eventData[0]['exflag'] = 1;
                                $entries[0] = (int) $eventData[0]['id'];
                            } elseif (!serendipity_db_bool($this->get_config('extended_only', false))) {
                                // We're in overview mode, and we want rating bars for all the entry IDs
                                foreach (array_keys($eventData) as $key) {
                                    if (isset($eventData[$key]['id'])) {
                                        $entries[$key] = (int) $eventData[$key]['id'];
                                    }
                                }
                            }
                            // Fetch votes for all entry IDs. Store them in an array for later usage.
                            $q = 'SELECT k.entryid, SUM(votes) AS votes, SUM(points) AS points, SUM(visits) AS visits
                                    FROM ' . $serendipity['dbPrefix'] . 'karma   AS k
                                   WHERE k.entryid IN (' . implode(', ', $entries) . ') GROUP BY k.entryid';
                            $sql = serendipity_db_query($q);
                            $rows = array();
                            if ($sql && is_array($sql)) {
                                foreach ($sql as $row) {
                                    $rows[$row['entryid']] = array('votes' => $row['votes'], 'points' => $row['points'], 'visits' => $row['visits']);
                                }
                            }
                            $this->prepareExits($entries);
                            // Add karma block to the footer of each entry
                            //
                            // The entries array was populated, above, so its keys match the eventData array,
                            // and overview entries are skipped if "extended only" is enabled
                            foreach (array_keys($entries) as $i) {
                                // Get the statistics
                                $entryid = $eventData[$i]['id'];
                                $votes = !empty($rows[$entryid]['votes']) ? $rows[$entryid]['votes'] : 0;
                                $points = !empty($rows[$entryid]['points']) ? $rows[$entryid]['points'] : 0;
                                $visits = !empty($rows[$entryid]['visits']) ? $rows[$entryid]['visits'] : 0;
                                $enough_votes = $track_karma && $votes >= $this->get_config('min_disp_votes', 0);
                                $enough_visits = $track_clicks && $visits >= $this->get_config('min_disp_visits', 0);
                                $textual_msg = true;
                                $textual_current = true;
                                $textual_visits = true;
                                if ($this->image_name != '0') {
                                    $textual_msg = $this->get_config('textual_msg', 'true');
                                    $textual_current = $this->get_config('textual_current', 'true');
                                    $textual_visits = $this->get_config('textual_visits', 'true');
                                }
                                // Where's the footer?  Normally it would be
                                // in eventData[n]['add_footer'] but if the
                                // cache plugin is used, it's in
                                // eventData[n]['properties']['ep_cache_add_footer'].
                                // This method retrieves it either way.
                                $footer =& $this->getFieldReference('add_footer', $eventData[$i]);
                                // Depending on what existed, $footer could
                                // be referencing the cached version, the
                                // uncached version, or even a new empty
                                // string.  In particular, if $eventData[$i]
                                // has no properties, and no 'add_footer' key,
                                // $footer is referencing a new empty string,
                                // so adding a karma bar to $footer would do
                                // nothing.
                                //
                                // We could be referencing an empty uncached
                                // 'add_footer', but empty cache entries are
                                // never returned.
                                //
                                // Reference a footer that will be printed
                                if (empty($footer) && !isset($eventData[$i]['add_footer']) && is_array($eventData[$i])) {
                                    $eventData[$i]['add_footer'] = '';
                                    $footer =& $eventData[$i]['add_footer'];
                                    // It's still empty, but it's referencing
                                    // the right place.
                                }
                                if ($track_exits) {
                                    $footer .= $this->getExits($entryid, true);
                                }
                                // Pick the appropriate intro msg and rating bar
                                // No msg or bar if karma is disabled
                                if ($track_karma) {
                                    if (isset($karma[$entryid])) {
                                        // We already voted for this one
                                        $msg = '<div class="serendipity_karmaSuccess">' . PLUGIN_KARMA_VOTED . '</div>';
                                        $myvote = $karma[$entryid];
                                        if ($this->get_config('rate_with_words', false)) {
                                            $myvote = $this->wordRating($myvote, 1);
                                        } elseif ($this->image_name != '0') {
                                            $myvote = $this->imageRating($myvote, 1);
                                        }
                                        // Just a current rating bar, if any
                                        $bar = $this->createRatingBar(null, $points, $votes);
                                    } elseif ($eventData[$i]['timestamp'] < $now - $max_karmatime) {
                                        // Too late to vote for this one
                                        $msg = '<div class="serendipity_karmaClosed">' . sprintf(PLUGIN_KARMA_CLOSED, $karmatime) . '</div>';
                                        // Just a current rating bar, if any
                                        $bar = $this->createRatingBar(null, $points, $votes);
                                    } else {
                                        // We can vote for this; make the whole voting block
                                        $rate_msg = $this->get_config('rate_msg', PLUGIN_KARMA_VOTETEXT);
                                        $msg = '<div class="serendipity_karmaVoting_text">' . $rate_msg . '</div>';
                                        // Full voting bar
                                        $bar = $this->createRatingBar($entryid, $points, $votes);
                                    }
                                }
                                // Create the karma block
                                $image_class = '';
                                if ($this->image_name != '0') {
                                    $image_class = ' serendipity_karmaVoting_images';
                                }
                                $karma_block = "<div class='serendipity_karmaVoting{$image_class}'><a id='karma_vote{$entryid}'></a>";
                                if ($textual_msg) {
                                    $karma_block .= $msg;
                                }
                                $karma_block .= $bar;
                                if ($enough_votes && $textual_current) {
                                    $curr_msg = $this->get_config('curr_msg', PLUGIN_KARMA_CURRENT);
                                    $karma_block .= '<span class="serendipity_karmaVoting_current">' . $curr_msg . '</span>';
                                }
                                if ($enough_visits && $textual_visits) {
                                    $karma_block .= '<span class="serendipity_karmaVoting_visits">' . PLUGIN_KARMA_VISITSCOUNT . '</span>';
                                }
                                $karma_block .= "\n</div>\n";
                                // Adjust rating points
                                if ($this->get_config('rate_with_words', false)) {
                                    $points = $this->wordRating($points, $votes);
                                } elseif ($this->image_name != '0') {
                                    $points = $this->imageRating($points, $votes);
                                }
                                /*
                                  print("<h3>--DEBUG: Karma block code:</h3>\n<pre>\n");
                                  print_r(htmlspecialchars($karma_block));
                                  print("\n</pre>\n");
                                */
                                // Substitute the % stuff and add it to the footer
                                $eventData[$i]['properties']['myvote'] = $myvote;
                                $eventData[$i]['properties']['points'] = $points;
                                $eventData[$i]['properties']['votes'] = $votes;
                                $eventData[$i]['properties']['visits'] = $visits;
                                $footer .= sprintf($karma_block, $myvote, $points, $votes, $visits, $url);
                            }
                            // foreach key in entries
                    }
                    // End switch on karma voting status
                    return true;
                    break;
                    // Display the Karma Log link on the sidebar
                // Display the Karma Log link on the sidebar
                case 'backend_sidebar_entries':
                    ?>
<li class="serendipitySideBarMenuLink serendipitySideBarMenuEntryLinks">
    <a href="?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=karmalog">
        <?php 
                    echo PLUGIN_KARMA_DISPLAY_LOG;
                    ?>
    </a>
</li>
<?php 
                    return true;
                    break;
                    // Display the Karma Log!
                    //case 'external_plugin':
                // Display the Karma Log!
                //case 'external_plugin':
                case 'backend_sidebar_entries_event_display_karmalog':
                    // Print any stored messages
                    //foreach ($serendipity['karma_messages'] as $msg) {
                    //    print("<div class='serendipityAdminInfo'>$msg</div>\n");
                    //}
                    // Was I asked to process any votes?
                    if (($serendipity['POST']['delete_button'] || $serendipity['POST']['approve_button']) && sizeof($serendipity['POST']['delete']) != 0 && serendipity_checkFormToken()) {
                        foreach ($serendipity['POST']['delete'] as $d => $i) {
                            $kdata = $serendipity['POST']['karmalog' . $i];
                            // validate posted variables
                            // posted points
                            $ppoints = $kdata['points'];
                            if (!is_numeric($ppoints) || (int) $ppoints < -2 || (int) $ppoints > 2) {
                                print "<div class='serendipityAdminMsgError'>" . PLUGIN_KARMA_INVALID_INPUT . "</div>\n";
                                return false;
                            }
                            // posted id
                            $pid = $kdata['entryid'];
                            if (!is_numeric($pid)) {
                                print "<div class='serendipityAdminMsgError'>" . PLUGIN_KARMA_INVALID_INPUT . "</div>\n";
                                return false;
                            }
                            // posted IP
                            $pip = long2ip(ip2long($kdata['ip']));
                            if ($pip == -1 || $pip === FALSE) {
                                print "<div class='serendipityAdminMsgError'>" . PLUGIN_KARMA_INVALID_INPUT . "</div>\n";
                                return false;
                            }
                            // posted user agent (need a better validator, I think)
                            $puser_agent = $kdata['user_agent'];
                            if (serendipity_db_escape_string($puser_agent) != $puser_agent) {
                                print "<div class='serendipityAdminMsgError'>" . PLUGIN_KARMA_INVALID_INPUT . "</div>\n";
                                return false;
                            }
                            // posted vote time
                            $pvotetime = $kdata['votetime'];
                            $unixsecs = date('U', $kdata['votetime']);
                            if ($pvotetime != $unixsecs) {
                                print "<div class='serendipityAdminMsgError'>" . PLUGIN_KARMA_INVALID_INPUT . "</div>\n";
                                return false;
                            }
                            // Remove karma from entry?
                            if ($serendipity['POST']['delete_button']) {
                                // Fetch vote total for the entry IDs
                                $q = 'SELECT k.*
                                    FROM ' . $serendipity['dbPrefix'] . 'karma   AS k
                                    WHERE k.entryid IN (' . $pid . ') GROUP BY k.entryid';
                                $sql = serendipity_db_query($q);
                                if (is_array($sql)) {
                                    $karma = $sql[0];
                                    $update = sprintf("UPDATE {$serendipity['dbPrefix']}karma\n                                        SET points   = %s,\n                                        votes    = %s\n                                        WHERE entryid  = %s", serendipity_db_escape_string($karma['points'] - $ppoints), serendipity_db_escape_string($karma['votes'] - 1), serendipity_db_escape_string($pid));
                                    $updated = serendipity_db_query($update);
                                    if ($updated != 1) {
                                        printf("<div class='serendipityAdminMsgError'>" . PLUGIN_KARMA_REMOVE_ERROR . "</div>\n", $pid);
                                        // Don't delete from karma log if we couldn't take away the points
                                        continue;
                                    }
                                } else {
                                    // This will only happen if someone is messing with the karma table or submit data
                                    printf("<div class='serendipityAdminMsgError'>" . PLUGIN_KARMA_UPDATE_ERROR . "</div>", $pid);
                                    continue;
                                }
                            }
                            // Remove vote from log (approved or deleted, doesn't matter)
                            $del = sprintf("DELETE FROM {$serendipity['dbPrefix']}karmalog\n                                WHERE entryid = %s AND ip = '%s' AND user_agent LIKE '%%%s%%' AND votetime = %s LIMIT 1", serendipity_db_escape_string($pid), serendipity_db_escape_string($pip), serendipity_db_escape_string($puser_agent), serendipity_db_escape_string($pvotetime));
                            $deleted = serendipity_db_query($del);
                            // User feedback
                            if ($deleted == 1) {
                                if ($serendipity['POST']['delete_button']) {
                                    printf("<div class='serendipityAdminMsgSuccess'>" . PLUGIN_KARMA_REMOVED_POINTS . "</div>\n", $ppoints, $pid);
                                } else {
                                    printf("<div class='serendipityAdminMsgSuccess'>" . PLUGIN_KARMA_APPROVED_POINTS . "</div>\n", $ppoints, $pid);
                                }
                            } else {
                                printf("<div class='serendipityAdminMsgError'>" . PLUGIN_KARMA_REMOVE_ERROR . "</div>\n", $pid);
                            }
                        }
                    }
                    // URL; expected to be event_display and karmalog, respectively
                    $url = '?serendipity[adminModule]=' . htmlspecialchars($serendipity['GET']['adminModule']) . '&serendipity[adminAction]=' . htmlspecialchars($serendipity['GET']['adminAction']);
                    // Filters
                    print "\n<form action='' method='get' name='karmafilters' id='karmafilters'>\n  <input type='hidden' name='serendipity[adminModule]' value='{$serendipity['GET']['adminModule']}' />\n  <input type='hidden' name='serendipity[adminAction]' value='{$serendipity['GET']['adminAction']}' />\n<table class='serendipity_admin_filters' width='100%'>\n<tr>\n  <td colspan='4' class='serendipity_admin_filters_headline'><strong>" . FILTERS . "</strong></td>\n</tr>\n<tr>\n  <td>User Agent:</td>\n  <td><input class='input_textbox' type='text' name='serendipity[filter][user_agent]' size='15' value='" . htmlspecialchars($serendipity['GET']['filter']['user_agent']) . "' /></td>\n  <td>" . IP . "</td>\n  <td><input class='input_textbox' type='text' name='serendipity[filter][ip]' size='15' value='" . htmlspecialchars($serendipity['GET']['filter']['ip']) . "' /></td>\n</tr>\n<tr>\n  <td>Entry ID:</td>\n  <td><input class='input_textbox' type='text' name='serendipity[filter][entryid]' size='15' value='" . htmlspecialchars($serendipity['GET']['filter']['entryid']) . "' /></td>\n  <td>Entry title:</td>\n  <td><input class='input_textbox' type='text' name='serendipity[filter][title]' size='30' value='" . htmlspecialchars($serendipity['GET']['filter']['title']) . "' /></td>\n</tr>\n</table>\n";
                    // Set all filters into $and and $searchString
                    if (!empty($serendipity['GET']['filter']['entryid'])) {
                        $val = $serendipity['GET']['filter']['entryid'];
                        $and .= "AND l.entryid = '" . serendipity_db_escape_string($val) . "'";
                        $searchString .= "&amp;serendipity['filter']['entryid']=" . htmlspecialchars($val);
                    }
                    if (!empty($serendipity['GET']['filter']['ip'])) {
                        $val = $serendipity['GET']['filter']['ip'];
                        $and .= "AND l.ip = '" . serendipity_db_escape_string($val) . "'";
                        $searchString .= "&amp;serendipity['filter']['ip']=" . htmlspecialchars($val);
                    }
                    if (!empty($serendipity['GET']['filter']['user_agent'])) {
                        $val = $serendipity['GET']['filter']['user_agent'];
                        $and .= "AND l.user_agent LIKE '%" . serendipity_db_escape_string($val) . "%'";
                        $searchString .= "&amp;serendipity['filter']['user_agent']=" . htmlspecialchars($val);
                    }
                    if (!empty($serendipity['GET']['filter']['title'])) {
                        $val = $serendipity['GET']['filter']['title'];
                        $and .= "AND e.title LIKE '%" . serendipity_db_escape_string($val) . "%'";
                        $searchString .= "&amp;serendipity['filter']['title']=" . htmlspecialchars($val);
                    }
                    // Sorting (controls go after filtering controls in form above)
                    $sort_order = array('votetime' => DATE, 'user_agent' => USER_AGENT, 'title' => TITLE, 'entryid' => 'ID');
                    if (empty($serendipity['GET']['sort']['ordermode']) || $serendipity['GET']['sort']['ordermode'] != 'ASC') {
                        $desc = true;
                        $serendipity['GET']['sort']['ordermode'] = 'DESC';
                    }
                    if (!empty($serendipity['GET']['sort']['order']) && !empty($sort_order[$serendipity['GET']['sort']['order']])) {
                        $curr_order = $serendipity['GET']['sort']['order'];
                        $orderby = serendipity_db_escape_string($curr_order . ' ' . $serendipity['GET']['sort']['ordermode']);
                    } else {
                        $curr_order = 'votetime';
                        $orderby = 'votetime ' . serendipity_db_escape_string($serendipity['GET']['sort']['ordermode']);
                    }
                    print "\n<div>" . SORT_BY . "\n<select name='serendipity[sort][order]'>\n";
                    foreach ($sort_order as $order => $val) {
                        print "\n  <option value='{$order}'" . ($curr_order == $order ? " selected='selected'" : '') . ">{$val}</option>\n";
                    }
                    print "\n</select>\n<select name='serendipity[sort][ordermode]'>\n  <option value='DESC'" . ($desc ? "selected='selected'" : '') . ">" . SORT_ORDER_DESC . "</option>\n  <option value='ASC'" . ($desc ? '' : "selected='selected'") . ">" . SORT_ORDER_ASC . "</option>\n</select>\n</div>\n<input type='submit' name='submit' value=' - " . GO . " - ' class='serendipityPrettyButton input_button' /> \n</form>\n";
                    // Paging (partly ripped from include/admin/comments.inc.php)
                    $commentsPerPage = (int) (!empty($serendipity['GET']['filter']['perpage']) ? $serendipity['GET']['filter']['perpage'] : 25);
                    $sql = serendipity_db_query("SELECT COUNT(*) AS total FROM {$serendipity['dbPrefix']}karmalog l WHERE 1 = 1 " . $and, true);
                    $totalVotes = $sql['total'];
                    $pages = $commentsPerPage == COMMENTS_FILTER_ALL ? 1 : ceil($totalVotes / (int) $commentsPerPage);
                    $page = (int) $serendipity['GET']['page'];
                    if ($page == 0 || $page > $pages) {
                        $page = 1;
                    }
                    if ($page > 1) {
                        $linkPrevious = $url . '&amp;serendipity[page]=' . ($page - 1) . $searchString;
                    }
                    if ($pages > $page) {
                        $linkNext = $url . '&amp;serendipity[page]=' . ($page + 1) . $searchString;
                    }
                    if ($commentsPerPage == COMMENTS_FILTER_ALL) {
                        $limit = '';
                    } else {
                        $limit = serendipity_db_limit_sql(serendipity_db_limit(($page - 1) * (int) $commentsPerPage, (int) $commentsPerPage));
                    }
                    // Variables for display
                    if ($linkPrevious) {
                        $linkPrevious = '<a href="' . $linkPrevious . '" class="serendipityIconLink"><img src="' . serendipity_getTemplateFile('admin/img/previous.png') . '" /></a>';
                    } else {
                        $linkPrevious = '&nbsp;';
                    }
                    if ($linkNext) {
                        $linkNext = '<a href="' . $linkNext . '" class="serendipityIconLinkRight"><img src="' . serendipity_getTemplateFile('admin/img/next.png') . '" /></a>';
                    } else {
                        $linkNext = '&nbsp;';
                    }
                    $paging = sprintf(PAGE_BROWSE_COMMENTS, $page, $pages, $totalVotes);
                    // Retrieve the next batch of karma votes
                    // [entryid, points, ip, user_agent, votetime]
                    $sql = serendipity_db_query("SELECT l.entryid AS entryid, l.points AS points, l.ip AS ip, l.user_agent AS user_agent, l.votetime AS votetime, e.title AS title FROM {$serendipity['dbPrefix']}karmalog l\n                        LEFT JOIN {$serendipity['dbPrefix']}entries e ON (e.id = l.entryid)\n                        WHERE 1 = 1 " . $and . "\n                        ORDER BY {$orderby} {$limit}");
                    // Start the form for display and deleting
                    if (is_array($sql)) {
                        print "<form action='' method='post' name='formMultiDelete' id='formMultiDelete'>\n" . serendipity_setFormToken() . "\n<script type='text/javascript'>\nfunction invertSelection() {\n    var f = document.formMultiDelete;\n    for (var i = 0; i < f.elements.length; i++) {\n        if( f.elements[i].type == 'checkbox' ) {\n            f.elements[i].checked = !(f.elements[i].checked);\n        }\n    }\n}\n</script>\n";
                        // Print the header paging table
                        print "\n<table width='100%' style='border-collapse: collapse;'>\n  <tr>\n  <td align='left'>{$linkPrevious}</td>\n  <td align='center'>{$paging}</td>\n  <td align='right'>{$linkNext}</td>\n  </tr>\n</table>\n";
                        // Start the vote table
                        print "\n<table class='karmalog' width='100%'>\n";
                        // Print each vote
                        $i = 0;
                        foreach ($sql as $vote) {
                            $i++;
                            // entryid, title, points, ip, user_agent, votetime
                            $entrylink = serendipity_archiveURL($vote['entryid'], $vote['title'], 'serendipityHTTPPath', true);
                            $entryFilterHtml = "<a class='serendipityIconLink' href='{$url}&serendipity[filter][entryid]={$vote['entryid']}'><img src='" . serendipity_getTemplateFile('admin/img/zoom.png') . "' /></a>";
                            $ipFilterHtml = "<a class='serendipityIconLink' href='{$url}&serendipity[filter][ip]={$vote['ip']}'><img src='" . serendipity_getTemplateFile('admin/img/zoom.png') . "' /></a>";
                            $timestr = strftime('%H:%M:%S<br />%n%a %b %d %Y', $vote['votetime']);
                            $cssClass = 'serendipity_admin_list_item serendipity_admin_list_item_';
                            $cssClass .= $i % 2 == 0 ? 'even' : 'uneven';
                            $barClass = str_replace(array('.', ' '), array('_', '_'), $this->image_name);
                            $barHtml = $this->createRatingBar(null, $vote['points'], 1, $barClass);
                            $barHtml = sprintf($barHtml, 'what', $vote['points'], '1');
                            print "\n  <tr class='{$cssClass}'>\n    <td rowspan='2' width='20' align='center'>\n      <input class='input_checkbox' type='checkbox' name='serendipity[delete][{$i}]' value='{$i}' tabindex='{$i}' />\n      <input type='hidden' name='serendipity[karmalog{$i}][points]' value='{$vote['points']}' />\n      <input type='hidden' name='serendipity[karmalog{$i}][entryid]' value='{$vote['entryid']}' />\n      <input type='hidden' name='serendipity[karmalog{$i}][votetime]' value='{$vote['votetime']}' />\n      <input type='hidden' name='serendipity[karmalog{$i}][ip]' value='{$vote['ip']}' />\n      <input type='hidden' name='serendipity[karmalog{$i}][user_agent]' value='{$vote['user_agent']}' />\n    </td>\n    <td>{$barHtml}</td>\n    <td colspan='2'><a href='{$entrylink}' title='{$vote['entryid']}' alt='{$vote['title']}'>{$vote['title']}</a> {$entryFilterHtml}</td>\n  </tr>\n  <tr class='{$cssClass}'>\n    <td>{$timestr}</td>\n    <td>{$vote['ip']} {$ipFilterHtml}</td>\n    <td>{$vote['user_agent']}</td>\n  </tr>\n";
                        }
                        // End the vote table
                        print "\n                            </table>\n                            ";
                        if (is_array($sql)) {
                            print "\n<input type='button' name='toggle' value='" . INVERT_SELECTIONS . "' onclick='invertSelection()' class='serendipityPrettyButton input_button' /> \n<input class='serendipityPrettyButton input_button' type='submit' value='" . PLUGIN_KARMA_DELETE_VOTES . "' name='serendipity[delete_button]' />\n<input class='serendipityPrettyButton input_button' type='submit' value='" . PLUGIN_KARMA_APPROVE_VOTES . "' name='serendipity[approve_button]' />\n</form>\n";
                        }
                        // Print the footer paging table
                        print "\n<table width='100%' style='border-collapse: collapse;'>\n  <tr>\n  <td align='left'>{$linkPrevious}</td>\n  <td align='center'>{$paging}</td>\n  <td align='right'>{$linkNext}</td>\n  </tr>\n</table>\n";
                    } else {
                        print "\n<div class='serendipityAdminMsgNotice'>No entries to display.</div>\n";
                    }
                    return true;
                    break;
                default:
                    return false;
            }
            // End switch on event hooks
        } else {
            return false;
        }
    }
 function getToken()
 {
     global $serendipity;
     if ($_SESSION['serendipityAuthedUser'] === true && $_SESSION['serendipityAuthorid'] > 0) {
         // Set the cookie according to our username. This way we can login on other machines.
         if (!isset($serendipity['COOKIE']['registered_markread_visitor'])) {
             serendipity_setCookie('registered_markread_visitor', md5($_SESSION['serendipityAuthorid'] . $_SESSION['serendipityUser']));
         }
         return $serendipity['COOKIE']['registered_markread_visitor'];
     } else {
         if (!isset($serendipity['COOKIE']['markread_visitor'])) {
             // This should be unique enough.
             serendipity_setCookie('markread_visitor', md5(time()) . md5($_SERVER['REMOTE_ADDR'] . $_SERVER['REQUEST_URI']));
             return $serendipity['COOKIE']['markread_visitor'];
         } else {
             // We already have a non-registered cookie item and are currently not logged in.
             return $serendipity['COOKIE']['markread_visitor'];
         }
     }
 }
 function event_hook($event, &$bag, &$eventData, $addData = null)
 {
     global $serendipity;
     $hooks =& $bag->get('event_hooks');
     if (isset($hooks[$event])) {
         switch ($event) {
             case 'external_plugin':
             case 'frontend_rss':
                 if (defined('STARTCAT_CATEGORY') && !isset($_GET['category']) && $serendipity['GET']['category'] == STARTCAT_CATEGORY) {
                     unset($serendipity['GET']['category']);
                 }
                 break;
             case 'genpage':
                 if (defined('STARTCAT_CATEGORY') && $serendipity['GET']['category'] == STARTCAT_CATEGORY && !empty($serendipity['GET']['viewAuthor'])) {
                     unset($serendipity['GET']['category']);
                 }
                 break;
             case 'frontend_configure':
                 if (!empty($serendipity['GET']['adminModule'])) {
                     return true;
                 }
                 $bc = $this->get_config('base_categories');
                 if (empty($bc)) {
                     $bc = $this->get_config('base_category');
                 }
                 if (!isset($serendipity['GET']['id']) && !empty($bc) && $bc != 'none' && $serendipity['GET']['category'] != 'all') {
                     $serendipity['GET']['category'] = $bc;
                     define('STARTCAT_CATEGORY', $bc);
                 }
                 if ($serendipity['GET']['category'] == 'all') {
                     unset($serendipity['GET']['category']);
                 }
                 $hc = $this->get_config('hide_categories');
                 if (empty($hc)) {
                     $hc = $this->get_config('hide_category');
                 }
                 if (!empty($hc) && $hc != 'none' && !isset($serendipity['GET']['hide_category'])) {
                     $serendipity['GET']['hide_category'] = $hc;
                 }
                 if (serendipity_db_bool($this->get_config('remembercat'))) {
                     if ((empty($serendipity['GET']['category']) || defined('STARTCAT_CATEGORY')) && !empty($serendipity['COOKIE']['category']) && !isset($serendipity['GET']['id'])) {
                         $serendipity['GET']['category'] = $serendipity['COOKIE']['category'];
                     }
                     if (is_array($serendipity['POST']['multiCat'])) {
                         $serendipity['GET']['category'] = implode(';', $serendipity['POST']['multiCat']);
                     }
                     if (is_array($serendipity['GET']['multiCat'])) {
                         $serendipity['GET']['category'] = implode(';', $serendipity['GET']['multiCat']);
                     }
                     if (!empty($serendipity['GET']['category'])) {
                         serendipity_setCookie('category', $serendipity['GET']['category']);
                     }
                 }
                 break;
         }
     }
 }