function introspect(&$propbag)
 {
     $this->title = $this->get_config('title', $this->title);
     $propbag->add('name', PLUGIN_SIDEBAR_IMAGESIDEBAR_NAME);
     $propbag->add('description', PLUGIN_SIDEBAR_IMAGESIDEBAR_DESC);
     $propbag->add('stackable', true);
     $propbag->add('author', 'Andrew Brown (Menalto code), Matthew Groeninger (Unified/Media Lib. Code), Stefan Lange-Hegermann (Zooomr Code), Matthew Maude (Coppermine code)');
     $propbag->add('version', '0.98');
     $propbag->add('license', 'BSD');
     $propbag->add('requirements', array('serendipity' => '0.8', 'smarty' => '2.6.7', 'php' => '4.1.0'));
     $propbag->add('groups', array('IMAGES'));
     //And now, off the beaten path.  Here we check to see if the configuration is being saved.  If so, lets just 'borrow' display_source so we can get the configuration right.
     if (isset($_POST['SAVECONF']) && serendipity_checkFormToken()) {
         $this->set_config('display_source', $_POST['serendipity']['plugin']['display_source']);
     }
     //Ok, now let's set the sub_plugin to the right one/ create the sub_plugin object.
     $this->object_extend = $this->create_sub_class(true);
     //add an array generated by 'set_configuration_array' to the propbag configuration.
     $config_array = $this->set_configuration_array($this->object_extend);
     $propbag->add('configuration', $config_array);
 }
예제 #2
0
                echo "Backtrace:<br />\n" . implode("<br />\n", $serendipity['debug']['pluginload']) . "<br />";
            }
            $bag = new serendipity_property_bag();
            $plugin->introspect($bag);
            if ($bag->is_set('configuration')) {
                /* Only play with the plugin if there is something to play with */
                echo '<script type="text/javascript">location.href = \'' . $serendipity['baseurl'] . '?serendipity[adminModule]=plugins&serendipity[plugin_to_conf]=' . $inst . '\';</script>';
                die;
            } else {
                /* If no config is available, redirect to plugin overview, because we do not want that a user can install the plugin a second time via accidental browser refresh */
                echo '<script type="text/javascript">location.href = \'' . $serendipity['baseurl'] . '?serendipity[adminModule]=plugins\';</script>';
                die;
            }
        }
    }
    if (isset($_POST['REMOVE']) && serendipity_checkFormToken()) {
        if (is_array($_POST['serendipity']['plugin_to_remove'])) {
            foreach ($_POST['serendipity']['plugin_to_remove'] as $key) {
                $plugin =& serendipity_plugin_api::load_plugin($key);
                if ($plugin->serendipity_owner == '0' || $plugin->serendipity_owner == $serendipity['authorid'] || serendipity_checkPermission('adminPluginsMaintainOthers')) {
                    serendipity_plugin_api::remove_plugin_instance($key);
                }
            }
        }
    }
    ?>

<?php 
    if (isset($_POST['SAVE'])) {
        ?>
    <div class="serendipityAdminMsgSuccess"><img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="<?php 
예제 #3
0
/**
 * Creates the necessary session data to be used by later iframe calls
 *
 * This function emits the actual <iframe> call.
 *
 * @access private
 * @see serendipity_is_iframe()
 * @param   string  Indicates whether an entry is previewed or saved. Save performs XML-RPC calls.
 * @param   mixed   The entry array (comes from HTTP POST request)
 * @return  boolean Indicates whether iframe data was stored
 */
function serendipity_iframe_create($mode, &$entry)
{
    global $serendipity;
    if (!empty($serendipity['POST']['no_save'])) {
        return true;
    }
    if (!serendipity_checkFormToken()) {
        return false;
    }
    $_SESSION['save_entry'] = $entry;
    $_SESSION['save_entry_POST'] = $serendipity['POST'];
    $attr = '';
    switch ($mode) {
        case 'save':
            $attr = ' height="100" ';
            break;
        case 'preview':
            $attr = ' height="300" ';
            break;
    }
    return '<iframe src="serendipity_admin.php?serendipity[is_iframe]=true&amp;serendipity[iframe_mode]=' . $mode . '" id="serendipity_iframe" name="serendipity_iframe" ' . $attr . ' width="100%" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" title="Serendipity">' . IFRAME_WARNING . '</iframe>';
}
예제 #4
0
# $Id: configuration.inc.php 2366 2008-11-06 11:44:43Z garvinhicking $
# Copyright (c) 2003-2005, Jannis Hermanns (on behalf the Serendipity Developer Team)
# All rights reserved.  See LICENSE file for licensing details
if (IN_serendipity !== true) {
    die("Don't hack!");
}
umask(00);
$umask = 0775;
@define('IN_installer', true);
if (!isset($_POST['installAction'])) {
    $_POST['installAction'] = '';
}
if (!serendipity_checkPermission('siteConfiguration') && !serendipity_checkPermission('blogConfiguration')) {
    return;
}
switch ($_POST['installAction'] && serendipity_checkFormToken()) {
    case 'check':
        $oldConfig = $serendipity;
        $res = serendipity_updateConfiguration();
        if (is_array($res)) {
            echo DIAGNOSTIC_ERROR;
            echo '<div class="serendipityAdminMsgError">- <img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_error.png') . '" alt="" />' . implode('<br />', $res) . '</div><br /><br />';
        } else {
            /* If we have new rewrite rules, then install them */
            $permalinkOld = array($oldConfig['serendipityHTTPPath'], $oldConfig['serendipityPath'], $oldConfig['baseURL'], $oldConfig['indexFile'], $oldConfig['rewrite']);
            $permalinkNew = array($serendipity['serendipityHTTPPath'], $serendipity['serendipityPath'], $serendipity['baseURL'], $serendipity['indexFile'], $serendipity['rewrite']);
            // Compare all old permalink section values against new one. A change in any of those
            // will force to update the .htaccess for rewrite rules.
            $permconf = serendipity_parseTemplate(S9Y_CONFIG_TEMPLATE);
            if (is_array($permconf) && is_array($permconf['permalinks']['items'])) {
                foreach ($permconf['permalinks']['items'] as $permitem) {
/**
 * Prints the content of the iframe.
 *
 * Called by serendipity_is_iframe, when preview is requested. Fetches data from session.
 * An iframe is used so that a single s9y page must not timeout on intensive operations,
 * and so that the frontend stylesheet can be embedded without screwing up the backend.
 *
 * @access private
 * @see serendipity_is_iframe()
 * @param   mixed   The entry array (comes from session variable)
 * @param   string  Indicates whether an entry is previewed or saved. Save performs XML-RPC calls.
 * @param   boolean Use smarty templating?
 * @return  boolean Indicates whether iframe data was printed
 */
function serendipity_iframe(&$entry, $mode = null, $use_smarty = true)
{
    global $serendipity;
    if (empty($mode) || !is_array($entry)) {
        return false;
    }
    if (!serendipity_checkFormToken()) {
        return false;
    }
    if ($use_smarty) {
        $serendipity['smarty_raw_mode'] = true;
        // Force output of Smarty stuff in the backend
        $serendipity['smarty_preview'] = true;
        serendipity_smarty_init();
        $serendipity['smarty']->assign('is_preview', true);
        ob_start();
    }
    $show = false;
    switch ($mode) {
        case 'save':
            echo '<div style="float: left; height: 75px"></div>';
            $res = serendipity_updertEntry($entry);
            if (is_string($res)) {
                echo '<div class="serendipity_msg_error">' . ERROR . ': <b>' . $res . '</b></div>';
            } else {
                if (!empty($serendipity['lastSavedEntry'])) {
                    // Last saved entry must be propagated to entry form so that if the user re-edits it,
                    // it needs to be stored with the new ID.
                    echo '<script type="text/javascript">parent.document.forms[\'serendipityEntry\'][\'serendipity[id]\'].value = "' . $serendipity['lastSavedEntry'] . '";</script>';
                }
                $entrylink = serendipity_archiveURL($res, $entry['title'], 'serendipityHTTPPath', true, array('timestamp' => $entry['timestamp']));
                echo '<div class="serendipityAdminMsgSuccess"><img style="height: 22px; width: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_success.png') . '" alt="" />' . ENTRY_SAVED . ' (<a href="' . $entrylink . '" target="_blank">' . VIEW . '</a>)</div>';
            }
            echo '<br style="clear: both" />';
            $show = true;
            break;
        case 'preview':
            echo '<div id="serendipity_preview_spacer" style="float: left; height: 225px"></div>';
            serendipity_printEntries(array($entry), $entry['extended'] != '' ? 1 : 0, true);
            echo '<br id="serendipity_preview_spacer2" style="clear: both" />';
            $show = true;
            break;
    }
    if ($use_smarty) {
        $preview = ob_get_contents();
        ob_end_clean();
        $serendipity['smarty']->assign_by_ref('preview', $preview);
        $serendipity['smarty']->display(serendipity_getTemplateFile('preview_iframe.tpl', 'serendipityPath'));
    }
    return $show;
}
예제 #6
0
                $dbn = 'latin1';
                break;
            case 'UTF-8':
                $dbn = 'utf8';
                break;
        }
        if ($dbn && $serendipity['dbNames']) {
            mysql_query("SET NAMES " . $dbn, $db);
        }
        $return =& mysql_query($query, $db);
        mysql_select_db($serendipity['dbName'], $serendipity['dbConn']);
        serendipity_db_reconnect();
        return $return;
    }
}
if (isset($serendipity['GET']['importFrom']) && serendipity_checkFormToken()) {
    /* Include the importer */
    $class = @(require_once S9Y_INCLUDE_PATH . 'include/admin/importers/' . basename($serendipity['GET']['importFrom']) . '.inc.php');
    if (!class_exists($class)) {
        die('FAILURE: Unable to require import module, possible syntax error?');
    }
    /* Init the importer with form data */
    $importer = new $class($serendipity['POST']['import']);
    /* Yes sir, we are importing if we have valid data */
    if ($importer->validateData()) {
        echo IMPORT_STARTING . '<br />';
        /* import() MUST return (bool)true, otherwise we assume it failed */
        if (($result = $importer->import()) !== true) {
            echo IMPORT_FAILED . ': ' . $result . '<br />';
        } else {
            echo IMPORT_DONE . '<br />';
 function insertevent(&$array)
 {
     global $serendipity;
     if (!serendipity_checkFormToken()) {
         return false;
     }
     return serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}mycalendar\n                                                 (eventname, eventurl, eventurltitle, eventdate, eventdate2)\n                                          VALUES ('" . serendipity_db_escape_string($array['eventname']) . "','" . serendipity_db_escape_string($array['eventurl']) . "','" . serendipity_db_escape_string($array['eventurltitle']) . "','" . serendipity_db_escape_string($array['eventdate']) . "','" . serendipity_db_escape_string($array['eventdate2']) . "')");
 }
예제 #8
0
global $serendipity;
$data = array();
switch ($serendipity['POST']['adminAction']) {
    case 'publish':
        if (!serendipity_checkFormToken()) {
            break;
        }
        $success = serendipity_updertEntry(array('id' => serendipity_specialchars($serendipity['POST']['id']), 'timestamp' => time(), 'isdraft' => 0));
        if (is_numeric($success)) {
            $data['published'] = $success;
        } else {
            $data['error_publish'] = $success;
        }
        break;
    case 'updateCheckDisable':
        if (!serendipity_checkFormToken() || !serendipity_checkPermission('blogConfiguration')) {
            break;
        }
        serendipity_set_config_var('updateCheck', false);
        break;
}
$user = serendipity_fetchAuthor($serendipity['authorid']);
// chrome-compatible, from Oliver Gassner, adapted from TextPattern. Hi guys, keep it up. :-)
$bookmarklet = "javascript:var%20d=document,w=window,e=w.getSelection,k=d.getSelection,x=d.selection,s=(e?e():(k)?k():(x?x.createRange().text:0)),f='" . $serendipity['baseURL'] . "',l=d.location,e=encodeURIComponent,p='serendipity_admin.php?serendipity[adminModule]=entries&serendipity[adminAction]=new&serendipity[title]='+e(d.title)+'&serendipity[body]='+e(s)+'&serendipity[url]='+location.href,u=f+p;a=function(){%20%20if(!w.open(u,'t','toolbar=0,resizable=1,scrollbars=1,status=1,width=800,height=800'))%20%20%20%20l.href=u;};if(/Firefox/.test(navigator.userAgent))%20%20setTimeout(a,0);else%20%20a();void(0)";
$data['bookmarklet'] = $bookmarklet;
$data['username'] = $user[0]['realname'];
$data['js_failure_file'] = serendipity_getTemplateFile('admin/serendipity_editor.js');
$output = array();
serendipity_plugin_api::hook_event('backend_frontpage_display', $output);
$data['backend_frontpage_display'] = $output['more'];
$data['usedVersion'] = $serendipity['version'];
예제 #9
0
        serendipity_approveComment((int) $serendipity['GET']['id'], (int) $rs['entry_id']);
        $msg .= DONE . ': ' . sprintf(COMMENT_APPROVED, (int) $serendipity['GET']['id']);
    }
}
if (isset($serendipity['GET']['adminAction']) && $serendipity['GET']['adminAction'] == 'pending' && serendipity_checkFormToken()) {
    $sql = "SELECT c.*, e.title, a.email as authoremail, a.mail_comments\n            FROM {$serendipity['dbPrefix']}comments c\n            LEFT JOIN {$serendipity['dbPrefix']}entries e ON (e.id = c.entry_id)\n            LEFT JOIN {$serendipity['dbPrefix']}authors a ON (e.authorid = a.authorid)\n            WHERE c.id = " . (int) $serendipity['GET']['id'] . " AND status = 'approved'";
    $rs = serendipity_db_query($sql, true);
    if ($rs === false) {
        $errormsg .= ERROR . ': ' . sprintf(COMMENT_ALREADY_APPROVED, (int) $serendipity['GET']['id']);
    } else {
        serendipity_approveComment((int) $serendipity['GET']['id'], (int) $rs['entry_id'], true, true);
        $msg .= DONE . ': ' . sprintf(COMMENT_MODERATED, (int) $serendipity['GET']['id']);
    }
}
/* We are asked to delete a comment */
if (isset($serendipity['GET']['adminAction']) && $serendipity['GET']['adminAction'] == 'delete' && serendipity_checkFormToken()) {
    serendipity_deleteComment($serendipity['GET']['id'], $serendipity['GET']['entry_id']);
    $msg .= DONE . ': ' . sprintf(COMMENT_DELETED, (int) $serendipity['GET']['id']);
}
/* We are either in edit mode, or preview mode */
if (isset($serendipity['GET']['adminAction']) && ($serendipity['GET']['adminAction'] == 'edit' || $serendipity['GET']['adminAction'] == 'reply') || isset($serendipity['POST']['preview'])) {
    $serendipity['smarty_raw_mode'] = true;
    // Force output of Smarty stuff in the backend
    serendipity_smarty_init();
    if ($serendipity['GET']['adminAction'] == 'reply' || $serendipity['GET']['adminAction'] == 'doReply') {
        $c = serendipity_fetchComments($serendipity['GET']['entry_id'], 1, 'co.id', false, 'NORMAL', ' AND co.id=' . (int) $serendipity['GET']['id']);
        if (isset($serendipity['POST']['preview'])) {
            $c[] = array('email' => $serendipity['POST']['email'], 'author' => $serendipity['POST']['name'], 'body' => $serendipity['POST']['comment'], 'url' => $serendipity['POST']['url'], 'timestamp' => time(), 'parent_id' => $serendipity['GET']['id']);
        }
        $target_url = '?serendipity[action]=admin&amp;serendipity[adminModule]=comments&amp;serendipity[adminAction]=doReply&amp;serendipity[id]=' . (int) $serendipity['GET']['id'] . '&amp;serendipity[entry_id]=' . (int) $serendipity['GET']['entry_id'] . '&amp;serendipity[noBanner]=true&amp;serendipity[noSidebar]=true&amp;' . serendipity_setFormToken('url');
        $codata = $serendipity['POST'];
예제 #10
0
    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;
        }
    }
