function event_hook($event, &$bag, &$eventData, $addData = null)
 {
     global $serendipity;
     $hooks =& $bag->get('event_hooks');
     if (isset($hooks[$event])) {
         switch ($event) {
             case 'entry_display':
                 if (!is_array($eventData)) {
                     return false;
                 }
                 $elements = count($eventData);
                 for ($i = 0; $i < $elements; $i++) {
                     if (empty($eventData[$i]['body'])) {
                         continue;
                     }
                     $eventData[$i]['add_footer'] .= '<script src="http://feeds.feedburner.com/~s/' . $this->get_config('feedburnerid', '') . '?i=' . serendipity_archiveURL($eventData[$i]['id'], $eventData[$i]['title'], 'baseURL', true, array('timestamp' => $entry['timestamp'])) . '" type="text/javascript" charset="utf-8"></script>';
                 }
                 return true;
                 break;
             default:
                 return false;
         }
     } else {
         return false;
     }
 }
 function generate_content(&$title)
 {
     global $serendipity;
     $number = $this->get_config('number');
     $showpicsonly = $this->get_config('showpicsonly');
     if (!$number || !is_numeric($number) || $number < 1) {
         $number = 5;
     }
     $title = PLUGIN_PHOTOBLOG_TITLE;
     if (!isset($serendipity['GET']['id']) || !is_numeric($serendipity['GET']['id'])) {
         $number = $number * $number + 1;
         $entries = serendipity_db_query("SELECT id,\n                                                title,\n                                                timestamp\n                                           FROM {$serendipity['dbPrefix']}entries\n                                          WHERE isdraft = 'false'\n                                       ORDER BY timestamp DESC\n                                          LIMIT {$number}");
     } else {
         $id = serendipity_db_escape_string($serendipity['GET']['id']);
         $entries1 = serendipity_db_query("SELECT id,\n                                                title,\n                                                timestamp\n                                           FROM {$serendipity['dbPrefix']}entries\n                                          WHERE isdraft = 'false'\n                                            AND id > {$id}\n                                       ORDER BY timestamp ASC\n                                          LIMIT {$number}");
         $number++;
         $entries2 = serendipity_db_query("SELECT id,\n                                                title,\n                                                timestamp\n                                           FROM {$serendipity['dbPrefix']}entries\n                                          WHERE isdraft = 'false'\n                                            AND id <= {$id}\n                                       ORDER BY timestamp DESC\n                                          LIMIT {$number}");
         if (isset($entries1) && is_array($entries1) && isset($entries2) && is_array($entries2)) {
             $entries = array_merge(array_reverse($entries1), $entries2);
         } elseif (isset($entries1) && is_array($entries1)) {
             $entries = array_reverse($entries1);
         } elseif (isset($entries2) && is_array($entries2)) {
             $entries = $entries2;
         }
     }
     if (isset($entries) && is_array($entries)) {
         foreach ($entries as $k => $entry) {
             $entryLink = serendipity_archiveURL($entry['id'], $entry['title'], 'serendipityHTTPPath', true, array('timestamp' => $entry['timestamp']));
             $photo = $this->getPhoto($entry['id']);
             if ($showpicsonly == 'true' && isset($photo) || $showpicsonly != 'true') {
                 if (isset($photo)) {
                     $file = serendipity_fetchImageFromDatabase($photo['photoid']);
                     $imgsrc = $serendipity['serendipityHTTPPath'] . $serendipity['uploadHTTPPath'] . $file['path'] . $file['name'] . '.' . $file['thumbnail_name'] . '.' . $file['extension'];
                     $thumbbasename = $file['path'] . $file['name'] . '.' . $file['thumbnail_name'] . '.' . $file['extension'];
                     $thumbName = $serendipity['serendipityHTTPPath'] . $serendipity['uploadHTTPPath'] . $thumbbasename;
                     $thumbsize = @getimagesize($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $thumbbasename);
                 }
                 echo '<a href="' . $entryLink . '" title="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['title']) : htmlspecialchars($entry['title'], ENT_COMPAT, LANG_CHARSET)) . '">';
                 if (isset($photo)) {
                     echo '<img style="margin:5px;" src="' . $imgsrc . '" width=' . $thumbsize[0] . ' height=' . $thumbsize[1];
                     if (isset($id) && $id == $entry['id']) {
                         echo ' border=4';
                     }
                     echo ' />';
                 } else {
                     if (isset($id) && $id == $entry['id']) {
                         echo '<b>';
                     }
                     echo $entry['title'];
                     if (isset($id) && $id == $entry['id']) {
                         echo '</b>';
                     }
                 }
                 echo '</a><br />';
             }
         }
     }
 }
 function showSearch()
 {
     global $serendipity;
     $this->setupDB();
     $term = serendipity_db_escape_string($serendipity['GET']['searchTerm']);
     if ($serendipity['dbType'] == 'postgres') {
         $group = '';
         $distinct = 'DISTINCT';
         $find_part = "(c.title ILIKE '%{$term}%' OR c.body ILIKE '%{$term}%')";
     } elseif ($serendipity['dbType'] == 'sqlite') {
         $group = 'GROUP BY id';
         $distinct = '';
         $term = serendipity_mb('strtolower', $term);
         $find_part = "(lower(c.title) LIKE '%{$term}%' OR lower(c.body) LIKE '%{$term}%')";
     } else {
         $group = 'GROUP BY id';
         $distinct = '';
         $term = str_replace('&quot;', '"', $term);
         if (preg_match('@["\\+\\-\\*~<>\\(\\)]+@', $term)) {
             $find_part = "MATCH(c.title,c.body) AGAINST('{$term}' IN BOOLEAN MODE)";
         } else {
             $find_part = "MATCH(c.title,c.body) AGAINST('{$term}')";
         }
     }
     $querystring = "SELECT c.title AS ctitle, c.body, c.author, c.entry_id, c.timestamp AS ctimestamp, c.url, c.type,\n                               e.id, e.title, e.timestamp\n                          FROM {$serendipity['dbPrefix']}comments AS c\n               LEFT OUTER JOIN {$serendipity['dbPrefix']}entries AS e\n                            ON e.id = c.entry_id\n                         WHERE c.status = 'approved'\n                           AND {$find_part}\n                               {$group}\n                      ORDER BY c.timestamp DESC";
     $results = serendipity_db_query($querystring, false, 'assoc');
     if (!is_array($results)) {
         if ($results !== 1 && $results !== true) {
             echo function_exists('serendipity_specialchars') ? serendipity_specialchars($results) : htmlspecialchars($results, ENT_COMPAT, LANG_CHARSET);
         }
         $results = array();
     }
     $myAddData = array("from" => "serendipity_plugin_commentsearch:generate_content");
     foreach ($results as $idx => $result) {
         $results[$idx]['permalink'] = serendipity_archiveURL($result['id'], $result['title'], 'baseURL', true, $result);
         $results[$idx]['comment'] = $result['body'];
         //(function_exists('serendipity_specialchars') ? serendipity_specialchars(strip_tags($result['body'])) : htmlspecialchars(strip_tags($result['body']), ENT_COMPAT, LANG_CHARSET));
         serendipity_plugin_api::hook_event('frontend_display', $results[$idx], $myAddData);
         // let the template decide, if we want to have tags or not
         $results[$idx]['commenthtml'] = $results[$idx]['comment'];
         $results[$idx]['comment'] = strip_tags($results[$idx]['comment']);
     }
     $serendipity['smarty']->assign(array('comment_searchresults' => count($results), 'comment_results' => $results));
     $filename = 'plugin_commentsearch_searchresults.tpl';
     $tfile = serendipity_getTemplateFile($filename, 'serendipityPath');
     if (!$tfile) {
         $tfile = dirname(__FILE__) . '/' . $filename;
     }
     $inclusion = $serendipity['smarty']->security_settings[INCLUDE_ANY];
     $serendipity['smarty']->security_settings[INCLUDE_ANY] = true;
     $content = $serendipity['smarty']->fetch('file:' . $tfile);
     $serendipity['smarty']->security_settings[INCLUDE_ANY] = $inclusion;
     echo $content;
 }
 function generate_content(&$title)
 {
     global $serendipity;
     $title = THUMBPAGE_TITLE;
     if ($serendipity['GET']['page'] != 'thumbs') {
         return true;
     }
     if (!headers_sent()) {
         header('HTTP/1.0 200');
         header('Status: 200 OK');
     }
     $entries = serendipity_db_query("SELECT id,\n                                                title,\n                                                timestamp\n                                           FROM {$serendipity['dbPrefix']}entries\n                                          WHERE isdraft = 'false'\n                                       ORDER BY timestamp DESC");
     if (isset($entries) && is_array($entries)) {
         $count = 0;
         echo '<table><tr>';
         foreach ($entries as $k => $entry) {
             echo '<td align="center">';
             $entryLink = serendipity_archiveURL($entry['id'], $entry['title'], 'serendipityHTTPPath', true, array('timestamp' => $entry['timestamp']));
             $photo = $this->getPhoto($entry['id']);
             if (isset($photo)) {
                 $file = serendipity_fetchImageFromDatabase($photo['photoid']);
                 $imgsrc = $serendipity['serendipityHTTPPath'] . $serendipity['uploadHTTPPath'] . $file['path'] . $file['name'] . '.' . $file['thumbnail_name'] . '.' . $file['extension'];
                 $thumbbasename = $file['path'] . $file['name'] . '.' . $file['thumbnail_name'] . '.' . $file['extension'];
                 $thumbName = $serendipity['serendipityHTTPPath'] . $serendipity['uploadHTTPPath'] . $thumbbasename;
                 $thumbsize = @getimagesize($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $thumbbasename);
             }
             echo '<a href="' . $entryLink . '" title="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['title']) : htmlspecialchars($entry['title'], ENT_COMPAT, LANG_CHARSET)) . '">';
             if (isset($photo)) {
                 echo '<img style="margin:5px;" src="' . $imgsrc . '" width=' . $thumbsize[0] . ' height=' . $thumbsize[1];
                 if (isset($id) && $id == $entry['id']) {
                     echo ' border=4';
                 }
                 echo ' />';
             } else {
                 if (isset($id) && $id == $entry['id']) {
                     echo '<b>';
                 }
                 echo $entry['title'];
                 if (isset($id) && $id == $entry['id']) {
                     echo '</b>';
                 }
             }
             echo '</a></td>';
             if ($count++ >= $this->get_config('number') - 1) {
                 $count = 0;
                 echo "</tr><tr>";
             }
         }
         echo "</tr></table>";
     }
 }
 function generate_content(&$title)
 {
     global $serendipity;
     $title = $this->get_config('title', $this->title);
     $timespan = $this->get_config('timespan', 30);
     $type = $this->get_config('type', 'IMDB');
     $q = "SELECT ep.entryid AS id, e.title, e.timestamp, ep.value as rating\n\n\t\t\t\t  FROM {$serendipity['dbPrefix']}entryproperties AS ep\n\t\t\t\t  JOIN {$serendipity['dbPrefix']}entries AS e\n\t\t\t\t    ON e.id = ep.entryid\n\n\t\t\t\t WHERE ep.property = 'cr_{$type}_rating'\n\t\t\t\t   AND e.timestamp > " . (time() - 86700 * (int) $timespan) . "\n\t\t\t\t ORDER BY ep.value DESC\n\t\t\t\t LIMIT 5";
     $rows = serendipity_db_query($q);
     if (!is_array($rows)) {
         echo "No movies during the last {$timespan} days! Maybe I dropped dead.";
     }
     echo '<ol class="movie {$type}">';
     foreach ($rows as $row) {
         $url = serendipity_archiveURL($row['id'], $row['title'], 'serendipityHTTPPath', true, array('timestamp' => $row['timestamp']));
         echo '<li><a href="' . $url . '">' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($row['title']) : htmlspecialchars($row['title'], ENT_COMPAT, LANG_CHARSET)) . '</a> (' . $row['rating'] . ')</li>';
     }
     echo '</ol>';
 }
