/**
 * Inserts the trackback URL for the current entry.
 *
 * The classes "pivotx-tracklink-text" and "pivotx-tracklink-url" can be used to style
 * the output.
 */
function smarty_tracklink($params, &$smarty)
{
    global $PIVOTX;
    $vars = $smarty->get_template_vars();
    if (isset($vars['entry'])) {
        $entry = $vars['entry'];
    } else {
        debug("The tracklink tag only works for entries");
        return "";
    }
    // Initialise the IP blocklist.
    $blocklist = new IPBlock();
    // check for entry's allow_comments, blocked IP address ...
    if (isset($entry['allow_comments']) && $entry['allow_comments'] == 0 || $blocklist->isBlocked($_SERVER['REMOTE_ADDR'])) {
        return "";
    }
    $params = cleanParams($params);
    $format = getDefault($params['format'], '<p><span class="pivotx-tracklink-text">' . __('Trackback link') . ': </span>' . '<span class="pivotx-tracklink-url">%url%</span></p>');
    $tb_url = $PIVOTX['paths']['host'] . makeFileLink($entry['code'], '', '');
    $trackback = getDefault($PIVOTX['config']->get('localised_trackback_name'), "trackback");
    if ($PIVOTX['config']->get('mod_rewrite') == 0) {
        $tb_url .= "&amp;{$trackback}";
        $tb_getkey_url = $tb_url . "&amp;getkey";
    } else {
        $tb_url .= "/{$trackback}/";
        $tb_getkey_url = $tb_url . "?getkey";
    }
    if ($PIVOTX['config']->get('hardened_trackback') != 1) {
        $output = str_replace("%url%", $tb_url, $format);
    } else {
        $tb_url = "<span id=\"tbgetter_%n%\">" . __('Please enable javascript to generate a trackback url') . "</span>";
        $tb_url .= "<script type=\"text/javascript\" src=\"{$tb_getkey_url}\"></script>\n";
        $tburl_gen = "<a href=\"#\"" . " title=\"" . __('Note: The url is valid for only 15 minutes after you opened this page!') . "\"" . " onclick=\"showTBURL_%n%(\\'tbgetter_%n%\\'); return false;\">" . __('Click to view the trackback url') . "</a>";
        $tb_url .= "\n<script type=\"text/javascript\">/*<![CDATA[*/\n" . "showTBURLgen_%n%('tbgetter_%n%', '{$tburl_gen}');\n/*]]>*/</script>\n";
        $tb_url = str_replace("%n%", $entry['code'], $tb_url);
        $output = str_replace("%url%", $tb_url, $format);
    }
    return $output;
}
/**
 * Returns the Javascript code and creates the key for hardened trackbacks.
 */