예제 #11
0
     // if entries end
     break;
 case 'delete':
     if (!serendipity_checkFormToken()) {
         break;
     }
     $newLoc = '?' . serendipity_setFormToken('url') . '&amp;serendipity[action]=admin&amp;serendipity[adminModule]=entries&amp;serendipity[adminAction]=doDelete&amp;serendipity[id]=' . (int) $serendipity['GET']['id'];
     $entry = serendipity_fetchEntry('id', $serendipity['GET']['id'], 1, 1);
     $data['switched_output'] = true;
     $data['is_delete'] = true;
     $data['newLoc'] = $newLoc;
     // for smartification printf had to turn into sprintf!!
     $data['rip_entry'] = sprintf(DELETE_SURE, $entry['id'] . ' - ' . serendipity_specialchars($entry['title']));
     break;
 case 'multidelete':
     if (!serendipity_checkFormToken()) {
         return;
         // blank content page, but default token check parameter is presenting a XSRF message when false
     }
     if (!is_array($serendipity['POST']['multiDelete'])) {
         echo '<div class="msg_notice"><span class="icon-attention-circled"></span> ' . sprintf(MULTICHECK_NO_ITEM, $_SERVER['HTTP_REFERER']) . '</div>' . "\n";
         break;
     }
     $ids = '';
     $data['rip_entry'] = array();
     foreach ($serendipity['POST']['multiDelete'] as $idx => $id) {
         $ids .= (int) $id . ',';
         $entry = serendipity_fetchEntry('id', $id, 1, 1);
         $data['is_multidelete'] = true;
         $data['rip_entry'][] = sprintf(DELETE_SURE, $entry['id'] . ' - ' . serendipity_specialchars($entry['title']));
     }
    function event_hook($event, &$bag, &$eventData, $addData = null)
    {
        global $serendipity;
        $hooks =& $bag->get('event_hooks');
        if (isset($hooks[$event])) {
            switch ($event) {
                // called when admin sidebar is being "built"
                case 'backend_sidebar_entries_images':
                    ?>
<li class="serendipitySideBarMenuLink serendipitySideBarMenuMediaLinks"><a href="?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=flickr">
                        <?php 
                    echo PLUGIN_EVENT_FLICKR_NAME;
                    ?>
</a></li><?php 
                    break;
                    // called when admin sidebar is been "drawn"
                // called when admin sidebar is been "drawn"
                case 'backend_sidebar_entries_event_display_flickr':
                    // he, is user allowed to import images ?!?
                    if (!serendipity_checkPermission('adminImagesAdd')) {
                        // TODO: add a message to the user ?!?
                        break;
                    }
                    // if method is POST, we must have a valid form token !
                    if ($_SERVER['REQUEST_METHOD'] == 'POST' && !serendipity_checkFormToken()) {
                        // TODO: add a message to the user ?!?
                        break;
                    }
                    ?>
                <?php 
                    echo PLUGIN_EVENT_FLICKR_IMPORT_BLAHBLAH;
                    ?>
                <script type="text/javascript">
                function flickr_showPage(p) {
                    var f = document.getElementById('flickr_uploadform');
                    f.elements['serendipity[flickr_page]'].value = p;
                    f.submit();
                }
                function flickr_doImport(url) {
                    var f = document.getElementById('flickr_uploadform');
                    f.elements['serendipity[adminModule]'].value = 'images';
                    f.elements['serendipity[adminAction]'].value = 'add';
                    f.elements['serendipity[imageurl]'].value = url;
                    f.submit();
                }
                function flickr_toggleExtended() {
                    var d = document.getElementById('flickr_extendedCriteria');
                    d.style.display = (d.style.display != '') ? '' : 'none';
                }
                </script>
                <h3><? echo PLUGIN_EVENT_FLICKR_IMPORT; ?></h3>
                <form action="?" method="POST" id="flickr_uploadform" enctype="multipart/form-data" onsubmit="">
                    <?php 
                    echo serendipity_setFormToken();
                    ?>
                    <?php 
                    // these two fields will only be used when an image has been chosen for dl
                    ?>
                    <input type="hidden" name="serendipity[imageurl]" value="" />
                    <input type="hidden" name="serendipity[imageimporttype]" value="image" />

                    <input type="hidden" name="serendipity[action]"      value="admin" />
                    <input type="hidden" name="serendipity[adminModule]" value="event_display" />
                    <input type="hidden" name="serendipity[adminAction]" value="flickr" />

                    <input type="hidden" name="serendipity[flickr_page]" value="1" />
                    Flickr username: <input class="input_textbox" name="serendipity[flickr_username]" value="<?php 
                    echo function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['flickr_username']) : htmlspecialchars($serendipity['POST']['flickr_username'], ENT_COMPAT, LANG_CHARSET);
                    ?>
" />
                    <input type="submit" value="<?php 
                    echo GO;
                    ?>
" class="serendipityPrettyButton input_button" /><br /><br />
                    <a style="border: 0pt none ; text-decoration: none;" href="#" onclick="flickr_toggleExtended(); return false"
                         title="<?php 
                    echo TOGGLE_OPTION;
                    ?>
">
                    <img border="0" src="<?php 
                    echo serendipity_getTemplateFile('img/plus.png');
                    ?>
" /> <?php 
                    echo TOGGLE_ALL;
                    ?>
</a>
                    <div id="flickr_extendedCriteria" <?php 
                    echo strlen($serendipity['POST']['flickr_username']) ? '' : 'style="display:none;"';
                    ?>
>
                        <p><?php 
                    echo PLUGIN_EVENT_FLICKR_TAGS;
                    ?>
 <input class="input_textbox" name="serendipity[flickr_tags]" value="<?php 
                    echo function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['flickr_tags']) : htmlspecialchars($serendipity['POST']['flickr_tags'], ENT_COMPAT, LANG_CHARSET);
                    ?>
" />
                        <?php 
                    echo PLUGIN_EVENT_FLICKR_KEYWORDS;
                    ?>
 <input class="input_textbox" name="serendipity[flickr_keywords]" value="<?php 
                    echo function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['flickr_keywords']) : htmlspecialchars($serendipity['POST']['flickr_keywords'], ENT_COMPAT, LANG_CHARSET);
                    ?>