Beispiel #6
0
 $serendipity['head_subtitle'] = COMMENTS;
 $serendipity['smarty_file'] = 'commentpopup.tpl';
 serendipity_smarty_init();
 if ($id == 0) {
     return false;
 } else {
     $serendipity['smarty']->assign('entry_id', $id);
 }
 if (isset($_GET['success']) && $_GET['success'] == 'true') {
     $serendipity['smarty']->assign(array('is_comment_added' => true, 'comment_url' => serendipity_specialchars($_GET['url']) . '&amp;serendipity[entry_id]=' . $id, 'comment_string' => explode('%s', COMMENT_ADDED_CLICK)));
 } else {
     if (!isset($serendipity['POST']['submit'])) {
         if ($serendipity['GET']['type'] == 'trackbacks') {
             $query = "SELECT title, timestamp FROM {$serendipity['dbPrefix']}entries WHERE id = '" . $id . "'";
             $entry = serendipity_db_query($query);
             $entry = serendipity_archiveURL($id, $entry[0]['title'], 'baseURL', true, array('timestamp' => $entry[0]['timestamp']));
             $serendipity['smarty']->assign(array('is_showtrackbacks' => true, 'comment_url' => $serendipity['baseURL'] . 'comment.php?type=trackback&amp;entry_id=' . $id, 'comment_entryurl' => $entry));
         } else {
             $query = "SELECT id, last_modified, timestamp, allow_comments, moderate_comments FROM {$serendipity['dbPrefix']}entries WHERE id = '" . $id . "'";
             $ca = serendipity_db_query($query, true);
             $comment_allowed = serendipity_db_bool($ca['allow_comments']) || !is_array($ca) ? true : false;
             $serendipity['smarty']->assign(array('is_showcomments' => true, 'is_comment_allowed' => $comment_allowed));
             if ($comment_allowed) {
                 serendipity_displayCommentForm($id, '?', NULL, $serendipity['POST'], true, serendipity_db_bool($ca['moderate_comments']), $ca);
             }
         }
     } else {
         $comment['url'] = $serendipity['POST']['url'];
         $comment['comment'] = trim($serendipity['POST']['comment']);
         $comment['name'] = $serendipity['POST']['name'];
         $comment['email'] = $serendipity['POST']['email'];
/**
 * 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)
{
    global $serendipity;
    if (empty($mode) || !is_array($entry)) {
        return false;
    }
    $data = array();
    $data['is_preview'] = true;
    $data['mode'] = $mode;
    switch ($mode) {
        case 'save':
            ob_start();
            $res = serendipity_updertEntry($entry);
            $data['updertHooks'] = ob_get_contents();
            ob_end_clean();
            if (is_string($res)) {
                $data['res'] = $res;
            }
            if (!empty($serendipity['lastSavedEntry'])) {
                $data['lastSavedEntry'] = $serendipity['lastSavedEntry'];
            }
            $data['entrylink'] = serendipity_archiveURL($res, $entry['title'], 'serendipityHTTPPath', true, array('timestamp' => $entry['timestamp']));
            break;
        case 'preview':
            $serendipity['smarty_preview'] = true;
            $data['preview'] = serendipity_printEntries(array($entry), $entry['extended'] != '' ? 1 : 0, true);
            break;
    }
    return serendipity_smarty_show('preview_iframe.tpl', $data);
}
    /**
     * @param string $event
     * @param serendipity_property_bag $bag
     * @param mixed $eventData
     * @param mixed $addData
     * @return bool
     */
    function event_hook($event, &$bag, &$eventData, $addData = null)
    {
        global $serendipity;
        switch ($event) {
            case 'backend_publish':
            case 'backend_save':
                serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}entryproperties WHERE entryid = '" . $eventData['id'] . "' AND property LIKE 'ep_flattr%'");
                foreach ($this->flattr_attrs as $attr => $attr_desc) {
                    serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}entryproperties (entryid, value, property) VALUES ('" . $eventData['id'] . "', '" . serendipity_db_escape_string($serendipity['POST']['properties']['ep_' . $attr]) . "', 'ep_" . $attr . "')");
                }
                return true;
                break;
            case 'backend_display':
                ?>
                    <fieldset style="margin: 5px">
                        <legend><?php 
                echo PLUGIN_FLATTR_NAME;
                ?>
</legend>
<?php 
                foreach ($this->flattr_attrs as $attr => $attr_desc) {
                    if (isset($serendipity['POST']['properties']['ep_' . $attr])) {
                        $val = $serendipity['POST']['properties']['ep_' . $attr];
                    } elseif (isset($eventData['id'])) {
                        $val = $eventData['properties']['ep_' . $attr];
                    } else {
                        $val = '';
                    }
                    echo '<label for="serendipity[properties][ep_' . $attr . ']" title="' . PLUGIN_FLATTR_NAME . '">
                            ' . $attr_desc . ':</label><br/>';
                    if ($attr == 'flattr_active' || $attr == 'flattr_lng' || $attr == 'flattr_cat') {
                        echo '<select name="serendipity[properties][ep_' . $attr . ']" id="properties_' . $attr . '" class="input_select">';
                        if ($attr == 'flattr_lng') {
                            $opt = $this->flattr_langs;
                            echo '<option value=""></option>' . "\n";
                        } elseif ($attr == 'flattr_cat') {
                            $opt = $this->flattr_cats;
                            echo '<option value=""></option>' . "\n";
                        } elseif ($attr == 'flattr_active') {
                            $opt = array('1' => YES, '-1' => NO);
                        }
                        foreach ($opt as $key => $kval) {
                            echo '<option value="' . $key . '" ' . ((string) $val == (string) $key ? 'selected="selected"' : '') . '>' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($kval) : htmlspecialchars($kval, ENT_COMPAT, LANG_CHARSET)) . '</option>' . "\n";
                        }
                        echo '</select>';
                    } else {
                        echo '<input type="text" name="serendipity[properties][ep_' . $attr . ']" id="properties_' . $attr . '" class="input_textbox" value="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($val) : htmlspecialchars($val, ENT_COMPAT, LANG_CHARSET)) . '" style="width: 100%" />' . "\n";
                    }
                    echo '<br />';
                }
                ?>
                    </fieldset>
<?php 
                return true;
                break;
            case 'frontend_header':
                $flattr_uid = substr($this->_addslashes($this->get_config('userid')), 0, 500);
                $flattr_btn = $this->_addslashes($this->get_config('flattr_btn'));
                $flattr_lng = substr($this->get_config('flattr_lng'), 0, 255);
                $flattr_cat = substr($this->get_config('flattr_cat'), 0, 255);
                ?>
<script type="text/javascript">
/* <![CDATA[ */
(function() {
    var s = document.createElement('script');
    var t = document.getElementsByTagName('script')[0];
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'https://api.flattr.com/js/0.6/load.js?mode=auto';
    s.src += '&popout=<?php 
                echo (int) $this->get_config('flattr_pop');
                ?>
';
    s.src += '&uid=<?php 
                echo $flattr_uid;
                ?>
';
    s.src += '&language=<?php 
                echo $flattr_lng;
                ?>
';
    s.src += '&category=<?php 
                echo $flattr_cat;
                ?>
';
    <?php 
                if (in_array($flattr_btn, array('default', 'compact'))) {
                    ?>
    s.src += '&button=<?php 
                    echo $flattr_btn;
                    ?>
';
    <?php 
                }
                ?>
    t.parentNode.insertBefore(s, t);
 })();
/* ]]> */
</script>
<?php 
                break;
            case 'frontend_display':
                if (empty($eventData['properties'])) {
                    $eventData['properties'] =& serendipity_fetchEntryProperties($eventData['id']);
                }
                if ($eventData['properties']['ep_flattr_active'] == '-1') {
                    return true;
                }
                if (empty($eventData['body']) && empty($eventData['extended'])) {
                    return true;
                }
                $flattr_uid = $this->_addslashes($this->get_config('userid'));
                $flattr_tle = $this->_addslashes($eventData['title']);
                $flattr_pop = (int) $this->get_config('flattr_pop');
                $flattr_dsc = $this->_addslashes($eventData['properties']['ep_flattr_dsc']);
                $flattr_cat = $this->_addslashes($eventData['properties']['ep_flattr_cat']);
                $flattr_lng = $this->_addslashes($eventData['properties']['ep_flattr_lng']);
                $flattr_tag = $this->_addslashes($eventData['properties']['ep_flattr_tag']);
                if (empty($flattr_dsc)) {
                    $flattr_dsc = $this->_addslashes($eventData['body']);
                }
                $flattr_dsc = strip_tags($flattr_dsc);
                if (empty($flattr_cat)) {
                    $flattr_cat = $this->get_config('flattr_cat');
                }
                if (empty($flattr_lng)) {
                    $flattr_lng = $this->get_config('flattr_lng');
                }
                if (empty($flattr_tag) && class_exists('serendipity_event_freetag')) {
                    $_tags = serendipity_event_freetag::getTagsForEntries(array($eventData['id']));
                    $tags = is_array($_tags) ? array_pop($_tags) : array();
                    $flattr_tag = implode(',', $tags);
                }
                $flattr_url = $this->_addslashes(serendipity_archiveURL($eventData['id'], $eventData['title'], 'baseURL', true, array('timestamp' => $eventData['timestamp'])));
                $flattr_btn = $this->_addslashes($this->get_config('flattr_btn'));
                $flattr_uid = substr($flattr_uid, 0, 500);
                $flattr_tle = substr($flattr_tle, 0, 500);
                $flattr_dsc = substr($flattr_dsc, 0, 1000);
                $flattr_cat = substr($flattr_cat, 0, 255);
                $flattr_lng = substr($flattr_lng, 0, 255);
                $flattr_tag = substr($flattr_tag, 0, 255);
                $flattr_url = substr($flattr_url, 0, 2048);
                $flattr_btn = substr($flattr_btn, 0, 255);
                if ($flattr_btn != 'default' && $flattr_btn != 'compact') {
                    $flattr = "<a href=\"https://flattr.com/submit/auto?" . "user_id=" . urlencode($flattr_uid) . "&" . "url=" . urlencode($flattr_url) . "&" . "title=" . urlencode($flattr_tle) . "&" . "description=" . urlencode($flattr_dsc) . "&" . "category=" . urlencode($flattr_cat) . "&" . "popout=" . urlencode($flattr_pop) . "&" . "language=" . urlencode($flattr_lng) . "\">" . $flattr_btn . "</a>";
                } else {
                    $flattr_tle2 = stripslashes($flattr_tle2);
                    $flattr_tle2 = function_exists('serendipity_specialchars') ? serendipity_specialchars($flattr_tle2) : htmlspecialchars($flattr_tle2, ENT_COMPAT, LANG_CHARSET);
                    $flattr = "\r\n<a class='FlattrButton' style='display:none;'\r\n    title=\"" . $flattr_tle2 . "\"\r\n    data-flattr-uid='" . $flattr_uid . "'\r\n    data-flattr-tags='" . $flattr_tag . "'\r\n    data-flattr-category='" . $flattr_cat . "'\r\n    data-flattr-language='" . $flattr_lng . "'\r\n    href='" . $flattr_url . "'>\r\n\r\n    " . stripslashes($flattr_dsc) . "\r\n</a>\r\n    ";
                }
                $field = $this->get_config('placement');
                if ($addData['from'] == 'functions_entries:updertEntry') {
                } elseif ($addData['from'] == 'functions_entries:printEntries_rss') {
                    $entryText =& $this->getFieldReference($field, $eventData);
                    $entryText .= function_exists('serendipity_specialchars') ? serendipity_specialchars($flattr) : htmlspecialchars($flattr, ENT_COMPAT, LANG_CHARSET);
                } else {
                    $entryText =& $this->getFieldReference($field, $eventData);
                    $entryText .= $flattr;
                }
                if ($field == 'extended') {
                    $eventData['is_extended'] = true;
                }
                break;
            case 'frontend_display:rss-1.0:namespace':
            case 'frontend_display:rss-2.0:namespace':
                if ($this->get_config('add_to_feed')) {
                    $eventData['display_dat'] .= '
   xmlns:atom="http://www.w3.org/2005/Atom"';
                }
                return true;
                break;
            case 'frontend_display:rss-1.0:per_entry':
            case 'frontend_display:rss-2.0:per_entry':
                if ($this->get_config('add_to_feed')) {
                    $flattr_uid = $this->_addslashes($this->get_config('userid'));
                    $flattr_uid = substr($flattr_uid, 0, 500);
                    $flattr_url = $this->_addslashes(serendipity_archiveURL($eventData['id'], $eventData['title'], 'baseURL', true, array('timestamp' => $eventData['timestamp'])));
                    $flattr_url = substr($flattr_url, 0, 2048);
                    $eventData['display_dat'] .= '
    <atom:link rel="payment" href="https://flattr.com/submit/auto?url=' . urlencode($flattr_url) . '&amp;user_id=' . $flattr_uid . '" type="text/html" />';
                }
                return true;
                break;
            case 'frontend_display:atom-1.0:per_entry':
                if ($this->get_config('add_to_feed')) {
                    $flattr_uid = $this->_addslashes($this->get_config('userid'));
                    $flattr_uid = substr($flattr_uid, 0, 500);
                    $flattr_url = $this->_addslashes(serendipity_archiveURL($eventData['id'], $eventData['title'], 'baseURL', true, array('timestamp' => $eventData['timestamp'])));
                    $flattr_url = substr($flattr_url, 0, 2048);
                    $eventData['display_dat'] .= '
    <link rel="payment" href="https://flattr.com/submit/auto?url=' . $flattr_url . '&amp;user_id=' . $flattr_uid . '" type="text/html" />';
                }
                return true;
                break;
        }
    }
    function event_hook($event, &$bag, &$eventData, $addData = null)
    {
        global $serendipity;
        $hooks =& $bag->get('event_hooks');
        if (isset($hooks[$event])) {
            switch ($event) {
                case 'css':
                    if (stristr($eventData, '.serendipity_babelfish')) {
                        // class exists in CSS, so a user has customized it and we don't need default
                        return true;
                    }
                    ?>

      .serendipity_babelfish {
         margin-left: auto;
         margin-right: 0px;
         text-align: right;
         font-size: 7pt;
         display: block;
         margin-top: 5px;
         margin-bottom: 0px;
      }

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

      .serendipity_babelfish a:hover {
         color: green;
      }
<?php 
                    return true;
                    break;
                case 'frontend_display':
                    if ($bag->get('scrambles_true_content') && is_array($addData) && isset($addData['no_scramble'])) {
                        return true;
                    }
                case 'frontend_display_cache':
                    $pairs = explode(',', $this->get_config('TranslationPairs'));
                    $msg = '';
                    foreach ($pairs as $pair) {
                        list($src_lang, $dst_lang) = explode('->', $pair);
                        if ($src_lang == $serendipity['lang']) {
                            if ($msg == '') {
                                $msg = '<div class="serendipity_babelfish">' . PLUGIN_BABELFISH_TRANSLATE;
                            }
                            $bfURL = urlencode(serendipity_archiveURL($eventData['id'], $eventData['title'], 'baseURL', true, array('timestamp' => $eventData['timestamp'])));
                            $bfFromLang = $src_lang;
                            $bfToLang = $dst_lang;
                            $line = $this->get_config('EngineURL');
                            eval("\$line = \"{$line}\";");
                            // dirrrrrrty
                            $msg .= ' <a href="' . $line . '">' . $dst_lang . '</a>';
                        }
                    }
                    $msg .= '</div>';
                    $eventData['body'] .= $msg;
                    break;
                default:
                    return false;
            }
        }
    }
/**
 * Send a comment notice to the admin/author of an entry
 *
 * @access public
 * @param  int      ID of the comment that has been made
 * @param  string   Author's email address to send the mail to
 * @param  string   The name of the sender
 * @param  string   The URL of the sender
 * @param  int      The ID of the entry that has been commented
 * @param  string   The title of the entry that has been commented
 * @param  string   The text of the comment
 * @param  string   The type of the comment (normal|trackback)
 * @param  boolean  Toggle Whether comments to this entry need approval
 * @return boolean  Return success of sending the mails
 */
function serendipity_sendComment($comment_id, $to, $fromName, $fromEmail, $fromUrl, $id, $title, $comment, $type = 'NORMAL', $moderate_comment = false)
{
    global $serendipity;
    if (empty($fromName)) {
        $fromName = ANONYMOUS;
    }
    $entryURI = serendipity_archiveURL($id, $title, 'baseURL');
    $path = $type == 'TRACKBACK' ? 'trackback' : 'comment';
    // Check for using Tokens
    if ($serendipity['useCommentTokens']) {
        $token = md5(uniqid(rand(), 1));
        $path = $path . "_token_" . $token;
        //Delete any comment tokens older than 1 week.
        serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}options\n                              WHERE okey LIKE 'comment_%' AND name < " . (time() - 604800));
        // Issue new comment moderation hash
        serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}options (name, value, okey)\n                              VALUES ('" . time() . "', '" . $token . "', 'comment_" . $comment_id . "')");
    }
    $deleteURI = serendipity_rewriteURL(PATH_DELETE . '/' . $path . '/' . $comment_id . '/' . $id . '-' . serendipity_makeFilename($title) . '.html', 'baseURL');
    $approveURI = serendipity_rewriteURL(PATH_APPROVE . '/' . $path . '/' . $comment_id . '/' . $id . '-' . serendipity_makeFilename($title) . '.html', 'baseURL');
    if ($type == 'TRACKBACK') {
        /******************* TRACKBACKS *******************/
        $subject = ($moderate_comment ? '[' . REQUIRES_REVIEW . '] ' : '') . NEW_TRACKBACK_TO . ' ' . $title;
        $text = sprintf(A_NEW_TRACKBACK_BLAHBLAH, $title) . "\n" . "\n" . REQUIRES_REVIEW . ': ' . ($moderate_comment ? YES : NO) . (isset($serendipity['moderate_reason']) ? ' (' . $serendipity['moderate_reason'] . ')' : '') . "\n" . LINK_TO_ENTRY . ': ' . $entryURI . "\n" . 'Weblog ' . NAME . ': ' . stripslashes($fromName) . "\n" . LINK_TO_REMOTE_ENTRY . ': ' . $fromUrl . "\n" . "\n" . EXCERPT . ':' . "\n" . strip_tags($comment) . "\n" . "\n" . '----' . "\n" . YOU_HAVE_THESE_OPTIONS . ($moderate_comment ? "\n" . str_repeat(' ', 2) . THIS_TRACKBACK_NEEDS_REVIEW : '') . "\n" . str_repeat(' ', 3) . str_pad(VIEW_ENTRY, 15) . ' -- ' . $entryURI . "\n" . str_repeat(' ', 3) . str_pad(DELETE_TRACKBACK, 15) . ' -- ' . $deleteURI . ($moderate_comment ? "\n" . str_repeat(' ', 3) . str_pad(APPROVE_TRACKBACK, 15) . ' -- ' . $approveURI : '');
    } else {
        /******************* COMMENTS *********************/
        $subject = ($moderate_comment ? '[' . REQUIRES_REVIEW . '] ' : '') . NEW_COMMENT_TO . ' ' . $title;
        $text = sprintf(A_NEW_COMMENT_BLAHBLAH, $serendipity['blogTitle'], $title) . "\n" . LINK_TO_ENTRY . ': ' . $entryURI . "\n" . "\n" . REQUIRES_REVIEW . ': ' . ($moderate_comment ? YES : NO) . (isset($serendipity['moderate_reason']) ? ' (' . $serendipity['moderate_reason'] . ')' : '') . "\n" . USER . ' ' . IP_ADDRESS . ': ' . $_SERVER['REMOTE_ADDR'] . "\n" . USER . ' ' . NAME . ': ' . $fromName . "\n" . USER . ' ' . EMAIL . ': ' . $fromEmail . "\n" . USER . ' ' . HOMEPAGE . ': ' . $fromUrl . "\n" . "\n" . COMMENTS . ': ' . "\n" . strip_tags($comment) . "\n" . "\n" . '----' . "\n" . YOU_HAVE_THESE_OPTIONS . ($moderate_comment ? "\n" . str_repeat(' ', 2) . THIS_COMMENT_NEEDS_REVIEW : '') . "\n" . str_repeat(' ', 3) . str_pad(VIEW_COMMENT, 15) . ' -- ' . $entryURI . '#c' . $comment_id . "\n" . str_repeat(' ', 3) . str_pad(DELETE_COMMENT, 15) . ' -- ' . $deleteURI . ($moderate_comment ? "\n" . str_repeat(' ', 3) . str_pad(APPROVE_COMMENT, 15) . ' -- ' . $approveURI : '');
    }
    return serendipity_sendMail($to, $subject, $text, $fromEmail, null, $fromName);
}
 function print_entry($x, &$entry, $header = false)
 {
     if ($header) {
         $this->pdf->AddPage();
         $this->pdf->SetFont('Courier', '', 12);
         $this->pdf->TOC_Add($header);
         $this->pdf->Cell(0, 10, $header, 1);
         $this->pdf->Ln();
         $this->pdf->Ln();
     }
     $entryLink = serendipity_archiveURL($entry['id'], $entry['title'], 'serendipityHTTPPath', true, array('timestamp' => $entry['timestamp']));
     serendipity_plugin_api::hook_event('frontend_display', $entry, array('no_scramble' => true));
     $posted_by = ' ' . POSTED_BY . ' ' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['author']) : htmlspecialchars($entry['author'], ENT_COMPAT, LANG_CHARSET));
     if (is_array($entry['categories']) && sizeof($entry['categories']) > 0) {
         $posted_by .= ' ' . IN . ' ';
         $cats = array();
         foreach ($entry['categories'] as $cat) {
             $cats[] = $cat['category_name'];
         }
         $posted_by .= implode(', ', $cats);
     }
     $posted_by .= ' ' . AT . ' ' . serendipity_strftime('%H:%M', $entry['timestamp']);
     $this->pdf->SetFont('Arial', 'B', 11);
     $this->pdf->Write(4, $this->prep_out($entry['title']) . "\n");
     $this->pdf->Ln();
     $this->pdf->SetFont('Arial', '', 10);
     $html = $this->prep_out($entry['body'] . $entry['extended']) . "\n";
     if (serendipity_db_bool($this->get_config('html2pdf'))) {
         $this->pdf->WriteHTML($html);
     } else {
         $this->pdf->Write(4, $html);
     }
     $this->pdf->Ln();
     $this->pdf->SetFont('Courier', '', 9);
     $this->pdf->Write(4, $this->prep_out($posted_by) . "\n");
     $this->pdf->Ln();
     if ($this->single) {
         $this->printComments(serendipity_fetchComments($entry['id']));
     }
 }
 function showInterface()
 {
     global $serendipity;
     if (isset($_POST['submitdopost'])) {
         $postid = $_POST['id'];
         $pbuserno = $_POST[pbuserid];
         $postinfo = $this->phoneblogz_post($postid, $pbuserno);
         if ($postinfo['error'] != false) {
             echo "ERROR: " . $postinfo['error'];
         }
     }
     $arr = getPostsForAccount($this->get_config("phoneblogz_accesscode"), $this->get_config("phoneblogz_password"));
     if (!empty($arr["error"])) {
         echo "ERROR: " . $arr["error"];
     } else {
         echo '<h3 style="text-align:center;">' . PLUGIN_EVENT_PHONEBLOGZ_SEEBELOW . '</h3>';
         echo "<table border='1'>";
         // TODO: i18n
         echo "<tr>\n";
         echo "<th>Date Posted</th>";
         echo "<th>Caller ID</th>";
         echo "<th>Left by</th>";
         echo "<th>Listen</th>";
         echo "<th>Download link</th>";
         echo "<th>Status</th>";
         echo "<th>Action</th>";
         echo "</tr>";
         for ($i = 0; $i < count($arr); ++$i) {
             $msg = $arr[$i];
             $status = "available";
             $action = "";
             $postid = $this->get_config("phoneblogz_status_" . $msg["messageid"]);
             if (!isset($postid)) {
                 $status = "not posted";
                 $action = "<form action='?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=phoneblogz' method='POST'>" . "<input type='hidden' name='pbuserid' value='" . $msg["userno"] . "'>" . "<input type='hidden' name='id' value='" . $msg["messageid"] . "'><input class='serendipityPrettyButton input_button' type='submit' name='submitdopost' value='post now'></form>";
             } else {
                 $status = "posted";
                 if ($postid > 0) {
                     $status .= " - <a href='" . serendipity_archiveURL($postid, 'preview') . "'>" . PREVIEW . "</a>";
                 }
                 $action = "<form action='?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=phoneblogz' method='POST'>" . "<input type='hidden' name='pbuserid' value='" . $msg["userno"] . "'>" . "<input type='hidden' name='id' value='" . $msg["messageid"] . "'><input class='serendipityPrettyButton input_button' type='submit' name='submitdopost' value='repost'></form>";
             }
             $posturl = "<a href='http://www.phoneblogz.com/listen.php?user="******"phoneblogz_accesscode") . "&id=" . $msg["messageid"] . "'>Click here</a>";
             $flashhtml = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ' . 'width="141" height="15" id="player" align="middle">';
             $flashhtml .= '<param name="allowScriptAccess" value="sameDomain" />';
             $flashhtml .= '<param name="FlashVars" value="msgid=' . $msg["messageid"] . '&amp;userid=' . $this->get_config("phoneblogz_accesscode") . '" />';
             $flashhtml .= '<param name="movie" value="http://www.phoneblogz.com/player2.swf?msgid=' . $msg["messageid"] . '&userid=' . $this->get_config("phoneblogz_accesscode") . '" />' . '<param name="quality" value="high" /><param name="bgcolor" value="#ffffff" />';
             $flashhtml .= '<embed src="http://www.phoneblogz.com/player2.swf" flashvars="msgid=' . $msg["messageid"] . '&amp;userid=' . $this->get_config("phoneblogz_accesscode") . '" ' . 'quality="high" bgcolor="#ffffff" width="141" height="15" name="player" align="middle" ' . 'allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
             $flashhtml .= '</object>';
             echo "<tr><td>" . $msg["timeleft"] . "</td><td>" . $msg["callerid"] . "</td><td>" . $msg["username"] . "</td><td>{$flashhtml}</td><td>{$posturl}</td><td>{$status}</td><td>{$action}</td></tr>";
         }
         echo "</table>";
     }
 }
/**
 * Search through link body, and automagically send a trackback ping.
 *
 * This is the trackback starter function that searches your text and sees if any
 * trackback URLs are in there
 *
 * @access public
 * @param   int     The ID of our entry
 * @param   string  The author of our entry
 * @param   string  The title of our entry
 * @param   string  The text of our entry
 * @param   boolean Dry-Run, without performing trackbacks?
 * @return
 */
