/**
 * Fetches and prints a listing of comments by author
 */
function serendipity_printCommentsByAuthor()
{
    global $serendipity;
    $type = serendipity_db_escape_string($serendipity['GET']['commentMode']);
    if ($type == 'comments' || empty($type)) {
        $type = 'NORMAL';
    } elseif ($type == 'trackbacks') {
        $type = 'TRACKBACK';
    } elseif ($type == 'comments_and_trackbacks') {
        $type = '%';
    }
    if (!empty($serendipity['GET']['viewCommentAuthor'])) {
        $sql_where = " AND co.author = '" . serendipity_db_escape_string($serendipity['GET']['viewCommentAuthor']) . "'";
        $group_by = "GROUP BY co.author";
    } else {
        $sql_where = " AND 1";
        // Required fake 'where' condition
        $group_by = "";
    }
    if (!empty($serendipity['GET']['commentStartTime'])) {
        $sql_where .= " AND co.timestamp >= " . (int) $serendipity['GET']['commentStartTime'];
    }
    if (!empty($serendipity['GET']['commentEndTime'])) {
        $sql_where .= " AND co.timestamp <= " . (int) $serendipity['GET']['commentEndTime'];
    }
    if (empty($serendipity['GET']['page'])) {
        $serendipity['GET']['page'] = 1;
    }
    $sql_limit = $serendipity['fetchLimit'] * ($serendipity['GET']['page'] - 1) . ',' . $serendipity['fetchLimit'];
    $c = serendipity_fetchComments(null, $sql_limit, 'co.entry_id DESC, co.id ASC', false, $type, $sql_where);
    $entry_comments = array();
    foreach ($c as $i => $comment) {
        if (!isset($entry_comments[$comment['entry_id']])) {
            $comment['link'] = serendipity_archiveURL($comment['entry_id'], $comment['title'], 'serendipityHTTPPath', true, array('timestamp' => $comment['entrytimestamp']));
            $entry_comments[$comment['entry_id']] = $comment;
        }
        $entry_comments[$comment['entry_id']]['comments'][] = $comment;
    }
    foreach ($entry_comments as $entry_id => $_data) {
        $entry_comments[$entry_id]['tpl_comments'] =& serendipity_printComments($_data['comments'], VIEWMODE_LINEAR, 0, null, 'COMMENTS', 'comments.tpl');
    }
    $serendipity['smarty']->assign_by_ref('comments_by_authors', $entry_comments);
    if (!empty($id)) {
        $and .= " AND co.entry_id = '" . (int) $id . "'";
    }
    if (!$showAll) {
        $and .= ' AND co.status = \'approved\'';
    }
    $fc = "SELECT count(co.id) AS counter\n                                  FROM {$serendipity['dbPrefix']}comments AS co\n                                 WHERE co.entry_id > 0\n                                   AND co.type LIKE '" . $type . "'\n                                   AND co.status = 'approved' " . $sql_where . " " . $group_by;
    $cc = serendipity_db_query($fc, true, 'assoc');
    if (!isset($cc['counter'])) {
        $totalComments = 0;
    } else {
        $totalComments = $cc['counter'];
    }
    serendipity_printEntryFooter('', $totalComments);
    serendipity_smarty_fetch('ENTRIES', 'comments_by_author.tpl');
    return true;
}
/**
 * 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);
    }
}