Esempio n. 1
0
/**
 * Retrieve adjacent post.
 *
 * Can either be next or previous post.
 *
 * @since 0.0.1
 *
 * @global hqdb $hqdb
 *
 * @param bool         $in_same_term   Optional. Whether post should be in a same taxonomy term.
 * @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
 * @param bool         $previous       Optional. Whether to retrieve previous post.
 * @param string       $taxonomy       Optional. Taxonomy, if $in_same_term is true. Default 'category'.
 * @return null|string|HQ_Post Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists.
 */
function get_adjacent_post($in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category')
{
    global $hqdb;
    if (!($post = get_post()) || !taxonomy_exists($taxonomy)) {
        return null;
    }
    $current_post_date = $post->post_date;
    $join = '';
    $where = '';
    if ($in_same_term || !empty($excluded_terms)) {
        $join = " INNER JOIN {$hqdb->term_relationships} AS tr ON p.ID = tr.object_id INNER JOIN {$hqdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
        $where = $hqdb->prepare("AND tt.taxonomy = %s", $taxonomy);
        if (!empty($excluded_terms) && !is_array($excluded_terms)) {
            // back-compat, $excluded_terms used to be $excluded_terms with IDs separated by " and "
            if (false !== strpos($excluded_terms, ' and ')) {
                _deprecated_argument(__FUNCTION__, '3.3', sprintf(__('Use commas instead of %s to separate excluded terms.'), "'and'"));
                $excluded_terms = explode(' and ', $excluded_terms);
            } else {
                $excluded_terms = explode(',', $excluded_terms);
            }
            $excluded_terms = array_map('intval', $excluded_terms);
        }
        if ($in_same_term) {
            if (!is_object_in_taxonomy($post->post_type, $taxonomy)) {
                return '';
            }
            $term_array = hq_get_object_terms($post->ID, $taxonomy, array('fields' => 'ids'));
            // Remove any exclusions from the term array to include.
            $term_array = array_diff($term_array, (array) $excluded_terms);
            $term_array = array_map('intval', $term_array);
            if (!$term_array || is_hq_error($term_array)) {
                return '';
            }
            $where .= " AND tt.term_id IN (" . implode(',', $term_array) . ")";
        }
        if (!empty($excluded_terms)) {
            $where .= " AND p.ID NOT IN ( SELECT tr.object_id FROM {$hqdb->term_relationships} tr LEFT JOIN {$hqdb->term_taxonomy} tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) WHERE tt.term_id IN (" . implode($excluded_terms, ',') . ') )';
        }
    }
    // 'post_status' clause depends on the current user.
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        $post_type_object = get_post_type_object($post->post_type);
        if (empty($post_type_object)) {
            $post_type_cap = $post->post_type;
            $read_private_cap = 'read_private_' . $post_type_cap . 's';
        } else {
            $read_private_cap = $post_type_object->cap->read_private_posts;
        }
        /*
         * Results should include private posts belonging to the current user, or private posts where the
         * current user has the 'read_private_posts' cap.
         */
        $private_states = get_post_stati(array('private' => true));
        $where .= " AND ( p.post_status = 'publish'";
        foreach ((array) $private_states as $state) {
            if (current_user_can($read_private_cap)) {
                $where .= $hqdb->prepare(" OR p.post_status = %s", $state);
            } else {
                $where .= $hqdb->prepare(" OR (p.post_author = %d AND p.post_status = %s)", $user_id, $state);
            }
        }
        $where .= " )";
    } else {
        $where .= " AND p.post_status = 'publish'";
    }
    $adjacent = $previous ? 'previous' : 'next';
    $op = $previous ? '<' : '>';
    $order = $previous ? 'DESC' : 'ASC';
    /**
     * Filter the JOIN clause in the SQL for an adjacent post query.
     *
     * The dynamic portion of the hook name, `$adjacent`, refers to the type
     * of adjacency, 'next' or 'previous'.
     *
     * @since 0.0.1
     *
     * @param string $join           The JOIN clause in the SQL.
     * @param bool   $in_same_term   Whether post should be in a same taxonomy term.
     * @param array  $excluded_terms Array of excluded term IDs.
     */
    $join = apply_filters("get_{$adjacent}_post_join", $join, $in_same_term, $excluded_terms);
    /**
     * Filter the WHERE clause in the SQL for an adjacent post query.
     *
     * The dynamic portion of the hook name, `$adjacent`, refers to the type
     * of adjacency, 'next' or 'previous'.
     *
     * @since 0.0.1
     *
     * @param string $where          The `WHERE` clause in the SQL.
     * @param bool   $in_same_term   Whether post should be in a same taxonomy term.
     * @param array  $excluded_terms Array of excluded term IDs.
     */
    $where = apply_filters("get_{$adjacent}_post_where", $hqdb->prepare("WHERE p.post_date {$op} %s AND p.post_type = %s {$where}", $current_post_date, $post->post_type), $in_same_term, $excluded_terms);
    /**
     * Filter the ORDER BY clause in the SQL for an adjacent post query.
     *
     * The dynamic portion of the hook name, `$adjacent`, refers to the type
     * of adjacency, 'next' or 'previous'.
     *
     * @since 0.0.1
     *
     * @param string $order_by The `ORDER BY` clause in the SQL.
     */
    $sort = apply_filters("get_{$adjacent}_post_sort", "ORDER BY p.post_date {$order} LIMIT 1");
    $query = "SELECT p.ID FROM {$hqdb->posts} AS p {$join} {$where} {$sort}";
    $query_key = 'adjacent_post_' . md5($query);
    $result = hq_cache_get($query_key, 'counts');
    if (false !== $result) {
        if ($result) {
            $result = get_post($result);
        }
        return $result;
    }
    $result = $hqdb->get_var($query);
    if (null === $result) {
        $result = '';
    }
    hq_cache_set($query_key, $result, 'counts');
    if ($result) {
        $result = get_post($result);
    }
    return $result;
}
Esempio n. 2
0
 /**
  * Get a list of comments matching the query vars.
  *
  * @since 0.0.1
  * @access public
  *
  * @global hqdb $hqdb HiveQueen database abstraction object.
  *
  * @return int|array The list of comments.
  */
 public function get_comments()
 {
     global $hqdb;
     $groupby = '';
     $this->parse_query();
     // Parse meta query
     $this->meta_query = new HQ_Meta_Query();
     $this->meta_query->parse_query_vars($this->query_vars);
     /**
      * Fires before comments are retrieved.
      *
      * @since 0.0.1
      *
      * @param HQ_Comment_Query &$this Current instance of HQ_Comment_Query, passed by reference.
      */
     do_action_ref_array('pre_get_comments', array(&$this));
     // Reparse query vars, in case they were modified in a 'pre_get_comments' callback.
     $this->meta_query->parse_query_vars($this->query_vars);
     if (!empty($this->meta_query->queries)) {
         $meta_query_clauses = $this->meta_query->get_sql('comment', $hqdb->comments, 'comment_ID', $this);
     }
     // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
     $key = md5(serialize(hq_array_slice_assoc($this->query_vars, array_keys($this->query_var_defaults))));
     $last_changed = hq_cache_get('last_changed', 'comment');
     if (!$last_changed) {
         $last_changed = microtime();
         hq_cache_set('last_changed', $last_changed, 'comment');
     }
     $cache_key = "get_comments:{$key}:{$last_changed}";
     if ($cache = hq_cache_get($cache_key, 'comment')) {
         $this->comments = $cache;
         return $this->comments;
     }
     $where = array();
     // Assemble clauses related to 'comment_approved'.
     $approved_clauses = array();
     // 'status' accepts an array or a comma-separated string.
     $status_clauses = array();
     $statuses = $this->query_vars['status'];
     if (!is_array($statuses)) {
         $statuses = preg_split('/[\\s,]+/', $statuses);
     }
     // 'any' overrides other statuses.
     if (!in_array('any', $statuses)) {
         foreach ($statuses as $status) {
             switch ($status) {
                 case 'hold':
                     $status_clauses[] = "comment_approved = '0'";
                     break;
                 case 'approve':
                     $status_clauses[] = "comment_approved = '1'";
                     break;
                 case 'all':
                 case '':
                     $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
                     break;
                 default:
                     $status_clauses[] = $hqdb->prepare("comment_approved = %s", $status);
                     break;
             }
         }
         if (!empty($status_clauses)) {
             $approved_clauses[] = '( ' . implode(' OR ', $status_clauses) . ' )';
         }
     }
     // User IDs or emails whose unapproved comments are included, regardless of $status.
     if (!empty($this->query_vars['include_unapproved'])) {
         $include_unapproved = $this->query_vars['include_unapproved'];
         // Accepts arrays or comma-separated strings.
         if (!is_array($include_unapproved)) {
             $include_unapproved = preg_split('/[\\s,]+/', $include_unapproved);
         }
         $unapproved_ids = $unapproved_emails = array();
         foreach ($include_unapproved as $unapproved_identifier) {
             // Numeric values are assumed to be user ids.
             if (is_numeric($unapproved_identifier)) {
                 $approved_clauses[] = $hqdb->prepare("( user_id = %d AND comment_approved = '0' )", $unapproved_identifier);
                 // Otherwise we match against email addresses.
             } else {
                 $approved_clauses[] = $hqdb->prepare("( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier);
             }
         }
     }
     // Collapse comment_approved clauses into a single OR-separated clause.
     if (!empty($approved_clauses)) {
         if (1 === count($approved_clauses)) {
             $where[] = $approved_clauses[0];
         } else {
             $where[] = '( ' . implode(' OR ', $approved_clauses) . ' )';
         }
     }
     $order = 'ASC' == strtoupper($this->query_vars['order']) ? 'ASC' : 'DESC';
     // Disable ORDER BY with 'none', an empty array, or boolean false.
     if (in_array($this->query_vars['orderby'], array('none', array(), false), true)) {
         $orderby = '';
     } elseif (!empty($this->query_vars['orderby'])) {
         $ordersby = is_array($this->query_vars['orderby']) ? $this->query_vars['orderby'] : preg_split('/[,\\s]/', $this->query_vars['orderby']);
         $orderby_array = array();
         $found_orderby_comment_ID = false;
         foreach ($ordersby as $_key => $_value) {
             if (!$_value) {
                 continue;
             }
             if (is_int($_key)) {
                 $_orderby = $_value;
                 $_order = $order;
             } else {
                 $_orderby = $_key;
                 $_order = $_value;
             }
             if (!$found_orderby_comment_ID && 'comment_ID' === $_orderby) {
                 $found_orderby_comment_ID = true;
             }
             $parsed = $this->parse_orderby($_orderby);
             if (!$parsed) {
                 continue;
             }
             $orderby_array[] = $parsed . ' ' . $this->parse_order($_order);
         }
         // If no valid clauses were found, order by comment_date_gmt.
         if (empty($orderby_array)) {
             $orderby_array[] = "{$hqdb->comments}.comment_date_gmt {$order}";
         }
         // To ensure determinate sorting, always include a comment_ID clause.
         if (!$found_orderby_comment_ID) {
             $comment_ID_order = '';
             // Inherit order from comment_date or comment_date_gmt, if available.
             foreach ($orderby_array as $orderby_clause) {
                 if (preg_match('/comment_date(?:_gmt)*\\ (ASC|DESC)/', $orderby_clause, $match)) {
                     $comment_ID_order = $match[1];
                     break;
                 }
             }
             // If no date-related order is available, use the date from the first available clause.
             if (!$comment_ID_order) {
                 foreach ($orderby_array as $orderby_clause) {
                     if (false !== strpos('ASC', $orderby_clause)) {
                         $comment_ID_order = 'ASC';
                     } else {
                         $comment_ID_order = 'DESC';
                     }
                     break;
                 }
             }
             // Default to DESC.
             if (!$comment_ID_order) {
                 $comment_ID_order = 'DESC';
             }
             $orderby_array[] = "{$hqdb->comments}.comment_ID {$comment_ID_order}";
         }
         $orderby = implode(', ', $orderby_array);
     } else {
         $orderby = "{$hqdb->comments}.comment_date_gmt {$order}";
     }
     $number = absint($this->query_vars['number']);
     $offset = absint($this->query_vars['offset']);
     if (!empty($number)) {
         if ($offset) {
             $limits = 'LIMIT ' . $offset . ',' . $number;
         } else {
             $limits = 'LIMIT ' . $number;
         }
     } else {
         $limits = '';
     }
     if ($this->query_vars['count']) {
         $fields = 'COUNT(*)';
     } else {
         switch (strtolower($this->query_vars['fields'])) {
             case 'ids':
                 $fields = "{$hqdb->comments}.comment_ID";
                 break;
             default:
                 $fields = "*";
                 break;
         }
     }
     $join = '';
     $post_id = absint($this->query_vars['post_id']);
     if (!empty($post_id)) {
         $where[] = $hqdb->prepare('comment_post_ID = %d', $post_id);
     }
     // Parse comment IDs for an IN clause.
     if (!empty($this->query_vars['comment__in'])) {
         $where[] = "{$hqdb->comments}.comment_ID IN ( " . implode(',', hq_parse_id_list($this->query_vars['comment__in'])) . ' )';
     }
     // Parse comment IDs for a NOT IN clause.
     if (!empty($this->query_vars['comment__not_in'])) {
         $where[] = "{$hqdb->comments}.comment_ID NOT IN ( " . implode(',', hq_parse_id_list($this->query_vars['comment__not_in'])) . ' )';
     }
     // Parse comment post IDs for an IN clause.
     if (!empty($this->query_vars['post__in'])) {
         $where[] = 'comment_post_ID IN ( ' . implode(',', hq_parse_id_list($this->query_vars['post__in'])) . ' )';
     }
     // Parse comment post IDs for a NOT IN clause.
     if (!empty($this->query_vars['post__not_in'])) {
         $where[] = 'comment_post_ID NOT IN ( ' . implode(',', hq_parse_id_list($this->query_vars['post__not_in'])) . ' )';
     }
     if ('' !== $this->query_vars['author_email']) {
         $where[] = $hqdb->prepare('comment_author_email = %s', $this->query_vars['author_email']);
     }
     if ('' !== $this->query_vars['karma']) {
         $where[] = $hqdb->prepare('comment_karma = %d', $this->query_vars['karma']);
     }
     // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
     $raw_types = array('IN' => array_merge((array) $this->query_vars['type'], (array) $this->query_vars['type__in']), 'NOT IN' => (array) $this->query_vars['type__not_in']);
     $comment_types = array();
     foreach ($raw_types as $operator => $_raw_types) {
         $_raw_types = array_unique($_raw_types);
         foreach ($_raw_types as $type) {
             switch ($type) {
                 // An empty translates to 'all', for backward compatibility
                 case '':
                 case 'all':
                     break;
                 case 'comment':
                 case 'comments':
                     $comment_types[$operator][] = "''";
                     break;
                 case 'pings':
                     $comment_types[$operator][] = "'pingback'";
                     $comment_types[$operator][] = "'trackback'";
                     break;
                 default:
                     $comment_types[$operator][] = $hqdb->prepare('%s', $type);
                     break;
             }
         }
         if (!empty($comment_types[$operator])) {
             $types_sql = implode(', ', $comment_types[$operator]);
             $where[] = "comment_type {$operator} ({$types_sql})";
         }
     }
     if ('' !== $this->query_vars['parent']) {
         $where[] = $hqdb->prepare('comment_parent = %d', $this->query_vars['parent']);
     }
     if (is_array($this->query_vars['user_id'])) {
         $where[] = 'user_id IN (' . implode(',', array_map('absint', $this->query_vars['user_id'])) . ')';
     } elseif ('' !== $this->query_vars['user_id']) {
         $where[] = $hqdb->prepare('user_id = %d', $this->query_vars['user_id']);
     }
     if ('' !== $this->query_vars['search']) {
         $search_sql = $this->get_search_sql($this->query_vars['search'], array('comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content'));
         // Strip leading 'AND'.
         $where[] = preg_replace('/^\\s*AND\\s*/', '', $search_sql);
     }
     // If any post-related query vars are passed, join the posts table.
     $join_posts_table = false;
     $plucked = hq_array_slice_assoc($this->query_vars, array('post_author', 'post_name', 'post_parent', 'post_status', 'post_type'));
     $post_fields = array_filter($plucked);
     if (!empty($post_fields)) {
         $join_posts_table = true;
         foreach ($post_fields as $field_name => $field_value) {
             // $field_value may be an array.
             $esses = array_fill(0, count((array) $field_value), '%s');
             $where[] = $hqdb->prepare(" {$hqdb->posts}.{$field_name} IN (" . implode(',', $esses) . ')', $field_value);
         }
     }
     // Comment author IDs for an IN clause.
     if (!empty($this->query_vars['author__in'])) {
         $where[] = 'user_id IN ( ' . implode(',', hq_parse_id_list($this->query_vars['author__in'])) . ' )';
     }
     // Comment author IDs for a NOT IN clause.
     if (!empty($this->query_vars['author__not_in'])) {
         $where[] = 'user_id NOT IN ( ' . implode(',', hq_parse_id_list($this->query_vars['author__not_in'])) . ' )';
     }
     // Post author IDs for an IN clause.
     if (!empty($this->query_vars['post_author__in'])) {
         $join_posts_table = true;
         $where[] = 'post_author IN ( ' . implode(',', hq_parse_id_list($this->query_vars['post_author__in'])) . ' )';
     }
     // Post author IDs for a NOT IN clause.
     if (!empty($this->query_vars['post_author__not_in'])) {
         $join_posts_table = true;
         $where[] = 'post_author NOT IN ( ' . implode(',', hq_parse_id_list($this->query_vars['post_author__not_in'])) . ' )';
     }
     if ($join_posts_table) {
         $join = "JOIN {$hqdb->posts} ON {$hqdb->posts}.ID = {$hqdb->comments}.comment_post_ID";
     }
     if (!empty($meta_query_clauses)) {
         $join .= $meta_query_clauses['join'];
         // Strip leading 'AND'.
         $where[] = preg_replace('/^\\s*AND\\s*/', '', $meta_query_clauses['where']);
         if (!$this->query_vars['count']) {
             $groupby = "{$hqdb->comments}.comment_ID";
         }
     }
     $date_query = $this->query_vars['date_query'];
     if (!empty($date_query) && is_array($date_query)) {
         $date_query_object = new HQ_Date_Query($date_query, 'comment_date');
         $where[] = preg_replace('/^\\s*AND\\s*/', '', $date_query_object->get_sql());
     }
     $where = implode(' AND ', $where);
     $pieces = array('fields', 'join', 'where', 'orderby', 'limits', 'groupby');
     /**
      * Filter the comment query clauses.
      *
      * @since 0.0.1
      *
      * @param array            $pieces A compacted array of comment query clauses.
      * @param HQ_Comment_Query &$this  Current instance of HQ_Comment_Query, passed by reference.
      */
     $clauses = apply_filters_ref_array('comments_clauses', array(compact($pieces), &$this));
     $fields = isset($clauses['fields']) ? $clauses['fields'] : '';
     $join = isset($clauses['join']) ? $clauses['join'] : '';
     $where = isset($clauses['where']) ? $clauses['where'] : '';
     $orderby = isset($clauses['orderby']) ? $clauses['orderby'] : '';
     $limits = isset($clauses['limits']) ? $clauses['limits'] : '';
     $groupby = isset($clauses['groupby']) ? $clauses['groupby'] : '';
     if ($where) {
         $where = 'WHERE ' . $where;
     }
     if ($groupby) {
         $groupby = 'GROUP BY ' . $groupby;
     }
     if ($orderby) {
         $orderby = "ORDER BY {$orderby}";
     }
     $this->request = "SELECT {$fields} FROM {$hqdb->comments} {$join} {$where} {$groupby} {$orderby} {$limits}";
     if ($this->query_vars['count']) {
         return $hqdb->get_var($this->request);
     }
     if ('ids' == $this->query_vars['fields']) {
         $this->comments = $hqdb->get_col($this->request);
         return array_map('intval', $this->comments);
     }
     $results = $hqdb->get_results($this->request);
     /**
      * Filter the comment query results.
      *
      * @since 0.0.1
      *
      * @param array            $results  An array of comments.
      * @param HQ_Comment_Query &$this    Current instance of HQ_Comment_Query, passed by reference.
      */
     $comments = apply_filters_ref_array('the_comments', array($results, &$this));
     hq_cache_add($cache_key, $comments, 'comment');
     if ('*' === $fields) {
         update_comment_cache($comments);
     }
     $this->comments = $comments;
     return $this->comments;
 }
Esempio n. 3
0
 /**
  * @global array  $comments
  * @global object $comment
  *
  * @param array $args
  * @param array $instance
  */
 public function widget($args, $instance)
 {
     global $comments, $comment;
     $cache = array();
     if (!$this->is_preview()) {
         $cache = hq_cache_get('widget_recent_comments', 'widget');
     }
     if (!is_array($cache)) {
         $cache = array();
     }
     if (!isset($args['widget_id'])) {
         $args['widget_id'] = $this->id;
     }
     if (isset($cache[$args['widget_id']])) {
         echo $cache[$args['widget_id']];
         return;
     }
     $output = '';
     $title = !empty($instance['title']) ? $instance['title'] : __('Recent Comments');
     /** This filter is documented in hq-includes/default-widgets.php */
     $title = apply_filters('widget_title', $title, $instance, $this->id_base);
     $number = !empty($instance['number']) ? absint($instance['number']) : 5;
     if (!$number) {
         $number = 5;
     }
     /**
      * Filter the arguments for the Recent Comments widget.
      *
      * @since 0.0.1
      *
      * @see HQ_Comment_Query::query() for information on accepted arguments.
      *
      * @param array $comment_args An array of arguments used to retrieve the recent comments.
      */
     $comments = get_comments(apply_filters('widget_comments_args', array('number' => $number, 'status' => 'approve', 'post_status' => 'publish')));
     $output .= $args['before_widget'];
     if ($title) {
         $output .= $args['before_title'] . $title . $args['after_title'];
     }
     $output .= '<ul id="recentcomments">';
     if (is_array($comments) && $comments) {
         // Prime cache for associated posts. (Prime post term cache if we need it for permalinks.)
         $post_ids = array_unique(hq_list_pluck($comments, 'comment_post_ID'));
         _prime_post_caches($post_ids, strpos(get_option('permalink_structure'), '%category%'), false);
         foreach ((array) $comments as $comment) {
             $output .= '<li class="recentcomments">';
             /* translators: comments widget: 1: comment author, 2: post link */
             $output .= sprintf(_x('%1$s on %2$s', 'widgets'), '<span class="comment-author-link">' . get_comment_author_link() . '</span>', '<a href="' . esc_url(get_comment_link($comment->comment_ID)) . '">' . get_the_title($comment->comment_post_ID) . '</a>');
             $output .= '</li>';
         }
     }
     $output .= '</ul>';
     $output .= $args['after_widget'];
     echo $output;
     if (!$this->is_preview()) {
         $cache[$args['widget_id']] = $output;
         hq_cache_set('widget_recent_comments', $cache, 'widget');
     }
 }
Esempio n. 4
0
/**
 * Display calendar with days that have posts as links.
 *
 * The calendar is cached, which will be retrieved, if it exists. If there are
 * no posts for the month, then it will not be displayed.
 *
 * @since 0.0.1
 *
 * @global hqdb      $hqdb
 * @global int       $m
 * @global int       $monthnum
 * @global int       $year
 * @global HQ_Locale $hq_locale
 * @global array     $posts
 *
 * @param bool $initial Optional, default is true. Use initial calendar names.
 * @param bool $echo    Optional, default is true. Set to false for return.
 * @return string|void String when retrieving.
 */
function get_calendar($initial = true, $echo = true)
{
    global $hqdb, $m, $monthnum, $year, $hq_locale, $posts;
    $key = md5($m . $monthnum . $year);
    if ($cache = hq_cache_get('get_calendar', 'calendar')) {
        if (is_array($cache) && isset($cache[$key])) {
            if ($echo) {
                /** This filter is documented in hq-includes/general-template.php */
                echo apply_filters('get_calendar', $cache[$key]);
                return;
            } else {
                /** This filter is documented in hq-includes/general-template.php */
                return apply_filters('get_calendar', $cache[$key]);
            }
        }
    }
    if (!is_array($cache)) {
        $cache = array();
    }
    // Quick check. If we have no posts at all, abort!
    if (!$posts) {
        $gotsome = $hqdb->get_var("SELECT 1 as test FROM {$hqdb->posts} WHERE post_type = 'post' AND post_status = 'publish' LIMIT 1");
        if (!$gotsome) {
            $cache[$key] = '';
            hq_cache_set('get_calendar', $cache, 'calendar');
            return;
        }
    }
    if (isset($_GET['w'])) {
        $w = '' . intval($_GET['w']);
    }
    // week_begins = 0 stands for Sunday
    $week_begins = intval(get_option('start_of_week'));
    // Let's figure out when we are
    if (!empty($monthnum) && !empty($year)) {
        $thismonth = '' . zeroise(intval($monthnum), 2);
        $thisyear = '' . intval($year);
    } elseif (!empty($w)) {
        // We need to get the month from MySQL
        $thisyear = '' . intval(substr($m, 0, 4));
        $d = ($w - 1) * 7 + 6;
        //it seems MySQL's weeks disagree with PHP's
        $thismonth = $hqdb->get_var("SELECT DATE_FORMAT((DATE_ADD('{$thisyear}0101', INTERVAL {$d} DAY) ), '%m')");
    } elseif (!empty($m)) {
        $thisyear = '' . intval(substr($m, 0, 4));
        if (strlen($m) < 6) {
            $thismonth = '01';
        } else {
            $thismonth = '' . zeroise(intval(substr($m, 4, 2)), 2);
        }
    } else {
        $thisyear = gmdate('Y', current_time('timestamp'));
        $thismonth = gmdate('m', current_time('timestamp'));
    }
    $unixmonth = mktime(0, 0, 0, $thismonth, 1, $thisyear);
    $last_day = date('t', $unixmonth);
    // Get the next and previous month and year with at least one post
    $previous = $hqdb->get_row("SELECT MONTH(post_date) AS month, YEAR(post_date) AS year\n\t\tFROM {$hqdb->posts}\n\t\tWHERE post_date < '{$thisyear}-{$thismonth}-01'\n\t\tAND post_type = 'post' AND post_status = 'publish'\n\t\t\tORDER BY post_date DESC\n\t\t\tLIMIT 1");
    $next = $hqdb->get_row("SELECT MONTH(post_date) AS month, YEAR(post_date) AS year\n\t\tFROM {$hqdb->posts}\n\t\tWHERE post_date > '{$thisyear}-{$thismonth}-{$last_day} 23:59:59'\n\t\tAND post_type = 'post' AND post_status = 'publish'\n\t\t\tORDER BY post_date ASC\n\t\t\tLIMIT 1");
    /* translators: Calendar caption: 1: month name, 2: 4-digit year */
    $calendar_caption = _x('%1$s %2$s', 'calendar caption');
    $calendar_output = '<table id="hq-calendar">
	<caption>' . sprintf($calendar_caption, $hq_locale->get_month($thismonth), date('Y', $unixmonth)) . '</caption>
	<thead>
	<tr>';
    $myweek = array();
    for ($wdcount = 0; $wdcount <= 6; $wdcount++) {
        $myweek[] = $hq_locale->get_weekday(($wdcount + $week_begins) % 7);
    }
    foreach ($myweek as $wd) {
        $day_name = $initial ? $hq_locale->get_weekday_initial($wd) : $hq_locale->get_weekday_abbrev($wd);
        $wd = esc_attr($wd);
        $calendar_output .= "\n\t\t<th scope=\"col\" title=\"{$wd}\">{$day_name}</th>";
    }
    $calendar_output .= '
	</tr>
	</thead>

	<tfoot>
	<tr>';
    if ($previous) {
        $calendar_output .= "\n\t\t" . '<td colspan="3" id="prev"><a href="' . get_month_link($previous->year, $previous->month) . '">&laquo; ' . $hq_locale->get_month_abbrev($hq_locale->get_month($previous->month)) . '</a></td>';
    } else {
        $calendar_output .= "\n\t\t" . '<td colspan="3" id="prev" class="pad">&nbsp;</td>';
    }
    $calendar_output .= "\n\t\t" . '<td class="pad">&nbsp;</td>';
    if ($next) {
        $calendar_output .= "\n\t\t" . '<td colspan="3" id="next"><a href="' . get_month_link($next->year, $next->month) . '">' . $hq_locale->get_month_abbrev($hq_locale->get_month($next->month)) . ' &raquo;</a></td>';
    } else {
        $calendar_output .= "\n\t\t" . '<td colspan="3" id="next" class="pad">&nbsp;</td>';
    }
    $calendar_output .= '
	</tr>
	</tfoot>

	<tbody>
	<tr>';
    $daywithpost = array();
    // Get days with posts
    $dayswithposts = $hqdb->get_results("SELECT DISTINCT DAYOFMONTH(post_date)\n\t\tFROM {$hqdb->posts} WHERE post_date >= '{$thisyear}-{$thismonth}-01 00:00:00'\n\t\tAND post_type = 'post' AND post_status = 'publish'\n\t\tAND post_date <= '{$thisyear}-{$thismonth}-{$last_day} 23:59:59'", ARRAY_N);
    if ($dayswithposts) {
        foreach ((array) $dayswithposts as $daywith) {
            $daywithpost[] = $daywith[0];
        }
    }
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'camino') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'safari') !== false) {
        $ak_title_separator = "\n";
    } else {
        $ak_title_separator = ', ';
    }
    $ak_titles_for_day = array();
    $ak_post_titles = $hqdb->get_results("SELECT ID, post_title, DAYOFMONTH(post_date) as dom " . "FROM {$hqdb->posts} " . "WHERE post_date >= '{$thisyear}-{$thismonth}-01 00:00:00' " . "AND post_date <= '{$thisyear}-{$thismonth}-{$last_day} 23:59:59' " . "AND post_type = 'post' AND post_status = 'publish'");
    if ($ak_post_titles) {
        foreach ((array) $ak_post_titles as $ak_post_title) {
            /** This filter is documented in hq-includes/post-template.php */
            $post_title = esc_attr(apply_filters('the_title', $ak_post_title->post_title, $ak_post_title->ID));
            if (empty($ak_titles_for_day['day_' . $ak_post_title->dom])) {
                $ak_titles_for_day['day_' . $ak_post_title->dom] = '';
            }
            if (empty($ak_titles_for_day["{$ak_post_title->dom}"])) {
                // first one
                $ak_titles_for_day["{$ak_post_title->dom}"] = $post_title;
            } else {
                $ak_titles_for_day["{$ak_post_title->dom}"] .= $ak_title_separator . $post_title;
            }
        }
    }
    // See how much we should pad in the beginning
    $pad = calendar_week_mod(date('w', $unixmonth) - $week_begins);
    if (0 != $pad) {
        $calendar_output .= "\n\t\t" . '<td colspan="' . esc_attr($pad) . '" class="pad">&nbsp;</td>';
    }
    $daysinmonth = intval(date('t', $unixmonth));
    for ($day = 1; $day <= $daysinmonth; ++$day) {
        if (isset($newrow) && $newrow) {
            $calendar_output .= "\n\t</tr>\n\t<tr>\n\t\t";
        }
        $newrow = false;
        if ($day == gmdate('j', current_time('timestamp')) && $thismonth == gmdate('m', current_time('timestamp')) && $thisyear == gmdate('Y', current_time('timestamp'))) {
            $calendar_output .= '<td id="today">';
        } else {
            $calendar_output .= '<td>';
        }
        if (in_array($day, $daywithpost)) {
            // any posts today?
            $calendar_output .= '<a href="' . get_day_link($thisyear, $thismonth, $day) . '" title="' . esc_attr($ak_titles_for_day[$day]) . "\">{$day}</a>";
        } else {
            $calendar_output .= $day;
        }
        $calendar_output .= '</td>';
        if (6 == calendar_week_mod(date('w', mktime(0, 0, 0, $thismonth, $day, $thisyear)) - $week_begins)) {
            $newrow = true;
        }
    }
    $pad = 7 - calendar_week_mod(date('w', mktime(0, 0, 0, $thismonth, $day, $thisyear)) - $week_begins);
    if ($pad != 0 && $pad != 7) {
        $calendar_output .= "\n\t\t" . '<td class="pad" colspan="' . esc_attr($pad) . '">&nbsp;</td>';
    }
    $calendar_output .= "\n\t</tr>\n\t</tbody>\n\t</table>";
    $cache[$key] = $calendar_output;
    hq_cache_set('get_calendar', $cache, 'calendar');
    if ($echo) {
        /**
         * Filter the HTML calendar output.
         *
         * @since 0.0.1
         *
         * @param string $calendar_output HTML output of the calendar.
         */
        echo apply_filters('get_calendar', $calendar_output);
    } else {
        /** This filter is documented in hq-includes/general-template.php */
        return apply_filters('get_calendar', $calendar_output);
    }
}
Esempio n. 5
0
/**
 * Set/update the value of a site transient.
 *
 * You do not need to serialize values, if the value needs to be serialize, then
 * it will be serialized before it is set.
 *
 * @since 0.0.1
 *
 * @see set_transient()
 *
 * @param string $transient  Transient name. Expected to not be SQL-escaped. Must be
 *                           40 characters or fewer in length.
 * @param mixed  $value      Transient value. Expected to not be SQL-escaped.
 * @param int    $expiration Optional. Time until expiration in seconds. Default 0.
 * @return bool False if value was not set and true if value was set.
 */