function getTracbackKeyJS($uri, $date)
{
    global $PIVOTX;
    // Abort immediately if hardened trackbacks isn't enabled.
    if ($PIVOTX['config']->get('hardened_trackback') != 1) {
        exit;
    }
    // Get the entry from the DB..
    $entry = $PIVOTX['db']->read_entry($uri, $date);
    // Exit if non-existing ID supplied
    if (empty($entry['code'])) {
        debug('Entry not found');
    } else {
        $id = intval($entry['code']);
    }
    $keydir = $PIVOTX['paths']["db_path"] . "tbkeys/";
    $tburl = $PIVOTX['paths']['host'] . makeFileLink($entry['code'], '', '');
    $trackback = getDefault($PIVOTX['config']->get('localised_trackback_name'), "trackback");
    if ($PIVOTX['config']->get('mod_rewrite') == 0) {
        $tburl .= "&amp;{$trackback}&amp;key=";
    } else {
        $tburl .= "/{$trackback}/?key=";
    }
    if (!strstr($_SERVER["HTTP_REFERER"], $_SERVER["SERVER_NAME"])) {
        // Creating a bogus key
        $tbkey = md5(microtime());
        debug("hardened trackbacks: illegal request - creating bogus key");
    } else {
        makeDir($keydir);
        $tbkey = md5($PIVOTX['config']->get('server_spam_key') . $_SERVER["REMOTE_ADDR"] . $id . time());
        if (!touch($keydir . $tbkey)) {
            debug("hardened trackbacks: directory {$keydir} isn't writable - can't create key");
        } else {
            chmodFile($keydir . $tbkey);
        }
    }
    // Getting the time offset between the web and file server (if there is any)
    $offset = timeDiffWebFile($tbkey_debug);
    // delete keys older than 15 minutes
    $nNow = time();
    $handle = opendir($keydir);
    while (false !== ($file = readdir($handle))) {
        $filepath = $keydir . $file;
        if (!is_dir($filepath) && $file != "index.html") {
            $Diff = $nNow - filectime($filepath);
            if ($Diff > 60 * 15 + $offset) {
                unlink($filepath);
            }
        }
    }
    closedir($handle);
    header('Content-Type: text/javascript');
    echo <<<EOM

function showTBURL_{$entry['code']}(element_id)  {
    var element = document.getElementById(element_id);
    element.innerHTML = '<br />{$tburl}' + '{$tbkey}';
}

function showTBURLgen_{$entry['code']}(element_id, tburl_gen)  {
    var element = document.getElementById(element_id);
    element.innerHTML = tburl_gen;
}

EOM;
    exit;
}
function sendMailComment($temp_comment, $notifications = '')
{
    global $PIVOTX;
    $cat_weblogs = $PIVOTX['weblogs']->getWeblogsWithCat($PIVOTX['db']->entry['category']);
    $addr_arr = array();
    foreach ($cat_weblogs as $this_weblog) {
        if ($PIVOTX['weblogs']->get($this_weblog, 'comment_sendmail') == 1) {
            $addr_arr = array_merge($addr_arr, explode(",", $PIVOTX['weblogs']->get($this_weblog, 'comment_emailto')));
        }
    }
    // make a nice title for the mail..
    if (strlen($PIVOTX['db']->entry['title']) > 2) {
        $title = $PIVOTX['db']->entry['title'];
        $title = strip_tags($title);
    } else {
        $title = substr($PIVOTX['db']->entry['introduction'], 0, 300);
        $title = strip_tags($title);
        $title = str_replace("\n", "", $title);
        $title = str_replace("\r", "", $title);
        $title = substr($title, 0, 60);
    }
    $title = i18n_str_to_utf8($title);
    // maybe send some mail to authors..
    if (count($addr_arr) > 0) {
        $adminurl = $PIVOTX['paths']['host'] . makeAdminPageLink();
        $id = safeString($temp_comment["name"], TRUE) . "-" . formatDate($temp_comment["date"], "%ye%%month%%day%%hour24%%minute%");
        $editlink = $adminurl . "?page=comments&uid=" . $PIVOTX['db']->entry['code'];
        $approvelink = $adminurl . "?page=comments";
        //$deletelink = $adminurl."menu=moderate_comments&".urlencode($id)."=2";
        //$blocklink = $adminurl."menu=entries&func=editcomments&id=". $PIVOTX['db']->entry['code']."&blocksingle=".$temp_comment['ip'];
        $comment = $temp_comment['comment'];
        // $comment = unentify($comment);
        $body = sprintf(__('"%s" posted the following comment') . ":\n\n", unentify($temp_comment['name']));
        $body .= sprintf("%s", $comment);
        $body .= sprintf("\n\n-------------\n\n");
        $body .= sprintf(__('Name') . ": %s\n", unentify($temp_comment['name']));
        $body .= sprintf(__('IP-address') . ": %s\n", $temp_comment['ip']);
        $body .= sprintf(__('Date') . ": %s\n", $temp_comment['date']);
        $body .= trim(sprintf(__('Email') . ": %s", $temp_comment['email'])) . "\n";
        $body .= trim(sprintf(__('URL') . ": %s\n", $temp_comment['url'])) . "\n";
        $body .= sprintf("\n" . __('This is a comment on entry "%s"') . "\n", $title);
        $body .= $notifications;
        $body .= sprintf("\n-------------\n\n");
        if ($PIVOTX['config']->get('moderate_comments') == 1) {
            $body .= sprintf(__('Moderate this comment') . ":\n%s\n", $approvelink);
            // $body.=sprintf("\n".__('Delete this comment').":\n%s\n", $deletelink);
        }
        $body .= sprintf("\n%s:\n%s%s\n", __('View this entry'), $PIVOTX['paths']['host'], makeFileLink($PIVOTX['db']->entry, "", ""));
        $body .= sprintf("\n%s:\n%s%s\n", __('View this comment'), $PIVOTX['paths']['host'], makeFileLink($PIVOTX['db']->entry, "", $id));
        $body .= sprintf("\n%s:\n%s\n", __('Edit this comment'), $editlink);
        //$body.=sprintf("\n%s:\n%s\n", __('Block this IP'), $blocklink );
        $body = i18n_str_to_utf8($body);
        // pivotxMail encodes the subject and adds the needed headers for UTF-8
        $subject = sprintf(__('New comment on entry "%s"'), $title);
        $addr_arr = array_unique($addr_arr);
        foreach ($addr_arr as $addr) {
            $addr = trim($addr);
            if (pivotxMail($addr, $subject, $body, $add_header)) {
                debug("Sent Mail to {$addr} for '" . $temp_comment['name'] . "'");
            } else {
                debug("Failed sending mail to {$addr} for '" . $temp_comment['name'] . "'");
                break;
            }
        }
    }
}
Beispiel #4
0
/**
 * Get Entries/Pages with a certain Tag
 *
 * @param string $tag
 * @param integer $skip
 * @return unknown
 */