function serendipity_handle_references($id, $author, $title, $text, $dry_run = false)
{
    global $serendipity;
    static $old_references = array();
    static $saved_references = array();
    static $saved_urls = array();
    if (is_object($serendipity['logger'])) {
        $serendipity['logger']->debug("serendipity_handle_references");
    }
    if ($dry_run) {
        // Store the current list of references. We might need to restore them for later user.
        $old_references = serendipity_db_query("SELECT * FROM {$serendipity['dbPrefix']}references WHERE (type = '' OR type IS NULL) AND entry_id = " . (int) $id, false, 'assoc');
        if (is_string($old_references)) {
            if (is_object($serendipity['logger'])) {
                $serendipity['logger']->debug($old_references);
            }
        }
        if (is_array($old_references) && count($old_references) > 0) {
            $current_references = array();
            foreach ($old_references as $idx => $old_reference) {
                // We need the current reference ID to restore it later.
                $saved_references[$old_reference['link'] . $old_reference['name']] = $current_references[$old_reference['link'] . $old_reference['name']] = $old_reference;
                $saved_urls[$old_reference['link']] = true;
            }
        }
        if (is_object($serendipity['logger'])) {
            $serendipity['logger']->debug("Got references in dry run: " . print_r($current_references, true));
        }
    } else {
        // A dry-run was called previously and restorable references are found. Restore them now.
        $del = serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}references WHERE (type = '' OR type IS NULL) AND entry_id = " . (int) $id);
        if (is_string($del)) {
            if (is_object($serendipity['logger'])) {
                $serendipity['logger']->debug($del);
            }
        }
        if (is_object($serendipity['logger'])) {
            $serendipity['logger']->debug("Deleted references");
        }
        if (is_array($old_references) && count($old_references) > 0) {
            $current_references = array();
            foreach ($old_references as $idx => $old_reference) {
                // We need the current reference ID to restore it later.
                $current_references[$old_reference['link'] . $old_reference['name']] = $old_reference;
                $q = serendipity_db_insert('references', $old_reference, 'show');
                $cr = serendipity_db_query($q);
                if (is_string($cr)) {
                    if (is_object($serendipity['logger'])) {
                        $serendipity['logger']->debug($cr);
                    }
                }
            }
        }
        if (is_object($serendipity['logger'])) {
            $serendipity['logger']->debug("Got references in final run:" . print_r($current_references, true));
        }
    }
    if (!preg_match_all('@<a[^>]+?href\\s*=\\s*["\']?([^\'" >]+?)[ \'"][^>]*>(.+?)</a>@i', $text, $matches)) {
        $matches = array(0 => array(), 1 => array());
    } else {
        // remove full matches
        array_shift($matches);
    }
    // Make trackback URL
    $url = serendipity_archiveURL($id, $title, 'baseURL');
    // Make sure that the trackback-URL does not point to https
    $url = str_replace('https://', 'http://', $url);
    // Add URL references
    $locations = $matches[0];
    $names = $matches[1];
    $checked_locations = array();
    serendipity_plugin_api::hook_event('backend_trackbacks', $locations);
    for ($i = 0, $j = count($locations); $i < $j; ++$i) {
        if (is_object($serendipity['logger'])) {
            $serendipity['logger']->debug("Checking {$locations[$i]}...");
        }
        if ($locations[$i][0] == '/') {
            $locations[$i] = 'http' . (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off' ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $locations[$i];
        }
        if (isset($checked_locations[$locations[$i]])) {
            if (is_object($serendipity['logger'])) {
                $serendipity['logger']->debug("Already checked");
            }
            continue;
        }
        if (preg_match_all('@<img[^>]+?alt=["\']?([^\'">]+?)[\'"][^>]+?>@i', $names[$i], $img_alt)) {
            if (is_array($img_alt) && is_array($img_alt[0])) {
                foreach ($img_alt[0] as $alt_idx => $alt_img) {
                    // Replace all <img>s within a link with their respective ALT tag, so that references
                    // can be stored with a title.
                    $names[$i] = str_replace($alt_img, $img_alt[1][$alt_idx], $names[$i]);
                }
            }
        }
        $query = "SELECT COUNT(id) FROM {$serendipity['dbPrefix']}references\n                                  WHERE entry_id = " . (int) $id . "\n                                    AND link = '" . serendipity_db_escape_string($locations[$i]) . "'\n                                    AND (type = '' OR type IS NULL)";
        $row = serendipity_db_query($query, true, 'num');
        if (is_string($row)) {
            if (is_object($serendipity['logger'])) {
                $serendipity['logger']->debug($row);
            }
        }
        $names[$i] = strip_tags($names[$i]);
        if (empty($names[$i])) {
            if (is_object($serendipity['logger'])) {
                $serendipity['logger']->debug("Found reference {$locations[$i]} w/o name. Adding location as name");
            }
            $names[$i] = $locations[$i];
        }
        if ($row[0] > 0 && isset($saved_references[$locations[$i] . $names[$i]])) {
            if (is_object($serendipity['logger'])) {
                $serendipity['logger']->debug("Found references for {$id}, skipping rest");
            }
            continue;
        }
        if (!isset($serendipity['noautodiscovery']) || !$serendipity['noautodiscovery']) {
            if (!$dry_run) {
                if (!isset($saved_urls[$locations[$i]])) {
                    if (is_object($serendipity['logger'])) {
                        $serendipity['logger']->debug("Enabling autodiscovery");
                    }
                    serendipity_reference_autodiscover($locations[$i], $url, $author, $title, serendipity_trackback_excerpt($text));
                } else {
                    if (is_object($serendipity['logger'])) {
                        $serendipity['logger']->debug("This reference was already used before in {$id} and therefore will not be trackbacked again");
                    }
                }
            } else {
                if (is_object($serendipity['logger'])) {
                    $serendipity['logger']->debug("Dry run: Skipping autodiscovery");
                }
            }
            $checked_locations[$locations[$i]] = true;
            // Store trackbacked link so that no further trackbacks will be sent to the same link
        } else {
            if (is_object($serendipity['logger'])) {
                $serendipity['logger']->debug("Skipping full autodiscovery");
            }
        }
    }
    $del = serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}references WHERE entry_id=" . (int) $id . " AND (type = '' OR type IS NULL)");
    if (is_string($del)) {
        if (is_object($serendipity['logger'])) {
            $serendipity['logger']->debug($del);
        }
    }
    if (is_object($serendipity['logger'])) {
        $serendipity['logger']->debug("Deleted references again");
    }
    if (!is_array($old_references)) {
        $old_references = array();
    }
    $duplicate_check = array();
    for ($i = 0; $i < $j; ++$i) {
        $i_link = serendipity_db_escape_string(strip_tags($names[$i]));
        $i_location = serendipity_db_escape_string($locations[$i]);
        // No link with same description AND same text should be inserted.
        if (isset($duplicate_check[$i_location . $i_link])) {
            continue;
        }
        if (isset($current_references[$locations[$i] . $names[$i]])) {
            $query = "INSERT INTO {$serendipity['dbPrefix']}references (id, entry_id, name, link) VALUES(";
            $query .= (int) $current_references[$locations[$i] . $names[$i]]['id'] . ", " . (int) $id . ", '" . $i_link . "', '" . $i_location . "')";
            $ins = serendipity_db_query($query);
            if (is_string($ins)) {
                if (is_object($serendipity['logger'])) {
                    $serendipity['logger']->debug($ins);
                }
            }
            $duplicate_check[$locations[$i] . $names[$i]] = true;
        } else {
            $query = "INSERT INTO {$serendipity['dbPrefix']}references (entry_id, name, link) VALUES(";
            $query .= (int) $id . ", '" . $i_link . "', '" . $i_location . "')";
            $ins = serendipity_db_query($query);
            if (is_string($ins)) {
                if (is_object($serendipity['logger'])) {
                    $serendipity['logger']->debug($ins);
                }
            }
            $old_references[] = array('id' => serendipity_db_insert_id('references', 'id'), 'name' => $i_link, 'link' => $i_location, 'entry_id' => (int) $id);
            $duplicate_check[$i_location . $i_link] = true;
        }
        if (is_object($serendipity['logger'])) {
            $serendipity['logger']->debug("Current lookup for {$locations[$i]}{$names[$i]} is" . print_r($current_references[$locations[$i] . $names[$i]], true));
        }
        if (is_object($serendipity['logger'])) {
            $serendipity['logger']->debug($query);
        }
    }
    if (is_object($serendipity['logger'])) {
        $serendipity['logger']->debug(print_r($old_references, true));
    }
    // Add citations
    preg_match_all('@<cite[^>]*>([^<]+)</cite>@i', $text, $matches);
    foreach ($matches[1] as $citation) {
        $query = "INSERT INTO {$serendipity['dbPrefix']}references (entry_id, name) VALUES(";
        $query .= (int) $id . ", '" . serendipity_db_escape_string($citation) . "')";
        $cite = serendipity_db_query($query);
        if (is_string($cite)) {
            if (is_object($serendipity['logger'])) {
                $serendipity['logger']->debug($cite);
            }
        }
    }
}
 function generate_content_custom(&$title)
 {
     global $serendipity;
     $update = true;
     $rotate_time = $this->get_config('media_rotate_time');
     $next_update = $this->get_config('media_next_update', '');
     if (@(include_once "Cache/Lite.php")) {
         $cache_obj = new Cache_Lite(array('cacheDir' => $serendipity['serendipityPath'] . 'templates_c/', 'automaticSerialization' => true));
         $cache_output = $cache_obj->get('mediasidebar_cache');
     } else {
         $cache_output = $this->get_config('media_cache_output', '');
     }
     if ($rotate_time != 0) {
         if ($next_update > time()) {
             $update = false;
         } else {
             $next_update = $this->calc_update_time($rotate_time, $next_update);
             $this->set_config('media_next_update', $next_update);
         }
     }
     $title = $this->get_config('title', $this->title);
     if ($update || $cache_output == '') {
         $output_str = '';
         if ($this->get_config('media_image_strict') == 'yes') {
             $strict = true;
         } else {
             $strict = false;
         }
         if ($this->get_config('media_hotlinks_only', 'no') == 'yes') {
             $dir_extension = $this->get_config('media_hotlink_base', '');
             if ($dir_extension != '') {
                 $dir_extension = $dir_extension . '%';
             }
             $directory = "http://%" . $dir_extension;
             $strict = false;
         } else {
             $directory = $this->get_config('media_base_directory');
         }
         if (version_compare((double) $serendipity['version'], '1.1', '>=')) {
             if ($directory == 'gallery') {
                 $directory = '';
             }
             $images_all = serendipity_fetchImagesFromDatabase(0, 0, $total, false, false, $directory, '', '', array(), $strict);
         } else {
             $images_all = $this->mediasidebar_getimage($directory, $strict);
         }
         $number = $this->get_config('media_number_images');
         $total_count = count($images_all);
         if ($total_count < $number) {
             $number = $total_count;
         }
         $images = array();
         $random_check = array();
         for ($counter = 0; $counter < $number; $counter += 1) {
             $checkit = rand(0, $total_count - 1);
             while (in_array($checkit, $random_check)) {
                 $checkit = rand(0, $total_count);
             }
             $random_check[] = $checkit;
             $images[] = $images_all[$checkit];
         }
         $width_test = $this->get_config('media_fixed_width');
         if ($width_test > 0) {
             $width_str = 'width:' . $width_test . 'px;';
         }
         if (is_array($images)) {
             $output_str .= $this->get_config('media_intro');
             foreach ($images as $image) {
                 if (isset($image['name'])) {
                     if ($image['hotlink'] == 1) {
                         $thumb_path = $image_path = $image['path'];
                     } else {
                         $image_path = $serendipity['serendipityHTTPPath'] . $serendipity['uploadPath'] . $image['path'] . $image['name'] . '.' . $image['extension'];
                         $thumb_path = $serendipity['serendipityHTTPPath'] . $serendipity['uploadPath'] . $image['path'] . $image['name'] . '.' . $image['thumbnail_name'] . '.' . $image['extension'];
                         if (!serendipity_isImage($image)) {
                             $thumb_path = serendipity_getTemplateFile('admin/img/mime_unknown.png');
                             $width_str = '';
                         }
                     }
                     $output_str .= '<div style="padding-top: 5px;">';
                     switch ($this->get_config("media_linkbehavior")) {
                         case 'entry':
                             $e = $this->fetchLinkedEntries($image['id'], $image_path, $thumb_path, true);
                             if (is_array($e)) {
                                 $link = serendipity_archiveURL($e[0]['id'], $e[0]['title'], 'serendipityHTTPPath', true, array('timestamp' => $e[0]['timestamp']));
                             } else {
                                 $link = $image_path;
                             }
                             $output_str .= '<a href="' . $link . '" title="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($e[0]['title']) : htmlspecialchars($e[0]['title'], ENT_COMPAT, LANG_CHARSET)) . '"><img style="border: 0px; ' . $width_str . '" src="' . $thumb_path . '" alt="" /></a>';
                             break;
                         case 'popup':
                             $output_str .= '<a href="' . $image_path . '" onclick="F1 = window.open(\'' . $image_path . '\',\'Zoom\',\'height=' . $image['dimensions_height'] . ',width=' . $image['dimensions_width'] . ',top=298,left=354,toolbar=no,menubar=no,location=no,resize=1,resizable=1,scrollbars=yes\'); return false;"><img style="border: 0px; ' . $width_str . '" src="' . $thumb_path . '" alt="" /></a>';
                             break;
                         case 'url':
                             $output_str .= '<a href="' . $this->get_config('media_url') . '"><img style="border: 0px; ' . $width_str . '" src="' . $thumb_path . '" alt="" /></a>';
                             break;
                         case 'gallery':
                             $gallery_str = $this->get_config('media_gal_permalink');
                             if (strstr($gallery_str, '?')) {
                                 $gallery_str = $gallery_str . '&serendipity[image]=' . $image['id'];
                             } else {
                                 $gallery_str = $gallery_str . '?serendipity[image]=' . $image['id'];
                             }
                             $output_str .= '<a href="' . $gallery_str . '"><img style="border: 0px; ' . $width_str . '" src="' . $thumb_path . '" alt="" /></a>';
                             break;
                         case 'inpage':
                         default:
                             $output_str .= '<a ' . $this->get_config('media_lightbox', '') . ' href="' . $image_path . '"><img style="border: 0px; ' . $width_str . '" src="' . $thumb_path . '" alt="" /></a>';
                             break;
                     }
                     $output_str .= '</div>';
                 }
             }
             $output_str .= $this->get_config('media_summery');
         } else {
             $output_str = 'Error accessing images.';
         }
         if (class_exists('Cache_Lite') && is_object($cache_obj)) {
             $cache_obj->save($output_str, 'mediasidebar_cache');
         } else {
             $this->set_config('media_cache_output', $output_str);
         }
     } else {
         $output_str = $cache_output;
     }
     echo $output_str;
 }
/**
 * This is not a XML RPC function. metaWeblog_getPost and metaWeblog_getRecentPosts produce exactly the same structure.
 * @param unknown_type $entry
 */