function set_site_transient($transient, $value, $expiration = 0)
{
    /**
     * Filter the value of a specific site transient before it is set.
     *
     * The dynamic portion of the hook name, `$transient`, refers to the transient name.
     *
     * @since 0.0.1
     *
     * @param mixed $value Value of site transient.
     */
    $value = apply_filters('pre_set_site_transient_' . $transient, $value);
    $expiration = (int) $expiration;
    if (hq_using_ext_object_cache()) {
        $result = hq_cache_set($transient, $value, 'site-transient', $expiration);
    } else {
        $transient_timeout = '_site_transient_timeout_' . $transient;
        $option = '_site_transient_' . $transient;
        if (false === get_site_option($option)) {
            if ($expiration) {
                add_site_option($transient_timeout, time() + $expiration);
            }
            $result = add_site_option($option, $value);
        } else {
            if ($expiration) {
                update_site_option($transient_timeout, time() + $expiration);
            }
            $result = update_site_option($option, $value);
        }
    }
    if ($result) {
        /**
         * Fires after the value for a specific site transient has been set.
         *
         * The dynamic portion of the hook name, `$transient`, refers to the transient name.
         *
         * @since 0.0.1
         *
         * @param mixed $value      Site transient value.
         * @param int   $expiration Time until expiration in seconds. Default 0.
         */
        do_action('set_site_transient_' . $transient, $value, $expiration);
        /**
         * Fires after the value for a site transient has been set.
         *
         * @since 0.0.1
         *
         * @param string $transient  The name of the site transient.
         * @param mixed  $value      Site transient value.
         * @param int    $expiration Time until expiration in seconds. Default 0.
         */
        do_action('setted_site_transient', $transient, $value, $expiration);
    }
    return $result;
}
Esempio n. 6
0
/**
 * Will clean the post in the cache.
 *
 * Cleaning means delete from the cache of the post. Will call to clean the term
 * object cache associated with the post ID.
 *
 * This function not run if $_hq_suspend_cache_invalidation is not empty. See
 * hq_suspend_cache_invalidation().
 *
 * @since 0.0.1
 *
 * @global bool $_hq_suspend_cache_invalidation
 * @global hqdb $hqdb HiveQueen database abstraction object.
 *
 * @param int|HQ_Post $post Post ID or post object to remove from the cache.
 */
