function staticpage_display($params, &$smarty)
{
    global $serendipity;
    if (empty($params['template'])) {
        $params['template'] = 'plugin_staticpage.tpl';
    }
    if (empty($params['pagevar'])) {
        $params['pagevar'] = 'staticpage_';
    }
    if (!empty($params['id'])) {
        $where = "id = '" . serendipity_db_escape_string($params['id']) . "'";
    } elseif (!empty($params['pagetitle'])) {
        $where = "pagetitle = '" . serendipity_db_escape_string($params['pagetitle']) . "'";
    } elseif (!empty($params['permalink'])) {
        $where = "permalink = '" . serendipity_db_escape_string($params['permalink']) . "'";
    } else {
        $smarty->trigger_error(__FUNCTION__ . ": missing 'id', 'permalink' or 'pagetitle' parameter");
        return;
    }
    if (!empty($params['authorid'])) {
        $where .= " AND authorid = " . (int) $params['authorid'];
    }
    if (empty($params['query'])) {
        $params['query'] = "SELECT *\n                              FROM {$serendipity['dbPrefix']}staticpages\n                             WHERE {$where}\n                             LIMIT 1";
    }
    $page = serendipity_db_query($params['query'], true, 'assoc');
    if (is_array($page)) {
        $old_staticpage = $serendipity['staticpage_plugin']->staticpage;
        $serendipity['staticpage_plugin']->staticpage =& $page;
        $serendipity['staticpage_plugin']->checkPage();
        echo $serendipity['staticpage_plugin']->parseStaticPage($params['pagevar'], $params['template']);
        $serendipity['staticpage_plugin']->staticpage = $old_staticpage;
        return;
    }
}
 static function addEntryProperties($entryId, $supported_properties, &$properties, $deleteMissing = true)
 {
     global $serendipity;
     // Get existing data
     $property = serendipity_fetchEntryProperties($entryId);
     foreach ($supported_properties as $prop_key) {
         $prop_val = isset($properties[$prop_key]) ? $properties[$prop_key] : null;
         if (!$deleteMissing && empty($prop_val)) {
             continue;
         }
         // Don't clear data if not allowed.
         $q = '';
         if (!isset($property[$prop_key]) && !empty($prop_val)) {
             if ($prop_val != '#') {
                 $q = "INSERT INTO {$serendipity['dbPrefix']}entryproperties (entryid, property, value) VALUES (" . (int) $entryId . ", '" . serendipity_db_escape_string($prop_key) . "', '" . serendipity_db_escape_string($prop_val) . "')";
             }
         } elseif ($property[$prop_key] != $prop_val && !empty($prop_val)) {
             if ($prop_val == '#') {
                 $q = "DELETE FROM {$serendipity['dbPrefix']}entryproperties WHERE entryid = " . (int) $entryId . " AND property = '" . serendipity_db_escape_string($prop_key) . "'";
             } else {
                 $q = "UPDATE {$serendipity['dbPrefix']}entryproperties SET value = '" . serendipity_db_escape_string($prop_val) . "' WHERE entryid = " . (int) $entryId . " AND property = '" . serendipity_db_escape_string($prop_key) . "'";
             }
         } elseif (empty($property[$prop_key])) {
             $q = "DELETE FROM {$serendipity['dbPrefix']}entryproperties WHERE entryid = " . (int) $entryId . " AND property = '" . serendipity_db_escape_string($prop_key) . "'";
         }
         if (!empty($q)) {
             serendipity_db_query($q);
         }
     }
 }
Example #3
0
 function set_config($item, $value)
 {
     global $serendipity;
     serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}options\n                               WHERE okey = 't_" . serendipity_db_escape_string($serendipity['template']) . "'\n                                 AND name = '" . serendipity_db_escape_string($item) . "'");
     serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}options (okey, name, value)\n                                   VALUES ('t_" . serendipity_db_escape_string($serendipity['template']) . "', '" . serendipity_db_escape_string($item) . "', '" . serendipity_db_escape_string($value) . "')");
     return true;
 }
 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 />';
             }
         }
     }
 }
/**
 * Create default groups, when migrating.
 *
 * @access private
 */
function serendipity_addDefaultGroups()
{
    global $serendipity;
    serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}groups");
    serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}groupconfig");
    serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}authorgroups");
    serendipity_addDefaultGroup(USERLEVEL_EDITOR_DESC, USERLEVEL_EDITOR);
    serendipity_addDefaultGroup(USERLEVEL_CHIEF_DESC, USERLEVEL_CHIEF);
    serendipity_addDefaultGroup(USERLEVEL_ADMIN_DESC, USERLEVEL_ADMIN);
}
 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;
 }
 static function table_created($table = PLUGIN_OEMBED_DATABASEVNAME)
 {
     global $serendipity;
     $q = "select count(*) from {$serendipity['dbPrefix']}" . $table;
     $row = serendipity_db_query($q, true, 'num');
     if (!is_numeric($row[0])) {
         // if the response we got back was an SQL error.. :P
         return false;
     } else {
         return true;
     }
 }
 /**
  * Update table for re-ordering
  *
  * @access public
  * @author Falk Doering
  * @param  string  Name of the table
  * @param  string  The direction ('up' or 'down')
  * @param  array   The update array
  * @param  array   The array containing the where clause
  * @return boolean
  */
 function doReorder($table, $moveto, $update_array, $where_array)
 {
     global $serendipity;
     if (is_array($update_array) && is_array($where_array)) {
         $where = '';
         foreach ($where_array as $key => $value) {
             if (strlen($where)) {
                 $where .= ' AND ';
             }
             $where .= $key . ' = ' . $value;
         }
         $q = 'SELECT ' . implode(", ", array_keys($update_array)) . '
                 FROM ' . $serendipity['dbPrefix'] . $table . '
                WHERE ' . $where;
         $old = serendipity_db_query($q, true, 'assoc');
         if (is_array($old)) {
             $where = array();
             $update = array();
             switch ($moveto) {
                 case 'up':
                     foreach ($update_array as $key => $value) {
                         if ($value) {
                             $where[$key] = $old[$key] - 1;
                             $update[$key] = $old[$key];
                             $update_1[$key] = $old[$key] - 1;
                         } else {
                             $where[$key] = $old[$key];
                         }
                     }
                     break;
                 case 'down':
                     foreach ($update_array as $key => $value) {
                         if ($value) {
                             $where[$key] = $old[$key] + 1;
                             $update[$key] = $old[$key];
                             $update_1[$key] = $old[$key] + 1;
                         } else {
                             $where[$key] = $old[$key];
                         }
                     }
                     break;
                 default:
                     return false;
             }
             serendipity_db_update($table, $where, $update);
             serendipity_db_update($table, $where_array, $update_1);
             return true;
         }
     }
     return false;
 }
 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 event_hook($event, &$bag, &$eventData, $addData = null)
 {
     global $serendipity;
     $hooks =& $bag->get('event_hooks');
     if (isset($hooks[$event])) {
         switch ($event) {
             case 'frontend_display':
                 if ($bag->get('scrambles_true_content') && is_array($addData) && isset($addData['no_scramble'])) {
                     return true;
                 }
             case 'frontend_display_cache':
                 $serendipity['encodeExitsCallback_entry_id'] = (int) (isset($eventData['entry_id']) ? $eventData['entry_id'] : $eventData['id']);
                 // Fetch all existing links from the database. They have been inserted there by our trackback-discovery.
                 if (empty($serendipity['encodeExitsCallback_entry_id'])) {
                     $this->links = array();
                 } else {
                     #echo "SELECT id, link FROM {$serendipity['dbPrefix']}references WHERE entry_id = {$serendipity['encodeExitsCallback_entry_id']} AND type = ''<br />\n";
                     $this->links = serendipity_db_query("SELECT id, link FROM {$serendipity['dbPrefix']}references WHERE entry_id = {$serendipity['encodeExitsCallback_entry_id']} AND (type = '' OR type IS NULL)", false, 'both', false, 'link', 'id');
                     #echo "<pre>" . print_r($this->links, true) . "</pre><br />\n";
                 }
                 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] = preg_replace_callback("#<a(.*)href=(\"|')http(s?)://([^\"']+)(\"|')([^>]*)>#isUm", array($this, '_encodeExitsCallback'), $eventData[$element]);
                         if ($temp['element'] == 'comment' && !empty($eventData['url'])) {
                             switch (trim($this->get_config('commentredirection'))) {
                                 case 'bmi':
                                     $eventData['url'] = 'http://bmi.pifo.biz/?' . $eventData['url'];
                                     break;
                                 case 's9y':
                                     $eventData['url'] = $this->_encodeExitsCallback(array(1 => ' ', 2 => '"', 3 => '', 4 => $eventData['url'], 5 => '"'), true);
                                     break;
                                 case 'google':
                                     $eventData['url'] = 'http://www.google.com/url?sa=D&q=' . $eventData['url'];
                                     break;
                                 default:
                                     break;
                             }
                         }
                     }
                 }
                 return true;
                 break;
             default:
                 return false;
         }
     } else {
         return false;
     }
 }
 function order_to_first()
 {
     global $serendipity;
     // Fetch minimum sort_order value. This will be the new value of our current plugin.
     $q = "SELECT MIN(sort_order) as sort_order_min FROM {$serendipity['dbPrefix']}plugins WHERE placement = '" . $addData['default_placement'] . "'";
     $rs = serendipity_db_query($q, true, 'num');
     // Fetch current sort_order of current plugin.
     $q = "SELECT sort_order FROM {$serendipity['dbPrefix']}plugins WHERE name = '" . $this->instance . "'";
     $cur = serendipity_db_query($q, true, 'num');
     // Increase sort_order of all plugins before current plugin by one.
     $q = "UPDATE {$serendipity['dbPrefix']}plugins SET sort_order = sort_order + 1 WHERE placement = '" . $addData['default_placement'] . "' AND sort_order < " . intval($cur[0]);
     serendipity_db_query($q);
     // Set current plugin as first plugin in queue.
     $q = "UPDATE {$serendipity['dbPrefix']}plugins SET sort_order = " . intval($rs[0]) . " WHERE name = '" . $this->instance . "'";
     serendipity_db_query($q);
 }