function getEntriesWithTag($tag, $skip = 0)
{
    global $PIVOTX;
    // How the entries are formated in the list
    $format_entry = "<li><a href='%link%'>%title%</a><br /><span>%excerpt%</span></li>\n";
    $filename = urlencode($tag) . '.tag';
    $tag = str_replace(" ", "+", $tag);
    if ($PIVOTX['config']->get('db_model') == "flat") {
        // Getting tags for flat files..
        if (file_exists($PIVOTX['paths']['db_path'] . "tagdata/{$filename}")) {
            $sEntriesString = file_get_contents($PIVOTX['paths']['db_path'] . "tagdata/{$filename}");
        } else {
            return "";
        }
        $aEntries = explode(",", $sEntriesString);
        rsort($aEntries);
        $aLinks = array();
        foreach ($aEntries as $nThisEntry) {
            $PIVOTX['db']->read_entry($nThisEntry);
            // Skip entries that aren't published - in case the tag index isn't up to date.
            if ($PIVOTX['db']->entry['status'] != 'publish') {
                continue;
            }
            $excerpt = makeExcerpt(parse_intro_or_body($PIVOTX['db']->entry['introduction'] . " " . $PIVOTX['db']->entry['body'], false, $PIVOTX['db']->entry['convert_lb']), 170);
            if ($PIVOTX['db']->entry["code"] != $skip) {
                $aLink = $format_entry;
                $aLink = str_replace("%link%", makeFileLink($PIVOTX['db']->entry["code"], '', ''), $aLink);
                $aLink = str_replace("%title%", $PIVOTX['db']->entry["title"], $aLink);
                $aLink = str_replace("%excerpt%", $excerpt, $aLink);
                $aLinks[] = $aLink;
            }
        }
    } else {
        // Getting tags for MySQL
        $tagtable = safeString($PIVOTX['config']->get('db_prefix') . "tags", true);
        $entriestable = safeString($PIVOTX['config']->get('db_prefix') . "entries", true);
        $pagestable = safeString($PIVOTX['config']->get('db_prefix') . "pages", true);
        // [JAN]
        // Set up DB factory
        $sqlFactory = new sqlFactory($PIVOTX['config']->get('db_model'), $PIVOTX['config']->get('db_databasename'), $PIVOTX['config']->get('db_hostname'), $PIVOTX['config']->get('db_username'), $PIVOTX['config']->get('db_password'));
        // Get a DB connection..
        $sql = $sqlFactory->getSqlInstance();
        //        $sql = new sql('mysql',
        //$PIVOTX['config']->get('db_databasename'),
        //                $PIVOTX['config']->get('db_hostname'),
        //                $PIVOTX['config']->get('db_username'),
        //                $PIVOTX['config']->get('db_password')
        //            );
        // [/JAN]
        $qry = array();
        $qry['select'] = "t.*";
        $qry['from'] = $tagtable . " AS t";
        $qry['order'] = "target_uid DESC";
        $qry['where'][] = "tag LIKE " . $sql->quote($tag);
        $qry['leftjoin'][$entriestable . " AS e"] = "t.target_uid = e.uid";
        $qry['leftjoin'][$pagestable . " AS p"] = "t.target_uid = p.uid";
        $qry['group'][] = "t.target_uid";
        $qry['group'][] = "t.contenttype";
        $sql->build_select($qry);
        $sql->query();
        //echo nl2br(htmlentities($sql->get_last_query()));
        $rows = $sql->fetch_all_rows();
        foreach ($rows as $row) {
            if ($row['contenttype'] == "entry") {
                $PIVOTX['db']->read_entry($row['target_uid']);
                // Skip entries that aren't published.
                if ($PIVOTX['db']->entry['status'] != "publish") {
                    continue;
                }
                $excerpt = makeExcerpt(parse_intro_or_body($PIVOTX['db']->entry['introduction'] . " " . $PIVOTX['db']->entry['body'], false, $PIVOTX['db']->entry['convert_lb']), 170);
                if ($PIVOTX['db']->entry["code"] != $skip) {
                    $aLink = $format_entry;
                    $aLink = str_replace("%link%", makeFileLink($PIVOTX['db']->entry["code"], '', ''), $aLink);
                    $aLink = str_replace("%title%", $PIVOTX['db']->entry["title"], $aLink);
                    $aLink = str_replace("%excerpt%", $excerpt, $aLink);
                    $aLinks[] = $aLink;
                }
            } else {
                if ($row['contenttype'] == "page") {
                    $page = $PIVOTX['pages']->getPage($row['target_uid']);
                    // Skip pages that aren't published.
                    if ($page['status'] != "publish") {
                        continue;
                    }
                    $title = $page['title'];
                    $excerpt = makeExcerpt(parse_intro_or_body($page['introduction'] . " " . $page['body'], false, $page['convert_lb']), 170);
                    $aLinks[] = "<li><a href=\"" . makePagelink($page['uri']) . "\">" . $title . "</a><br />\n{$excerpt}</li>\n";
                }
            }
        }
    }
    if (count($aLinks) > 0) {
        $sLinkList = "<ul class='taglist'>\n";
        $sLinkList .= implode("\n", $aLinks);
        $sLinkList .= "</ul>\n";
        return $sLinkList;
    } else {
        return "";
    }
}
Beispiel #5
0
/**
 * Page for the Bookmarklet.
 */