function clean_post_cache($post)
{
    global $_hq_suspend_cache_invalidation, $hqdb;
    if (!empty($_hq_suspend_cache_invalidation)) {
        return;
    }
    $post = get_post($post);
    if (empty($post)) {
        return;
    }
    hq_cache_delete($post->ID, 'posts');
    hq_cache_delete($post->ID, 'post_meta');
    clean_object_term_cache($post->ID, $post->post_type);
    hq_cache_delete('hq_get_archives', 'general');
    /**
     * Fires immediately after the given post's cache is cleaned.
     *
     * @since 0.0.1
     *
     * @param int     $post_id Post ID.
     * @param HQ_Post $post    Post object.
     */
    do_action('clean_post_cache', $post->ID, $post);
    if ('page' == $post->post_type) {
        hq_cache_delete('all_page_ids', 'posts');
        /**
         * Fires immediately after the given page's cache is cleaned.
         *
         * @since 0.0.1
         *
         * @param int $post_id Post ID.
         */
        do_action('clean_page_cache', $post->ID);
    }
    hq_cache_set('last_changed', microtime(), 'posts');
}
Esempio n. 7
0
/**
 * Check the plugins directory and retrieve all plugin files with plugin data.
 *
 * HiveQueen only supports plugin files in the base plugins directory
 * (hq-content/plugins) and in one directory above the plugins directory
 * (hq-content/plugins/my-plugin). The file it looks for has the plugin data
 * and must be found in those two locations. It is recommended to keep your
 * plugin files in their own directories.
 *
 * The file with the plugin data is the file that will be included and therefore
 * needs to have the main execution for the plugin. This does not mean
 * everything must be contained in the file and it is recommended that the file
 * be split for maintainability. Keep everything in one file for extreme
 * optimization purposes.
 *
 * @since 0.0.1
 *
 * @param string $plugin_folder Optional. Relative path to single plugin folder.
 * @return array Key is the plugin file path and the value is an array of the plugin data.
 */