/**
 * Fetch a list of trackbacks for an entry
 *
 * @access public
 * @param   int     The ID of the entry
 * @param   string  How many trackbacks to show
 * @param   boolean If true, also non-approved trackbacks will be shown
 * @return
 */
function &serendipity_fetchTrackbacks($id, $limit = null, $showAll = false)
{
    global $serendipity;
    if (!$showAll) {
        $and = "AND status = 'approved'";
    }
    $query = "SELECT * FROM {$serendipity['dbPrefix']}comments WHERE entry_id = '" . (int) $id . "' AND (type = 'TRACKBACK' OR type = 'PINGBACK') {$and} ORDER BY id";
    if (isset($limit)) {
        $limit = serendipity_db_limit_sql($limit);
        $query .= " {$limit}";
    }
    $comments = serendipity_db_query($query);
    if (!is_array($comments)) {
        return array();
    }
    return $comments;
}
 function generate_content(&$title)
 {
     global $serendipity;
     $title = $this->get_config('title', $this->title);
     $authors_query = "SELECT realname, username, authorid FROM {$serendipity['dbPrefix']}authors";
     $row_authors = serendipity_db_query($authors_query);
     echo '<ul class="plainList">';
     foreach ($row_authors as $entry) {
         if (function_exists('serendipity_authorURL')) {
             $entryLink = serendipity_authorURL($entry);
         } else {
             $entryLink = serendipity_rewriteURL(PATH_AUTHORS . '/' . serendipity_makePermalink(PERM_AUTHORS, array('id' => $entry['authorid'], 'title' => $entry['realname'])));
         }
         echo '<li><a href="' . $entryLink . '">' . $entry['realname'] . '</a></li>';
     }
     echo '</ul>';
 }
Example #14
0
/**
 * Perform a query to insert an associative array into a specific SQL table
 *
 * You can pass a tablename and an array of input data to insert into an array.
 *
 * @access  public
 * @param   string      Name of the SQL table
 * @param   array       Associative array of keys/values to insert into the table. Escaping is done automatically.
 * @param  string   What do do with the SQL query (execute, display)
 * @return array    Returns the result of the SQL query
 */
function serendipity_db_insert($table, $values, $action = 'execute')
{
    global $serendipity;
    $names = implode(',', array_keys($values));
    $vals = '';
    foreach ($values as $k => $v) {
        if (strlen($vals)) {
            $vals .= ', ';
        }
        $vals .= '\'' . serendipity_db_escape_string($v) . '\'';
    }
    $q = "INSERT INTO {$serendipity['dbPrefix']}{$table} ({$names}) values ({$vals})";
    if ($action == 'execute') {
        return serendipity_db_query($q);
    } else {
        return $q;
    }
}
 function generate_content(&$title)
 {
     global $serendipity;
     $title = $this->get_config('title');
     $count = $this->get_config('count');
     if ($count < 1) {
         $count = 1;
     }
     $rows = serendipity_db_query("select {$serendipity['dbPrefix']}authors.username,\nSUM({$serendipity['dbPrefix']}karma.points) as score, SUM({$serendipity['dbPrefix']}karma.votes) as\nvotes,SUM({$serendipity['dbPrefix']}karma.points) / SUM({$serendipity['dbPrefix']}karma.votes) as overall FROM\n{$serendipity['dbPrefix']}entries, {$serendipity['dbPrefix']}karma, {$serendipity['dbPrefix']}authors WHERE {$serendipity['dbPrefix']}entries.id = {$serendipity['dbPrefix']}karma.entryid\nAND {$serendipity['dbPrefix']}authors.authorid = {$serendipity['dbPrefix']}entries.authorid " . "GROUP BY {$serendipity['dbPrefix']}authors.username ORDER BY score DESC; ");
     echo "<table>";
     echo "<tr><th style='background-color: #DDDDDD'>" . PLUGIN_KARMARANKING_AUTHOR . "</th>";
     echo "<th style='background-color: #DDDDDD'>" . PLUGIN_KARMARANKING_TOTAL . "</th></tr>";
     #var_dump($rows);
     foreach ($rows as $row) {
         echo "<tr><td>" . $row[0] . "</td><td style='text-align: center'>" . $row[1] . "</td></tr>";
     }
     echo "</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>';
 }
Example #17
0
    <input type="hidden" name="serendipity[getstep]" value="3">
<?php 
    $config = serendipity_parseTemplate(S9Y_CONFIG_TEMPLATE);
    serendipity_printConfigTemplate($config, $from, true, false, false);
    ?>
    <div align="center"><input name="submit" type="submit" value="<?php 
    echo COMPLETE_INSTALLATION;
    ?>
" class="serendipityPrettyButton input_button"></div>
</form>