function metaWeblog_createPostRpcValue($entry)
{
    global $serendipity;
    $values = array('dateCreated' => new XML_RPC_Value(XML_RPC_iso8601_encode($entry['timestamp'], $serendipity['XMLRPC_GMT']) . ($serendipity['XMLRPC_GMT'] ? 'Z' : ''), 'dateTime.iso8601'), 'postid' => new XML_RPC_Value($entry['id'], 'string'), 'userid' => new XML_RPC_Value($entry['authorid'], 'string'), 'description' => new XML_RPC_Value($entry['body'], 'string'), 'mt_excerpt' => new XML_RPC_Value('', 'string'), 'mt_allow_comments' => new XML_RPC_Value($entry['allow_comments'] ? 1 : 0, 'int'), 'mt_text_more' => new XML_RPC_Value($entry['extended'], 'string'), 'mt_allow_pings' => new XML_RPC_Value($entry['allow_comments'] ? 1 : 0, 'int'), 'mt_convert_breaks' => new XML_RPC_Value('', 'string'), 'mt_keywords' => new XML_RPC_Value(isset($entry['mt_keywords']) ? $entry['mt_keywords'] : '', 'string'), 'title' => new XML_RPC_Value($entry['title'], 'string'), 'permaLink' => new XML_RPC_Value(serendipity_archiveURL($entry['id'], $entry['title'], 'baseURL', true, array('timestamp' => $entry['timestamp'])), 'string'), 'link' => new XML_RPC_Value(serendipity_archiveURL($entry['id'], $entry['title'], 'baseURL', true, array('timestamp' => $entry['timestamp'])), 'string'));
    // Add geo coords if given:
    if (isset($entry['properties'])) {
        if (isset($entry['properties']['geo_lat']) && isset($entry['properties']['geo_long'])) {
            $geo_lat = new XML_RPC_Value(array('key' => new XML_RPC_Value('geo_latitude', 'string'), 'value' => new XML_RPC_Value($entry['properties']['geo_lat'], 'double')), 'struct');
            $geo_long = new XML_RPC_Value(array('key' => new XML_RPC_Value('geo_longitude', 'string'), 'value' => new XML_RPC_Value($entry['properties']['geo_long'], 'double')), 'struct');
            $values['custom_fields'] = new XML_RPC_Value(array($geo_lat, $geo_long), 'array');
        }
    }
    // Add Categories. metaWeblog supports names only.
    if (isset($entry['categories'])) {
        $rpc_categories = array();
        foreach ($entry['categories'] as $category) {
            $rpc_categories[] = new XML_RPC_Value($category['category_name'], 'string');
        }
        $values['categories'] = new XML_RPC_Value($rpc_categories, 'array');
    }
    if (XMLRPC_WP_COMPATIBLE) {
        $values['wp_slug'] = new XML_RPC_Value(serendipity_archiveURL($entry['id'], $entry['title'], 'baseURL', true, array('timestamp' => $entry['timestamp'])), 'string');
        $values['wp_author_id'] = new XML_RPC_Value($entry['authorid'], 'string');
        $values['wp_author_display_name'] = new XML_RPC_Value($entry['author'], 'string');
        $values['wp_post_format'] = new XML_RPC_Value('standard', 'string');
        $draft = isset($entry['isdraft']) && serendipity_db_bool($entry['isdraft']);
        $values['post_status'] = new XML_RPC_Value($draft ? 'draft' : 'publish', 'string');
        $values['date_created_gmt'] = new XML_RPC_Value(XML_RPC_iso8601_encode($entry['timestamp'], 1) . 'Z', 'dateTime.iso8601');
        $modified = empty($entry['last_modified']) ? $entry['timestamp'] : $entry['last_modified'];
        $values['date_modified'] = new XML_RPC_Value(XML_RPC_iso8601_encode($modified, 1) . 'Z', 'dateTime.iso8601');
        $values['date_modified_gmt'] = new XML_RPC_Value(XML_RPC_iso8601_encode($modified, 1) . 'Z', 'dateTime.iso8601');
        // Extended Article Properties supports passwords.
        $entry_properties = serendipity_fetchEntryProperties($entry['id']);
        if (is_array($entry_properties)) {
            $values['wp_password'] = new XML_RPC_Value($entry_properties['ep_entrypassword'], 'string');
        } else {
            $values['wp_password'] = new XML_RPC_Value('', 'string');
        }
    }
    return new XML_RPC_Value($values, 'struct');
}
 function generate_content(&$title)
 {
     global $serendipity;
     $title = $this->get_config('title', $this->title);
     $intro = $this->get_config('intro');
     $outro = $this->get_config('outro');
     $maxlength = $this->get_config('maxlength');
     $max_entries = $this->get_config('max_entries');
     $min_age = $this->get_config('min_age');
     $max_age = $this->get_config('max_age');
     $specialage = $this->get_config('specialage');
     $displaydate = $this->get_config('displaydate', 'true');
     $dateformat = $this->get_config('dateformat');
     $full = serendipity_db_bool($this->get_config('full'));
     $displayauthor = serendipity_db_bool($this->get_config('displayauthor', false));
     if (!is_numeric($min_age) || $min_age < 0 || $specialage == 'year') {
         $min_age = 365 + date('L', serendipity_serverOffsetHour());
     }
     if (!is_numeric($max_age) || $max_age < 1 || $specialage == 'year') {
         $max_age = 365 + date('L', serendipity_serverOffsetHour());
     }
     if (!is_numeric($max_entries) || $max_entries < 1) {
         $max_entries = 5;
     }
     if (!is_numeric($maxlength) || $maxlength < 0) {
         $maxlength = 30;
     }
     if (strlen($dateformat) < 1) {
         $dateformat = '%a, %d.%m.%Y %H:%M';
     }
     $oldLim = $serendipity['fetchLimit'];
     $nowts = serendipity_serverOffsetHour();
     $maxts = mktime(23, 59, 59, date('m', $nowts), date('d', $nowts), date('Y', $nowts));
     $mints = mktime(0, 0, 0, date('m', $nowts), date('d', $nowts), date('Y', $nowts));
     $e = serendipity_fetchEntries(array($mints - $max_age * 86400, $maxts - $min_age * 86400), $full, $max_entries);
     $serendipity['fetchLimit'] = $oldLim;
     echo empty($intro) ? '' : '<div class="serendipity_history_intro">' . $intro . '</div>' . "\n";
     if (!is_array($e)) {
         return false;
     }
     if (($e_c = count($e)) == 0) {
         return false;
     }
     for ($x = 0; $x < $e_c; $x++) {
         $url = serendipity_archiveURL($e[$x]['id'], $e[$x]['title'], 'serendipityHTTPPath', true, array('timestamp' => $e[$x]['timestamp']));
         $date = $displaydate == '0' ? '' : serendipity_strftime($dateformat, $e[$x]['timestamp']);
         $author = $displayauthor ? $e[$x]['author'] . ': ' : '';
         echo '<div class="serendipity_history_info">';
         if ($displayauthor) {
             echo '<span class="serendipity_history_author">' . $author . ' </span>';
         }
         if ($displaydate) {
             echo '<span class="serendipity_history_date">' . $date . ' </span>';
         }
         $t = $maxlength == 0 || strlen($e[$x]['title']) <= $maxlength ? $e[$x]['title'] : trim(serendipity_mb('substr', $e[$x]['title'], 0, $maxlength - 3)) . ' [...]';
         echo '<a href="' . $url . '" title="' . str_replace("'", "`", serendipity_specialchars($e[$x]['title'])) . '">"' . serendipity_specialchars($t) . '"</a></div>';
         if ($full) {
             echo '<div class="serendipity_history_body">' . strip_tags($e[$x]['body']) . '</div>';
         }
     }
     echo empty($outro) ? '' : '<div class="serendipity_history_outro">' . $outro . '</div>';
 }
 function generateSitemap(&$bag)
 {
     global $serendipity;
     // decide which NULL-function to use
     switch ($serendipity['dbType']) {
         case 'postgres':
             $sqlnullfunction = 'COALESCE';
             break;
         case 'sqlite':
         case 'mysql':
         case 'mysqli':
             $sqlnullfunction = 'IFNULL';
             break;
         default:
             $sqlnullfunction = '';
     }
     $hooks =& $bag->get('event_hooks');
     $do_pingback = serendipity_db_bool($this->get_config('sitemap_pingback', false));
     $pingback_url = $this->get_config('sitemap_pingback_urls', false);
     // start the xml
     $sitemap_xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
     $sitemap_xml .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n";
     $sitemap_xml .= "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
     $sitemap_xml .= "\txsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\n";
     $sitemap_xml .= "\t\t\thttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n";
     // add link to the main page
     $this->addtoxml($sitemap_xml, $serendipity['baseURL'], time(), 0.6);
     // fetch all entries from the db (tested with: mysql, sqlite, postgres)
     $entries = serendipity_db_query('SELECT
                             entries.id AS id,
                             entries.title AS title,
                             ' . $sqlnullfunction . '(entries.last_modified,0) AS timestamp_1,
                             ' . $sqlnullfunction . '(MAX(comments.timestamp),0) AS timestamp_2
                         FROM ' . $serendipity['dbPrefix'] . 'entries entries
                         LEFT JOIN ' . $serendipity['dbPrefix'] . 'comments comments
                         ON entries.id = comments.entry_id
                         WHERE entries.isdraft = \'false\'
                         GROUP BY entries.id, entries.title, entries.last_modified
                         ORDER BY entries.id', false, 'assoc');
     if (is_array($entries)) {
         // add entries
         foreach ($entries as $entry) {
             $max = max($entry['timestamp_1'] + 0, $entry['timestamp_2'] + 0);
             $url = serendipity_archiveURL($entry['id'], $entry['title']);
             $this->addtoxml($sitemap_xml, $url, $max, 0.7);
         }
     }
     // add possible perm links
     $permlink = serendipity_db_query('SELECT entryid, timestamp, value
                          FROM ' . $serendipity['dbPrefix'] . 'entryproperties AS entryproperties,
                               ' . $serendipity['dbPrefix'] . 'entries AS entries
                          WHERE entryproperties.property = \'permalink\'
                                AND entries.id=entryproperties.entryid', false, 'assoc');
     if (is_array($permlink)) {
         foreach ($permlink as $cur) {
             $path_quoted = preg_quote($serendipity['serendipityHTTPPath'], '#');
             $url = $serendipity['baseURL'] . preg_replace("#{$path_quoted}#", '', $cur['value'], 1);
             $cur_time = $cur['timestamp'] == 0 ? null : (int) $cur['timestamp'];
             $this->addtoxml($sitemap_xml, $url, $cur_time, 0.8);
         }
         // check for the right order of plugins
         $order = serendipity_db_query('SELECT name, sort_order
                          FROM ' . $serendipity['dbPrefix'] . 'plugins plugins
                          WHERE plugins.name LIKE \'%serendipity_event_mobile_output%\'
                             OR plugins.name LIKE \'%serendipity_event_custom_permalinks%\'
                          ORDER BY plugins.sort_order', false, 'assoc');
         if (is_array($order)) {
             if (strpos($order[0]['name'], 'serendipity_event_custom_permalinks') === FALSE) {
                 echo '<br/>' . PLUGIN_EVENT_MOBILE_OUTPUT_SITEMAP_PERMALINK_WARNING . '<br/>';
             }
         }
     }
     // fetch categories and their last entry date (tested with: mysql, sqlite, postgres)
     $q = 'SELECT
                             category.categoryid AS id,
                             category_name,
                             category_description,
                             MAX(entries.last_modified) AS last_mod
                         FROM
                             ' . $serendipity['dbPrefix'] . 'category category,
                             ' . $serendipity['dbPrefix'] . 'entrycat entrycat,
                             ' . $serendipity['dbPrefix'] . 'entries entries
                         WHERE
                             category.categoryid = entrycat.categoryid
                             AND
                             entrycat.entryid = entries.id
                         GROUP BY
                             category.categoryid,
                             category.category_name,
                             category.category_description
                         ORDER BY category.categoryid';
     $categories = serendipity_db_query($q, false, 'assoc');
     // add categories
     if (is_array($categories)) {
         foreach ($categories as $category) {
             $max = 0 + $category['last_mod'];
             /* v0.9 */
             if (version_compare((double) $serendipity['version'], '0.9', '>=')) {
                 $data = array('categoryid' => $category['id'], 'category_name' => $category['category_name'], 'category_description' => $category['category_description']);
                 $url = serendipity_categoryURL($data);
             } else {
                 $url = serendipity_rewriteURL(PATH_CATEGORIES . '/' . serendipity_makePermalink(PERM_CATEGORIES, array('id' => $category['id'], 'title' => $category['category_name'])));
             }
             $this->addtoxml($sitemap_xml, $url, $max, 0.4);
         }
     } else {
         $categories = array();
     }
     // finish the xml
     $sitemap_xml .= "</urlset>\n";
     $do_gzip = serendipity_db_bool($this->get_config('gzip_sitemap', true));
     // decide whether to use gzip-output or not
     if ($do_gzip && function_exists('gzencode')) {
         $filename = '/mobile_sitemap.xml.gz';
         $temp = gzencode($sitemap_xml);
         // only use the compressed data and filename if no error occured
         if (!($temp === FALSE)) {
             $sitemap_xml = $temp;
         } else {
             $filename = '/mobile_sitemap.xml';
         }
     } else {
         $filename = '/mobile_sitemap.xml';
     }
     // write result to file
     $outfile = fopen($serendipity['serendipityPath'] . $filename, 'w');
     if ($outfile === false) {
         echo '<strong>' . PLUGIN_EVENT_MOBILE_OUTPUT_SITEMAP_FAILEDOPEN . '</strong>';
         return false;
     }
     flock($outfile, LOCK_EX);
     fputs($outfile, $sitemap_xml);
     flock($outfile, LOCK_UN);
     fclose($outfile);
     // Walk through the list of pingback-URLs
     foreach (explode(';', $pingback_url) as $cur_pingback_url) {
         $pingback_name = PLUGIN_EVENT_MOBILE_OUTPUT_SITEMAP_UNKNOWN_HOST;
         $cur_url = sprintf($cur_pingback_url, rawurlencode($serendipity['baseURL'] . $filename));
         // extract domain-portion from URL
         if (preg_match('@^https?://([^/]+)@', $cur_pingback_url, $matches) > 0) {
             $pingback_name = $matches[1];
         }
         if (!serendipity_db_bool($eventData['isdraft']) && $do_pingback && $cur_url) {
             $answer = $this->send_ping($cur_url);
             if ($answer) {
                 printf(PLUGIN_EVENT_MOBILE_OUTPUT_SITEMAP_REPORT_OK, $pingback_name);
             } else {
                 printf(PLUGIN_EVENT_MOBILE_OUTPUT_SITEMAP_REPORT_ERROR, $pingback_name, $cur_url);
             }
         } else {
             printf(PLUGIN_EVENT_MOBILE_OUTPUT_SITEMAP_REPORT_MANUAL, $pingback_name, $cur_url);
         }
     }
     return true;
 }
 function getRelatedEntriesHtml(&$entries, $extended_smarty = false)
 {
     global $serendipity;
     if (!is_array($entries)) {
         return false;
     }
     $entrylink = $serendipity['baseURL'] . ($serendipity['rewrite'] == 'none' ? $serendipity['indexFile'] . '?/' : '/');
     if ($extended_smarty) {
         $return = array();
         $return['description'] = PLUGIN_EVENT_FREETAG_RELATED_ENTRIES;
         foreach ($entries as $entryid => $title) {
             $return['entries'][] = '<a href="' . serendipity_archiveURL($entryid, $title) . '" title="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($title) : htmlspecialchars($title, ENT_COMPAT, LANG_CHARSET)) . '">' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($title) : htmlspecialchars($title, ENT_COMPAT, LANG_CHARSET)) . '</a>';
         }
     } else {
         $return = '<div class="serendipity_freeTag_related">' . PLUGIN_EVENT_FREETAG_RELATED_ENTRIES . '<ul class="plainList">';
         foreach ($entries as $entryid => $title) {
             $return .= '<li> <a href="' . serendipity_archiveURL($entryid, $title) . '" title="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($title) : htmlspecialchars($title, ENT_COMPAT, LANG_CHARSET)) . '">' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($title) : htmlspecialchars($title, ENT_COMPAT, LANG_CHARSET)) . '</a></li>';
         }
         $return .= '</ul></div>';
     }
     return $return;
 }
/**
 * 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;
}
serendipity_plugin_api::hook_event('plugin_dashboard_updater', $output, $data['curVersion']);
$data['updateButton'] = $output;
// Can be set through serendipity_config_local.inc.php
if (!isset($serendipity['dashboardCommentsLimit'])) {
    $serendipity['dashboardCommentsLimit'] = 5;
}
if (!isset($serendipity['dashboardLimit'])) {
    $serendipity['dashboardLimit'] = 5;
}
if (!isset($serendipity['dashboardDraftLimit'])) {
    $serendipity['dashboardDraftLimit'] = 5;
}
$comments = serendipity_db_query("SELECT c.*, e.title FROM {$serendipity['dbPrefix']}comments c\n                                    LEFT JOIN {$serendipity['dbPrefix']}entries e ON (e.id = c.entry_id)\n                                    ORDER BY c.id DESC LIMIT " . (int) $serendipity['dashboardCommentsLimit']);
if (is_array($comments) && count($comments) > 0) {
    foreach ($comments as &$comment) {
        $comment['entrylink'] = serendipity_archiveURL($comment['entry_id'], 'comments', 'serendipityHTTPPath', true) . '#c' . $comment['id'];
        $comment['fullBody'] = $comment['body'];
        $comment['summary'] = serendipity_mb('substr', $comment['body'], 0, 100);
        if (strlen($comment['fullBody']) > strlen($comment['summary'])) {
            $comment['excerpt'] = true;
            // When summary is not the full body, strip HTML tags from summary, as it might break and leave unclosed HTML.
            $comment['fullBody'] = nl2br(serendipity_specialchars($comment['fullBody']));
            $comment['summary'] = nl2br(strip_tags($comment['summary']));
        }
    }
}
$data['comments'] = $comments;
$entries = serendipity_fetchEntries(false, false, (int) $serendipity['dashboardLimit'], true, false, 'timestamp DESC', 'e.timestamp >= ' . serendipity_serverOffsetHour());
$entriesAmount = count($entries);
if ($entriesAmount < (int) $serendipity['dashboardDraftLimit']) {
    // there is still space for drafts
 function &getBlacklist($where, $api_key, &$eventData, &$addData)
 {
     global $serendipity;
     $ret = false;
     require_once S9Y_PEAR_PATH . 'HTTP/Request.php';
     if (function_exists('serendipity_request_start')) {
         serendipity_request_start();
     }
     // this switch statement is a leftover from blogg.de support (i.e. there were more options than just one). Leaving it in place in case we get more options again in the future.
     switch ($where) {
         case 'akismet.com':
             // DEBUG
             //$this->log($this->logfile, $eventData['id'], 'AKISMET_SAFETY', 'Akismet verification takes place', $addData);
             $ret = array();
             $data = array('blog' => $serendipity['baseURL'], 'user_agent' => $_SERVER['HTTP_USER_AGENT'], 'referrer' => $_SERVER['HTTP_REFERER'], 'user_ip' => $_SERVER['REMOTE_ADDR'] != getenv('SERVER_ADDR') ? $_SERVER['REMOTE_ADDR'] : getenv('HTTP_X_FORWARDED_FOR'), 'permalink' => serendipity_archiveURL($eventData['id'], $eventData['title'], 'serendipityHTTPPath', true, array('timestamp' => $eventData['timestamp'])), 'comment_type' => $addData['type'] == 'NORMAL' ? 'comment' : strtolower($addData['type']), 'comment_author' => $addData['name'], 'comment_author_email' => $addData['email'], 'comment_author_url' => $addData['url'], 'comment_content' => $addData['comment']);
             $this->akismetRequest($api_key, $data, $ret);
             break;
         default:
             break;
     }
     if (function_exists('serendipity_request_end')) {
         serendipity_request_end();
     }
     return $ret;
 }
/**
 * Create a link that can be used within a RSS feed to indicate a permalink for an entry or comment
 *
 * @access public
 * @param   array       The input entry array
 * @param   boolean     Toggle whether the link will be for a COMMENT [true] or an ENTRY [false]
 * @return  string      A permalink for the given entry
 */
function serendipity_rss_getguid($entry, $comments = false)
{
    global $serendipity;
    $id = isset($entry['entryid']) && $entry['entryid'] != '' ? $entry['entryid'] : $entry['id'];
    // When using %id%, we can make the GUID shorter and independent from the title.
    // If not using %id%, the entryid needs to be used for uniqueness.
    if (stristr($serendipity['permalinkStructure'], '%id%') !== FALSE) {
        $title = 'guid';
    } else {
        $title = $id;
    }
    $guid = serendipity_archiveURL($id, $title, 'baseURL', true, array('timestamp' => $entry['timestamp']));
    if ($comments == true) {
        $guid .= '#c' . $entry['commentid'];
    }
    return $guid;
}
Beispiel #23
0
/**
 * Shows the entry panel overview
 *
 * Shows a list of existing entries, with pagination and cookie-remember settings.
 *
 * @access public
 * @return null
 */
function serendipity_drawList()
{
    global $serendipity, $sort_order, $per_page;
    $filter_import = array('author', 'category', 'isdraft');
    $sort_import = array('perPage', 'ordermode', 'order');
    foreach ($filter_import as $f_import) {
        serendipity_restoreVar($serendipity['COOKIE']['entrylist_filter_' . $f_import], $serendipity['GET']['filter'][$f_import]);
        serendipity_JSsetCookie('entrylist_filter_' . $f_import, $serendipity['GET']['filter'][$f_import]);
    }
    foreach ($sort_import as $s_import) {
        serendipity_restoreVar($serendipity['COOKIE']['entrylist_sort_' . $s_import], $serendipity['GET']['sort'][$s_import]);
        serendipity_JSsetCookie('entrylist_sort_' . $s_import, $serendipity['GET']['sort'][$s_import]);
    }
    $perPage = !empty($serendipity['GET']['sort']['perPage']) ? $serendipity['GET']['sort']['perPage'] : $per_page[0];
    $page = (int) $serendipity['GET']['page'];
    $offSet = $perPage * $page;
    if (empty($serendipity['GET']['sort']['ordermode']) || $serendipity['GET']['sort']['ordermode'] != 'ASC') {
        $serendipity['GET']['sort']['ordermode'] = 'DESC';
    }
    if (!empty($serendipity['GET']['sort']['order']) && !empty($sort_order[$serendipity['GET']['sort']['order']])) {
        $orderby = serendipity_db_escape_string($serendipity['GET']['sort']['order'] . ' ' . $serendipity['GET']['sort']['ordermode']);
    } else {
        $orderby = 'timestamp ' . serendipity_db_escape_string($serendipity['GET']['sort']['ordermode']);
    }
    $filter = array();
    if (!empty($serendipity['GET']['filter']['author'])) {
        $filter[] = "e.authorid = '" . serendipity_db_escape_string($serendipity['GET']['filter']['author']) . "'";
    }
    if (!empty($serendipity['GET']['filter']['category'])) {
        $filter[] = "ec.categoryid = '" . serendipity_db_escape_string($serendipity['GET']['filter']['category']) . "'";
    }
    if (!empty($serendipity['GET']['filter']['isdraft'])) {
        if ($serendipity['GET']['filter']['isdraft'] == 'draft') {
            $filter[] = "e.isdraft = 'true'";
        } elseif ($serendipity['GET']['filter']['isdraft'] == 'publish') {
            $filter[] = "e.isdraft = 'false'";
        }
    }
    if (!empty($serendipity['GET']['filter']['body'])) {
        if ($serendipity['dbType'] == 'mysql') {
            $filter[] = "MATCH (title,body,extended) AGAINST ('" . serendipity_db_escape_string($serendipity['GET']['filter']['body']) . "')";
            $full = true;
        }
    }
    $filter_sql = implode(' AND ', $filter);
    // Fetch the entries
    $entries = serendipity_fetchEntries(false, false, serendipity_db_limit($offSet, $perPage + 1), true, false, $orderby, $filter_sql);
    ?>
<div class="serendipity_admin_list">
<form action="?" method="get">
    <input type="hidden" name="serendipity[action]"      value="admin"      />
    <input type="hidden" name="serendipity[adminModule]" value="entries"    />
    <input type="hidden" name="serendipity[adminAction]" value="editSelect" />
    <table width="100%" class="serendipity_admin_filters">
        <tr>
            <td class="serendipity_admin_filters_headline" colspan="6"><strong><?php 
    echo FILTERS;
    ?>
</strong> - <?php 
    echo FIND_ENTRIES;
    ?>
</td>
        </tr>
        <tr>
            <td valign="top" width="80"><?php 
    echo AUTHOR;
    ?>
</td>
            <td valign="top">
                <select name="serendipity[filter][author]">
                    <option value="">--</option>
<?php 
    $users = serendipity_fetchUsers('', null, true);
    if (is_array($users)) {
        foreach ($users as $user) {
            if (isset($user['artcount']) && $user['artcount'] < 1) {
                continue;
            }
            echo '<option value="' . $user['authorid'] . '" ' . (isset($serendipity['GET']['filter']['author']) && $serendipity['GET']['filter']['author'] == $user['authorid'] ? 'selected="selected"' : '') . '>' . htmlspecialchars($user['realname']) . '</option>' . "\n";
        }
    }
    ?>
              </select> <select name="serendipity[filter][isdraft]">
                    <option value="all"><?php 
    echo COMMENTS_FILTER_ALL;
    ?>
</option>
                    <option value="draft"   <?php 
    echo isset($serendipity['GET']['filter']['isdraft']) && $serendipity['GET']['filter']['isdraft'] == 'draft' ? 'selected="selected"' : '';
    ?>
><?php 
    echo DRAFT;
    ?>
</option>
                    <option value="publish" <?php 
    echo isset($serendipity['GET']['filter']['isdraft']) && $serendipity['GET']['filter']['isdraft'] == 'publish' ? 'selected="selected"' : '';
    ?>
><?php 
    echo PUBLISH;
    ?>
</option>
                </select>
            </td>
            <td valign="top" width="80"><?php 
    echo CATEGORY;
    ?>
</td>
            <td valign="top">
                <select name="serendipity[filter][category]">
                    <option value="">--</option>
<?php 
    $categories = serendipity_fetchCategories();
    $categories = serendipity_walkRecursive($categories, 'categoryid', 'parentid', VIEWMODE_THREADED);
    foreach ($categories as $cat) {
        echo '<option value="' . $cat['categoryid'] . '"' . ($serendipity['GET']['filter']['category'] == $cat['categoryid'] ? ' selected="selected"' : '') . '>' . str_repeat('&nbsp;', $cat['depth']) . htmlspecialchars($cat['category_name']) . '</option>' . "\n";
    }
    ?>
              </select>
            </td>
            <td valign="top" width="80"><?php 
    echo CONTENT;
    ?>
</td>
            <td valign="top"><input class="input_textbox" size="10" type="text" name="serendipity[filter][body]" value="<?php 
    echo isset($serendipity['GET']['filter']['body']) ? htmlspecialchars($serendipity['GET']['filter']['body']) : '';
    ?>
" /></td>
        </tr>
        <tr>
            <td class="serendipity_admin_filters_headline" colspan="6"><strong><?php 
    echo SORT_ORDER;
    ?>
</strong></td>
        </tr>
        <tr>
            <td>
                <?php 
    echo SORT_BY;
    ?>
            </td>
            <td>
                <select name="serendipity[sort][order]">
<?php 
    foreach ($sort_order as $so_key => $so_val) {
        echo '<option value="' . $so_key . '" ' . (isset($serendipity['GET']['sort']['order']) && $serendipity['GET']['sort']['order'] == $so_key ? 'selected="selected"' : '') . '>' . $so_val . '</option>' . "\n";
    }
    ?>
              </select>
            </td>
            <td><?php 
    echo SORT_ORDER;
    ?>
</td>
            <td>
                <select name="serendipity[sort][ordermode]">
                    <option value="DESC" <?php 
    echo isset($serendipity['GET']['sort']['ordermode']) && $serendipity['GET']['sort']['ordermode'] == 'DESC' ? 'selected="selected"' : '';
    ?>
><?php 
    echo SORT_ORDER_DESC;
    ?>
</option>
                    <option value="ASC" <?php 
    echo isset($serendipity['GET']['sort']['ordermode']) && $serendipity['GET']['sort']['ordermode'] == 'ASC' ? 'selected="selected"' : '';
    ?>
><?php 
    echo SORT_ORDER_ASC;
    ?>
</option>
                </select>
            </td>
            <td><?php 
    echo ENTRIES_PER_PAGE;
    ?>
</td>
            <td>
                <select name="serendipity[sort][perPage]">
<?php 
    foreach ($per_page as $per_page_nr) {
        echo '<option value="' . $per_page_nr . '"   ' . (isset($serendipity['GET']['sort']['perPage']) && $serendipity['GET']['sort']['perPage'] == $per_page_nr ? 'selected="selected"' : '') . '>' . $per_page_nr . '</option>' . "\n";
    }
    ?>
                </select>
            </td>
        </tr>
        <tr>
            <td align="right" colspan="6"><input type="submit" name="go" value="<?php 
    echo GO;
    ?>
" class="serendipityPrettyButton input_button" /></td>
        </tr>
    </table>
    </form>

    <table class="serendipity_admin_list" cellpadding="5" width="100%">
<?php 
    if (is_array($entries)) {
        $count = count($entries);
        $qString = '?serendipity[adminModule]=entries&amp;serendipity[adminAction]=editSelect';
        foreach ((array) $serendipity['GET']['sort'] as $k => $v) {
            $qString .= '&amp;serendipity[sort][' . $k . ']=' . $v;
        }
        foreach ((array) $serendipity['GET']['filter'] as $k => $v) {
            $qString .= '&amp;serendipity[filter][' . $k . ']=' . $v;
        }
        $linkPrevious = $qString . '&amp;serendipity[page]=' . ($page - 1);
        $linkNext = $qString . '&amp;serendipity[page]=' . ($page + 1);
        ?>
        <tr>
            <td>
                <?php 
        if ($offSet > 0) {
            ?>
                    <a href="<?php 
            echo $linkPrevious;
            ?>
" class="serendipityIconLink"><img src="<?php 
            echo serendipity_getTemplateFile('admin/img/previous.png');
            ?>
" /><?php 
            echo PREVIOUS;
            ?>
</a>
                <?php 
        }
        ?>
            </td>
            <td align="right">
                <?php 
        if ($count > $perPage) {
            ?>
                    <a href="<?php 
            echo $linkNext;
            ?>
" class="serendipityIconLinkRight"><?php 
            echo NEXT;
            ?>
<img src="<?php 
            echo serendipity_getTemplateFile('admin/img/next.png');
            ?>
" /></a>
                <?php 
        }
        ?>
            </td>
        </tr>
    </table>
    <script type="text/javascript">
    function invertSelection() {
        var f = document.formMultiDelete;
        for (var i = 0; i < f.elements.length; i++) {
            if (f.elements[i].type == 'checkbox') {
                f.elements[i].checked = !(f.elements[i].checked);
            }
        }
    }
    </script>
    <form action="?" method="post" name="formMultiDelete" id="formMultiDelete">
        <?php 
        echo serendipity_setFormToken();
        ?>
        <input type="hidden" name="serendipity[action]" value="admin" />
        <input type="hidden" name="serendipity[adminModule]" value="entries" />
        <input type="hidden" name="serendipity[adminAction]" value="multidelete" />
<?php 
        // Print the entries
        $rows = 0;
        foreach ($entries as $entry) {
            $rows++;
            if ($rows > $perPage) {
                continue;
            }
            // Find out if the entry has been modified later than 30 minutes after creation
            if ($entry['timestamp'] <= $entry['last_modified'] - 60 * 30) {
                $lm = '<a href="#" title="' . LAST_UPDATED . ': ' . serendipity_formatTime(DATE_FORMAT_SHORT, $entry['last_modified']) . '" onclick="alert(this.title)"><img src="' . serendipity_getTemplateFile('admin/img/clock.png') . '" alt="*" style="border: 0px none ; vertical-align: bottom;" /></a>';
            } else {
                $lm = '';
            }
            if (!$serendipity['showFutureEntries'] && $entry['timestamp'] >= serendipity_serverOffsetHour()) {
                $entry_pre = '<a href="#" title="' . ENTRY_PUBLISHED_FUTURE . '" onclick="alert(this.title)"><img src="' . serendipity_getTemplateFile('admin/img/clock_future.png') . '" alt="*" style="border: 0px none ; vertical-align: bottom;" /></a> ';
            } else {
                $entry_pre = '';
            }
            if (serendipity_db_bool($entry['properties']['ep_is_sticky'])) {
                $entry_pre .= ' ' . STICKY_POSTINGS . ': ';
            }
            if (serendipity_db_bool($entry['isdraft'])) {
                $entry_pre .= ' ' . DRAFT . ': ';
            }
            ?>
<!--            <div class="serendipity_admin_list_item serendipity_admin_list_item_<?php 
            echo $rows % 2 ? 'even' : 'uneven';
            ?>
"> -->
            <div class="serendipity_admin_list_item serendipity_admin_list_item_<?php 
            echo $rows % 2 ? 'even' : 'uneven';
            ?>
">

                <table width="100%" cellspacing="0" cellpadding="3">
                    <tr>
                        <td>
                            <strong><?php 
            echo $entry_pre;
            ?>
<a href="?serendipity[action]=admin&amp;serendipity[adminModule]=entries&amp;serendipity[adminAction]=edit&amp;serendipity[id]=<?php 
            echo $entry['id'];
            ?>
" title="#<?php 
            echo $entry['id'];
            ?>
"><?php 
            echo serendipity_truncateString(htmlspecialchars($entry['title']), 50);
            ?>
</a></strong>
                        </td>
                        <td align="right">
                            <?php 
            echo serendipity_formatTime(DATE_FORMAT_SHORT, $entry['timestamp']) . ' ' . $lm;
            ?>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <?php 
            echo POSTED_BY . ' ' . htmlspecialchars($entry['author']);
            if (count($entry['categories'])) {
                echo ' ' . IN . ' ';
                $cats = array();
                foreach ($entry['categories'] as $cat) {
                    $caturl = serendipity_categoryURL($cat);
                    $cats[] = '<a href="' . $caturl . '">' . htmlspecialchars($cat['category_name']) . '</a>';
                }
                echo implode(', ', $cats);
            }
            $entry['link'] = serendipity_archiveURL($entry['id'], $entry['title'], 'serendipityHTTPPath', true, array('timestamp' => $entry['timestamp']));
            $entry['preview_link'] = '?serendipity[noBanner]=true&amp;serendipity[noSidebar]=true&amp;serendipity[action]=admin&amp;serendipity[adminModule]=entries&amp;serendipity[adminAction]=preview&amp;serendipity[id]=' . $entry['id'];
            ?>

                        </td>
                        <td align="right">
                            <?php 
            if (serendipity_db_bool($entry['isdraft']) || !$serendipity['showFutureEntries'] && $entry['timestamp'] >= serendipity_serverOffsetHour()) {
                ?>
                            <a target="_blank" href="<?php 
                echo $entry['preview_link'];
                ?>
" title="<?php 
                echo PREVIEW . ' #' . $entry['id'];
                ?>
" class="serendipityIconLink"><img src="<?php 
                echo serendipity_getTemplateFile('admin/img/zoom.png');
                ?>
" alt="<?php 
                echo PREVIEW;
                ?>
" /><?php 
                echo PREVIEW;
                ?>
</a>
                            <?php 
            } else {
                ?>
                            <a target="_blank" href="<?php 
                echo $entry['link'];
                ?>
" title="<?php 
                echo VIEW . ' #' . $entry['id'];
                ?>
" class="serendipityIconLink"><img src="<?php 
                echo serendipity_getTemplateFile('admin/img/zoom.png');
                ?>
" alt="<?php 
                echo VIEW;
                ?>
" /><?php 
                echo VIEW;
                ?>
</a>
                            <?php 
            }
            ?>
                            <a href="?serendipity[action]=admin&amp;serendipity[adminModule]=entries&amp;serendipity[adminAction]=edit&amp;serendipity[id]=<?php 
            echo $entry['id'];
            ?>
" title="<?php 
            echo EDIT . ' #' . $entry['id'];
            ?>
" class="serendipityIconLink"><img src="<?php 
            echo serendipity_getTemplateFile('admin/img/edit.png');
            ?>
" alt="<?php 
            echo EDIT;
            ?>
" /><?php 
            echo EDIT;
            ?>
</a>
                            <a href="?<?php 
            echo serendipity_setFormToken('url');
            ?>
&amp;serendipity[action]=admin&amp;serendipity[adminModule]=entries&amp;serendipity[adminAction]=delete&amp;serendipity[id]=<?php 
            echo $entry['id'];
            ?>
" title="<?php 
            echo DELETE . ' #' . $entry['id'];
            ?>
" class="serendipityIconLink"><img src="<?php 
            echo serendipity_getTemplateFile('admin/img/delete.png');
            ?>
" alt="<?php 
            echo DELETE;
            ?>
" /><?php 
            echo DELETE;
            ?>
</a>
                            <input class="input_checkbox" type="checkbox" name="serendipity[multiDelete][]" value="<?php 
            echo $entry['id'];
            ?>
" />
                        </td>
                    </tr>
                </table>
            </div>
<?php 
        }
        // end entries output
        ?>
        <table class="serendipity_admin_list" cellpadding="5" width="100%">
            <tr>
                <td>
                    <?php 
        if ($offSet > 0) {
            ?>
                        <a href="<?php 
            echo $linkPrevious;
            ?>
" class="serendipityIconLink"><img src="<?php 
            echo serendipity_getTemplateFile('admin/img/previous.png');
            ?>
" /><?php 
            echo PREVIOUS;
            ?>
</a>
                    <?php 
        }
        ?>
                </td>
                <td align="right">
                    <?php 
        if ($count > $perPage) {
            ?>
                        <a href="<?php 
            echo $linkNext;
            ?>
" class="serendipityIconLinkRight"><?php 
            echo NEXT;
            ?>
<img src="<?php 
            echo serendipity_getTemplateFile('admin/img/next.png');
            ?>
" /></a>
                    <?php 
        }
        ?>
                </td>
            </tr>
        </table>

        <table class="serendipity_admin_list" cellpadding="0" width="100%">
            <tr>
                <td align="right">
                    <input type="button" name="toggle" value="<?php 
        echo INVERT_SELECTIONS;
        ?>
" onclick="invertSelection()" class="serendipityPrettyButton input_button" />
                    <input type="submit" name="toggle" value="<?php 
        echo DELETE_SELECTED_ENTRIES;
        ?>
" class="serendipityPrettyButton input_button" />
                </td>
            </tr>
        </table>
        </form>

        <div class="serendipity_admin_list_item serendipity_admin_list_item_<?php 
        echo ($rows + 1) % 2 ? 'even' : 'uneven';
        ?>
">
            <table width="100%" cellspacing="0" cellpadding="3">
                    <tr>
                        <td>
                            <form action="?" method="get">
                                <input type="hidden" name="serendipity[action]"      value="admin"      />
                                <input type="hidden" name="serendipity[adminModule]" value="entries"    />
                                <input type="hidden" name="serendipity[adminAction]" value="editSelect" />
                            <?php 
        echo EDIT_ENTRY;
        ?>
: #<input class="input_textbox" type="text" size="3" name="serendipity[id]" /> <input type="submit" name="serendipity[editSubmit]" value="<?php 
        echo GO;
        ?>
" class="serendipityPrettyButton input_button" />
                            </form>
                        </td>
                    </tr>
            </table>
        </div>
 <?php 
    } else {
        // We've got nothing
        ?>
        <tr>
            <td align="center" class="serendipityAdminMsgNote">
                <img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="<?php 
        echo serendipity_getTemplateFile('admin/img/admin_msg_note.png');
        ?>
" alt="" />
                <?php 
        echo NO_ENTRIES_TO_PRINT;
        ?>
            </td>
        </tr>
    </table>
<?php 
    }
    ?>
</div>
<?php 
}
/**
 * Parses entries to display them for RSS/Atom feeds to be passed on to generic Smarty templates
 *
 * This function searches for existing RSS feed template customizations. As long as a template
 * with the same name as the $version variable exists, it will be emitted.
 *
 * @access public
 * @see serendipity_fetchEntries(), rss.php
 * @param   array       A superarray of entries to output
 * @param   string      The version/type of a RSS/Atom feed to display (atom1_0, rss2_0 etc)
 * @param   boolean     If true, this is a comments feed. If false, it's an Entry feed.
 * @param   boolean     Indicates if this feed is a fulltext feed (true) or only excercpt (false)
 * @param   boolean     Indicates if E-Mail addresses should be shown (true) or hidden (false)
 * @return
 */
function serendipity_printEntries_rss(&$entries, $version, $comments = false, $fullFeed = false, $showMail = true)
{
    global $serendipity;
    $options = array('version' => $version, 'comments' => $comments, 'fullFeed' => $fullFeed, 'showMail' => $showMail);
    serendipity_plugin_api::hook_event('frontend_entries_rss', $entries, $options);
    if (is_array($entries)) {
        foreach ($entries as $key => $_entry) {
            $entry =& $entries[$key];
            if (isset($entry['entrytimestamp'])) {
                $e_ts = $entry['entrytimestamp'];
            } else {
                $e_ts = $entry['timestamp'];
            }
            $entry['feed_id'] = isset($entry['entryid']) && !empty($entry['entryid']) ? $entry['entryid'] : $entry['id'];
            // set feed guid only, if not already defined externaly
            if (empty($entry['feed_guid'])) {
                $entry['feed_guid'] = serendipity_rss_getguid($entry, $options['comments']);
            }
            $entry['feed_entryLink'] = serendipity_archiveURL($entry['feed_id'], $entry['title'], 'baseURL', true, array('timestamp' => $e_ts));
            if ($options['comments'] == true) {
                // Display username as part of the title for easier feed-readability
                if ($entry['type'] == 'TRACKBACK' && !empty($entry['ctitle'])) {
                    $entry['author'] .= ' - ' . $entry['ctitle'];
                }
                $entry['title'] = (!empty($entry['author']) ? $entry['author'] : ANONYMOUS) . ': ' . $entry['title'];
                // No HTML allowed here:
                $entry['body'] = strip_tags($entry['body']);
            }
            // Embed a link to extended entry, if existing
            if ($options['fullFeed']) {
                $entry['body'] .= ' ' . $entry['extended'];
                $ext = '';
            } elseif ($entry['exflag']) {
                $ext = '<br /><a href="' . $entry['feed_entryLink'] . '#extended">' . sprintf(VIEW_EXTENDED_ENTRY, htmlspecialchars($entry['title'])) . '</a>';
            } else {
                $ext = '';
            }
            $addData = array('from' => 'functions_entries:printEntries_rss', 'rss_options' => $options);
            serendipity_plugin_api::hook_event('frontend_display', $entry, $addData);
            // Do some relative -> absolute URI replacing magic. Replaces all HREF/SRC (<a>, <img>, ...) references to only the serendipitypath with the full baseURL URI
            // garvin: Could impose some problems. Closely watch this one.
            $entry['body'] = preg_replace('@(href|src)=("|\')(' . preg_quote($serendipity['serendipityHTTPPath']) . ')(.*)("|\')(.*)>@imsU', '\\1=\\2' . $serendipity['baseURL'] . '\\4\\2\\6>', $entry['body']);
            // jbalcorn: clean up body for XML compliance as best we can.
            $entry['body'] = xhtml_cleanup($entry['body']);
            // extract author information
            if (isset($entry['no_email']) && $entry['no_email'] || $options['showMail'] === FALSE) {
                $entry['email'] = '*****@*****.**';
                // RSS Feeds need an E-Mail address!
            } elseif (empty($entry['email'])) {
                $query = "select email FROM {$serendipity['dbPrefix']}authors WHERE authorid = '" . serendipity_db_escape_string($entry['authorid']) . "'";
                $results = serendipity_db_query($query);
                $entry['email'] = $results[0]['email'];
            }
            if (!is_array($entry['categories'])) {
                $entry['categories'] = array(0 => array('category_name' => $entry['category_name'], 'feed_category_name' => serendipity_utf8_encode(htmlspecialchars($entry['category_name'])), 'categoryURL' => serendipity_categoryURL($entry, 'baseURL')));
            } else {
                foreach ($entry['categories'] as $cid => $_cat) {
                    $cat =& $entry['categories'][$cid];
                    $cat['categoryURL'] = serendipity_categoryURL($cat, 'baseURL');
                    $cat['feed_category_name'] = serendipity_utf8_encode(htmlspecialchars($cat['category_name']));
                }
            }
            // Prepare variables
            // 1. UTF8 encoding + htmlspecialchars.
            $entry['feed_title'] = serendipity_utf8_encode(htmlspecialchars($entry['title']));
            $entry['feed_blogTitle'] = serendipity_utf8_encode(htmlspecialchars($serendipity['blogTitle']));
            $entry['feed_title'] = serendipity_utf8_encode(htmlspecialchars($entry['title']));
            $entry['feed_author'] = serendipity_utf8_encode(htmlspecialchars($entry['author']));
            $entry['feed_email'] = serendipity_utf8_encode(htmlspecialchars($entry['email']));
            // 2. gmdate
            $entry['feed_timestamp'] = gmdate('Y-m-d\\TH:i:s\\Z', serendipity_serverOffsetHour($entry['timestamp']));
            $entry['feed_last_modified'] = gmdate('Y-m-d\\TH:i:s\\Z', serendipity_serverOffsetHour($entry['last_modified']));
            $entry['feed_timestamp_r'] = date('r', serendipity_serverOffsetHour($entry['timestamp']));
            // 3. UTF8 encoding
            $entry['feed_body'] = serendipity_utf8_encode($entry['body']);
            $entry['feed_ext'] = serendipity_utf8_encode($ext);
            $entry_hook = 'frontend_display:unknown:per-entry';
            switch ($version) {
                case 'opml1.0':
                    $entry_hook = 'frontend_display:opml-1.0:per_entry';
                    break;
                case '0.91':
                    $entry_hook = 'frontend_display:rss-0.91:per_entry';
                    break;
                case '1.0':
                    $entry_hook = 'frontend_display:rss-1.0:per_entry';
                    break;
                case '2.0':
                    $entry_hook = 'frontend_display:rss-2.0:per_entry';
                    break;
                case 'atom0.3':
                    $entry_hook = 'frontend_display:atom-0.3:per_entry';
                    break;
                case 'atom1.0':
                    $entry_hook = 'frontend_display:atom-1.0:per_entry';
                    break;
            }
            serendipity_plugin_api::hook_event($entry_hook, $entry);
            $entry['per_entry_display_dat'] = $entry['display_dat'];
        }
    }
}
 function generate_content(&$title)
 {
     global $serendipity;
     $number = $this->get_config('number');
     $dateformat = $this->get_config('dateformat');
     $category = $this->get_config('category', 'none');
     $show_where = $this->get_config('show_where', 'both');
     if ($show_where == 'extended' && (!isset($serendipity['GET']['id']) || !is_numeric($serendipity['GET']['id']))) {
         return false;
     } else {
         if ($show_where == 'overview' && isset($serendipity['GET']['id']) && is_numeric($serendipity['GET']['id'])) {
             return false;
         }
     }
     if ($category == '_cur') {
         $category = $serendipity['GET']['category'];
         if (empty($category) && !empty($serendipity['GET']['id'])) {
             $entry = serendipity_fetchEntry('id', $serendipity['GET']['id']);
             $category = $entry['categories'][0]['categoryid'];
         }
     }
     $title = $this->get_config('title', $this->title);
     $number_from_sw = $this->get_config('number_from');
     $randomize = $this->get_config('randomize') == "yes" ? true : false;
     $sql_condition = array();
     $sql_condition['joins'] = '';
     $sql_condition['and'] = '';
     if ($category != 'none' && !empty($category)) {
         $sql_categories = array();
         if (is_numeric($category)) {
             $sql_categories[] = $category;
         } else {
             $sql_categories = explode('^', $category);
         }
         $category_parts = array();
         foreach ($sql_categories as $sql_category) {
             $category_parts[] = "\n" . implode(' AND ', serendipity_fetchCategoryRange($sql_category));
         }
         $sql_condition['and'] .= ' AND (c.category_left BETWEEN ' . implode(' OR c.category_left BETWEEN ', $category_parts) . ')';
     }
     if (!$number || !is_numeric($number) || $number < 1) {
         $number = 10;
     }
     $sql_number = serendipity_db_limit_sql($number);
     $db = $serendipity['dbType'];
     switch ($number_from_sw) {
         case 'skip':
             $sql_number = serendipity_db_limit_sql(serendipity_db_limit($serendipity['fetchLimit'], $number));
             break;
     }
     if (!$dateformat || strlen($dateformat) < 1) {
         $dateformat = '%A, %B %e %Y';
     }
     if ($randomize) {
         if ($db == 'mysql' || $db == 'mysqli') {
             $sql_order = "ORDER BY RAND()";
         } else {
             // SQLite and PostgreSQL support this, hooray.
             $sql_order = "ORDER BY RANDOM()";
         }
     } else {
         $sql_order = "ORDER BY timestamp DESC ";
     }
     $sql_condition['and'] .= "AND timestamp <= " . time();
     serendipity_ACL_SQL($sql_condition, $category == 'none');
     if (!stristr($sql_condition['joins'], $serendipity['dbPrefix'] . 'category')) {
         $sql_condition['joins'] = ' LEFT OUTER JOIN ' . $serendipity['dbPrefix'] . 'category AS c  ON ec.categoryid = c.categoryid ' . $sql_condition['joins'];
     }
     if (!stristr($sql_condition['joins'], $serendipity['dbPrefix'] . 'entrycat')) {
         $sql_condition['joins'] = ' LEFT OUTER JOIN ' . $serendipity['dbPrefix'] . 'entrycat AS ec ON id = ec.entryid ' . $sql_condition['joins'];
     }
     $entries_query = "SELECT DISTINCT id,\n                                title,\n                                timestamp,\n                                epm.value AS multilingual_title\n                           FROM {$serendipity['dbPrefix']}entries AS e\n                                {$sql_condition['joins']}\n\n                LEFT OUTER JOIN {$serendipity['dbPrefix']}entryproperties AS epm\n                             ON (epm.entryid = e.id AND epm.property = 'multilingual_title_" . $serendipity['lang'] . "')\n\n                          WHERE isdraft = 'false' {$sql_condition['and']}\n                                {$sql_order}\n                                {$sql_number}";
     $entries = serendipity_db_query($entries_query);
     if (is_string($entries)) {
         echo $entries . "<br />\n";
         echo $entries_query . "<br />\n";
     }
     if (isset($entries) && is_array($entries)) {
         echo '<dl>' . "\n";
         foreach ($entries as $k => $entry) {
             if (!empty($entry['multilingual_title'])) {
                 $entry['title'] = $entry['multilingual_title'];
             }
             $entryLink = serendipity_archiveURL($entry['id'], $entry['title'], 'serendipityHTTPPath', true, array('timestamp' => $entry['timestamp']));
             if (empty($entry['title'])) {
                 $entry['title'] = '#' . $entry['id'];
             }
             echo '<dt class="serendipity_recententries_entrylink"><a href="' . $entryLink . '" title="' . serendipity_specialchars($entry['title']) . '">' . serendipity_specialchars($entry['title']) . '</a></dt>' . "\n" . '<dd class="serendipity_recententries_entrydate serendipitySideBarDate">' . serendipity_specialchars(serendipity_strftime($dateformat, $entry['timestamp'])) . '</dd>' . "\n";
         }
         echo '</dl>' . "\n\n";
     }
 }
    function showElementEntrylist($filter = array(), $limit = 0)
    {
        global $serendipity;
        $filter_sql = implode(' AND ', $filter);
        $orderby = 'timestamp DESC';
        // Fetch the entries
        $entries = serendipity_fetchEntries(false, false, $limit, true, false, $orderby, $filter_sql);
        $rows = 0;
        if (!is_array($entries)) {
            return;
        }
        foreach ($entries as $entry) {
            $rows++;
            // Find out if the entry has been modified later than 30 minutes after creation
            if ($entry['timestamp'] <= $entry['last_modified'] - 60 * 30) {
                $lm = '<a href="#" title="' . LAST_UPDATED . ': ' . serendipity_formatTime(DATE_FORMAT_SHORT, $entry['last_modified']) . '" onclick="alert(this.title)"><img src="' . serendipity_getTemplateFile('admin/img/clock.png') . '" alt="*" style="border: 0px none ; vertical-align: bottom;" /></a>';
            } else {
                $lm = '';
            }
            if (!$serendipity['showFutureEntries'] && $entry['timestamp'] >= serendipity_serverOffsetHour()) {
                $entry_pre = '<a href="#" title="' . ENTRY_PUBLISHED_FUTURE . '" onclick="alert(this.title)"><img src="' . serendipity_getTemplateFile('admin/img/clock_future.png') . '" alt="*" style="border: 0px none ; vertical-align: bottom;" /></a> ';
            } else {
                $entry_pre = '';
            }
            if (serendipity_db_bool($entry['properties']['ep_is_sticky'])) {
                $entry_pre .= ' ' . STICKY_POSTINGS . ': ';
            }
            if (serendipity_db_bool($entry['isdraft'])) {
                $entry_pre .= ' ' . DRAFT . ': ';
            }
            ?>
            <div class="serendipity_admin_list_item serendipity_admin_list_item_<?php 
            echo $rows % 2 ? 'even' : 'uneven';
            ?>
">

                <table width="100%" cellspacing="0" cellpadding="3">
                    <tr>
                        <td>
                            <strong><?php 
            echo $entry_pre;
            ?>
<a href="?serendipity[action]=admin&amp;serendipity[adminModule]=entries&amp;serendipity[adminAction]=edit&amp;serendipity[id]=<?php 
            echo $entry['id'];
            ?>
" title="#<?php 
            echo $entry['id'];
            ?>
"><?php 
            echo serendipity_truncateString(function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['title']) : htmlspecialchars($entry['title'], ENT_COMPAT, LANG_CHARSET), 50);
            ?>
</a></strong>
                        </td>
                        <td align="right">
                            <?php 
            echo serendipity_formatTime(DATE_FORMAT_SHORT, $entry['timestamp']) . ' ' . $lm;
            ?>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <?php 
            echo POSTED_BY . ' ' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['author']) : htmlspecialchars($entry['author'], ENT_COMPAT, LANG_CHARSET));
            if (count($entry['categories'])) {
                echo ' ' . IN . ' ';
                $cats = array();
                foreach ($entry['categories'] as $cat) {
                    $caturl = serendipity_categoryURL($cat);
                    $cats[] = '<a href="' . $caturl . '">' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($cat['category_name']) : htmlspecialchars($cat['category_name'], ENT_COMPAT, LANG_CHARSET)) . '</a>';
                }
                echo implode(', ', $cats);
            }
            $entry['link'] = serendipity_archiveURL($entry['id'], $entry['title'], 'serendipityHTTPPath', true, array('timestamp' => $entry['timestamp']));
            $entry['preview_link'] = '?serendipity[noBanner]=true&amp;serendipity[noSidebar]=true&amp;serendipity[action]=admin&amp;serendipity[adminModule]=entries&amp;serendipity[adminAction]=preview&amp;serendipity[id]=' . $entry['id'];
            ?>

                        </td>
                        <td align="right">
                            <?php 
            if (serendipity_db_bool($entry['isdraft']) || !$serendipity['showFutureEntries'] && $entry['timestamp'] >= serendipity_serverOffsetHour()) {
                ?>
                            <a target="_blank" href="<?php 
                echo $entry['preview_link'];
                ?>
&amp;<?php 
                echo serendipity_setFormToken('url');
                ?>
" title="<?php 
                echo PREVIEW . ' #' . $entry['id'];
                ?>
" class="serendipityIconLink"><img src="<?php 
                echo serendipity_getTemplateFile('admin/img/zoom.png');
                ?>
" alt="<?php 
                echo PREVIEW;
                ?>
" /><?php 
                echo PREVIEW;
                ?>
</a>
                            <?php 
            } else {
                ?>
                            <a target="_blank" href="<?php 
                echo $entry['link'];
                ?>
" title="<?php 
                echo VIEW . ' #' . $entry['id'];
                ?>
" class="serendipityIconLink"><img src="<?php 
                echo serendipity_getTemplateFile('admin/img/zoom.png');
                ?>
" alt="<?php 
                echo VIEW;
                ?>
" /><?php 
                echo VIEW;
                ?>
</a>
                            <?php 
            }
            ?>
                            <a href="?serendipity[action]=admin&amp;serendipity[adminModule]=entries&amp;serendipity[adminAction]=edit&amp;serendipity[id]=<?php 
            echo $entry['id'];
            ?>
" title="<?php 
            echo EDIT . ' #' . $entry['id'];
            ?>
" class="serendipityIconLink"><img src="<?php 
            echo serendipity_getTemplateFile('admin/img/edit.png');
            ?>
" alt="<?php 
            echo EDIT;
            ?>
" /><?php 
            echo EDIT;
            ?>
</a>
                        </td>
                    </tr>
                </table>
            </div>
<?php 
        }
        // end entries output
    }
 function generate_content(&$title)
 {
     global $serendipity;
     $title = $this->get_config('title', $this->title);
     $max_entries = $this->get_config('max_entries');
     $max_chars = $this->get_config('max_chars');
     $wordwrap = $this->get_config('wordwrap');
     $dateformat = $this->get_config('dateformat');
     if (!$max_entries || !is_numeric($max_entries) || $max_entries < 1) {
         $max_entries = 15;
     }
     if (!$max_chars || !is_numeric($max_chars) || $max_chars < 1) {
         $max_chars = 120;
     }
     if (!$wordwrap || !is_numeric($wordwrap) || $wordwrap < 1) {
         $wordwrap = 30;
     }
     if (!$dateformat || strlen($dateformat) < 1) {
         $dateformat = '%a, %d.%m.%Y %H:%M';
     }
     $viewtype = '';
     if ($this->get_config('viewmode') == 'comments') {
         $viewtype .= ' AND co.type = \'NORMAL\'';
     } elseif ($this->get_config('viewmode') == 'trackbacks') {
         $viewtype .= ' AND (co.type = \'TRACKBACK\' OR co.type = \'PINGBACK\')';
     }
     $cond = array();
     $cond['and'] = ' AND e.isdraft = \'false\' ';
     if ($this->get_config('authorid') == 'login') {
         serendipity_ACL_SQL($cond, true);
         serendipity_plugin_api::hook_event('frontend_fetchentries', $cond, array('source' => 'entries'));
     }
     $q = 'SELECT    co.body              AS comment,
                     co.timestamp         AS stamp,
                     co.author            AS user,
                     e.title              AS subject,
                     e.timestamp          AS entrystamp,
                     e.id                 AS entry_id,
                     co.id                AS comment_id,
                     co.type              AS comment_type,
                     co.url               AS comment_url,
                     co.title             AS comment_title,
                     co.email             AS comment_email
             FROM    ' . $serendipity['dbPrefix'] . 'comments AS co,
                     ' . $serendipity['dbPrefix'] . 'entries  AS e
                     ' . $cond['joins'] . '
            WHERE    e.id = co.entry_id
              AND    NOT (co.type = \'TRACKBACK\' AND co.author = \'' . serendipity_db_escape_string($serendipity['blogTitle']) . '\' AND co.title != \'\')
              AND    co.status = \'approved\'
                     ' . $viewtype . '
                     ' . $cond['and'] . '
         ORDER BY    co.timestamp DESC
         LIMIT ' . $max_entries;
     $sql = serendipity_db_query($q);
     // echo $q;
     if ($sql && is_array($sql)) {
         foreach ($sql as $key => $row) {
             if (function_exists('mb_strimwidth')) {
                 $comment = mb_strimwidth(strip_tags($row['comment']), 0, $max_chars, " [...]", LANG_CHARSET);
             } else {
                 $comments = wordwrap(strip_tags($row['comment']), $max_chars, '@@@', 1);
                 $aComment = explode('@@@', $comments);
                 $comment = $aComment[0];
                 if (count($aComment) > 1) {
                     $comment .= ' [...]';
                 }
             }
             $showurls = $this->get_config('showurls', 'trackbacks');
             $isTrackBack = $row['comment_type'] == 'TRACKBACK' || $row['comment_type'] == 'PINGBACK';
             if ($row['comment_url'] != '' && ($isTrackBack && ($showurls == 'trackbacks' || $showurls == 'all') || !$isTrackBack && ($showurls == 'comments' || $showurls == 'all'))) {
                 /* Fix invalid cases in protocoll part */
                 $row['comment_url'] = preg_replace('@^http://@i', 'http://', $row['comment_url']);
                 $row['comment_url'] = preg_replace('@^https://@i', 'https://', $row['comment_url']);
                 if (substr($row['comment_url'], 0, 7) != 'http://' && substr($row['comment_url'], 0, 8) != 'https://') {
                     $row['comment_url'] = 'http://' . $row['comment_url'];
                 }
                 $user = '******' . htmlspecialchars(strip_tags($row['comment_url'])) . '" title="' . htmlspecialchars(strip_tags($row['comment_title'])) . '">' . htmlspecialchars(strip_tags($row['user'])) . '</a>';
             } else {
                 $user = htmlspecialchars(strip_tags($row['user']));
             }
             $user = trim($user);
             if (empty($user)) {
                 $user = PLUGIN_COMMENTS_ANONYMOUS;
             }
             if (function_exists('mb_strimwidth')) {
                 $pos = 0;
                 $parts = array();
                 $enc = LANG_CHARSET;
                 $comment_len = mb_strlen($comment, $enc);
                 while ($pos < $comment_len) {
                     $part = mb_strimwidth($comment, $pos, $wordwrap, '', $enc);
                     $pos += mb_strlen($part, $enc);
                     $parts[] = $part;
                 }
                 $comment = implode("\n", $parts);
             } else {
                 $comment = wordwrap($comment, $wordwrap, "\n", 1);
             }
             $entry = array('comment' => $comment, 'email' => $row['comment_email'], 'url' => $row['comment_url'], 'author' => $row['user']);
             // Let's help the BBCOde plugin a bit:
             if (class_exists('serendipity_event_bbcode')) {
                 $entry['comment'] = preg_replace('@((\\[.*)[\\n\\r]+(.*\\]))+@imsU', '\\2\\3', $entry['comment']);
                 $entry['comment'] = preg_replace('@((\\[.+\\].*)[\\r\\n]+(.*\\[/.+\\]))+@imsU', '\\2\\3', $entry['comment']);
             }
             $addData = array('from' => 'serendipity_plugin_comments:generate_content');
             serendipity_plugin_api::hook_event('frontend_display', $entry, $addData);
             printf('<div class="plugin_comment_wrap">' . PLUGIN_COMMENTS_ABOUT . '</div>', '<div class="plugin_comment_subject"><span class="plugin_comment_author">' . $user . '</span>', ' <a class="highlight" href="' . serendipity_archiveURL($row['entry_id'], $row['subject'], 'baseURL', true, array('timestamp' => $row['entrystamp'])) . '#c' . $row['comment_id'] . '" title="' . htmlspecialchars($row['subject']) . '">' . htmlspecialchars($row['subject']) . '</a></div>' . "\n" . '<div class="plugin_comment_date">' . htmlspecialchars(serendipity_strftime($dateformat, $row['stamp'])) . '</div>' . "\n" . '<div class="plugin_comment_body">' . strip_tags($entry['comment'], '<br /><img><a>') . '</div>' . "\n\n");
         }
     }
 }
    function event_hook($event, &$bag, &$eventData, $addData = null)
    {
        global $serendipity;
        $hooks =& $bag->get('event_hooks');
        if (isset($hooks[$event])) {
            switch ($event) {
                case 'backend_image_addform':
                    if ($serendipity['version'][0] < 2) {
                        if (class_exists('ZipArchive')) {
                            $checkedY = "";
                            $checkedN = "";
                            $this->get_config('unzipping') ? $checkedY = ' checked="checked"' : ($checkedN = ' checked="checked"');
                            ?>
            <br />
            <div>
                <strong><?php 
                            echo PLUGIN_EVENT_IMAGESELECTORPLUS_UNZIP_FILES;
                            ?>
</strong><br />
                <?php 
                            echo PLUGIN_EVENT_IMAGESELECTORPLUS_UNZIP_FILES_DESC;
                            ?>
                <div>
                    <input type="radio" class="input_radio" id="unzip_yes" name="serendipity[unzip_archives]" value="<?php 
                            echo YES;
                            ?>
"<?php 
                            echo $checkedY;
                            ?>
><label for="unzip_yes"><?php 
                            echo YES;
                            ?>
</label>
                    <input type="radio" class="input_radio" id="unzip_no" name="serendipity[unzip_archives]" value="<?php 
                            echo NO;
                            ?>
"<?php 
                            echo $checkedN;
                            ?>
><label for="unzip_no"><?php 
                            echo NO;
                            ?>
</label>
                </div>
            </div>
<?php 
                        }
                        ?>
            <br />
            <strong><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_QUICKBLOG;
                        ?>
:</strong><br />
            <em><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_QUICKBLOG_DESC;
                        ?>
</em>
            <table id="quickblog_table" style="width: 50%">
                <tr>
                    <td nowrap="nowrap"><?php 
                        echo TITLE;
                        ?>
</td>
                    <td><input class="input_textbox" name="serendipity[quickblog][title]" type="text" style="width: 90%" /></td>
                </tr>

                <tr>
                    <td nowrap="nowrap"><?php 
                        echo ENTRY_BODY;
                        ?>
</td>
                    <td><textarea name="serendipity[quickblog][body]" style="width: 90%; height: 200px"></textarea></td>
                </tr>

                <tr>
                    <td nowrap="nowrap"><?php 
                        echo CATEGORY;
                        ?>
</td>
                    <td><select name="serendipity[quickblog][category]">
                        <option value=""><?php 
                        echo NO_CATEGORY;
                        ?>
</option>
                    <?php 
                        if (is_array($cats = serendipity_fetchCategories())) {
                            $cats = serendipity_walkRecursive($cats, 'categoryid', 'parentid', VIEWMODE_THREADED);
                            foreach ($cats as $cat) {
                                echo '<option value="' . $cat['categoryid'] . '">' . str_repeat('&nbsp;', $cat['depth']) . $cat['category_name'] . '</option>' . "\n";
                            }
                        }
                        ?>
                    </select></td>
                </tr>

                <tr>
                    <td nowrap="nowrap"><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_TARGET;
                        ?>
</td>
                    <td><select id="select_image_target" name="serendipity[quickblog][target]">
                        <option value="none"<?php 
                        echo serendipity_ifRemember('target', 'none', false, 'selected');
                        ?>
><?php 
                        echo NONE;
                        ?>
</option>
                        <option value="js"<?php 
                        echo serendipity_ifRemember('target', 'js', false, 'selected');
                        ?>
><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_TARGET_JS;
                        ?>
</option>
                        <option value="plugin"<?php 
                        echo serendipity_ifRemember('target', 'plugin', false, 'selected');
                        ?>
><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_TARGET_ENTRY;
                        ?>
</option>
                        <option value="_blank"<?php 
                        echo serendipity_ifRemember('target', '_blank', false, 'selected');
                        ?>
><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_TARGET_BLANK;
                        ?>
</option>
                    </select></td>
                </tr>

                <tr>
                    <td nowrap="nowrap"><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_ASOBJECT;
                        ?>
</td>
                    <td>
                        <input type="radio" class="input_radio" id="image_yes" name="serendipity[quickblog][isobject]" value="<?php 
                        echo YES;
                        ?>
"><label for="image_yes"><?php 
                        echo YES;
                        ?>
</label>
                        <input type="radio" class="input_radio" id="image_no" name="serendipity[quickblog][isobject]" value="<?php 
                        echo NO;
                        ?>
" checked="checked"><label for="image_no"><?php 
                        echo NO;
                        ?>
</label>
                    </td>
                </tr>

                <tr>
                    <td nowrap="nowrap"><?php 
                        echo IMAGE_SIZE;
                        ?>
</td>
                    <td><input class="input_textbox" name="serendipity[quickblog][size]" value="<?php 
                        echo $serendipity['thumbSize'];
                        ?>
" type="text" style="width: 50px" /></td>
                </tr>

                <tr>
                    <td align="center" colspan="2"><br /></td>
                </tr>
            </table>
            <div>
                <em><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_IMAGE_SIZE_DESC;
                        ?>
</em>
            </div>
<?php 
                    } else {
                        ?>

        <div id="imageselectorplus">

<?php 
                        if (class_exists('ZipArchive')) {
                            $checkedY = "";
                            $checkedN = "";
                            $this->get_config('unzipping') ? $checkedY = ' checked="checked"' : ($checkedN = ' checked="checked"');
                            ?>
            <div class="clearfix radio_field">
                <h4><?php 
                            echo PLUGIN_EVENT_IMAGESELECTORPLUS_UNZIP_FILES;
                            ?>
</h4>
                <?php 
                            echo PLUGIN_EVENT_IMAGESELECTORPLUS_UNZIP_FILES_DESC;
                            ?>
                <div>
                    <input type="radio" class="input_radio" id="unzip_yes" name="serendipity[unzip_archives]" value="<?php 
                            echo YES;
                            ?>
"<?php 
                            echo $checkedY;
                            ?>
><label for="unzip_yes"><?php 
                            echo YES;
                            ?>
</label>
                    <input type="radio" class="input_radio" id="unzip_no" name="serendipity[unzip_archives]" value="<?php 
                            echo NO;
                            ?>
"<?php 
                            echo $checkedN;
                            ?>
><label for="unzip_no"><?php 
                            echo NO;
                            ?>
</label>
                </div>
            </div>
<?php 
                        }
                        ?>
            <h4><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_QUICKBLOG;
                        ?>
:</h4>
            <em><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_QUICKBLOG_DESC;
                        ?>
</em>
            <div id="quickblog_tablefield" class="clearfix">
                <div class="quickblog_form_field">
                    <label for="quickblog_titel"><?php 
                        echo TITLE;
                        ?>
</label>
                    <input id="quickblog_title" class="input_textbox" name="serendipity[quickblog][title]" type="text">
                </div>

                <div class="quickblog_textarea_field">
                    <label for="nuggets2"><?php 
                        echo ENTRY_BODY;
                        ?>
</label>
                    <textarea id="nuggets2" class="quickblog_nugget" data-tarea="nuggets2" name="serendipity[quickblog][body]" rows="10" cols="80"></textarea>
<?php 
                        if ($serendipity['wysiwyg']) {
                            $plugins = serendipity_plugin_api::enum_plugins('*', false, 'serendipity_event_nl2br');
                            ?>
                    <input name="serendipity[properties][disable_markups][]" type="hidden" value="<?php 
                            echo $plugins[0]['name'];
                            ?>
">
<?php 
                            if (!class_exists('serendipity_event_ckeditor')) {
                                ?>
                    <script src="<?php 
                                echo $serendipity['serendipityHTTPPath'];
                                ?>
htmlarea/ckeditor/ckeditor/ckeditor.js"></script>
<?php 
                            }
                            // just add a simple basic toolbar, since we cannot use embedded plugins here
                            ?>
                    <script>
                        CKEDITOR.replace( 'nuggets2',
                        {
                            toolbar : [['Format'],['Bold','Italic','Underline','Superscript','-','NumberedList','BulletedList','Outdent','Blockquote'],['JustifyBlock','JustifyCenter','JustifyRight'],['Link','Unlink'],['Source']],
                            toolbarGroups: null
                        });
                    </script>
<?php 
                        }
                        ?>
                </div>

                <div class="quickblog_form_field">
                    <label for="quickblog_select"><?php 
                        echo CATEGORY;
                        ?>
</label>
                    <select id="quickblog_select" name="serendipity[quickblog][category]">
                        <option value=""><?php 
                        echo NO_CATEGORY;
                        ?>
</option>
                    <?php 
                        if (is_array($cats = serendipity_fetchCategories())) {
                            $cats = serendipity_walkRecursive($cats, 'categoryid', 'parentid', VIEWMODE_THREADED);
                            foreach ($cats as $cat) {
                                echo '<option value="' . $cat['categoryid'] . '">' . str_repeat('&nbsp;', $cat['depth']) . $cat['category_name'] . '</option>' . "\n";
                            }
                        }
                        ?>
                    </select>
                </div>

                <div class="quickblog_form_select">
                    <label for="select_image_target"><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_TARGET;
                        ?>
</label>
                    <select id="select_image_target" name="serendipity[quickblog][target]">
                        <option value="none"<?php 
                        echo serendipity_ifRemember('target', 'none', false, 'selected');
                        ?>
><?php 
                        echo NONE;
                        ?>
</option>
                        <option value="js"<?php 
                        echo serendipity_ifRemember('target', 'js', false, 'selected');
                        ?>
><?php 
                        echo MEDIA_TARGET_JS;
                        ?>
</option>
                        <option value="plugin"<?php 
                        echo serendipity_ifRemember('target', 'plugin', false, 'selected');
                        ?>
><?php 
                        echo MEDIA_ENTRY;
                        ?>
</option>
                        <option value="_blank"<?php 
                        echo serendipity_ifRemember('target', '_blank', false, 'selected');
                        ?>
><?php 
                        echo MEDIA_TARGET_BLANK;
                        ?>
</option>
                    </select>
                </div>

                <div class="clearfix radio_field quickblog_radio_field">
                    <label><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_ASOBJECT;
                        ?>
</label>
                    <div>
                        <input type="radio" class="input_radio" id="image_yes" name="serendipity[quickblog][isobject]" value="<?php 
                        echo YES;
                        ?>
"><label for="image_yes"><?php 
                        echo YES;
                        ?>
</label>
                        <input type="radio" class="input_radio" id="image_no" name="serendipity[quickblog][isobject]" value="<?php 
                        echo NO;
                        ?>
" checked="checked"><label for="image_no"><?php 
                        echo NO;
                        ?>
</label>
                    </div>
                </div>

                <div class="quickblog_form_field">
                    <label for="quickblog_isize"><?php 
                        echo IMAGE_SIZE;
                        ?>
</label>
                    <input id="quickblog_isize" class="input_textbox" name="serendipity[quickblog][size]" value="<?php 
                        echo $serendipity['thumbSize'];
                        ?>
" type="text">
                </div>
            </div>
            <em><?php 
                        echo PLUGIN_EVENT_IMAGESELECTORPLUS_IMAGE_SIZE_DESC;
                        ?>
</em>
        </div>
<?php 
                    }
                    break;
                case 'backend_image_add':
                    global $new_media;
                    // if file is zip archive and unzipping enabled
                    // unzip file and add all images to database
                    // retrieve file type
                    $target_zip = $eventData;
                    preg_match('@(^.*/)+(.*)\\.+(\\w*)@', $target_zip, $matches);
                    $target_dir = $matches[1];
                    $basename = $matches[2];
                    $extension = $matches[3];
                    $authorid = isset($serendipity['POST']['all_authors']) && $serendipity['POST']['all_authors'] == 'true' ? '0' : $serendipity['authorid'];
                    // only if unzipping function exists, we have archive file and unzipping set to yes
                    if (class_exists('ZipArchive') && $extension == 'zip' && $serendipity['POST']['unzip_archives'] == YES) {
                        // now unzip
                        $zip = new ZipArchive();
                        $res = $zip->open($target_zip);
                        if ($res === TRUE) {
                            $files_to_unzip = array();
                            $extracted_images = array();
                            for ($i = 0; $i < $zip->numFiles; $i++) {
                                $file_to_extract = $zip->getNameIndex($i);
                                if (file_exists($target_dir . $file_to_extract)) {
                                    echo '(' . $file_to_extract . ') ' . ERROR_FILE_EXISTS_ALREADY . '<br />';
                                } else {
                                    $files_to_unzip[] = $file_to_extract;
                                    $extracted_images[] = $target_dir . $file_to_extract;
                                }
                            }
                            $zip->extractTo($target_dir, $files_to_unzip);
                            $zip->close();
                            echo PLUGIN_EVENT_IMAGESELECTORPLUS_UNZIP_OK;
                        } else {
                            echo PLUGIN_EVENT_IMAGESELECTORPLUS_UNZIP_FAILED;
                        }
                        // now proceed all unzipped images
                        foreach ($extracted_images as $target) {
                            preg_match('@(^.*/)+(.*)\\.+(\\w*)@', $target, $matches);
                            $real_dir = $matches[1];
                            $basename = $matches[2];
                            $extension = $matches[3];
                            $tfile = $basename . "." . $extension;
                            preg_match('@' . $serendipity['uploadPath'] . '(.*/)@', $target, $matches);
                            $image_directory = $matches[1];
                            // make thumbnails for new images
                            $thumbs = array(array('thumbSize' => $serendipity['thumbSize'], 'thumb' => $serendipity['thumbSuffix']));
                            serendipity_plugin_api::hook_event('backend_media_makethumb', $thumbs);
                            foreach ($thumbs as $thumb) {
                                // Create thumbnail
                                if ($created_thumbnail = serendipity_makeThumbnail($tfile, $image_directory, $thumb['thumbSize'], $thumb['thumb'])) {
                                    echo PLUGIN_EVENT_IMAGESELECTORPLUS_UNZIP_IMAGE_FROM_ARCHIVE . " - " . THUMB_CREATED_DONE . '<br />';
                                }
                            }
                            // Insert into database
                            $image_id = serendipity_insertImageInDatabase($tfile, $image_directory, $authorid, null, $realname);
                            echo PLUGIN_EVENT_IMAGESELECTORPLUS_UNZIP_IMAGE_FROM_ARCHIVE . " ({$tfile}) " . PLUGIN_EVENT_IMAGESELECTORPLUS_UNZIP_ADD_TO_DB . "<br />";
                            $new_media[] = array('image_id' => $image_id, 'target' => $target, 'created_thumbnail' => $created_thumbnail);
                        }
                    }
                case 'backend_image_addHotlink':
                    // Re-Scale thumbnails?
                    $max_scale = array('width' => (int) $this->get_config('thumb_max_width'), 'height' => (int) $this->get_config('thumb_max_height'));
                    if ($max_scale['width'] > 0 || $max_scale['height'] > 0) {
                        $this->resizeThumb($max_scale, $eventData);
                    }
                    if (empty($serendipity['POST']['quickblog']['title'])) {
                        break;
                    }
                    $file = basename($eventData);
                    $directory = str_replace($serendipity['serendipityPath'] . $serendipity['uploadPath'], '', dirname($eventData) . '/');
                    $size = (int) $serendipity['POST']['quickblog']['size'];
                    // check default Serendipity thumbSize, to make this happen like standard image uploads, and to get one "fullsize" image instance only,
                    // else create another quickblog image "resized" instance, to use as entries thumbnail image
                    if ($serendipity['thumbSize'] != $size) {
                        $oldSuffix = $serendipity['thumbSuffix'];
                        $serendipity['thumbSuffix'] = 'quickblog';
                        serendipity_makeThumbnail($file, $directory, $size);
                        $serendipity['thumbSuffix'] = $oldSuffix;
                    }
                    // Non-image object link generation
                    if ($serendipity['POST']['quickblog']['isobject'] == YES) {
                        $objfile = serendipity_parseFileName($file);
                        $filename = $objfile[0];
                        $suffix = $objfile[1];
                        $obj_mime = serendipity_guessMime($suffix);
                        $objpath = $serendipity['serendipityHTTPPath'] . $serendipity['uploadPath'] . $directory . $filename . '.' . $suffix;
                        // try to know about a working environment for imagemagicks pdf preview generation
                        if ($serendipity['magick'] === true && strtolower($suffix) == 'pdf' && $serendipity['thumbSize'] == $size) {
                            $objpreview = $serendipity['serendipityHTTPPath'] . $serendipity['uploadPath'] . $directory . $filename . '.' . $serendipity['thumbSuffix'] . '.' . $suffix . '.png';
                        } else {
                            $objpreview = serendipity_getTemplateFile('admin/img/mime_' . preg_replace('@[^0-9a-z_\\-]@i', '-', $obj_mime) . '.png');
                        }
                        if (!$objpreview || empty($objpreview)) {
                            $objpreview = serendipity_getTemplateFile('admin/img/mime_unknown.png');
                        }
                    }
                    // New draft post
                    $entry = array();
                    $entry['isdraft'] = 'false';
                    $entry['title'] = function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['quickblog']['title']) : htmlspecialchars($serendipity['POST']['quickblog']['title'], ENT_COMPAT, LANG_CHARSET);
                    if (isset($objpath) && !empty($objpath)) {
                        $entry['body'] = '<a href="' . $objpath . '"><img alt="" class="serendipity_image_left serendipity_quickblog_image" src="' . $objpreview . '">' . $filename . '</a> (-' . $obj_mime . '-)<p>' . $serendipity['POST']['quickblog']['body'] . '</p>';
                    } else {
                        $entry['body'] = '<!--quickblog:' . $serendipity['POST']['quickblog']['target'] . '|' . $eventData . '-->' . $serendipity['POST']['quickblog']['body'];
                    }
                    $entry['authorid'] = $serendipity['authorid'];
                    $entry['exflag'] = false;
                    $entry['categories'][0] = function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['POST']['quickblog']['category']) : htmlspecialchars($serendipity['POST']['quickblog']['category'], ENT_COMPAT, LANG_CHARSET);
                    #$entry['allow_comments']    = 'true'; // both disabled
                    #$entry['moderate_comments'] = 'false'; // to take default values
                    $serendipity['POST']['properties']['fake'] = 'fake';
                    $id = serendipity_updertEntry($entry);
                    break;
                case 'frontend_display':
                    // auto resizing images based on width and/or height attributes in img tag
                    if (serendipity_db_bool($this->get_config('autoresize'))) {
                        if (!empty($eventData['body'])) {
                            $eventData['body'] = $this->substituteImages($eventData['body']);
                        }
                        if (!empty($eventData['extended'])) {
                            $eventData['extended'] = $this->substituteImages($eventData['extended']);
                        }
                    }
                    if (empty($eventData['body'])) {
                        return;
                    }
                    // displaying quickblog posts
                    if (is_object($serendipity['smarty']) && preg_match('@<!--quickblog:(.+)-->@imsU', $eventData['body'], $filematch)) {
                        $eventData['body'] = $this->parse_quickblog_post($filematch[1], $eventData['body']);
                    }
                    // displaying galleries introduced by markup
                    foreach ($this->markup_elements as $temp) {
                        if (serendipity_db_bool($this->get_config($temp['name'], true)) && isset($eventData[$temp['element']]) && !$eventData['properties']['ep_disable_markup_' . $this->instance] && !isset($serendipity['POST']['properties']['disable_markup_' . $this->instance])) {
                            $element = $temp['element'];
                            $eventData[$element] = $this->media_insert($eventData[$element], $eventData);
                        }
                    }
                    return true;
                    break;
                case 'backend_entry_presave':
                    if (is_numeric($eventData['id'])) {
                        $eventData['body'] = str_replace('{{s9yisp_entryid}}', $eventData['id'], $eventData['body']);
                        $eventData['extended'] = str_replace('{{s9yisp_entryid}}', $eventData['id'], $eventData['extended']);
                        $this->gotMilk = true;
                    } else {
                        $this->cache['body'] = $eventData['body'];
                        $this->cache['extended'] = $eventData['extended'];
                    }
                    break;
                case 'backend_publish':
                case 'backend_save':
                    if ($this->gotMilk === false) {
                        $old = md5($this->cache['body']) . md5($this->cache['extended']);
                        $this->cache['body'] = str_replace('{{s9yisp_entryid}}', $eventData['id'], $this->cache['body']);
                        $this->cache['extended'] = str_replace('{{s9yisp_entryid}}', $eventData['id'], $this->cache['extended']);
                        $new = md5($this->cache['body']) . md5($this->cache['extended']);
                        if ($old != $new) {
                            serendipity_db_query("UPDATE {$serendipity['dbPrefix']}entries\n                                                     SET body     = '" . serendipity_db_escape_string($this->cache['body']) . "',\n                                                         extended = '" . serendipity_db_escape_string($this->cache['extended']) . "'\n                                                   WHERE       id = " . (int) $eventData['id']);
                        }
                    }
                    break;
                case 'entry_display':
                    if ($this->selected()) {
                        if (is_array($eventData)) {
                            $eventData['clean_page'] = true;
                            // This is important to not display an entry list!
                        } else {
                            $eventData = array('clean_page' => true);
                        }
                    }
                    break;
                case 'entries_header':
                    if (!$this->selected()) {
                        return true;
                    }
                    if ($serendipity['version'][0] > 1) {
                        return true;
                    }
                    if (!headers_sent()) {
                        header('HTTP/1.0 200');
                        header('Status: 200 OK');
                    }
                    $entry = serendipity_fetchEntry('id', $serendipity['GET']['id']);
                    $imageid = $serendipity['GET']['image'];
                    $imgsrc = '';
                    if (preg_match('@<a title="([^"]+)" id="s9yisp' . $imageid . '"></a>@imsU', $entry['body'], $imgmatch)) {
                        $imgsrc = $imgmatch[1];
                    } elseif (preg_match('@<a title="([^"]+)" id="s9yisp' . $imageid . '"></a>@imsU', $entry['extended'], $imgmatch)) {
                        $imgsrc = $imgmatch[1];
                    } else {
                        return;
                    }
                    $link = '<a href="' . serendipity_archiveURL($serendipity['GET']['id'], $entry['title'], 'baseURL', true, array('timestamp' => $entry['timestamp'])) . '#s9yisp' . $imageid . '">';
                    echo '<div class="serendipity_Entry_Date">
                             <h3 class="serendipity_date">' . serendipity_formatTime(DATE_FORMAT_ENTRY, $entry['timestamp']) . '</h3>';
                    echo '<h4 class="serendipity_title"><a href="#">' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($entry['title']) : htmlspecialchars($entry['title'], ENT_COMPAT, LANG_CHARSET)) . '</a></h4>';
                    echo '<div class="serendipity_entry"><div class="serendipity_entry_body">';
                    echo '<div class="serendipity_center">' . $link . '<!-- s9ymdb:' . $entry['id'] . ' --><img src="' . $imgsrc . '" /></a></div>';
                    echo '<br />';
                    echo $link . '&lt;&lt; ' . BACK . '</a>';
                    echo "</div>\n</div>\n</div>\n";
                    return true;
                    break;
                case 'frontend_image_add_unknown':
                case 'frontend_image_add_filenameonly':
                case 'frontend_image_selector_submit':
                case 'frontend_image_selector_more':
                case 'frontend_image_selector_imagecomment':
                case 'frontend_image_selector_imagealign':
                case 'frontend_image_selector_imagesize':
                case 'frontend_image_selector_hiddenfields':
                case 'frontend_image_selector_imagelink':
                    return true;
                    break;
                case 'css_backend':
                    if ($serendipity['version'][0] > 1) {
                        ?>

#imageselectorplus .radio_field input {
    margin: 0 0.5em;
}
#quickblog_tablefield {
   display: table-cell;
}
#uploadform .quickblog_nugget {
    margin-left: 0;
    padding: 0;
}
#quickblog_tablefield .quickblog_form_field {
    margin: .375em 0;
}
#quickblog_tablefield .quickblog_radio_field div label,
#quickblog_tablefield .radio_field label {
    padding-left: .5em;
}
#quickblog_tablefield .quickblog_form_select {
    margin-top: 0.75em;
    margin-bottom: 0.75em;
}
#quickblog_tablefield .quickblog_radio_field label {
    padding-left: 0;
}
#quickblog_tablefield .quickblog_radio_field div {
    display: inline;
}
#quickblog_tablefield .quickblog_radio_field input {
    margin-left: 0.5em;
}