function get_plugins($plugin_folder = '')
{
    if (!($cache_plugins = hq_cache_get('plugins', 'plugins'))) {
        $cache_plugins = array();
    }
    if (isset($cache_plugins[$plugin_folder])) {
        return $cache_plugins[$plugin_folder];
    }
    $hq_plugins = array();
    $plugin_root = HQ_PLUGIN_DIR;
    if (!empty($plugin_folder)) {
        $plugin_root .= $plugin_folder;
    }
    // Files in hq-content/plugins directory
    $plugins_dir = @opendir($plugin_root);
    $plugin_files = array();
    if ($plugins_dir) {
        while (($file = readdir($plugins_dir)) !== false) {
            if (substr($file, 0, 1) == '.') {
                continue;
            }
            if (is_dir($plugin_root . '/' . $file)) {
                $plugins_subdir = @opendir($plugin_root . '/' . $file);
                if ($plugins_subdir) {
                    while (($subfile = readdir($plugins_subdir)) !== false) {
                        if (substr($subfile, 0, 1) == '.') {
                            continue;
                        }
                        if (substr($subfile, -4) == '.php') {
                            $plugin_files[] = "{$file}/{$subfile}";
                        }
                    }
                    closedir($plugins_subdir);
                }
            } else {
                if (substr($file, -4) == '.php') {
                    $plugin_files[] = $file;
                }
            }
        }
        closedir($plugins_dir);
    }
    if (empty($plugin_files)) {
        return $hq_plugins;
    }
    foreach ($plugin_files as $plugin_file) {
        if (!is_readable("{$plugin_root}/{$plugin_file}")) {
            continue;
        }
        $plugin_data = get_plugin_data("{$plugin_root}/{$plugin_file}", false, false);
        //Do not apply markup/translate as it'll be cached.
        if (empty($plugin_data['Name'])) {
            continue;
        }
        $hq_plugins[plugin_basename($plugin_file)] = $plugin_data;
    }
    uasort($hq_plugins, '_sort_uname_callback');
    $cache_plugins[$plugin_folder] = $hq_plugins;
    hq_cache_set('plugins', $cache_plugins, 'plugins');
    return $hq_plugins;
}