<?php 
} elseif ((int) $serendipity['GET']['step'] == 3) {
    $serendipity['dbPrefix'] = $_POST['dbPrefix'];
    echo CHECK_DATABASE_EXISTS . '...';
    $t = serendipity_db_query("SELECT * FROM {$serendipity['dbPrefix']}authors", false, 'both', false, false, false, true);
    if (is_array($t)) {
        echo ' <strong>' . THEY_DO . '</strong>, ' . WONT_INSTALL_DB_AGAIN;
        echo '<br />';
        echo '<br />';
    } else {
        echo ' <strong>' . THEY_DONT . '</strong>';
        echo '<br />';
        echo CREATE_DATABASE;
        serendipity_installDatabase();
        echo ' <strong>' . DONE . '</strong><br />';
        echo sprintf(CREATING_PRIMARY_AUTHOR, htmlspecialchars($_POST['user'])) . '...';
        $authorid = serendipity_addAuthor($_POST['user'], $_POST['pass'], $_POST['realname'], $_POST['email'], USERLEVEL_ADMIN, 1);
        $mail_comments = serendipity_db_bool($_POST['want_mail']) ? 1 : 0;
        serendipity_set_user_var('mail_comments', $mail_comments, $authorid);
        serendipity_set_user_var('mail_trackbacks', $mail_comments, $authorid);
 function event_hook($event, &$bag, &$eventData, $addData = null)
 {
     global $serendipity;
     static $login_url = null;
     if ($login_url === null) {
         $login_url = $serendipity['baseURL'] . $serendipity['indexFile'] . '?/plugin/loginbox';
     }
     $hooks =& $bag->get('event_hooks');
     if (isset($hooks[$event])) {
         switch ($event) {
             case 'frontend_saveComment':
                 if (!isset($serendipity['csuccess'])) {
                     $serendipity['csuccess'] = 'true';
                 }
                 if (serendipity_db_bool($this->get_config('registered_only')) && !serendipity_userLoggedIn() && $addData['source2'] != 'adduser') {
                     $eventData = array('allow_comments' => false);
                     $serendipity['messagestack']['comments'][] = PLUGIN_ADDUSER_REGISTERED_ONLY_REASON;
                     return false;
                 }
                 if (serendipity_db_bool($this->get_config('registered_only')) && !$this->inGroup() && $addData['source2'] != 'adduser') {
                     $eventData = array('allow_comments' => false);
                     $serendipity['messagestack']['comments'][] = PLUGIN_ADDUSER_REGISTERED_ONLY_REASON;
                     return false;
                 }
                 if (serendipity_db_bool($this->get_config('true_identities')) && !serendipity_userLoggedIn()) {
                     $user = str_replace(" b", '', $addData['name']);
                     $user = serendipity_db_escape_string(preg_replace('@\\s+@', ' ', trim($user)));
                     $user = trim($user);
                     $authors = serendipity_db_query("SELECT authorid FROM {$serendipity['dbPrefix']}authors WHERE realname = '" . $user . "'");
                     if (is_array($authors) && isset($authors[0]['authorid'])) {
                         $eventData = array('allow_comments' => false);
                         $serendipity['messagestack']['comments'][] = sprintf(PLUGIN_ADDUSER_REGISTERED_CHECK_REASON, $login_url, 'onclick="javascript:loginbox = window.open(this.href, \'loginbox\', \'width=300,height=300,locationbar=no,menubar=no,personalbar=no,statusbar=yes,status=yes,toolbar=no\'); return false;"');
                     }
                 }
                 break;
             case 'external_plugin':
                 if ($eventData != 'loginbox') {
                     return true;
                 }
                 $out = array();
                 serendipity_plugin_api::hook_event('backend_login_page', $out);
                 serendipity_smarty_init();
                 $serendipity['smarty']->assign(array('loginform_add' => $out, 'loginform_url' => $login_url, 'loginform_user' => $_SESSION['serendipityUser'], 'loginform_mail' => $_SESSION['serendipityEmail'], 'close_window' => defined('LOGIN_ACTION'), 'is_logged_in' => serendipity_userLoggedIn(), 'is_error' => defined('LOGIN_ERROR')));
                 $filename = 'loginbox.tpl';
                 $tfile = serendipity_getTemplateFile($filename, 'serendipityPath');
                 if (!$tfile || $tfile == $filename) {
                     $tfile = dirname(__FILE__) . '/' . $filename;
                 }
                 $inclusion = $serendipity['smarty']->security_settings[INCLUDE_ANY];
                 $serendipity['smarty']->security_settings[INCLUDE_ANY] = true;
                 $serendipity['smarty']->display($tfile);
                 break;
             case 'frontend_display':
                 if (serendipity_db_bool($this->get_config('registered_only')) && !serendipity_userLoggedIn()) {
                     $serendipity['messagestack']['comments'][] = sprintf(PLUGIN_ADDUSER_REGISTERED_ONLY_REASON, $serendipity['baseURL'] . $serendipity['indexFile'] . '?serendipity[subpage]=adduser', $serendipity['baseURL'] . 'serendipity_admin.php');
                     $eventData['allow_comments'] = false;
                 }
                 break;
             case 'frontend_configure':
                 if (isset($serendipity['POST']['action']) && isset($serendipity['POST']['user']) && isset($serendipity['POST']['pass'])) {
                     serendipity_login();
                     if (serendipity_userLoggedIn()) {
                         define('LOGIN_ACTION', 'login');
                         header('X-s9y-auth: Login');
                     } else {
                         define('LOGIN_ERROR', true);
                     }
                 } elseif (isset($serendipity['POST']['action']) && isset($serendipity['POST']['logout'])) {
                     serendipity_logout();
                     if (!serendipity_userLoggedIn()) {
                         header('X-s9y-auth: Logout');
                         define('LOGIN_ACTION', 'logout');
                     }
                 }
                 if ((serendipity_db_bool($this->get_config('registered_only')) || serendipity_db_bool($this->get_config('true_identities'))) && $_SESSION['serendipityAuthedUser']) {
                     if (defined('IN_serendipity_admin') && $serendipity['GET']['adminAction'] == 'doEdit') {
                         // void
                     } else {
                         $serendipity['COOKIE']['name'] = isset($_SESSION['serendipityRealname']) ? $_SESSION['serendipityRealname'] : $_SESSION['serendipityUser'];
                         $serendipity['COOKIE']['email'] = $_SESSION['serendipityEmail'];
                         if ($serendipity['POST']['comment']) {
                             $serendipity['POST']['name'] = $serendipity['COOKIE']['name'];
                             $serendipity['POST']['email'] = $serendipity['COOKIE']['email'];
                         }
                     }
                 }
                 return true;
                 break;
             case 'entry_display':
                 if ($serendipity['GET']['subpage'] == 'adduser' || $serendipity['POST']['subpage'] == 'adduser' || !empty($serendipity['GET']['adduser_activation']) || !empty($this->clean_page)) {
                     if (is_array($eventData)) {
                         $eventData['clean_page'] = true;
                     }
                 }
                 break;
             case 'entries_header':
                 if ($serendipity['GET']['subpage'] == 'adduser' || $serendipity['POST']['subpage'] == 'adduser' || !empty($serendipity['GET']['adduser_activation'])) {
                     $this->clean_page = true;
                     $url = $serendipity['baseURL'] . $serendipity['indexFile'];
                     $hidden['subpage'] = 'adduser';
                     $username = substr($serendipity['POST']['adduser_user'], 0, 40);
                     $password = substr($serendipity['POST']['adduser_pass'], 0, 32);
                     $email = $serendipity['POST']['adduser_email'];
                     echo '<div id="adduser_form" style="padding-left: 4px; padding-right: 10px"><a id="adduser"></a>';
                     // Get the config from the sidebar plugin
                     $pair_config = array('userlevel' => USERLEVEL_EDITOR, 'no_create' => false, 'right_publish' => false, 'instructions' => $this->get_config('instructions', ''), 'usergroups' => array(), 'straight_insert' => false, 'approve' => false, 'use_captcha' => false);
                     $config = serendipity_db_query("SELECT name, value FROM {$serendipity['dbPrefix']}config WHERE name LIKE 'serendipity_plugin_adduser:%'");
                     if (is_array($config)) {
                         foreach ($config as $conf) {
                             $names = explode('/', $conf['name']);
                             if ($names[1] == 'instructions' && !empty($pair_config['instructions'])) {
                                 continue;
                             }
                             if ($names[1] == 'usergroups') {
                                 $ug = (array) explode(',', $conf['value']);
                                 foreach ($ug as $cid) {
                                     if ($cid === false || empty($cid)) {
                                         continue;
                                     }
                                     $pair_config[$names[1]][$cid] = $cid;
                                 }
                             } else {
                                 $pair_config[$names[1]] = serendipity_get_bool($conf['value']);
                             }
                         }
                     }
                     if (!serendipity_common_adduser::adduser($username, $password, $email, $pair_config['userlevel'], $pair_config['usergroups'], $pair_config['no_create'], $pair_config['right_publish'], $pair_config['straight_insert'], $pair_config['approve'], $pair_config['use_captcha'])) {
                         serendipity_common_adduser::loginform($url, $hidden, $pair_config['instructions'], $username, $password, $email, $pair_config['use_captcha']);
                     }
                     echo '</div>';
                 }
                 return true;
                 break;
             default:
                 return false;
         }
     } else {
         return false;
     }
 }
 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");
         }
     }
 }