" size="30" /></p>
                        <?php 
                    echo SORT_BY;
                    ?>
 <select id="flickr_sort" name="serendipity[flickr_sort]">
                        <option value=""></option>
                        <?
                            // See API for details (http://www.flickr.com/services/api/flickr.photos.search.html)
                            $flickr_goodSortOrders = array(
                                'date-posted-asc'=>'By date of post, ascending',
                                'date-posted-desc'=>'By date of post, descending',
                                'date-taken-asc'=>'By date of take, ascending',
                                'date-taken-desc'=>'By date of take, descending',
                                'interestingness-asc'=>'By interestingness, ascending',
                                'interestingness-desc'=>'By interestingness, ascending',
                                'relevance'=>'By revelance'
                            );

                            // compute sort order
                            $sortOrder = (isset($serendipity['POST']['flickr_keywords']) &&
                                array_key_exists($serendipity['POST']['flickr_keywords'], $flickr_goodSortOrders) ?
                                (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['flickr_keywords']) : htmlspecialchars($serendipity['POST']['flickr_keywords'], ENT_COMPAT, LANG_CHARSET)) : '');

                            // display possible options for sort order
                            foreach($flickr_goodSortOrders as $value => $description) {
                                echo '<option value="'.$value.'"';
                                if($sortOrder == $value) echo(' selected="true"');
                                echo '>'.$description.'</option>';
                            }
                        ?>
                        </select>
                    </div>
                </form>
                <?php 
                    // in the second step, we show latest photos (thumbs) for given username
                    if ($serendipity['POST']['adminAction'] == 'flickr') {
                        // make use of phpFlikr lib (http://www.phpflickr.com/)
                        require_once dirname(__FILE__) . '/phpFlickr/phpFlickr.php';
                        $f = new phpFlickr($this->get_config('api_key'));
                        $i = 0;
                        if (!empty($serendipity['POST']['flickr_username'])) {
                            // Find the NSID of the username inputted via the form
                            $nsid = $f->people_findByUsername($serendipity['POST']['flickr_username']);
                            // Get the friendly URL of the user's photos
                            $photos_url = $f->urls_getUserPhotos($nsid);
                            echo '<h4 style="margin-bottom: 0; padding-bottom: 0;">Photos of <em>';
                            echo (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['flickr_username']) : htmlspecialchars($serendipity['POST']['flickr_username'], ENT_COMPAT, LANG_CHARSET)) . '</em> at ';
                            echo '<a href="' . $photos_url . '" target="_blank">' . $photos_url . '</a></h4>';
                            // default page is number one
                            if (empty($serendipity['POST']['flickr_page']) || !is_numeric($serendipity['POST']['flickr_page'])) {
                                $serendipity['POST']['flickr_page'] = 1;
                            }
                            // make sure page is a number between 1 and 500 (range allowed by flickr API)
                            $serendipity['POST']['flickr_page'] = min(500, max(1, (int) $serendipity['POST']['flickr_page']));
                            echo '<h5 style="margin-top: 0; padding-top: 0;">Displaying page ' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['flickr_page']) : htmlspecialchars($serendipity['POST']['flickr_page'], ENT_COMPAT, LANG_CHARSET)) . '</h5>';
                            // Search is made depending on selected criterias
                            $searchCriteria = array();
                            // make sure sort order is non empty AND valid
                            if (isset($serendipity['POST']['flickr_sort']) && strlen(trim($serendipity['POST']['flickr_sort'])) && array_key_exists($serendipity['POST']['flickr_keywords'], $flickr_goodSortOrders)) {
                                $searchCriteria['sort'] = function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['flickr_sort']) : htmlspecialchars($serendipity['POST']['flickr_sort'], ENT_COMPAT, LANG_CHARSET);
                            }
                            // TODO: clean up tags of unwanted characters (keep only [a-zA-Z0-9_-])
                            if (isset($serendipity['POST']['flickr_tags']) && strlen(trim($serendipity['POST']['flickr_tags']))) {
                                $searchCriteria['tags'] = implode(',', explode(' ', function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['flickr_tags']) : htmlspecialchars($serendipity['POST']['flickr_tags'], ENT_COMPAT, LANG_CHARSET)));
                            }
                            // TODO: cleanup keywords
                            if (isset($serendipity['POST']['flickr_keywords']) && strlen(trim($serendipity['POST']['flickr_keywords']))) {
                                $searchCriteria['text'] = function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['flickr_keywords']) : htmlspecialchars($serendipity['POST']['flickr_keywords'], ENT_COMPAT, LANG_CHARSET);
                            }
                            if (count($searchCriteria)) {
                                // It seems the user wants an advanced search
                                $searchCriteria['user_id'] = $nsid;
                                $photos = $f->photos_search($searchCriteria);
                            } else {
                                // No extra criteria, get the user's next 12 public photos (+1 to show > next or not !)
                                $photos = $f->people_getPublicPhotos($nsid, NULL, 13, $serendipity['POST']['flickr_page']);
                                // Get user's tags (if any)
                                /*$tags = $f->tags_getListUser($nsid);
                                  if(is_array($tags['tags']['tag'])) {
                                      echo implode(',', $tags['tags']['tag']);
                                      echo "<br />\n";
                                  }*/
                            }
                            // Loop through the photos and output the html
                            foreach ($photos['photo'] as $photo) {
                                echo '<a title="Add to library" href="javascript:flickr_doImport(\'' . $f->buildPhotoURL($photo, 'Original') . '\');" ';
                                echo 'onclick="return confirm(\'Import this photo into the media library ?\');">';
                                echo '<img border="0" alt="' . $photo['title'] . '" src=' . $f->buildPhotoURL($photo, 'Square') . ' />';
                                echo '</a>';
                                // break before the 13th photo (if any)
                                if (++$i == 12) {
                                    break;
                                }
                                // If it reaches the sixth photo, insert a line break
                                if ($i % 6 == 0) {
                                    echo "<br />\n";
                                }
                            }
                            // end foreach
                            echo "<br />\n";
                            // navigate through pages of photos
                            if ($serendipity['POST']['flickr_page'] > 1) {
                                echo '<a href="javascript:flickr_showPage(' . (int) ($serendipity['POST']['flickr_page'] - 1) . ');">Previous</a>';
                            }
                            echo '&nbsp;&nbsp;';
                            if (count($photos['photo']) > 12) {
                                echo '<a href="javascript:flickr_showPage(' . (int) ($serendipity['POST']['flickr_page'] + 1) . ');">Next</a>';
                            }
                        }
                        // end if
                    }
                    // end if
                    return true;
                    break;
                default:
                    return false;
                    break;
            }
        } else {
            return false;
        }
    }