function pageBookmarklet()
{
    global $PIVOTX;
    // check if the user is logged in.
    if (!$PIVOTX['session']->isLoggedIn()) {
        pageLogin('small');
        die;
    }
    $currentuser = $PIVOTX['users']->getUser($PIVOTX['session']->currentUsername());
    $entry = array();
    if ($PIVOTX['config']->get('default_category') != "") {
        $entry['category'] = array($PIVOTX['config']->get('default_category'));
    }
    if ($PIVOTX['config']->get('default_post_status') != "") {
        $entry['status'] = $PIVOTX['config']->get('default_post_status');
    }
    $entry['link'] = makeFileLink(array('date' => date("Y-m-d-H-i-s")), "", "");
    $entry['publish_date'] = date("Y-m-d-H-i-s", strtotime('+1 month'));
    // Set some things, based on referring page..
    $entry['introduction'] = "";
    // Execute the hook, if present..
    $PIVOTX['extensions']->executeHook('begin_bookmarklet', $entry);
    if (!empty($_GET['selection'])) {
        $entry['introduction'] .= "<p>&nbsp;</p>\n\n<blockquote>\n" . $_GET['selection'] . "\n</blockquote>\n\n";
    }
    if (!empty($_GET['title'])) {
        $entry['title'] = sanitizeTitle($_GET['title']);
        $entry['introduction'] .= sprintf("<p><a href='%s'>%s</a></p>", $_GET['url'], $entry['title']);
    } else {
        $entry['introduction'] .= sprintf("<p><a href='%s'>%s</a></p>", $_GET['url'], __("link"));
    }
    $PIVOTX['extensions']->executeHook('end_bookmarklet', $entry);
    // Make sure we only show the allowed categories.. Superadmins can always
    // see and use all categories..
    $categories = $PIVOTX['categories']->getCategories();
    if ($currentuser['userlevel'] < PIVOTX_UL_SUPERADMIN) {
        $allowedcats = $PIVOTX['categories']->allowedCategories($currentuser['username']);
        foreach ($categories as $key => $value) {
            if (!in_array($value['name'], $allowedcats)) {
                unset($categories[$key]);
            }
        }
    }
    if (!isset($_POST['title'])) {
        // Show the screen..
        $PIVOTX['template']->assign('entry', $entry);
        $PIVOTX['template']->assign('categories', $categories);
        $PIVOTX['template']->assign('pivotxsession', $PIVOTX['session']->getCSRF());
        $PIVOTX['template']->assign('entryuser', $PIVOTX['users']->getUser($entry['user']));
        renderTemplate('bookmarklet_entry.tpl');
    } else {
        // Make sure the current user is properly logged in, and that the request is legitimate
        $PIVOTX['session']->checkCSRF($_POST['pivotxsession']);
        // Sanitize the $_POST into an entry we can store
        $entry = sanitizePostedEntry($entry);
        if ($PIVOTX['config']->get('allow_comments') != "") {
            $entry['allow_comments'] = $PIVOTX['config']->get('allow_comments');
        }
        $entry['user'] = $currentuser['username'];
        $PIVOTX['extensions']->executeHook('entry_edit_beforesave', $entry);
        $entry = $PIVOTX['db']->set_entry($entry);
        if ($PIVOTX['db']->save_entry(TRUE)) {
            $message = sprintf(__('Your entry "%s" was successfully saved.'), '<em>' . trimText($entry['title'], 25) . '</em>');
            $PIVOTX['extensions']->executeHook('entry_edit_aftersave', $entry);
        } else {
            $message = sprintf(__('Your entry "%s" was NOT successfully saved.'), '<em>' . trimText($entry['title'], 25) . '</em>');
            $PIVOTX['extensions']->executeHook('entry_edit_aftersave_failed', $entry);
        }
        // Remove the compiled/parsed pages from the cache.
        if ($PIVOTX['config']->get('smarty_cache')) {
            $PIVOTX['template']->clear_cache();
        }
        // Show the screen..
        $PIVOTX['template']->assign('message', $message);
        $PIVOTX['template']->assign('uid', $PIVOTX['db']->entry['uid']);
        renderTemplate('bookmarklet_menu.tpl');
    }
}
Beispiel #6
0
 /**
  * Sets the current entry to the contents of $entry - flat file
  * implementation.
  *
  * Returns the inserted entry as it got stored in the database with
  * correct code/id.
  *
  * @param array $entry The entry to be inserted
  * @return array
  */
 function set_entry($entry)
 {
     $this->entry = $entry;
     if ($this->entry['code'] == '>') {
         if (is_array($this->date_index)) {
             ksort($this->date_index);
             $max = end($this->date_index);
             $max = key($this->date_index);
             $max = $max + 1;
             $this->entry['code'] = $max;
         } else {
             $this->entry['code'] = 1;
         }
     }
     // UID also needs to be set to be consistent with the
     // data/result from the SQL db.
     $this->entry['uid'] = $this->entry['code'];
     $this->entry['link'] = makeFileLink($this->entry, '', '');
     $this->update_index();
     return $this->entry;
 }