/**
 * 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 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 log($logfile, $id, $switch, $reason, $comment)
 {
     global $serendipity;
     $method = $this->get_config('logtype');
     switch ($method) {
         case 'file':
             if (empty($logfile)) {
                 return;
             }
             if (strpos($logfile, '%') !== false) {
                 $logfile = strftime($logfile);
             }
             $fp = @fopen($logfile, 'a+');
             if (!is_resource($fp)) {
                 return;
             }
             fwrite($fp, sprintf('[%s] - [%s: %s] - [#%s, Name "%s", E-Mail "%s", URL "%s", User-Agent "%s", IP %s] - [%s]' . "\n", date('Y-m-d H:i:s', serendipity_serverOffsetHour()), $switch, $reason, $id, str_replace("\n", ' ', $comment['name']), str_replace("\n", ' ', $comment['email']), str_replace("\n", ' ', $comment['url']), str_replace("\n", ' ', $_SERVER['HTTP_USER_AGENT']), $_SERVER['REMOTE_ADDR'], str_replace("\n", ' ', $comment['comment'])));
             fclose($fp);
             break;
         case 'none':
             return;
             break;
         case 'db':
         default:
             $q = sprintf("INSERT INTO {$serendipity['dbPrefix']}spamblocklog\n                                          (timestamp, type, reason, entry_id, author, email, url,  useragent, ip,   referer, body)\n                                   VALUES (%d,        '%s',  '%s',  '%s',     '%s',   '%s',  '%s', '%s',      '%s', '%s',    '%s')", serendipity_serverOffsetHour(), serendipity_db_escape_string($switch), serendipity_db_escape_string($reason), serendipity_db_escape_string($id), serendipity_db_escape_string($comment['name']), serendipity_db_escape_string($comment['email']), serendipity_db_escape_string($comment['url']), substr(serendipity_db_escape_string($_SERVER['HTTP_USER_AGENT']), 0, 255), serendipity_db_escape_string($_SERVER['REMOTE_ADDR']), substr(serendipity_db_escape_string(isset($_SESSION['HTTP_REFERER']) ? $_SESSION['HTTP_REFERER'] : $_SERVER['HTTP_REFERER']), 0, 255), serendipity_db_escape_string($comment['comment']));
             serendipity_db_query($q);
             break;
     }
 }
 function generate_content(&$title)
 {
     global $serendipity;
     $title = $this->get_config('title', $this->title);
     $to_lower = serendipity_db_bool($this->get_config('lowercase_tags', 'true'));
     if ($this->get_config('max_tags', 0) != 0) {
         $limit = "LIMIT " . $this->get_config('max_tags', 0);
     } else {
         $limit = '';
     }
     $query = "SELECT et.tag, count(et.tag) AS total\n                    FROM {$serendipity['dbPrefix']}entrytags AS et\n         LEFT OUTER JOIN {$serendipity['dbPrefix']}entries AS e\n                      ON et.entryid = e.id\n                   WHERE e.isdraft = 'false' " . (!serendipity_db_bool($serendipity['showFutureEntries']) ? " AND e.timestamp <= " . time() : '') . "\n                GROUP BY et.tag\n                  HAVING count(et.tag) >= " . $this->get_config('treshold_tag_count') . "\n                ORDER BY total DESC {$limit}";
     $rows = serendipity_db_query($query);
     if (!is_array($rows)) {
         return;
     }
     // not sure if we can optimize this loop... :/
     // Probably through some SQL magick.
     foreach ($rows as $r) {
         if ($to_lower) {
             // set to_lower for frontend sidebar list/clouds (new)
             foreach ($r as &$t) {
                 if (function_exists('mb_strtolower')) {
                     $t = mb_strtolower($t);
                 } else {
                     $t = strtolower($t);
                 }
             }
         }
         $tags[$r['tag']] = $r['total'];
     }
     if ($this->get_config('order_by') == 'tag') {
         uksort($tags, 'strnatcasecmp');
         serendipity_plugin_api::hook_event('sort', $tags);
     } else {
         if ($this->get_config('order_by') == 'total') {
             serendipity_db_bool($this->get_config('sort_desc', 'false')) ? arsort($tags) : asort($tags);
         }
     }
     $xml = serendipity_db_bool($this->get_config('show_xml', 'true'));
     $nl = serendipity_db_bool($this->get_config('show_newline', 'true'));
     $scaling = serendipity_db_bool($this->get_config('scale_tag', 'false'));
     $useRotCanvas = serendipity_db_bool($this->get_config('use_rotacloud', 'false'));
     $useWordCloud = serendipity_db_bool($this->get_config('use_wordcloud', 'false'));
     serendipity_event_freetag::displayTags($tags, $xml, $nl, $scaling, $this->get_config('max_percent', 300), $this->get_config('min_percent', 100), serendipity_db_bool($this->get_config('use_flash')), serendipity_db_bool($this->get_config('flash_bg_trans', 'false')), $this->get_config('flash_tag_color', 'ff6600'), $this->get_config('flash_bg_color', 'ffffff'), $this->get_config('flash_width', 190), $this->get_config('flash_speed', 100), $this->get_config('taglink'), $this->get_config('template'), $this->get_config('xml_image', 'img/xml.gif'), $useRotCanvas, $this->get_config('rotacloud_tag_color', '3E5F81'), $this->get_config('rotacloud_tag_border_color', 'B1C1D1'), $this->get_config('rotacloud_width', '300'), $useWordCloud);
 }
Example #24
0
 function import()
 {
     global $serendipity;
     // Save this so we can return it to its original value at the end of this method.
     $noautodiscovery = isset($serendipity['noautodiscovery']) ? $serendipity['noautodiscovery'] : false;
     if ($this->data['autodiscovery'] == 'false') {
         $serendipity['noautodiscovery'] = 1;
     }
     $this->getTransTable();
     $this->data['prefix'] = serendipity_db_escape_string($this->data['prefix']);
     $users = array();
     $categories = array();
     $entries = array();
     if (!extension_loaded('pgsql')) {
         return PGSQL_REQUIRED;
     }
     $wpdb = pg_connect("{$this->data}['host'], {$this->data}['port'], {$this->data}['user'], {$this->data}['pass'], {$this->data}['name']");
     if (!$wpdb) {
         return sprintf(PGSQL_COULDNT_CONNECT, $this->data['pass']);
     }
     /* Users */
     $res = pg_query($wpdb, "SELECT ID, user_login, user_pass, user_email, user_level FROM {$this->data['prefix']}users;");
     if (!$res) {
         return sprintf(COULDNT_SELECT_USER_INFO, pg_last_error($wpdb));
     }
     for ($x = 0; $x < pg_num_rows($res); $x++) {
         $users[$x] = pg_fetch_assoc($res);
         $data = array('right_publish' => $users[$x]['user_level'] >= 1 ? 1 : 0, 'realname' => $users[$x]['user_login'], 'username' => $users[$x]['user_login'], 'password' => $users[$x]['user_pass']);
         // WP uses md5, too.
         if ($users[$x]['user_level'] <= 1) {
             $data['userlevel'] = USERLEVEL_EDITOR;
         } elseif ($users[$x]['user_level'] < 5) {
             $data['userlevel'] = USERLEVEL_CHIEF;
         } else {
             $data['userlevel'] = USERLEVEL_ADMIN;
         }
         if ($serendipity['serendipityUserlevel'] < $data['userlevel']) {
             $data['userlevel'] = $serendipity['serendipityUserlevel'];
         }
         serendipity_db_insert('authors', $this->strtrRecursive($data));
         $users[$x]['authorid'] = serendipity_db_insert_id('authors', 'authorid');
     }
     /* Categories */
     $res = @pg_query($wpdb, "SELECT cat_ID, cat_name, category_description, category_parent FROM {$this->data['prefix']}categories ORDER BY category_parent, cat_ID;");
     if (!$res) {
         return sprintf(COULDNT_SELECT_CATEGORY_INFO, pg_last_error($wpdb));
     }
     // Get all the info we need
     for ($x = 0; $x < pg_num_rows($res); $x++) {
         $categories[] = pg_fetch_assoc($res);
     }
     // Insert all categories as top level (we need to know everyone's ID before we can represent the hierarchy).
     for ($x = 0; $x < sizeof($categories); $x++) {
         $cat = array('category_name' => $categories[$x]['cat_name'], 'category_description' => $categories[$x]['category_description'], 'parentid' => 0, 'category_left' => 0, 'category_right' => 0);
         serendipity_db_insert('category', $this->strtrRecursive($cat));
         $categories[$x]['categoryid'] = serendipity_db_insert_id('category', 'categoryid');
     }
     // There has to be a more efficient way of doing this...
     foreach ($categories as $cat) {
         if ($cat['category_parent'] != 0) {
             // Find the parent
             $par_id = 0;
             foreach ($categories as $possible_par) {
                 if ($possible_par['cat_ID'] == $cat['category_parent']) {
                     $par_id = $possible_par['categoryid'];
                     break;
                 }
             }
             if ($par_id != 0) {
                 serendipity_db_query("UPDATE {$serendipity['dbPrefix']}category SET parentid={$par_id} WHERE categoryid={$cat['categoryid']};");
             }
             // else { echo "D'oh! " . random_string_of_profanity(); }
         }
     }
     serendipity_rebuildCategoryTree();
     /* Entries */
     $res = @pg_query($wpdb, "SELECT * FROM {$this->data['prefix']}posts ORDER BY post_date;");
     if (!$res) {
         return sprintf(COULDNT_SELECT_ENTRY_INFO, pg_last_error($wpdb));
     }
     for ($x = 0; $x < pg_num_rows($res); $x++) {
         $entries[$x] = pg_fetch_assoc($res);
         $entry = array('title' => $this->decode($entries[$x]['post_title']), 'isdraft' => $entries[$x]['post_status'] == 'publish' ? 'false' : 'true', 'allow_comments' => $entries[$x]['comment_status'] == 'open' ? 'true' : 'false', 'timestamp' => strtotime($entries[$x]['post_date']), 'body' => $this->strtr($entries[$x]['post_content']));
         foreach ($users as $user) {
             if ($user['ID'] == $entries[$x]['post_author']) {
                 $entry['authorid'] = $user['authorid'];
                 break;
             }
         }
         if (!is_int($entries[$x]['entryid'] = serendipity_updertEntry($entry))) {
             return $entries[$x]['entryid'];
         }
     }
     /* Entry/category */
     $res = @pg_query($wpdb, "SELECT * FROM {$this->data['prefix']}post2cat;");
     if (!$res) {
         return sprintf(COULDNT_SELECT_ENTRY_INFO, pg_last_error($wpdb));
     }
     while ($a = pg_fetch_assoc($res)) {
         foreach ($categories as $category) {
             if ($category['cat_ID'] == $a['category_id']) {
                 foreach ($entries as $entry) {
                     if ($a['post_id'] == $entry['ID']) {
                         $data = array('entryid' => $entry['entryid'], 'categoryid' => $category['categoryid']);
                         serendipity_db_insert('entrycat', $this->strtrRecursive($data));
                         break;
                     }
                 }
                 break;
             }
         }
     }
     /* Comments */
     $res = @pg_query($wpdb, "SELECT * FROM {$this->data['prefix']}comments;");
     if (!$res) {
         return sprintf(COULDNT_SELECT_COMMENT_INFO, pg_last_error($wpdb));
     }
     while ($a = pg_fetch_assoc($res)) {
         foreach ($entries as $entry) {
             if ($entry['ID'] == $a['comment_post_ID']) {
                 $comment = array('entry_id ' => $entry['entryid'], 'parent_id' => 0, 'timestamp' => strtotime($a['comment_date']), 'author' => $a['comment_author'], 'email' => $a['comment_author_email'], 'url' => $a['comment_author_url'], 'ip' => $a['comment_author_IP'], 'status' => empty($a['comment_approved']) || $a['comment_approved'] == '1' ? 'approved' : 'pending', 'subscribed' => 'false', 'body' => $a['comment_content'], 'type' => 'NORMAL');
                 serendipity_db_insert('comments', $this->strtrRecursive($comment));
                 if ($comment['status'] == 'approved') {
                     $cid = serendipity_db_insert_id('comments', 'id');
                     serendipity_approveComment($cid, $entry['entryid'], true);
                 }
             }
         }
     }
     $serendipity['noautodiscovery'] = $noautodiscovery;
     // That was fun.
     return true;
 }
 /**
  * Check if Honey Pot or Captcha have been filled correctly (or if any
  * other indications for spam can be found).
  *
  * @param  array $eventData
  * @param  array $addData
  * @return bool
  */
 function checkComment(&$eventData, &$addData)
 {
     global $serendipity;
     if ("NORMAL" == $addData['type']) {
         // only supported for normal comments
         // Check for Honey Pot:
         $phone = $serendipity['POST']['phone'];
         if ($this->useHoneyPot && (!empty($phone) || $phone == '0')) {
             if (mb_strlen($phone) > 40) {
                 $phone = mb_substr($phone, 0, 40) . '..';
             }
             $this->spamlog($eventData['id'], 'REJECTED', "BEE Honeypot [" . $phone . "]", $addData);
             $eventData = array('allow_comments' => false);
             return false;
         }
         // Check hidden Captcha
         if (PLUGIN_EVENT_SPAMBLOCK_SWTCH_OFF != $this->hiddenCaptchaHandle) {
             $answer = trim(strtolower($serendipity['POST']['beecaptcha']));
             $correctAnswer = $this->getCaptchaAnswer();
             $correctAnswer['answer'] = strtolower($correctAnswer['answer']);
             $isCorrect = false;
             // If provided answer is longer than 1000 characters and RegExp matching is on,
             // reject comment for security reasons (minimize risk of ReDoS)
             if ($this->useRegularExpressions && mb_strlen($answer) > 1000) {
                 $this->processComment($this->hiddenCaptchaHandle, $eventData, $addData, PLUGIN_EVENT_SPAMBLOCK_BEE_ERROR_HCAPTCHA, "BEE HiddenCaptcha [ Captcha input too long ]");
                 return false;
             }
             if ($this->captchaQuestionType == 'custom' && $this->useRegularExpressions) {
                 // Sanitize regular expression and remove answer part
                 $pattern = preg_replace('/^\\s*\\/(.*)\\/\\s*[imsxeADSUXJu]*\\s*$/s', '$1', $correctAnswer['pattern']);
                 // Try to match pattern with given answer
                 $match = @preg_match('/' . $pattern . '/si', $answer);
                 // If pattern contains errors, fall back to basic string comparison
                 if ($match === false) {
                     $this->useRegularExpressions = false;
                 } else {
                     $isCorrect = $match === 1;
                 }
             }
             if ($this->captchaQuestionType != 'custom' || !$this->useRegularExpressions) {
                 $isCorrect = $answer == $correctAnswer['answer'];
             }
             // Also allow numbers as words
             if (!$isCorrect && $this->captchaQuestionType == 'math') {
                 $number = $this->generateNumberString($correctAnswer['answer']);
                 $isCorrect = $answer == $number && $number != 'ERROR';
             }
             if (!$isCorrect) {
                 if (mb_strlen($answer) > 40) {
                     $answer = mb_substr($answer, 0, 40) . '..';
                 }
                 $this->processComment($this->hiddenCaptchaHandle, $eventData, $addData, PLUGIN_EVENT_SPAMBLOCK_BEE_ERROR_HCAPTCHA, "BEE HiddenCaptcha [ {$correctAnswer['answer']} != {$answer} ]");
                 return $isCorrect;
             }
         }
         // AntiSpam check, the general spamblock supports, too: Only if spamblock is not installed.
         if (!class_exists('serendipity_event_spamblock')) {
             // Check for required fields. Don't log but tell the user about the fields.
             $required_fields = $this->get_config('required_fields', '');
             if (!empty($required_fields)) {
                 $required_field_list = explode(',', $required_fields);
                 foreach ($required_field_list as $required_field) {
                     $required_field = trim($required_field);
                     if (empty($addData[$required_field])) {
                         $this->reject($eventData, $addData, sprintf(PLUGIN_EVENT_SPAMBLOCK_BEE_REASON_REQUIRED_FIELD, $required_field));
                         return false;
                     }
                 }
             }
         }
     }
     // AntiSpam check, the general spamblock supports, too: Only if spamblock is not installed.
     if (!class_exists('serendipity_event_spamblock')) {
         // Check if entry title is the same as comment body
         $spamHandle = $this->get_config('entrytitle', PLUGIN_EVENT_SPAMBLOCK_SWTCH_REJECT);
         if (PLUGIN_EVENT_SPAMBLOCK_SWTCH_OFF != $spamHandle) {
             // Remove the blog name from the comment which might be in <title>
             $comment = str_replace($serendipity['blogTitle'], '', $addData['comment']);
             $comment = str_replace($eventData['title'], '', $comment);
             // Now blog- and entry title was stripped from comment.
             // Remove special letters, that might have been between them:
             $comment = trim(preg_replace('@[\\s\\-_:\\(\\)\\|/]*@', '', $comment));
             // Now that we stripped blog and entry title: Do we have an empty comment?
             if (empty($comment)) {
                 $this->processComment($spamHandle, $eventData, $addData, PLUGIN_EVENT_SPAMBLOCK_BEE_ERROR_BODY, "BEE Body the same as title");
                 return false;
             }
         }
         // This check loads from DB, so do it last!
         // Check if we already have a comment with the same body. (it's a reload normaly)
         $spamHandle = $this->get_config('samebody', PLUGIN_EVENT_SPAMBLOCK_SWTCH_REJECT);
         if (PLUGIN_EVENT_SPAMBLOCK_SWTCH_OFF != $spamHandle) {
             $query = "SELECT count(id) AS counter FROM {$serendipity['dbPrefix']}comments WHERE type = '" . $addData['type'] . "' AND body = '" . serendipity_db_escape_string($addData['comment']) . "'";
             // This is a little different to the normal Spam Plugin:
             // We allow the same comment, if it is a trackback, but never on the same article
             // (One article sending trackbacks to more than one local article)
             if ($addData['type'] == 'PINGBACK' || $addData['type'] == 'TRACKBACK') {
                 $query .= ' AND entry_id=' . $eventData['id'];
             }
             $row = serendipity_db_query($query, true);
             if (is_array($row) && $row['counter'] > 0) {
                 $this->processComment($spamHandle, $eventData, $addData, PLUGIN_EVENT_SPAMBLOCK_BEE_ERROR_BODY, "BEE Body already saved");
                 return false;
             }
         }
     }
     return true;
 }