예제 #13
0
}
/* Delete a group */
if (isset($_POST['DELETE_YES']) && serendipity_checkFormToken()) {
    $group = serendipity_fetchGroup($serendipity['POST']['group']);
    serendipity_deleteGroup($serendipity['POST']['group']);
    printf('<div class="serendipityAdminMsgSuccess"><img style="height: 22px; width: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_success.png') . '" alt="" />' . DELETED_GROUP . '</div>', htmlspecialchars($serendipity['POST']['group']), htmlspecialchars($group['name']));
}
/* Save new group */
if (isset($_POST['SAVE_NEW']) && serendipity_checkFormToken()) {
    $serendipity['POST']['group'] = serendipity_addGroup($serendipity['POST']['name']);
    $perms = serendipity_getAllPermissionNames();
    serendipity_updateGroupConfig($serendipity['POST']['group'], $perms, $serendipity['POST'], false, $serendipity['POST']['forbidden_plugins'], $serendipity['POST']['forbidden_hooks']);
    printf('<div class="serendipityAdminMsgSuccess"><img style="height: 22px; width: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_success.png') . '" alt="" />' . CREATED_GROUP . '</div>', '#' . htmlspecialchars($serendipity['POST']['group']) . ', ' . htmlspecialchars($serendipity['POST']['name']));
}
/* Edit a group */
if (isset($_POST['SAVE_EDIT']) && serendipity_checkFormToken()) {
    $perms = serendipity_getAllPermissionNames();
    serendipity_updateGroupConfig($serendipity['POST']['group'], $perms, $serendipity['POST'], false, $serendipity['POST']['forbidden_plugins'], $serendipity['POST']['forbidden_hooks']);
    printf('<div class="serendipityAdminMsgSuccess"><img style="height: 22px; width: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_success.png') . '" alt="" />' . MODIFIED_GROUP . '</div>', htmlspecialchars($serendipity['POST']['name']));
}
if ($serendipity['GET']['adminAction'] != 'delete') {
    ?>
    <table width="100%">
        <tr>
            <td><strong><?php 
    echo GROUP;
    ?>
</strong></td>
            <td width="200">&nbsp;</td>
        </tr>
        <tr>
예제 #14
0
     $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);
     if (!is_array($file) || !serendipity_checkPermission('adminImagesDelete') || !serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid']) {
         return;
     }
     if (empty($serendipity['adminFile_redirect'])) {
         $serendipity['adminFile_redirect'] = serendipity_specialchars($_SERVER['HTTP_REFERER']);
     }
     $data['case_rotateCCW'] = true;
     if (serendipity_rotateImg($serendipity['GET']['fid'], 90)) {
         $data['rotate_img_done'] = true;
         $data['adminFile_redirect'] = $serendipity['adminFile_redirect'];
     }
     break;
 case 'scale':
     $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);
     if (!is_array($file) || !serendipity_checkFormToken() || !serendipity_checkPermission('adminImagesDelete') || !serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid']) {
         return;
     }
     $data['case_scale'] = true;
     $data['print_SCALING_IMAGE'] = sprintf(SCALING_IMAGE, $file['path'] . $file['name'] . '.' . $file['extension'], (int) $serendipity['GET']['width'], (int) $serendipity['GET']['height']);
     $data['extraParems'] = serendipity_generateImageSelectorParems();
     $data['print_serendipity_scaleImg'] = serendipity_scaleImg($serendipity['GET']['fid'], $serendipity['GET']['width'], $serendipity['GET']['height']);
     break;
 case 'scaleSelect':
     $file = serendipity_fetchImageFromDatabase($serendipity['GET']['fid']);
     if (!is_array($file) || !serendipity_checkPermission('adminImagesDelete') || !serendipity_checkPermission('adminImagesMaintainOthers') && $file['authorid'] != '0' && $file['authorid'] != $serendipity['authorid']) {
         return;
     }
     $data['extraParems'] = serendipity_generateImageSelectorParems("form");
     $data['case_scaleSelect'] = true;
     $s = getimagesize($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $file['path'] . $file['name'] . ($file['extension'] ? '.' . $file['extension'] : ""));
    function shownotes()
    {
        global $serendipity;
        if ($serendipity['version'][0] < 2) {
            echo '<h3>' . PLUGIN_ADMINNOTES_TITLE . '</h3>';
        } else {
            echo '<h2>' . PLUGIN_ADMINNOTES_TITLE . '</h2>';
        }
        if (!serendipity_db_bool($this->get_config('feedback')) && $serendipity['serendipityUserlevel'] < USERLEVEL_CHIEF) {
            return false;
        }
        switch ($_REQUEST['action']) {
            case 'edit':
                $entry = $this->getMyNotes((int) $_REQUEST['note']);
                $mode = 'update';
            case 'new':
                if (!isset($mode)) {
                    $mode = 'insert';
                }
                if (!is_array($entry)) {
                    $entry = array();
                }
                if ($_REQUEST['submit']) {
                    $valid_groups = serendipity_getAllGroups($serendipity['authorid']);
                    $targets = array();
                    if (is_array($_REQUEST['note_target'])) {
                        foreach ($_REQUEST['note_target'] as $groupid) {
                            $found = false;
                            foreach ($valid_groups as $group) {
                                if ($group['confkey'] == $groupid) {
                                    $found = true;
                                    break;
                                }
                            }
                            if ($found) {
                                $targets[] = (int) $groupid;
                            }
                        }
                    }
                    if ($mode == 'update') {
                        $noteid = (int) $_REQUEST['note'];
                        $q = serendipity_db_query("UPDATE {$serendipity['dbPrefix']}adminnotes\n                                                 SET authorid = {$serendipity['authorid']},\n                                                     subject = '" . serendipity_db_escape_string($_REQUEST['note_subject']) . "',\n                                                     body = '" . serendipity_db_escape_string($_REQUEST['note_body']) . "',\n                                                     notetype = '" . serendipity_db_escape_string($_REQUEST['note_notetype']) . "'\n                                               WHERE noteid = {$noteid}");
                        $q = serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}adminnotes_to_groups WHERE noteid = {$noteid}");
                        foreach ($targets as $target) {
                            $q = serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}adminnotes_to_groups (noteid, groupid) VALUES ({$noteid}, {$target})");
                        }
                        if (is_string($q)) {
                            echo $q . "<br />\n";
                        }
                    } else {
                        serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}adminnotes (authorid, notetime, subject, body, notetype) VALUES ('" . $serendipity['authorid'] . "', " . time() . ", '" . serendipity_db_escape_string($_REQUEST['note_subject']) . "', '" . serendipity_db_escape_string($_REQUEST['note_body']) . "', '" . serendipity_db_escape_string($_REQUEST['note_notetype']) . "')");
                        $noteid = serendipity_db_insert_id('adminnotes', 'noteid');
                        foreach ($targets as $target) {
                            serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}adminnotes_to_groups (noteid, groupid) VALUES ({$noteid}, {$target})");
                        }
                    }
                    if ($serendipity['version'][0] < 2) {
                        echo '<div class="serendipityAdminMsgSuccess"><img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_success.png') . '" alt="" />' . DONE . ': ' . sprintf(SETTINGS_SAVED_AT, serendipity_strftime('%H:%M:%S')) . '</div>';
                    } else {
                        echo '<span class="msg_success"><span class="icon-ok-circled"></span> ' . DONE . ': ' . sprintf(SETTINGS_SAVED_AT, serendipity_strftime('%H:%M:%S')) . '</span>';
                    }
                }
                echo '<p>' . PLUGIN_ADMINNOTES_FEEDBACK_INFO . '</p>';
                echo '<form action="?" method="post">';
                echo serendipity_setFormToken();
                echo '<input type="hidden" name="serendipity[adminModule]" value="event_display" />';
                echo '<input type="hidden" name="serendipity[adminAction]" value="adminnotes" />';
                echo '<input type="hidden" name="action" value="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($_REQUEST['action']) : htmlspecialchars($_REQUEST['action'], ENT_COMPAT, LANG_CHARSET)) . '" />';
                echo '<input type="hidden" name="note" value="' . $entry['noteid'] . '" />';
                echo '<input type="hidden" name="note_notetype" value="note" />';
                if ($serendipity['version'][0] < 2) {
                    echo TITLE . '<br />';
                    echo '<input class="input_textbox" type="text" name="note_subject" value="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['subject']) : htmlspecialchars($entry['subject'], ENT_COMPAT, LANG_CHARSET)) . '" /><br /><br />';
                } else {
                    echo '<div class="form_field">';
                    echo '<label for="note_subject" class="block_level">' . TITLE . '</label>';
                    echo '<input id="note_subject" type="text" name="note_subject" value="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['subject']) : htmlspecialchars($entry['subject'], ENT_COMPAT, LANG_CHARSET)) . '">';
                    echo '</div>';
                }
                if ($serendipity['version'][0] < 2) {
                    echo USERCONF_GROUPS . '<br />';
                } else {
                    echo '<div class="form_multiselect">';
                    echo '<label for="note_target" class="block_level">' . USERCONF_GROUPS . '</label>';
                }
                $valid_groups = serendipity_getAllGroups($serendipity['authorid']);
                if (isset($_REQUEST['note_target'])) {
                    $selected = $_REQUEST['note_target'];
                } elseif ($mode == 'update') {
                    $sql = serendipity_db_query("SELECT * FROM {$serendipity['dbPrefix']}adminnotes_to_groups");
                    $selected = array();
                    foreach ($sql as $row) {
                        $selected[] = $row['groupid'];
                    }
                }
                echo '<select id="note_target" name="note_target[]" multiple="multiple" size="5">';
                foreach ($valid_groups as $group) {
                    # PRESELECT!
                    if (in_array($group['confkey'], (array) $selected) || count($selected) == 0) {
                        $is_selected = 'selected="selected"';
                    } else {
                        $is_selected = '';
                    }
                    echo '<option ' . $is_selected . ' value="' . $group['confkey'] . '">' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($group['confvalue']) : htmlspecialchars($group['confvalue'], ENT_COMPAT, LANG_CHARSET)) . '</option>' . "\n";
                }
                if ($serendipity['version'][0] < 2) {
                    echo '</select><br /><br />';
                } else {
                    echo '</select></div>';
                }
                if ($serendipity['version'][0] < 2) {
                    echo ENTRY_BODY . '<br />';
                } else {
                    echo '<div class="form_area">';
                    echo '<label for="note_body" class="block_level">' . ENTRY_BODY . '</label>';
                }
                echo '<textarea id="note_body" rows=10 cols=80 name="note_body">' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['body']) : htmlspecialchars($entry['body'], ENT_COMPAT, LANG_CHARSET)) . '</textarea>';
                if ($serendipity['version'][0] < 2) {
                    echo '<br /><br />';
                    echo '<input type="submit" name="submit" value="' . SAVE . '" class="serendipityPrettyButton input_button" />';
                } else {
                    echo '</div>';
                    echo '<div class="form_buttons"><input type="submit" name="submit" value="' . SAVE . '"></div>';
                }
                echo '</form>';
                break;
            case 'delete':
                $newLoc = '?' . serendipity_setFormToken('url') . '&amp;serendipity[adminModule]=event_display&amp;serendipity[adminAction]=adminnotes&amp;action=isdelete&amp;note=' . (int) $_REQUEST['note'];
                $entry = $this->getMyNotes((int) $_REQUEST['note']);
                if ($serendipity['version'][0] > 1) {
                    echo '<span class="msg_hint"><span class="icon-help-circled"></span> ';
                }
                printf(DELETE_SURE, $entry['noteid'] . ' - ' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['subject']) : htmlspecialchars($entry['subject'], ENT_COMPAT, LANG_CHARSET)));
                if ($serendipity['version'][0] > 1) {
                    echo '</span>';
                }
                if ($serendipity['version'][0] < 2) {
                    ?>
                    <br />
                    <br />
                    <div>
                        <a href="<?php 
                    echo function_exists('serendipity_specialchars') ? serendipity_specialchars($_SERVER["HTTP_REFERER"]) : htmlspecialchars($_SERVER["HTTP_REFERER"], ENT_COMPAT, LANG_CHARSET);
                    ?>
" class="serendipityPrettyButton"><?php 
                    echo NOT_REALLY;
                    ?>
</a>
                        <?php 
                    echo str_repeat('&nbsp;', 10);
                    ?>
                        <a href="<?php 
                    echo $newLoc;
                    ?>
" class="serendipityPrettyButton"><?php 
                    echo DUMP_IT;
                    ?>
</a>
                    </div>
<?php 
                } else {
                    ?>
                    <div class="form_buttons">
                        <a class="button_link state_submit" href="<?php 
                    echo $newLoc;
                    ?>
"><?php 
                    echo DUMP_IT;
                    ?>
</a>
                        <a class="button_link state_cancel" href="<?php 
                    echo function_exists('serendipity_specialchars') ? serendipity_specialchars($_SERVER["HTTP_REFERER"]) : htmlspecialchars($_SERVER["HTTP_REFERER"], ENT_COMPAT, LANG_CHARSET);
                    ?>
"><?php 
                    echo NOT_REALLY;
                    ?>
</a>
                    </div>
<?php 
                }
                break;
            case 'isdelete':
                if (!serendipity_checkFormToken()) {
                    break;
                }
                $entry = $this->getMyNotes((int) $_REQUEST['note']);
                if (isset($entry['noteid'])) {
                    serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}adminnotes           WHERE noteid = " . (int) $_REQUEST['note']);
                    serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}adminnotes_to_groups WHERE noteid = " . (int) $_REQUEST['note']);
                }
                if ($serendipity['version'][0] > 1) {
                    echo '<span class="msg_success"><span class="icon-ok-circled"></span> ';
                }
                printf(RIP_ENTRY, $entry['noteid'] . ' - ' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['subject']) : htmlspecialchars($entry['subject'], ENT_COMPAT, LANG_CHARSET)));
                if ($serendipity['version'][0] > 1) {
                    echo '</span>';
                }
                break;
            default:
                $notes = $this->getMyNotes(false);
                echo '<ol class="note_list plainList">';
                if (is_array($notes)) {
                    foreach ($notes as $note) {
                        if ($serendipity['version'][0] < 2) {
                            echo '<li><strong>' . $note['subject'] . '</strong> ' . POSTED_BY . ' ' . $note['realname'] . ' ' . ON . ' ' . serendipity_strftime(DATE_FORMAT_SHORT, $note['notetime']) . '<br />';
                            echo '<a class="serendipityPrettyButton" href="?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=adminnotes&amp;action=edit&amp;note=' . $note['noteid'] . '">' . EDIT . '</a> ';
                            echo '<a class="serendipityPrettyButton" href="?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=adminnotes&amp;action=delete&amp;note=' . $note['noteid'] . '">' . DELETE . '</a> ';
                            echo '<br /><br /></li>';
                        } else {
                            echo '<li><h3>' . $note['subject'] . '</h3><p>' . POSTED_BY . ' ' . $note['realname'] . ' ' . ON . ' ' . serendipity_strftime(DATE_FORMAT_SHORT, $note['notetime']) . '</p>';
                            echo '<div class="form_buttons"><a class="button_link state_submit" href="?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=adminnotes&amp;action=edit&amp;note=' . $note['noteid'] . '">' . EDIT . '</a> ';
                            echo '<a class="button_link state_cancel" href="?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=adminnotes&amp;action=delete&amp;note=' . $note['noteid'] . '">' . DELETE . '</a></div></li>';
                        }
                    }
                }
                echo '</ol>';
                if ($serendipity['version'][0] < 2) {
                    echo '<a class="serendipityPrettyButton" href="?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=adminnotes&amp;action=new">' . NEW_ENTRY . '</a>';
                } else {
                    echo '<div class="form_buttons"><a class="button_link state_submit" href="?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=adminnotes&amp;action=new">' . NEW_ENTRY . '</a></div>';
                }
                break;
        }
    }