Beispiel #7
0
 /**
  * Read a bunch of entries
  *
  * @param array $params
  * @return array
  */
 function read_entries($params)
 {
     global $PIVOTX;
     $qry = array();
     $qry['select'] = "e.*, e.uid AS code, e.comment_count AS commcount, e.comment_names AS commnames, e.trackback_count AS trackcount, e.trackback_names AS tracknames";
     $qry['from'] = $this->entriestable . " AS e";
     if (!empty($params['offset'])) {
         $params['date'] = "";
         $qry['limit'] = intval($params['offset']) . ", " . $params['show'];
     } else {
         $qry['limit'] = $params['show'];
     }
     if (substr($params['orderby'], 0, 12) == "extrafields_") {
         if (empty($params['extrafields'])) {
             $qry['select'] .= ", ef.target_uid, ef.value";
             $qry['leftjoin'][$this->extrafieldstable . " AS ef"] = "e.uid = ef.target_uid";
         }
         $qry['where'][] = "ef.contenttype = 'entry'";
         $qry['where'][] = "ef.fieldkey = '" . safeString(substr($params['orderby'], 12)) . "'";
         if ($params['ordertype'] == "int") {
             $orderby = "CAST(ef.value as SIGNED)";
         } else {
             $orderby = "ef.value";
         }
     } elseif (!empty($params['orderby'])) {
         if ($params['ordertype'] == "int") {
             $orderby = "CAST(e." . safeString($params['orderby'], true) . " as SIGNED)";
         } else {
             $orderby = "e." . safeString($params['orderby'], true);
         }
     } else {
         $orderby = "e.date";
     }
     if ($params['order'] == "random") {
         $qry['order'] = "RAND()";
     } elseif ($params['order'] == "desc") {
         $qry['order'] = $orderby . " DESC";
     } else {
         $qry['order'] = $orderby . " ASC";
     }
     if (!empty($params['uid'])) {
         if (is_array($params['uid'])) {
             $aUids = $params['uid'];
         } else {
             $aUids = explode(",", $params['uid']);
         }
         foreach ($aUids as $k => $uid) {
             if (!is_numeric($uid)) {
                 unset($aUids[$k]);
             }
         }
         if (!empty($aUids)) {
             $uids = implode(', ', $aUids);
             $qry['where'][] = "e.uid in (" . $uids . ")";
         }
     } else {
         if (!empty($params['start'])) {
             $params['date'] = "";
             $params['start'] = explode("-", $params['start']);
             $start = sprintf("%s-%02s-%02s %02s:%02s:00", $params['start'][0], $params['start'][1], $params['start'][2], $params['start'][3], $params['start'][4]);
             $qry['where'][] = $orderby . " > " . $this->sql->quote($start);
         }
         if (!empty($params['end'])) {
             $params['date'] = "";
             $params['end'] = explode("-", $params['end']);
             $end = sprintf("%s-%02s-%02s %02s:%02s:00", $params['end'][0], $params['end'][1], $params['end'][2], $params['end'][3], $params['end'][4]);
             $qry['where'][] = $orderby . " < " . $this->sql->quote($end);
         }
         if (!empty($params['date'])) {
             $params['date'] = explode("-", $params['date']);
             $year = (int) $params['date'][0];
             if (count($params['date']) == 1) {
                 $start = sprintf("%s-%02s-%02s 00:00:00", $year, 1, 1);
                 $year++;
                 $end = sprintf("%s-%02s-%02s 00:00:00", $year, 1, 1);
             } elseif (count($params['date']) == 2) {
                 $month = (int) $params['date'][1];
                 $start = sprintf("%s-%02s-%02s 00:00:00", $year, $month, 1);
                 $month++;
                 if ($month > 12) {
                     $month = 1;
                     $year++;
                 }
                 $end = sprintf("%s-%02s-%02s 00:00:00", $year, $month, 1);
             } else {
                 $month = (int) $params['date'][1];
                 $day = (int) $params['date'][2];
                 $start = sprintf("%s-%02s-%02s 00:00:00", $year, $month, $day);
                 $end = sprintf("%s-%02s-%02s 23:59:00", $year, $month, $day);
             }
             $qry['where'][] = "{$orderby} > " . $this->sql->quote($start);
             $qry['where'][] = "{$orderby} < " . $this->sql->quote($end);
         }
         // Do not use a limit if a date range is given
         if (!empty($params['start']) && !empty($params['end']) || !empty($params['date'])) {
             unset($qry['limit']);
         }
         if (!empty($params['status'])) {
             $qry['where'][] = "e.status = " . $this->sql->quote($params['status']);
         }
         if (!empty($params['user'])) {
             $qry['where'][] = "e.user = "******"e.date DESC, e.uid DESC";
         $qry['group'] = "e.date, e.uid";
         //[/JAN]
         if (!empty($params['cats'])) {
             $qry['select'] .= ", c.category";
             $qry['leftjoin'][$this->categoriestable . " AS c"] = "e.uid = c.target_uid";
             if (is_array($params['cats'])) {
                 $qry['where'][] = "c.category IN('" . implode("', '", $params['cats']) . "')";
             } else {
                 $qry['where'][] = "c.category= " . $this->sql->quote($params['cats']);
             }
             $qry['where'][] = "c.contenttype= 'entry'";
         }
         if (!empty($params['tags'])) {
             $qry['select'] .= ", t.tag";
             $qry['leftjoin'][$this->tagstable . " AS t"] = "e.uid = t.target_uid";
             if (strpos($params['tags'], ",") !== false) {
                 $aTags = explode(",", str_replace(" ", "", $params['tags']));
                 $tags = implode("', '", $aTags);
                 $qry['where'][] = "t.tag IN ('" . $tags . "')";
             } else {
                 $qry['where'][] = "t.tag= " . $this->sql->quote($params['tags']);
             }
             $qry['where'][] = "t.contenttype= 'entry'";
         }
         if (!empty($params['extrafields'])) {
             $qry['select'] .= ", ef.target_uid";
             $qry['leftjoin'][$this->extrafieldstable . " AS ef"] = "e.uid = ef.target_uid";
             foreach ($params['extrafields'] as $k => $v) {
                 $qry['where_or'][] = "(ef.contenttype='entry' AND ef.fieldkey = '" . $k . "' AND ef.value = '" . $v . "')";
             }
         }
     }
     if ($params['count_only'] === true) {
         // if we only want to count - override the select, group and order
         $qry['select'] = 'count(e.uid) as number';
         unset($qry['order']);
         unset($qry['group']);
         //debug_printr($qry);
         $query = $this->sql->build_select($qry);
         //debug(nl2br($query));
         $this->sql->query();
         $result = $this->sql->fetch_row();
         // return the result and skip the recht if read_entries
         return $result;
     }
     $query = $this->sql->build_select($qry);
     $this->sql->query();
     // echo nl2br(htmlentities($query));
     $rows = $this->sql->fetch_all_rows();
     $entries = array();
     if (!is_array($rows)) {
         $rows = array();
     }
     foreach ($rows as $entry) {
         $entries[$entry['uid']] = $entry;
         // Make the 'excerpts'..
         $entries[$entry['uid']]['excerpt'] = makeExcerpt($entry['introduction']);
         // Set the link..
         $entries[$entry['uid']]['link'] = makeFileLink($entry, '', '');
     }
     if (is_array($entries)) {
         $ids = makeValuepairs($entries, '', 'uid');
         $ids = "'" . implode("', '", $ids) . "'";
         // Ok, now we need to do a second query to get the correct arrays with all of the categories.
         $this->sql->query("SELECT * FROM " . $this->categoriestable . " AS c WHERE contenttype = 'entry' AND target_uid IN ({$ids})");
         $tempcats = $this->sql->fetch_all_rows();
         if ($tempcats) {
             // group them together by entry.
             foreach ($tempcats as $cat) {
                 $cats[$cat['target_uid']][] = $cat['category'];
             }
             // Add them to our simple cache, for later retrieval..
             $PIVOTX['cache']->setMultiple("categories", $cats);
             // Now, attach the categories to the entries..
             foreach ($cats as $uid => $cat) {
                 foreach ($entries as $key => $entry) {
                     if ($entries[$key]['uid'] == $uid) {
                         $entries[$key]['category'] = $cat;
                         continue;
                     }
                 }
             }
         }
         // And a third query to get the correct records with all of the extra fields.
         $this->sql->query("SELECT * FROM " . $this->extrafieldstable . " AS e WHERE contenttype='entry' AND target_uid IN ({$ids})");
         $tempfields = $this->sql->fetch_all_rows();
         // Now, attach the tempfields to the entries..
         if (!empty($tempfields)) {
             foreach ($tempfields as $tempfield) {
                 foreach ($entries as $key => $entry) {
                     if ($entries[$key]['uid'] == $tempfield['target_uid']) {
                         if (!is_array($entries[$key]['extrafields'])) {
                             $entries[$key]['extrafields'] = array();
                         }
                         // Check if it's a serialised value..
                         if (is_array(unserialize($temp_field['value']))) {
                             $temp_field['value'] = unserialize($temp_field['value']);
                         }
                         $entries[$key]['extrafields'][$tempfield['fieldkey']] = $tempfield['value'];
                     }
                 }
             }
         }
     }
     // Add them to our simple cache, for later retrieval..
     $PIVOTX['cache']->setMultiple("entries", $entries);
     return $entries;
 }