<?php 
                    }
                    break;
                case 'css':
                    ?>

#content .serendipity_quickblog_image {
    border: medium none transparent;
}
.serendipity_mediainsert_gallery {
    border: 1px solid #C0C0C0;
    margin: 0px;
    overflow: auto;
    padding: 0.4em;
}

<?php 
                    break;
                case 'frontend_image_selector':
                    if ($serendipity['version'][0] < 2) {
                        $eventData['finishJSFunction'] = 'serendipity_imageSelectorPlus_done(\'' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['GET']['textarea']) : htmlspecialchars($serendipity['GET']['textarea'], ENT_COMPAT, LANG_CHARSET)) . '\')';
                    } else {
                        $eventData['finishJSFunction'] = 'serendipity.serendipity_imageSelector_done(\'' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($serendipity['GET']['textarea']) : htmlspecialchars($serendipity['GET']['textarea'], ENT_COMPAT, LANG_CHARSET)) . '\')';
                    }
                    return true;
                    break;
                default:
                    return false;
            }
        } else {
            return false;
        }
    }
/**
 * Passes the list of fetched entries from serendipity_fetchEntries() on to the Smarty layer
 *
 * This function contains all the core logic to group and prepare entries to be shown in your
 * $entries.tpl template. It groups them by date, so that you can easily loop on the set of
 * entries.
 * This function is not only used for printing all entries, but also for printing individual
 * entries.
 * Several central Event hooks are executed here for the whole page flow, like header+footer data.
 *
 * @see serendipity_fetchEntries()
 * @see serendipity_searchEntries()
 * @access public
 * @param   array       The array of entries with all of its data
 * @param   boolean     Toggle whether the extended portion of an entry is requested (via $serendipity['GET']['id'] single entry view)
 * @param   boolean     Indicates if this is a preview
 * @param   string      The name of the SMARTY block that this gets parsed into
 * @param   boolean     Indicates whether the assigned smarty variables should be parsed. When set to "return", no smarty parsing is done.
 * @param   boolean     Indicates whether to apply footer/header event hooks
 * @param   boolean     Indicates whether the pagination footer should be displayed
 * @param   mixed       Indicates whether the input $entries array is already grouped in preparation for the smarty $entries output array [TRUE], or if it shall be grouped by date [FALSE] or if a plugin hook shall be executed to modify data ['plugin']. This setting can also be superseded by a 'entry_display' hook.
 * @return
 */