예제 #16
0
<?php

# $Id$
# Copyright (c) 2003-2005, Jannis Hermanns (on behalf the Serendipity Developer Team)
# All rights reserved.  See LICENSE file for licensing details
if (IN_serendipity !== true) {
    die("Don't hack!");
}
if (!serendipity_checkPermission('personalConfiguration')) {
    return;
}
$from = array();
if ($serendipity['GET']['adminAction'] == 'save' && serendipity_checkFormToken()) {
    $config = serendipity_parseTemplate(S9Y_CONFIG_USERTEMPLATE);
    if ((!serendipity_checkPermission('adminUsersEditUserlevel') || !serendipity_checkPermission('adminUsersMaintainOthers')) && (int) $_POST['userlevel'] > $serendipity['serendipityUserlevel']) {
        echo '<div class="serendipityAdminMsgError"><img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_error.png') . '" alt="" />' . CREATE_NOT_AUTHORIZED_USERLEVEL . '</div>';
    } elseif (empty($_POST['username'])) {
        echo '<div class="serendipityAdminMsgError"><img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_error.png') . '" alt="" />' . USERCONF_CHECK_USERNAME_ERROR . '</div>';
    } elseif (!empty($_POST['password']) && $_POST['check_password'] != $_SESSION['serendipityPassword'] && serendipity_passwordhash($_POST['check_password']) != $_SESSION['serendipityPassword']) {
        echo '<div class="serendipityAdminMsgError"><img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_error.png') . '" alt="" />' . USERCONF_CHECK_PASSWORD_ERROR . '</div>';
    } else {
        $valid_groups = serendipity_getGroups($serendipity['authorid'], true);
        foreach ($config as $category) {
            foreach ($category['items'] as $item) {
                if (in_array('groups', $item['flags'])) {
                    if (serendipity_checkPermission('adminUsersMaintainOthers')) {
                        // Void, no fixing neccessarry
                    } elseif (serendipity_checkPermission('adminUsersMaintainSame')) {
                        if (!is_array($_POST[$item['var']])) {
                            continue;
                        }
예제 #17
0
    echo '<div class="serendipityAdminMsgSuccess"><img style="height: 22px; width: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_success.png') . '" alt="" />' . sprintf(TEMPLATE_SET, htmlspecialchars($serendipity['GET']['theme'])) . '</div>';
}
?>

<?php 
if (@file_exists($serendipity['serendipityPath'] . $serendipity['templatePath'] . $serendipity['template'] . '/layout.php')) {
    echo '<div class="serendipityAdminMsgNote"><img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_note.png') . '" alt="" />' . WARNING_TEMPLATE_DEPRECATED . '</div>';
}
echo '<h3>' . STYLE_OPTIONS . ' (' . $serendipity['template'] . ')</h3>';
if (file_exists($serendipity['serendipityPath'] . $serendipity['templatePath'] . $serendipity['template'] . '/config.inc.php')) {
    serendipity_smarty_init();
    include_once $serendipity['serendipityPath'] . $serendipity['templatePath'] . $serendipity['template'] . '/config.inc.php';
}
if (is_array($template_config)) {
    serendipity_plugin_api::hook_event('backend_templates_configuration_top', $template_config);
    if ($serendipity['POST']['adminAction'] == 'configure' && serendipity_checkFormToken()) {
        $storage = new template_option();
        $storage->import($template_config);
        foreach ($serendipity['POST']['template'] as $option => $value) {
            $storage->set_config($option, $value);
        }
        echo '<div class="serendipityAdminMsgSuccess"><img style="height: 22px; width: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_success.png') . '" alt="" />' . DONE . ': ' . sprintf(SETTINGS_SAVED_AT, serendipity_strftime('%H:%M:%S')) . '</div>';
    }
    echo '<form method="post" action="serendipity_admin.php">';
    echo '<input type="hidden" name="serendipity[adminModule]" value="templates" />';
    echo '<input type="hidden" name="serendipity[adminAction]" value="configure" />';
    echo serendipity_setFormToken();
    include S9Y_INCLUDE_PATH . 'include/functions_plugins_admin.inc.php';
    $template_vars =& serendipity_loadThemeOptions($template_config);
    $template_options = new template_option();
    $template_options->import($template_config);
 function event_hook($event, &$bag, &$eventData, $addData = null)
 {
     global $serendipity;
     $debug = true;
     $hooks =& $bag->get('event_hooks');
     if (isset($hooks[$event])) {
         $captchas_ttl = $this->get_config('captchas_ttl', 7);
         $_captchas = $this->get_config('captchas', 'yes');
         $captchas = $_captchas !== 'no' && ($_captchas === 'yes' || $_captchas === 'scramble' || serendipity_db_bool($_captchas));
         // Check if the entry is older than the allowed amount of time. Enforce kaptchas if that is true
         // of if kaptchas are activated for every entry
         $show_captcha = $captchas && isset($eventData['timestamp']) && ($captchas_ttl < 1 || $eventData['timestamp'] < time() - $captchas_ttl * 60 * 60 * 24) ? true : false;
         // Plugins can override with custom captchas
         if (isset($serendipity['plugins']['disable_internal_captcha'])) {
             $show_captcha = false;
         }
         $forcemoderation = $this->get_config('forcemoderation', 60);
         $forcemoderation_treat = $this->get_config('forcemoderation_treat', 'moderate');
         $forcemoderationt = $this->get_config('forcemoderationt', 60);
         $forcemoderationt_treat = $this->get_config('forcemoderationt_treat', 'moderate');
         $links_moderate = $this->get_config('links_moderate', 10);
         $links_reject = $this->get_config('links_reject', 20);
         if (function_exists('imagettftext') && function_exists('imagejpeg')) {
             $max_char = 5;
             $min_char = 3;
             $use_gd = true;
         } else {
             $max_char = $min_char = 5;
             $use_gd = false;
         }
         switch ($event) {
             case 'fetchcomments':
                 if (is_array($eventData) && !$_SESSION['serendipityAuthedUser'] && serendipity_db_bool($this->get_config('hide_email', false))) {
                     // Will force emails to be not displayed in comments and RSS feed for comments. Will not apply to logged in admins (so not in the backend as well)
                     @reset($eventData);
                     while (list($idx, $comment) = each($eventData)) {
                         $eventData[$idx]['no_email'] = true;
                     }
                 }
                 break;
             case 'frontend_saveComment':
                 /*
                     $fp = fopen('/tmp/spamblock2.log', 'a');
                     fwrite($fp, date('Y-m-d H:i') . "\n" . print_r($eventData, true) . "\n" . print_r($addData, true) . "\n");
                     fclose($fp);
                 */
                 if (!is_array($eventData) || serendipity_db_bool($eventData['allow_comments'])) {
                     $this->checkScheme();
                     $serendipity['csuccess'] = 'true';
                     $logfile = $this->logfile = $this->get_config('logfile', $serendipity['serendipityPath'] . 'spamblock.log');
                     $required_fields = $this->get_config('required_fields', '');
                     $checkmail = $this->get_config('checkmail');
                     // Check CSRF [comments only, cannot be applied to trackbacks]
                     if ($addData['type'] == 'NORMAL' && serendipity_db_bool($this->get_config('csrf', true))) {
                         if (!serendipity_checkFormToken(false)) {
                             $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_CSRF_REASON, $addData);
                             $eventData = array('allow_comments' => false);
                             $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_CSRF_REASON;
                         }
                     }
                     // Check required fields
                     if ($addData['type'] == 'NORMAL' && !empty($required_fields)) {
                         $required_field_list = explode(',', $required_fields);
                         foreach ($required_field_list as $required_field) {
                             $required_field = trim($required_field);
                             if (empty($addData[$required_field])) {
                                 $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_REQUIRED_FIELD, $addData);
                                 $eventData = array('allow_comments' => false);
                                 $serendipity['messagestack']['comments'][] = sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_REQUIRED_FIELD, $required_field);
                                 return false;
                             }
                         }
                     }
                     /*
                     if ($addData['type'] != 'NORMAL' && empty($addData['name'])) {
                         $eventData = array('allow_coments' => false);
                         $this->log($logfile, $eventData['id'], 'INVALIDGARV', 'INVALIDGARV', $addData);
                         return false;
                     }
                     */
                     // Check whether to allow comments from registered authors
                     if (serendipity_userLoggedIn() && $this->inGroup()) {
                         return true;
                     }
                     // Check if the user has verified himself via email already.
                     if ($addData['type'] == 'NORMAL' && (string) $checkmail === 'verify_once') {
                         $auth = serendipity_db_query("SELECT *\n                                                            FROM {$serendipity['dbPrefix']}options\n                                                           WHERE okey  = 'mail_confirm'\n                                                             AND name  = '" . serendipity_db_escape_string($addData['email']) . "'\n                                                             AND value = '" . serendipity_db_escape_string($addData['name']) . "'", true);
                         if (!is_array($auth)) {
                             // Filter authors names, Filter URL, Filter Content, Filter Emails, Check for maximum number of links before rejecting
                             // moderate false
                             if (false === $this->wordfilter($logfile, $eventData, $wordmatch, $addData, true)) {
                                 // already there #$this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_FILTER_WORDS, $addData);
                                 // already there #$eventData = array('allow_comments' => false);
                                 // already there #$serendipity['messagestack']['emails'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY;
                                 return false;
                             } elseif (serendipity_db_bool($this->get_config('killswitch', false)) === true) {
                                 $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_KILLSWITCH, $addData);
                                 $eventData = array('allow_comments' => false);
                                 $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_KILLSWITCH;
                                 return false;
                             } else {
                                 $this->log($logfile, $eventData['id'], 'MODERATE', PLUGIN_EVENT_SPAMBLOCK_CHECKMAIL_VERIFICATION_MAIL, $addData);
                                 $eventData['moderate_comments'] = true;
                                 $eventData['status'] = 'confirm1';
                                 $serendipity['csuccess'] = 'moderate';
                                 $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_CHECKMAIL_VERIFICATION_MAIL;
                                 return false;
                             }
                         } else {
                             // User is allowed to post message, bypassing other checks as if he were logged in.
                             return true;
                         }
                     }
                     // Check if entry title is the same as comment body
                     if (serendipity_db_bool($this->get_config('entrytitle')) && trim($eventData['title']) == trim($addData['comment'])) {
                         $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_TITLE, $addData);
                         $eventData = array('allow_comments' => false);
                         $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY;
                         return false;
                     }
                     // Check for global emergency moderation
                     if (serendipity_db_bool($this->get_config('killswitch', false)) === true) {
                         $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_KILLSWITCH, $addData);
                         $eventData = array('allow_comments' => false);
                         $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_KILLSWITCH;
                         return false;
                     }
                     // Check for not allowing trackbacks/pingbacks/wfwcomments
                     if (($addData['type'] != 'NORMAL' || $addData['source'] == 'API') && $this->get_config('disable_api_comments', 'none') != 'none') {
                         if ($this->get_config('disable_api_comments') == 'reject') {
                             $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_API, $addData);
                             $eventData = array('allow_comments' => false);
                             $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_REASON_API;
                             return false;
                         } elseif ($this->get_config('disable_api_comments') == 'moderate') {
                             $this->log($logfile, $eventData['id'], 'MODERATE', PLUGIN_EVENT_SPAMBLOCK_REASON_API, $addData);
                             $eventData['moderate_comments'] = true;
                             $serendipity['csuccess'] = 'moderate';
                             $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_REASON_API;
                         }
                     }
                     // Check if sender ip is matching trackback/pingback ip (ip validation)
                     $trackback_ipvalidation_option = $this->get_config('trackback_ipvalidation', 'moderate');
                     if (($addData['type'] == 'TRACKBACK' || $addData['type'] == 'PINGBACK') && $trackback_ipvalidation_option != 'no') {
                         $this->IsHardcoreSpammer();
                         $exclude_urls = explode(';', $this->get_config('trackback_ipvalidation_url_exclude', $this->get_default_exclude_urls()));
                         $found_exclude_url = false;
                         foreach ($exclude_urls as $exclude_url) {
                             $exclude_url = trim($exclude_url);
                             if (empty($exclude_url)) {
                                 continue;
                             }
                             $found_exclude_url = preg_match('@' . $exclude_url . '@', $addData['url']);
                             if ($found_exclude_url) {
                                 break;
                             }
                         }
                         if (!$found_exclude_url) {
                             $parts = @parse_url($addData['url']);
                             $tipval_method = $trackback_ipvalidation_option == 'reject' ? 'REJECTED' : 'MODERATE';
                             // Getting host from url successfully?
                             if (!is_array($parts)) {
                                 // not a valid URL
                                 $this->log($logfile, $eventData['id'], $tipval_method, sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $addData['url'], '', ''), $addData);
                                 if ($trackback_ipvalidation_option == 'reject') {
                                     $eventData = array('allow_comments' => false);
                                     $serendipity['messagestack']['comments'][] = sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $addData['url']);
                                     return false;
                                 } else {
                                     $eventData['moderate_comments'] = true;
                                     $serendipity['csuccess'] = 'moderate';
                                     $serendipity['moderate_reason'] = sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $addData['url']);
                                 }
                             }
                             $trackback_ip = preg_replace('/[^0-9.]/', '', gethostbyname($parts['host']));
                             $sender_ip = preg_replace('/[^0-9.]/', '', $_SERVER['REMOTE_ADDR']);
                             $sender_ua = $debug ? ', ua="' . $_SERVER['HTTP_USER_AGENT'] . '"' : '';
                             // Is host ip and sender ip matching?
                             if ($trackback_ip != $sender_ip) {
                                 $this->log($logfile, $eventData['id'], $tipval_method, sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $parts['host'], $trackback_ip, $sender_ip . $sender_ua), $addData);
                                 if ($trackback_ipvalidation_option == 'reject') {
                                     $eventData = array('allow_comments' => false);
                                     $serendipity['messagestack']['comments'][] = sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $parts['host'], $trackback_ip, $sender_ip . $sender_ua);
                                     return false;
                                 } else {
                                     $eventData['moderate_comments'] = true;
                                     $serendipity['csuccess'] = 'moderate';
                                     $serendipity['moderate_reason'] = sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $parts['host'], $trackback_ip, $sender_ip . $sender_ua);
                                 }
                             }
                         }
                     }
                     // Filter Akismet Blacklist?
                     $akismet_apikey = $this->get_config('akismet');
                     $akismet = $this->get_config('akismet_filter');
                     if (!empty($akismet_apikey) && ($akismet == 'moderate' || $akismet == 'reject') && !isset($addData['skip_akismet'])) {
                         $spam = $this->getBlacklist('akismet.com', $akismet_apikey, $eventData, $addData);
                         if ($spam['is_spam'] !== false) {
                             $this->IsHardcoreSpammer();
                             if ($akismet == 'moderate') {
                                 $this->log($logfile, $eventData['id'], 'MODERATE', PLUGIN_EVENT_SPAMBLOCK_REASON_AKISMET_SPAMLIST . ': ' . $spam['message'], $addData);
                                 $eventData['moderate_comments'] = true;
                                 $serendipity['csuccess'] = 'moderate';
                                 $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY . ' (Akismet)';
                             } else {
                                 $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_AKISMET_SPAMLIST . ': ' . $spam['message'], $addData);
                                 $eventData = array('allow_comments' => false);
                                 $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY;
                                 return false;
                             }
                         }
                     }
                     // Check Trackback URLs?
                     if (($addData['type'] == 'TRACKBACK' || $addData['type'] == 'PINGBACK') && serendipity_db_bool($this->get_config('trackback_check_url'))) {
                         require_once S9Y_PEAR_PATH . 'HTTP/Request.php';
                         if (function_exists('serendipity_request_start')) {
                             serendipity_request_start();
                         }
                         $req = new HTTP_Request($addData['url'], array('allowRedirects' => true, 'maxRedirects' => 5, 'readTimeout' => array(5, 0)));
                         $is_valid = false;
                         if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') {
                             $is_valid = false;
                         } else {
                             $fdata = $req->getResponseBody();
                             // Check if the target page contains a link to our blog
                             if (preg_match('@' . preg_quote($serendipity['baseURL'], '@') . '@i', $fdata)) {
                                 $is_valid = true;
                             } else {
                                 $is_valid = false;
                             }
                         }
                         if (function_exists('serendipity_request_end')) {
                             serendipity_request_end();
                         }
                         if ($is_valid === false) {
                             $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_TRACKBACKURL, $addData);
                             $eventData = array('allow_comments' => false);
                             $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_REASON_TRACKBACKURL;
                             return false;
                         }
                     }
                     if (false === $this->wordfilter($logfile, $eventData, $wordmatch, $addData)) {
                         return false;
                     }
                     // Check for maximum number of links before rejecting
                     $link_count = substr_count(strtolower($addData['comment']), 'http://');
                     if ($links_reject > 0 && $link_count > $links_reject) {
                         $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_LINKS_REJECT, $addData);
                         $eventData = array('allow_comments' => false);
                         $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY;
                         return false;
                     }
                     // Captcha checking
                     if ($show_captcha && $addData['type'] == 'NORMAL') {
                         if (!isset($_SESSION['spamblock']['captcha']) || !isset($serendipity['POST']['captcha']) || strtolower($serendipity['POST']['captcha']) != strtolower($_SESSION['spamblock']['captcha'])) {
                             $this->log($logfile, $eventData['id'], 'REJECTED', sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_CAPTCHAS, $serendipity['POST']['captcha'], $_SESSION['spamblock']['captcha']), $addData);
                             $eventData = array('allow_comments' => false);
                             $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_CAPTCHAS;
                             return false;
                         } else {
                             // DEBUG
                             //                                $this->log($logfile, $eventData['id'], 'REJECTED', 'Captcha passed: ' . $serendipity['POST']['captcha'] . ' / ' . $_SESSION['spamblock']['captcha'] . ' // Source: ' . $_SERVER['REQUEST_URI'], $addData);
                         }
                     } else {
                         // DEBUG
                         //                            $this->log($logfile, $eventData['id'], 'REJECTED', 'Captcha not needed: ' . $serendipity['POST']['captcha'] . ' / ' . $_SESSION['spamblock']['captcha'] . ' // Source: ' . $_SERVER['REQUEST_URI'], $addData);
                     }
                     // Check for forced comment moderation (X days)
                     if ($addData['type'] == 'NORMAL' && $forcemoderation > 0 && $eventData['timestamp'] < time() - $forcemoderation * 60 * 60 * 24) {
                         $this->log($logfile, $eventData['id'], $forcemoderation_treat, PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION, $addData);
                         if ($forcemoderation_treat == 'reject') {
                             $eventData = array('allow_comments' => false);
                             $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION;
                             return false;
                         } else {
                             $eventData['moderate_comments'] = true;
                             $serendipity['csuccess'] = 'moderate';
                             $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION;
                         }
                     }
                     // Check for forced trackback moderation
                     if ($addData['type'] != 'NORMAL' && $forcemoderationt > 0 && $eventData['timestamp'] < time() - $forcemoderationt * 60 * 60 * 24) {
                         $this->log($logfile, $eventData['id'], $forcemoderationt_treat, PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION, $addData);
                         if ($forcemoderationt_treat == 'reject') {
                             $eventData = array('allow_comments' => false);
                             $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION;
                             return false;
                         } else {
                             $eventData['moderate_comments'] = true;
                             $serendipity['csuccess'] = 'moderate';
                             $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION;
                         }
                     }
                     // Check for maximum number of links before forcing moderation
                     if ($links_moderate > 0 && $link_count > $links_moderate) {
                         $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_LINKS_MODERATE, $addData);
                         $eventData['moderate_comments'] = true;
                         $serendipity['csuccess'] = 'moderate';
                         $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_REASON_LINKS_MODERATE;
                     }
                     // Check for identical comments. We allow to bypass trackbacks from our server to our own blog.
                     if ($this->get_config('bodyclone', true) === true && $_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR'] && $addData['type'] != 'PINGBACK') {
                         $query = "SELECT count(id) AS counter FROM {$serendipity['dbPrefix']}comments WHERE type = '" . $addData['type'] . "' AND body = '" . serendipity_db_escape_string($addData['comment']) . "'";
                         $row = serendipity_db_query($query, true);
                         if (is_array($row) && $row['counter'] > 0) {
                             $this->IsHardcoreSpammer();
                             $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_BODYCLONE, $addData);
                             $eventData = array('allow_comments' => false);
                             $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY;
                             return false;
                         }
                     }
                     // Check last IP
                     if ($addData['type'] == 'NORMAL' && $this->get_config('ipflood', 2) != 0) {
                         $query = "SELECT max(timestamp) AS last_post FROM {$serendipity['dbPrefix']}comments WHERE ip = '" . serendipity_db_escape_string($_SERVER['REMOTE_ADDR']) . "'";
                         $row = serendipity_db_query($query, true);
                         if (is_array($row) && $row['last_post'] > time() - $this->get_config('ipflood', 2) * 60) {
                             $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_IPFLOOD, $addData);
                             $eventData = array('allow_comments' => false);
                             $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_IP;
                             return false;
                         }
                     }
                     if ($addData['type'] == 'NORMAL' && (string) $checkmail === 'verify_always') {
                         $this->log($logfile, $eventData['id'], 'MODERATE', PLUGIN_EVENT_SPAMBLOCK_CHECKMAIL_VERIFICATION_MAIL, $addData);
                         $eventData['moderate_comments'] = true;
                         $eventData['status'] = 'confirm';
                         $serendipity['csuccess'] = 'moderate';
                         $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_CHECKMAIL_VERIFICATION_MAIL;
                         return false;
                     }
                     // Check invalid email
                     if ($addData['type'] == 'NORMAL' && serendipity_db_bool($this->get_config('checkmail', false))) {
                         if (!empty($addData['email']) && strstr($addData['email'], '@') === false) {
                             $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_CHECKMAIL, $addData);
                             $eventData = array('allow_comments' => false);
                             $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_REASON_CHECKMAIL;
                             return false;
                         }
                     }
                     if ($eventData['moderate_comments'] == true) {
                         return false;
                     }
                 }
                 return true;
                 break;
             case 'frontend_comment':
                 if (serendipity_db_bool($this->get_config('hide_email', false))) {
                     echo '<div class="serendipity_commentDirection serendipity_comment_spamblock">' . PLUGIN_EVENT_SPAMBLOCK_HIDE_EMAIL_NOTICE . '</div>';
                 }
                 if ((string) $this->get_config('checkmail') === 'verify_always' || (string) $this->get_config('checkmail') === 'verify_once') {
                     echo '<div class="serendipity_commentDirection serendipity_comment_spamblock">' . PLUGIN_EVENT_SPAMBLOCK_CHECKMAIL_VERIFICATION_INFO . '</div>';
                 }
                 if (serendipity_db_bool($this->get_config('csrf', true))) {
                     echo serendipity_setFormToken('form');
                 }
                 // Check whether to allow comments from registered authors
                 if (serendipity_userLoggedIn() && $this->inGroup()) {
                     return true;
                 }
                 if ($show_captcha) {
                     echo '<div class="serendipity_commentDirection serendipity_comment_captcha">';
                     if (!isset($serendipity['POST']['preview']) || strtolower($serendipity['POST']['captcha'] != strtolower($_SESSION['spamblock']['captcha']))) {
                         echo '<br />' . PLUGIN_EVENT_SPAMBLOCK_CAPTCHAS_USERDESC . '<br />';
                         echo $this->show_captcha($use_gd);
                         echo '<br />';
                         echo '<label for="captcha">' . PLUGIN_EVENT_SPAMBLOCK_CAPTCHAS_USERDESC3 . '</label><br /><input class="input_textbox" type="text" size="5" name="serendipity[captcha]" value="" id="captcha" />';
                     } elseif (isset($serendipity['POST']['captcha'])) {
                         echo '<input type="hidden" name="serendipity[captcha]" value="' . serendipity_specialchars($serendipity['POST']['captcha']) . '" />';
                     }
                     echo '</div>';
                 }
                 return true;
                 break;
             case 'external_plugin':
                 $parts = explode('_', (string) $eventData);
                 if (!empty($parts[1])) {
                     $param = (int) $parts[1];
                 } else {
                     $param = null;
                 }
                 $methods = array('captcha');
                 if (!in_array($parts[0], $methods)) {
                     return;
                 }
                 list($musec, $msec) = explode(' ', microtime());
                 $srand = (double) $msec + (double) $musec * 100000;
                 srand($srand);
                 mt_srand($srand);
                 $width = 120;
                 $height = 40;
                 $bgcolors = explode(',', $this->get_config('captcha_color', '255,255,255'));
                 $fontfiles = array('Vera.ttf', 'VeraSe.ttf', 'chumbly.ttf', '36daysago.ttf');
                 if ($use_gd) {
                     $strings = $this->random_string($max_char, $min_char);
                     $fontname = $fontfiles[array_rand($fontfiles)];
                     $font = $serendipity['serendipityPath'] . 'plugins/serendipity_event_spamblock/' . $fontname;
                     if (!file_exists($font)) {
                         // Search in shared plugin directory
                         $font = S9Y_INCLUDE_PATH . 'plugins/serendipity_event_spamblock/' . $fontname;
                     }
                     if (!file_exists($font)) {
                         die(PLUGIN_EVENT_SPAMBLOCK_ERROR_NOTTF);
                     }
                     header('Content-Type: image/jpeg');
                     $image = imagecreate($width, $height);
                     // recommended use of imagecreatetruecolor() returns a black backgroundcolor
                     $bgcol = imagecolorallocate($image, trim($bgcolors[0]), trim($bgcolors[1]), trim($bgcolors[2]));
                     // imagettftext($image, 10, 1, 1, 15, imagecolorallocate($image, 255, 255, 255), $font, 'String: ' . $string);
                     $pos_x = 5;
                     foreach ($strings as $idx => $charidx) {
                         $color = imagecolorallocate($image, mt_rand(50, 235), mt_rand(50, 235), mt_rand(50, 235));
                         $size = mt_rand(15, 21);
                         $angle = mt_rand(-20, 20);
                         $pos_y = ceil($height - mt_rand($size / 3, $size / 2));
                         imagettftext($image, $size, $angle, $pos_x, $pos_y, $color, $font, $this->chars[$charidx]);
                         $pos_x = $pos_x + $size + 2;
                     }
                     if ($_captchas === 'scramble') {
                         $line_diff = mt_rand(5, 15);
                         $pixel_col = imagecolorallocate($image, trim($bgcolors[0]) - mt_rand(10, 50), trim($bgcolors[1]) - mt_rand(10, 50), trim($bgcolors[2]) - mt_rand(10, 50));
                         for ($y = $line_diff; $y < $height; $y += $line_diff) {
                             $row_diff = mt_rand(5, 15);
                             for ($x = $row_diff; $x < $width; $x += $row_diff) {
                                 imagerectangle($image, $x, $y, $x + 1, $y + 1, $pixel_col);
                             }
                         }
                     }
                     imagejpeg($image, NULL, 90);
                     // NULL fixes https://bugs.php.net/bug.php?id=63920
                     imagedestroy($image);
                 } else {
                     header('Content-Type: image/png');
                     $output_char = strtolower($_SESSION['spamblock']['captcha'][$parts[1] - 1]);
                     $cap = $serendipity['serendipityPath'] . 'plugins/serendipity_event_spamblock/captcha_' . $output_char . '.png';
                     if (!file_exists($cap)) {
                         $cap = S9Y_INCLUDE_PATH . 'plugins/serendipity_event_spamblock/captcha_' . $output_char . '.png';
                     }
                     if (file_exists($cap)) {
                         echo file_get_contents($cap);
                     }
                 }
                 return true;
                 break;
             case 'backend_comments_top':
                 // Tell Akismet about spam or not spam
                 $tell_id = null;
                 if (isset($serendipity['GET']['spamIsSpam'])) {
                     $tell_spam = true;
                     $tell_id = $serendipity['GET']['spamIsSpam'];
                 }
                 if (isset($serendipity['GET']['spamNotSpam'])) {
                     $tell_spam = false;
                     $tell_id = $serendipity['GET']['spamNotSpam'];
                 }
                 if ($tell_id !== null) {
                     $akismet_apikey = $this->get_config('akismet');
                     $akismet = $this->get_config('akismet_filter');
                     if (!empty($akismet_apikey)) {
                         $this->tellAboutComment('akismet.com', $akismet_apikey, $tell_id, $tell_spam);
                     }
                 }
                 // Add Author to blacklist. If already filtered, it will be removed from the filter. (AKA "Toggle")
                 if (isset($serendipity['GET']['spamBlockAuthor'])) {
                     $item = $this->getComment('author', $serendipity['GET']['spamBlockAuthor']);
                     $items =& $this->checkFilter('authors', $item, true);
                     $this->set_config('contentfilter_authors', implode(';', $items));
                 }
                 // Add URL to blacklist. If already filtered, it will be removed from the filter. (AKA "Toggle")
                 if (isset($serendipity['GET']['spamBlockURL'])) {
                     $item = $this->getComment('url', $serendipity['GET']['spamBlockURL']);
                     $items =& $this->checkFilter('urls', $item, true);
                     $this->set_config('contentfilter_urls', implode(';', $items));
                 }
                 // Add E-mail to blacklist. If already filtered, it will be removed from the filter. (AKA "Toggle")
                 if (isset($serendipity['GET']['spamBlockEmail'])) {
                     $item = $this->getComment('email', $serendipity['GET']['spamBlockEmail']);
                     $items =& $this->checkFilter('emails', $item, true);
                     $this->set_config('contentfilter_emails', implode(';', $items));
                 }
                 echo '<a class="button_link" title="' . PLUGIN_EVENT_SPAMBLOCK_CONFIG . '" href="serendipity_admin.php?serendipity[adminModule]=plugins&amp;serendipity[plugin_to_conf]=' . $this->instance . '"><span class="icon-medkit"></span><span class="visuallyhidden"> ' . PLUGIN_EVENT_SPAMBLOCK_CONFIG . '</span></a>';
                 return true;
                 break;
             case 'backend_view_comment':
                 $author_is_filtered = $this->checkFilter('authors', $eventData['author']);
                 $clink = 'comment_' . $eventData['id'];
                 $randomString = '&amp;random=' . substr(sha1(rand()), 0, 10);
                 # the random string will force browser to reload the page,
                 # so the server knows who to block/unblock when clicking again on the same link,
                 # see http://stackoverflow.com/a/2573986/2508518, http://stackoverflow.com/a/14043346/2508518
                 $akismet_apikey = $this->get_config('akismet');
                 $akismet = $this->get_config('akismet_filter');
                 if (!empty($akismet_apikey)) {
                     $eventData['action_more'] .= ' <a class="button_link actions_extra" title="' . PLUGIN_EVENT_SPAMBLOCK_SPAM . '" href="serendipity_admin.php?serendipity[adminModule]=comments&amp;serendipity[spamIsSpam]=' . $eventData['id'] . $addData . '#' . $clink . '"><span class="icon-block"></span><span class="visuallyhidden"> ' . PLUGIN_EVENT_SPAMBLOCK_SPAM . '</span></a>';
                     $eventData['action_more'] .= ' <a class="button_link actions_extra" title="' . PLUGIN_EVENT_SPAMBLOCK_NOT_SPAM . '" href="serendipity_admin.php?serendipity[adminModule]=comments&amp;serendipity[spamNotSpam]=' . $eventData['id'] . $addData . '#' . $clink . '"><span class="icon-ok-circled"></span><span class="visuallyhidden"> ' . PLUGIN_EVENT_SPAMBLOCK_NOT_SPAM . '</span></a>';
                 }
                 $eventData['action_author'] .= ' <a class="button_link" title="' . ($author_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_AUTHOR : PLUGIN_EVENT_SPAMBLOCK_ADD_AUTHOR) . '" href="serendipity_admin.php?serendipity[adminModule]=comments&amp;serendipity[spamBlockAuthor]=' . $eventData['id'] . $addData . $randomString . '#' . $clink . '"><span class="icon-' . ($author_is_filtered ? 'ok-circled' : 'block') . '"></span><span class="visuallyhidden"> ' . ($author_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_AUTHOR : PLUGIN_EVENT_SPAMBLOCK_ADD_AUTHOR) . '</span></a>';
                 if (!empty($eventData['url'])) {
                     $url_is_filtered = $this->checkFilter('urls', $eventData['url']);
                     $eventData['action_url'] .= ' <a class="button_link" title="' . ($url_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_URL : PLUGIN_EVENT_SPAMBLOCK_ADD_URL) . '" href="serendipity_admin.php?serendipity[adminModule]=comments&amp;serendipity[spamBlockURL]=' . $eventData['id'] . $addData . $randomString . '#' . $clink . '"><span class="icon-' . ($url_is_filtered ? 'ok-circled' : 'block') . '"></span><span class="visuallyhidden"> ' . ($url_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_URL : PLUGIN_EVENT_SPAMBLOCK_ADD_URL) . '</span></a>';
                 }
                 if (!empty($eventData['email'])) {
                     $email_is_filtered = $this->checkFilter('emails', $eventData['email']);
                     $eventData['action_email'] .= ' <a class="button_link" title="' . ($email_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_EMAIL : PLUGIN_EVENT_SPAMBLOCK_ADD_EMAIL) . '" href="serendipity_admin.php?serendipity[adminModule]=comments&amp;serendipity[spamBlockEmail]=' . $eventData['id'] . $addData . $randomString . '#' . $clink . '"><span class="icon-' . ($email_is_filtered ? 'ok-circled' : 'block') . '"></span><span class="visuallyhidden"> ' . ($email_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_EMAIL : PLUGIN_EVENT_SPAMBLOCK_ADD_EMAIL) . '</span></a>';
                 }
                 return true;
                 break;
             case 'backend_sidebar_admin_appearance':
                 echo '<li><a href="serendipity_admin.php?serendipity[adminModule]=plugins&amp;serendipity[plugin_to_conf]=' . $this->instance . '">' . PLUGIN_EVENT_SPAMBLOCK_TITLE . '</a></li>';
                 return true;
                 break;
             default:
                 return false;
                 break;
         }
     } 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 < $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;
        }
    }