/**
 * Moves a media directory
 *
 * @param  string   The old directory
 * @param  string   The new directory
 * @param  string   The type of what to remove (dir|file|filedir)
 * @param  string   An item id of a file
 * @return boolean
 *
 */
function serendipity_moveMediaDirectory($oldDir, $newDir, $type = 'dir', $item_id = null, $file = null)
{
    global $serendipity;
    $real_oldDir = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $oldDir;
    $real_newDir = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $newDir;
    if ($type == 'dir') {
        if (!is_dir($real_oldDir)) {
            printf(ERROR_FILE_NOT_EXISTS . '<br />', $oldDir);
            return false;
        }
        if (is_dir($real_newDir)) {
            printf(ERROR_FILE_EXISTS . '<br />', $newDir);
            return false;
        }
        if (!rename($real_oldDir, $real_newDir)) {
            printf(MEDIA_DIRECTORY_MOVE_ERROR . '<br />', $newDir);
            return false;
        }
        printf(MEDIA_DIRECTORY_MOVED . '<br />', $newDir);
        $dirs = serendipity_db_query("SELECT id, path\n                                        FROM {$serendipity['dbPrefix']}images\n                                       WHERE path LIKE '" . serendipity_db_escape_string($oldDir) . "%'", false, 'assoc');
        if (is_array($dirs)) {
            foreach ($dirs as $dir) {
                $old = $dir['path'];
                $new = preg_replace('@^(' . preg_quote($oldDir) . ')@i', $newDir, $old);
                serendipity_db_query("UPDATE {$serendipity['dbPrefix']}images\n                                         SET path = '" . serendipity_db_escape_string($new) . "'\n                                       WHERE id = {$dir['id']}");
            }
        }
        $dirs = serendipity_db_query("SELECT groupid, artifact_id, artifact_type, artifact_mode, artifact_index\n                                        FROM {$serendipity['dbPrefix']}access\n                                       WHERE artifact_type = 'directory'\n                                         AND artifact_index LIKE '" . serendipity_db_escape_string($oldDir) . "%'", false, 'assoc');
        if (is_array($dirs)) {
            foreach ($dirs as $dir) {
                $old = $dir['artifact_index'];
                $new = preg_replace('@^(' . preg_quote($oldDir) . ')@i', $newDir, $old);
                serendipity_db_query("UPDATE {$serendipity['dbPrefix']}access\n                                         SET artifact_index = '" . serendipity_db_escape_string($new) . "'\n                                       WHERE groupid        = '" . serendipity_db_escape_string($dir['groupid']) . "'\n                                         AND artifact_id    = '" . serendipity_db_escape_string($dir['artifact_id']) . "'\n                                         AND artifact_type  = '" . serendipity_db_escape_string($dir['artifact_type']) . "'\n                                         AND artifact_mode  = '" . serendipity_db_escape_string($dir['artifact_mode']) . "'\n                                         AND artifact_index = '" . serendipity_db_escape_string($dir['artifact_index']) . "'");
            }
        }
    }
    if ($type == 'file') {
        if (serendipity_isActiveFile(basename($newDir))) {
            printf(ERROR_FILE_FORBIDDEN, htmlspecialchars($newDir));
            return false;
        }
        if ($file['hotlink']) {
            serendipity_updateImageInDatabase(array('realname' => $newDir, 'name' => $newDir), $item_id);
        } else {
            $file_new = $file['path'] . $newDir . '.';
            $file_old = $file['path'] . $file['name'] . '.';
            $newfile = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $file_new . $file['extension'];
            $oldfile = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $file_old . $file['extension'];
            if ($newDir != '' && file_exists($oldfile) && !file_exists($newfile)) {
                $renameValues = array(array('from' => $oldfile, 'to' => $newfile, 'thumb' => $serendipity['thumbSuffix'], 'fthumb' => $file['thumbnail_name'], 'oldDir' => $oldDir, 'newDir' => $newDir, 'type' => $type, 'item_id' => $item_id, 'file' => $file));
                serendipity_plugin_api::hook_event('backend_media_rename', $renameValues);
                // Rename file
                rename($renameValues[0]['from'], $renameValues[0]['to']);
                foreach ($renameValues as $renameData) {
                    // Rename thumbnail
                    rename($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $file['path'] . $file['name'] . (!empty($renameData['fthumb']) ? '.' . $renameData['fthumb'] : '') . '.' . $file['extension'], $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $file['path'] . $newDir . '.' . $renameData['thumb'] . '.' . $file['extension']);
                }
                serendipity_updateImageInDatabase(array('thumbnail_name' => $renameValues[0]['thumb'], 'realname' => $newDir, 'name' => $newDir), $item_id);
                $oldDir = $file_old;
                $newDir = $file_new;
                $real_oldDir = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $oldDir;
                $real_newDir = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $newDir;
                // Forward user to overview (we don't want the user's back button to rename things again)
            } else {
                if (!file_exists($oldfile)) {
                    echo ERROR_FILE_NOT_EXISTS;
                } elseif (file_exists($newfile)) {
                    echo ERROR_FILE_EXISTS;
                } else {
                    echo ERROR_SOMETHING;
                }
                return false;
            }
        }
    } elseif ($type == 'filedir') {
        serendipity_db_query("UPDATE {$serendipity['dbPrefix']}images\n                                 SET path = '" . serendipity_db_escape_string($newDir) . "'\n                               WHERE id   = " . (int) $item_id);
        $pick = serendipity_db_query("SELECT * FROM  {$serendipity['dbPrefix']}images\n                               WHERE id   = " . (int) $item_id, true, 'assoc');
        // Move thumbs
        $oldfile = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $oldDir . $pick['name'] . '.' . $pick['extension'];
        $newfile = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $newDir . $pick['name'] . '.' . $pick['extension'];
        $renameValues = array(array('from' => $oldfile, 'to' => $newfile, 'thumb' => $serendipity['thumbSuffix'], 'fthumb' => $pick['thumbnail_name'], 'oldDir' => $oldDir, 'newDir' => $newDir, 'type' => $type, 'item_id' => $item_id, 'file' => $file, 'name' => $pick['name']));
        serendipity_plugin_api::hook_event('backend_media_rename', $renameValues);
        // Rename file
        rename($renameValues[0]['from'], $renameValues[0]['to']);
        foreach ($renameValues as $renameData) {
            // Rename thumbnail
            rename($serendipity['serendipityPath'] . $serendipity['uploadPath'] . $oldDir . $pick['name'] . (!empty($renameData['fthumb']) ? '.' . $renameData['fthumb'] : '') . '.' . $pick['extension'], $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $newDir . $pick['name'] . '.' . $renameData['thumb'] . '.' . $pick['extension']);
        }
        $oldDir .= $pick['name'];
        $newDir .= $pick['name'];
    } elseif ($type == 'dir') {
        $renameValues = array(array('from' => $oldfile, 'to' => $newfile, 'thumb' => $serendipity['thumbSuffix'], 'fthumb' => $file['thumbnail_name'], 'oldDir' => $oldDir, 'newDir' => $newDir, 'type' => $type, 'item_id' => $item_id, 'file' => $file));
        serendipity_plugin_api::hook_event('backend_media_rename', $renameValues);
    }
    // Only MySQL supported, since I don't know how to use REGEXPs differently.
    if ($serendipity['dbType'] != 'mysql' && $serendipity['dbType'] != 'mysqli') {
        echo MEDIA_DIRECTORY_MOVE_ENTRY . '<br />';
        return true;
    }
    $q = "SELECT id, body, extended\n            FROM {$serendipity['dbPrefix']}entries\n           WHERE body     REGEXP '(src=|href=|window.open.)(\\'|\")(" . serendipity_db_escape_String($serendipity['baseURL'] . $serendipity['uploadHTTPPath'] . $oldDir) . "|" . serendipity_db_escape_string($serendipity['serendipityHTTPPath'] . $serendipity['uploadHTTPPath'] . $oldDir) . ")'\n              OR extended REGEXP '(src=|href=|window.open.)(\\'|\")(" . serendipity_db_escape_String($serendipity['baseURL'] . $serendipity['uploadHTTPPath'] . $oldDir) . "|" . serendipity_db_escape_string($serendipity['serendipityHTTPPath'] . $serendipity['uploadHTTPPath'] . $oldDir) . ")'\n    ";
    $dirs = serendipity_db_query($q);
    if (is_array($dirs)) {
        foreach ($dirs as $dir) {
            $dir['body'] = preg_replace('@(src=|href=|window.open.)(\'|")(' . preg_quote($serendipity['baseURL'] . $serendipity['uploadHTTPPath'] . $oldDir) . '|' . preg_quote($serendipity['serendipityHTTPPath'] . $serendipity['uploadHTTPPath'] . $oldDir) . ')@', '\\1\\2' . $serendipity['serendipityHTTPPath'] . $serendipity['uploadHTTPPath'] . $newDir, $dir['body']);
            $dir['extended'] = preg_replace('@(src=|href=|window.open.)(\'|")(' . preg_quote($serendipity['baseURL'] . $serendipity['uploadHTTPPath'] . $oldDir) . '|' . preg_quote($serendipity['serendipityHTTPPath'] . $serendipity['uploadHTTPPath'] . $oldDir) . ')@', '\\1\\2' . $serendipity['serendipityHTTPPath'] . $serendipity['uploadHTTPPath'] . $newDir, $dir['extended']);
            $uq = "UPDATE {$serendipity['dbPrefix']}entries\n                                     SET body     = '" . serendipity_db_escape_string($dir['body']) . "' ,\n                                         extended = '" . serendipity_db_escape_string($dir['extended']) . "'\n                                   WHERE id       = " . serendipity_db_escape_string($dir['id']);
            serendipity_db_query($uq);
        }
        printf(MEDIA_DIRECTORY_MOVE_ENTRIES . '<br />', count($dirs));
    }
    return true;
}
 function verify()
 {
     global $serendipity;
     $url = 'https://browserid.org/verify';
     $assert = $_POST['assert'];
     $params = 'assertion=' . $assert . '&audience=' . urlencode($serendipity['baseURL']);
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_POST, 2);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
     $result = curl_exec($ch);
     curl_close($ch);
     $response = json_decode($result);
     if (isset($response) && $response->status == 'okay') {
         $email = $response->email;
         $audience = $response->audience;
         if ($audience != $serendipity['baseURL']) {
             // The login has the wrong host!
             $response->status = 'errorhost';
             $response->message = "Internal error logging you in (wrong host: {$audience})";
             $_SESSION['serendipityAuthedUser'] = false;
             @session_destroy();
         } else {
             // host ist correct, check what we have with this email
             $password = md5($email);
             $query = "SELECT DISTINCT a.email, a.authorid, a.userlevel, a.right_publish, a.realname\r\n                     FROM\r\n                       {$serendipity['dbPrefix']}authors AS a\r\n                     WHERE\r\n                       a.email = '{$email}'";
             $row = serendipity_db_query($query, true, 'assoc');
             if (is_array($row)) {
                 serendipity_setCookie('old_session', session_id());
                 serendipity_setAuthorToken();
                 $_SESSION['serendipityUser'] = $serendipity['serendipityUser'] = $row['realname'];
                 $_SESSION['serendipityPassword'] = $serendipity['serendipityPassword'] = $password;
                 $_SESSION['serendipityEmail'] = $serendipity['serendipityEmail'] = $email;
                 $_SESSION['serendipityAuthorid'] = $serendipity['authorid'] = $row['authorid'];
                 $_SESSION['serendipityUserlevel'] = $serendipity['serendipityUserlevel'] = $row['userlevel'];
                 $_SESSION['serendipityAuthedUser'] = $serendipity['serendipityAuthedUser'] = true;
                 $_SESSION['serendipityRightPublish'] = $serendipity['serendipityRightPublish'] = $row['right_publish'];
                 // Prevent session manupulation:
                 $_SESSION['serendipityBrowserID'] = $this->get_install_token();
                 serendipity_load_configuration($serendipity['authorid']);
             } else {
                 // No user found for that email!
                 $response->status = 's9yunknown';
                 $response->message = "Sorry, we don't have a user for {$email}";
                 $_SESSION['serendipityAuthedUser'] = false;
                 @session_destroy();
             }
         }
         $result = json_encode($response);
     }
     echo $result;
 }