function serendipity_printEntries($entries, $extended = 0, $preview = false, $smarty_block = 'ENTRIES', $smarty_fetch = true, $use_hooks = true, $use_footer = true, $use_grouped_array = false)
{
    global $serendipity;
    if ($use_hooks) {
        $addData = array('extended' => $extended, 'preview' => $preview);
        serendipity_plugin_api::hook_event('entry_display', $entries, $addData);
        if (isset($entries['clean_page']) && $entries['clean_page'] === true) {
            if ($serendipity['view'] == '404') {
                $serendipity['view'] = 'plugin';
            }
            $serendipity['smarty']->assign(array('plugin_clean_page' => true, 'view' => $serendipity['view']));
            serendipity_smarty_fetch($smarty_block, 'entries.tpl', true);
            return;
            // no display of this item
        }
    }
    // We shouldn't return here, because we want Smarty to handle the output
    if (!is_array($entries) || $entries[0] == false || !isset($entries[0]['timestamp'])) {
        $entries = array();
    }
    // A plugin executed in entry_display should be able to change the way of ordering entries. Forward-Thinking. ;)
    if (isset($entries['use_grouped_array'])) {
        $use_grouped_array = $entries['use_grouped_array'];
    }
    if ($use_grouped_array === false) {
        // Use grouping by date (default)
        $dategroup = array();
        for ($x = 0, $num_entries = count($entries); $x < $num_entries; $x++) {
            if (!empty($entries[$x]['properties']['ep_is_sticky']) && serendipity_db_bool($entries[$x]['properties']['ep_is_sticky'])) {
                $entries[$x]['is_sticky'] = true;
                $key = 'sticky';
            } else {
                $key = date('Ymd', serendipity_serverOffsetHour($entries[$x]['timestamp']));
            }
            $dategroup[$key]['date'] = $entries[$x]['timestamp'];
            $dategroup[$key]['is_sticky'] = isset($entries[$x]['is_sticky']) && serendipity_db_bool($entries[$x]['is_sticky']) ? true : false;
            $dategroup[$key]['entries'][] =& $entries[$x];
        }
    } elseif ($use_grouped_array === 'plugin') {
        // Let a plugin do the grouping
        serendipity_plugin_api::hook_event('entry_groupdata', $entries);
        $dategroup =& $entries;
    } else {
        $dategroup =& $entries;
    }
    foreach ($dategroup as $dategroup_idx => $properties) {
        foreach ($properties['entries'] as $x => $_entry) {
            if ($smarty_fetch === 'return') {
                $entry =& $dategroup[$dategroup_idx]['entries'][$x];
                // PHP4 Compat
            } else {
                // DISABLED - made problems with custom plugins
                // $entry = &$properties['entries'][$x]; // PHP4 Compat
                $entry =& $dategroup[$dategroup_idx]['entries'][$x];
                // PHP4 Compat
            }
            if (!empty($entry['properties']['ep_cache_body'])) {
                $entry['body'] =& $entry['properties']['ep_cache_body'];
                $entry['is_cached'] = true;
            }
            //--JAM: Highlight-span search terms
            if ($serendipity['action'] == 'search') {
                $searchterms = str_replace('"', '', $serendipity['GET']['searchterms']);
                $searchterms = explode($searchterms, ' ');
                foreach ($searchterms as $searchdx => $searchterm) {
                    $searchclass = "foundterm foundterm" . $searchdx;
                    $entry['body'] = str_replace($searchterm, '<span class="' . $searchclass . '">' . $searchterm . '</span>', $entry['body']);
                }
            }
            if (!empty($entry['properties']['ep_cache_extended'])) {
                $entry['extended'] =& $entry['properties']['ep_cache_extended'];
                $entry['is_cached'] = true;
            }
            if ($preview) {
                $entry['author'] = $entry['realname'];
                $entry['authorid'] = $serendipity['authorid'];
            }
            $addData = array('from' => 'functions_entries:printEntries');
            if ($entry['is_cached']) {
                $addData['no_scramble'] = true;
            }
            serendipity_plugin_api::hook_event('frontend_display', $entry, $addData);
            if ($preview) {
                $entry['author'] = $entry['realname'];
                $entry['authorid'] = $serendipity['authorid'];
            }
            $entry['author'] = htmlspecialchars($entry['author']);
            $authorData = array('authorid' => $entry['authorid'], 'username' => $entry['loginname'], 'email' => $entry['email'], 'realname' => $entry['author']);
            $entry['link'] = serendipity_archiveURL($entry['id'], $entry['title'], 'serendipityHTTPPath', true, array('timestamp' => $entry['timestamp']));
            $entry['commURL'] = serendipity_archiveURL($entry['id'], $entry['title'], 'baseURL', false, array('timestamp' => $entry['timestamp']));
            $entry['html_title'] = $entry['title'];
            $entry['title'] = htmlspecialchars($entry['title']);
            $entry['title_rdf'] = preg_replace('@-{2,}@', '-', $entry['html_title']);
            $entry['rdf_ident'] = serendipity_archiveURL($entry['id'], $entry['title_rdf'], 'baseURL', true, array('timestamp' => $entry['timestamp']));
            $entry['link_rdf'] = serendipity_rewriteURL(PATH_FEEDS . '/ei_' . $entry['id'] . '.rdf');
            $entry['title_rdf'] = htmlspecialchars($entry['title_rdf']);
            $entry['link_allow_comments'] = $serendipity['baseURL'] . 'comment.php?serendipity[switch]=enable&amp;serendipity[entry]=' . $entry['id'];
            $entry['link_deny_comments'] = $serendipity['baseURL'] . 'comment.php?serendipity[switch]=disable&amp;serendipity[entry]=' . $entry['id'];
            $entry['allow_comments'] = serendipity_db_bool($entry['allow_comments']);
            $entry['moderate_comments'] = serendipity_db_bool($entry['moderate_comments']);
            $entry['viewmode'] = $serendipity['GET']['cview'] == VIEWMODE_LINEAR ? VIEWMODE_LINEAR : VIEWMODE_THREADED;
            $entry['link_popup_comments'] = $serendipity['serendipityHTTPPath'] . 'comment.php?serendipity[entry_id]=' . $entry['id'] . '&amp;serendipity[type]=comments';
            $entry['link_popup_trackbacks'] = $serendipity['serendipityHTTPPath'] . 'comment.php?serendipity[entry_id]=' . $entry['id'] . '&amp;serendipity[type]=trackbacks';
            $entry['link_edit'] = $serendipity['baseURL'] . 'serendipity_admin.php?serendipity[action]=admin&amp;serendipity[adminModule]=entries&amp;serendipity[adminAction]=edit&amp;serendipity[id]=' . $entry['id'];
            $entry['link_trackback'] = $serendipity['baseURL'] . 'comment.php?type=trackback&amp;entry_id=' . $entry['id'];
            $entry['link_viewmode_threaded'] = $serendipity['serendipityHTTPPath'] . $serendipity['indexFile'] . '?url=' . $entry['commURL'] . '&amp;serendipity[cview]=' . VIEWMODE_THREADED;
            $entry['link_viewmode_linear'] = $serendipity['serendipityHTTPPath'] . $serendipity['indexFile'] . '?url=' . $entry['commURL'] . '&amp;serendipity[cview]=' . VIEWMODE_LINEAR;
            $entry['link_author'] = serendipity_authorURL($authorData);
            if (is_array($entry['categories'])) {
                foreach ($entry['categories'] as $k => $v) {
                    if (!isset($entry['categories'][$k]['category_link'])) {
                        $entry['categories'][$k]['category_link'] = serendipity_categoryURL($entry['categories'][$k]);
                    }
                }
            }
            if (strlen($entry['extended'])) {
                $entry['has_extended'] = true;
            }
            if (isset($entry['exflag']) && $entry['exflag'] && ($extended || $preview)) {
                $entry['is_extended'] = true;
            }
            if (serendipity_db_bool($entry['allow_comments']) || !isset($entry['allow_comments']) || $entry['comments'] > 0) {
                $entry['has_comments'] = true;
                $entry['label_comments'] = $entry['comments'] == 1 ? COMMENT : COMMENTS;
            }
            if (serendipity_db_bool($entry['allow_comments']) || !isset($entry['allow_comments']) || $entry['trackbacks'] > 0) {
                $entry['has_trackbacks'] = true;
                $entry['label_trackbacks'] = $entry['trackbacks'] == 1 ? TRACKBACK : TRACKBACKS;
            }
            if ($_SESSION['serendipityAuthedUser'] === true && ($_SESSION['serendipityAuthorid'] == $entry['authorid'] || serendipity_checkPermission('adminEntriesMaintainOthers'))) {
                $entry['is_entry_owner'] = true;
            }
            $entry['display_dat'] = '';
            serendipity_plugin_api::hook_event('frontend_display:html:per_entry', $entry);
            $entry['plugin_display_dat'] =& $entry['display_dat'];
            if ($preview) {
                ob_start();
                serendipity_plugin_api::hook_event('backend_preview', $entry);
                $entry['backend_preview'] = ob_get_contents();
                ob_end_clean();
            }
            /* IF WE ARE DISPLAYING A FULL ENTRY */
            if (isset($serendipity['GET']['id'])) {
                $comment_add_data = array('comments_messagestack' => isset($serendipity['messagestack']['comments']) ? (array) $serendipity['messagestack']['comments'] : array(), 'is_comment_added' => isset($serendipity['GET']['csuccess']) && $serendipity['GET']['csuccess'] == 'true' ? true : false, 'is_comment_moderate' => isset($serendipity['GET']['csuccess']) && $serendipity['GET']['csuccess'] == 'moderate' ? true : false);
                $serendipity['smarty']->assign($comment_add_data);
                serendipity_displayCommentForm($entry['id'], $serendipity['serendipityHTTPPath'] . $serendipity['indexFile'] . '?url=' . $entry['commURL'], true, $serendipity['POST'], true, serendipity_db_bool($entry['moderate_comments']), $entry);
            }
            // END FULL ENTRY LOGIC
        }
        // end foreach-loop (entries)
    }
    // end foreach-loop (dates)
    if (!isset($serendipity['GET']['id']) && (!isset($serendipity['hidefooter']) || $serendipity['hidefooter'] == false) && $num_entries <= $serendipity['fetchLimit'] && $use_footer) {
        serendipity_printEntryFooter();
    }
    if ($smarty_fetch === 'return') {
        return $dategroup;
    }
    $serendipity['smarty']->assign_by_ref('entries', $dategroup);
    unset($entries, $dategroup);
    if (isset($serendipity['short_archives']) && $serendipity['short_archives']) {
        serendipity_smarty_fetch($smarty_block, 'entries_summary.tpl', true);
    } elseif ($smarty_fetch == true) {
        serendipity_smarty_fetch($smarty_block, 'entries.tpl', true);
    }
}
    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;
        }
    }