예제 #20
0
</a>
    <?php 
        echo str_repeat('&nbsp;', 10);
        ?>
    <a href="<?php 
        echo $newLoc;
        ?>
" class="serendipityPrettyButton input_button"><?php 
        echo DUMP_IT;
        ?>
</a>
</div>
<?php 
        break;
    case 'multidelete':
        if (!serendipity_checkFormToken() || !is_array($serendipity['POST']['multiDelete'])) {
            break;
        }
        $ids = '';
        foreach ($serendipity['POST']['multiDelete'] as $idx => $id) {
            $ids .= (int) $id . ',';
            $entry = serendipity_fetchEntry('id', $id, 1, 1);
            printf(DELETE_SURE, $entry['id'] . ' - ' . htmlspecialchars($entry['title']));
            echo '<br />';
        }
        $newLoc = '?' . serendipity_setFormToken('url') . '&amp;serendipity[action]=admin&amp;serendipity[adminModule]=entries&amp;serendipity[adminAction]=doMultiDelete&amp;serendipity[id]=' . $ids;
        ?>
<br />
<br />
<div>
    <a href="<?php 
예제 #21
0
# Copyright (c) 2003-2005, Jannis Hermanns (on behalf the Serendipity Developer Team)
# All rights reserved.  See LICENSE file for licensing details
if (IN_serendipity !== true) {
    die("Don't hack!");
}
umask(00);
$umask = 0775;
@define('IN_installer', true);
if (!isset($_POST['installAction'])) {
    $_POST['installAction'] = '';
}
if (!serendipity_checkPermission('siteConfiguration') && !serendipity_checkPermission('blogConfiguration')) {
    return;
}
$data = array();
if ($_POST['installAction'] == 'check' && serendipity_checkFormToken()) {
    $data['installAction'] = 'check';
    $oldConfig = $serendipity;
    $res = serendipity_updateConfiguration();
    $data['res'] = $res;
    if (is_array($res)) {
        $data['diagnosticError'] = true;
    } else {
        /* If we have new rewrite rules, then install them */
        $permalinkOld = array($oldConfig['serendipityHTTPPath'], $oldConfig['serendipityPath'], $oldConfig['defaultBaseURL'], $oldConfig['indexFile'], $oldConfig['rewrite']);
        $permalinkNew = array($serendipity['serendipityHTTPPath'], $serendipity['serendipityPath'], $serendipity['defaultBaseURL'], $serendipity['indexFile'], $serendipity['rewrite']);
        // Compare all old permalink section values against new one. A change in any of those
        // will force to update the .htaccess for rewrite rules.
        $permconf = serendipity_parseTemplate(S9Y_CONFIG_TEMPLATE);
        if (is_array($permconf) && is_array($permconf['permalinks']['items'])) {
            foreach ($permconf['permalinks']['items'] as $permitem) {