function serveEntry($matches)
{
    global $serendipity;
    $serendipity['view'] = 'entry';
    $uri = $_SERVER['REQUEST_URI'];
    if (isset($serendipity['GET']['id'])) {
        $matches[1] = (int) $serendipity['GET']['id'];
    } elseif (isset($_GET['p'])) {
        $matches[1] = $_GET['p'];
    } else {
        $matches[1] = serendipity_searchPermalink($serendipity['permalinkStructure'], $uri, !empty($matches[2]) ? $matches[2] : $matches[1], 'entry');
    }
    serendipity_rememberComment();
    if (!empty($serendipity['POST']['submit']) && !isset($_REQUEST['serendipity']['csuccess'])) {
        $comment['url'] = $serendipity['POST']['url'];
        $comment['comment'] = trim($serendipity['POST']['comment']);
        $comment['name'] = $serendipity['POST']['name'];
        $comment['email'] = $serendipity['POST']['email'];
        $comment['subscribe'] = $serendipity['POST']['subscribe'];
        $comment['parent_id'] = $serendipity['POST']['replyTo'];
        if (!empty($comment['comment'])) {
            if (serendipity_saveComment($serendipity['POST']['entry_id'], $comment, 'NORMAL')) {
                $sc_url = ($_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . (strstr($_SERVER['REQUEST_URI'], '?') ? '&' : '?') . 'serendipity[csuccess]=' . (isset($serendipity['csuccess']) ? $serendipity['csuccess'] : 'true');
                if (serendipity_isResponseClean($sc_url)) {
                    header('Status: 302 Found');
                    header('Location: ' . $sc_url);
                }
                exit;
            } else {
                $serendipity['messagestack']['comments'][] = COMMENT_NOT_ADDED;
            }
        } else {
            $serendipity['messagestack']['comments'][] = sprintf(EMPTY_COMMENT, '', '');
        }
    }
    $id = (int) $matches[1];
    if ($id === 0) {
        $id = false;
    }
    $_GET['serendipity']['action'] = 'read';
    $_GET['serendipity']['id'] = $id;
    $title = serendipity_db_query("SELECT title FROM {$serendipity['dbPrefix']}entries WHERE id={$id} AND isdraft = 'false' " . (!serendipity_db_bool($serendipity['showFutureEntries']) ? " AND timestamp <= " . serendipity_db_time() : ''), true);
    if (is_array($title)) {
        $serendipity['head_title'] = serendipity_specialchars($title[0]);
        $serendipity['head_subtitle'] = serendipity_specialchars($serendipity['blogTitle']);
    } else {
        $serendipity['view'] = '404';
        $serendipity['viewtype'] = '404_1';
        header('HTTP/1.0 404 Not found');
        header('Status: 404 Not found');
    }
    include S9Y_INCLUDE_PATH . 'include/genpage.inc.php';
}
Example #29
0
/**
 * Prepares a Serendipty query input to fully valid SQL. Replaces certain "template" variables.
 *
 * @access public
 * @param  string   SQL query with template variables to convert
 * @return ressource    SQL ressource handle of the executed query
 */
function serendipity_db_schema_import($query)
{
    static $search = array('{AUTOINCREMENT}', '{PRIMARY}', '{UNSIGNED}', '{FULLTEXT}', '{BOOLEAN}', '{UTF_8}', '{TEXT}');
    static $replace = array('INTEGER', 'PRIMARY KEY', '', '', 'BOOLEAN NOT NULL', '', 'LONGTEXT');
    if (stristr($query, '{FULLTEXT_MYSQL}')) {
        return true;
    }
    $query = trim(str_replace($search, $replace, $query));
    if ($query[0] == '@') {
        // Errors are expected to happen (like duplicate index creation)
        return serendipity_db_query(substr($query, 1), false, 'both', false, false, false, true);
    } else {
        return serendipity_db_query($query);
    }
}
Example #30
0
$data['updateCheck'] = $serendipity['updateCheck'];
$data['curVersion'] = serendipity_getCurrentVersion();
$data['update'] = version_compare($data['usedVersion'], $data['curVersion'], '<');
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());