Example #1
0
/**
 * Display archive links based on type and format.
 *
 * @since 1.2.0
 *
 * @see get_archives_link()
 *
 * @global wpdb      $wpdb
 * @global WP_Locale $wp_locale
 *
 * @param string|array $args {
 *     Default archive links arguments. Optional.
 *
 *     @type string     $type            Type of archive to retrieve. Accepts 'daily', 'weekly', 'monthly',
 *                                       'yearly', 'postbypost', or 'alpha'. Both 'postbypost' and 'alpha'
 *                                       display the same archive link list as well as post titles instead
 *                                       of displaying dates. The difference between the two is that 'alpha'
 *                                       will order by post title and 'postbypost' will order by post date.
 *                                       Default 'monthly'.
 *     @type string|int $limit           Number of links to limit the query to. Default empty (no limit).
 *     @type string     $format          Format each link should take using the $before and $after args.
 *                                       Accepts 'link' (`<link>` tag), 'option' (`<option>` tag), 'html'
 *                                       (`<li>` tag), or a custom format, which generates a link anchor
 *                                       with $before preceding and $after succeeding. Default 'html'.
 *     @type string     $before          Markup to prepend to the beginning of each link. Default empty.
 *     @type string     $after           Markup to append to the end of each link. Default empty.
 *     @type bool       $show_post_count Whether to display the post count alongside the link. Default false.
 *     @type bool|int   $echo            Whether to echo or return the links list. Default 1|true to echo.
 *     @type string     $order           Whether to use ascending or descending order. Accepts 'ASC', or 'DESC'.
 *                                       Default 'DESC'.
 * }
 * @return string|void String when retrieving.
 */
function wp_get_archives($args = '')
{
    global $wpdb, $wp_locale;
    $defaults = array('type' => 'monthly', 'limit' => '', 'format' => 'html', 'before' => '', 'after' => '', 'show_post_count' => false, 'echo' => 1, 'order' => 'DESC');
    $r = wp_parse_args($args, $defaults);
    if ('' == $r['type']) {
        $r['type'] = 'monthly';
    }
    if (!empty($r['limit'])) {
        $r['limit'] = absint($r['limit']);
        $r['limit'] = ' LIMIT ' . $r['limit'];
    }
    $order = strtoupper($r['order']);
    if ($order !== 'ASC') {
        $order = 'DESC';
    }
    // this is what will separate dates on weekly archive links
    $archive_week_separator = '&#8211;';
    // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
    $archive_date_format_over_ride = 0;
    // options for daily archive (only if you over-ride the general date format)
    $archive_day_date_format = 'Y/m/d';
    // options for weekly archive (only if you over-ride the general date format)
    $archive_week_start_date_format = 'Y/m/d';
    $archive_week_end_date_format = 'Y/m/d';
    if (!$archive_date_format_over_ride) {
        $archive_day_date_format = get_option('date_format');
        $archive_week_start_date_format = get_option('date_format');
        $archive_week_end_date_format = get_option('date_format');
    }
    /**
     * Filter the SQL WHERE clause for retrieving archives.
     *
     * @since 2.2.0
     *
     * @param string $sql_where Portion of SQL query containing the WHERE clause.
     * @param array  $r         An array of default arguments.
     */
    $where = apply_filters('getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r);
    /**
     * Filter the SQL JOIN clause for retrieving archives.
     *
     * @since 2.2.0
     *
     * @param string $sql_join Portion of SQL query containing JOIN clause.
     * @param array  $r        An array of default arguments.
     */
    $join = apply_filters('getarchives_join', '', $r);
    $output = '';
    $last_changed = wp_cache_get('last_changed', 'posts');
    if (!$last_changed) {
        $last_changed = microtime();
        wp_cache_set('last_changed', $last_changed, 'posts');
    }
    $limit = $r['limit'];
    if ('monthly' == $r['type']) {
        $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date {$order} {$limit}";
        $key = md5($query);
        $key = "wp_get_archives:{$key}:{$last_changed}";
        if (!($results = wp_cache_get($key, 'posts'))) {
            $results = $wpdb->get_results($query);
            wp_cache_set($key, $results, 'posts');
        }
        if ($results) {
            $after = $r['after'];
            foreach ((array) $results as $result) {
                $url = get_month_link($result->year, $result->month);
                /* translators: 1: month name, 2: 4-digit year */
                $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($result->month), $result->year);
                if ($r['show_post_count']) {
                    $r['after'] = '&nbsp;(' . $result->posts . ')' . $after;
                }
                $output .= get_archives_link($url, $text, $r['format'], $r['before'], $r['after']);
            }
        }
    } elseif ('yearly' == $r['type']) {
        $query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date) ORDER BY post_date {$order} {$limit}";
        $key = md5($query);
        $key = "wp_get_archives:{$key}:{$last_changed}";
        if (!($results = wp_cache_get($key, 'posts'))) {
            $results = $wpdb->get_results($query);
            wp_cache_set($key, $results, 'posts');
        }
        if ($results) {
            $after = $r['after'];
            foreach ((array) $results as $result) {
                $url = get_year_link($result->year);
                $text = sprintf('%d', $result->year);
                if ($r['show_post_count']) {
                    $r['after'] = '&nbsp;(' . $result->posts . ')' . $after;
                }
                $output .= get_archives_link($url, $text, $r['format'], $r['before'], $r['after']);
            }
        }
    } elseif ('daily' == $r['type']) {
        $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date {$order} {$limit}";
        $key = md5($query);
        $key = "wp_get_archives:{$key}:{$last_changed}";
        if (!($results = wp_cache_get($key, 'posts'))) {
            $results = $wpdb->get_results($query);
            wp_cache_set($key, $results, 'posts');
        }
        if ($results) {
            $after = $r['after'];
            foreach ((array) $results as $result) {
                $url = get_day_link($result->year, $result->month, $result->dayofmonth);
                $date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $result->year, $result->month, $result->dayofmonth);
                $text = mysql2date($archive_day_date_format, $date);
                if ($r['show_post_count']) {
                    $r['after'] = '&nbsp;(' . $result->posts . ')' . $after;
                }
                $output .= get_archives_link($url, $text, $r['format'], $r['before'], $r['after']);
            }
        }
    } elseif ('weekly' == $r['type']) {
        $week = _wp_mysql_week('`post_date`');
        $query = "SELECT DISTINCT {$week} AS `week`, YEAR( `post_date` ) AS `yr`, DATE_FORMAT( `post_date`, '%Y-%m-%d' ) AS `yyyymmdd`, count( `ID` ) AS `posts` FROM `{$wpdb->posts}` {$join} {$where} GROUP BY {$week}, YEAR( `post_date` ) ORDER BY `post_date` {$order} {$limit}";
        $key = md5($query);
        $key = "wp_get_archives:{$key}:{$last_changed}";
        if (!($results = wp_cache_get($key, 'posts'))) {
            $results = $wpdb->get_results($query);
            wp_cache_set($key, $results, 'posts');
        }
        $arc_w_last = '';
        if ($results) {
            $after = $r['after'];
            foreach ((array) $results as $result) {
                if ($result->week != $arc_w_last) {
                    $arc_year = $result->yr;
                    $arc_w_last = $result->week;
                    $arc_week = get_weekstartend($result->yyyymmdd, get_option('start_of_week'));
                    $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
                    $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
                    $url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', home_url(), '', '?', '=', $arc_year, '&amp;', '=', $result->week);
                    $text = $arc_week_start . $archive_week_separator . $arc_week_end;
                    if ($r['show_post_count']) {
                        $r['after'] = '&nbsp;(' . $result->posts . ')' . $after;
                    }
                    $output .= get_archives_link($url, $text, $r['format'], $r['before'], $r['after']);
                }
            }
        }
    } elseif ('postbypost' == $r['type'] || 'alpha' == $r['type']) {
        $orderby = 'alpha' == $r['type'] ? 'post_title ASC ' : 'post_date DESC, ID DESC ';
        $query = "SELECT * FROM {$wpdb->posts} {$join} {$where} ORDER BY {$orderby} {$limit}";
        $key = md5($query);
        $key = "wp_get_archives:{$key}:{$last_changed}";
        if (!($results = wp_cache_get($key, 'posts'))) {
            $results = $wpdb->get_results($query);
            wp_cache_set($key, $results, 'posts');
        }
        if ($results) {
            foreach ((array) $results as $result) {
                if ($result->post_date != '0000-00-00 00:00:00') {
                    $url = get_permalink($result);
                    if ($result->post_title) {
                        /** This filter is documented in wp-includes/post-template.php */
                        $text = strip_tags(apply_filters('the_title', $result->post_title, $result->ID));
                    } else {
                        $text = $result->ID;
                    }
                    $output .= get_archives_link($url, $text, $r['format'], $r['before'], $r['after']);
                }
            }
        }
    }
    if ($r['echo']) {
        echo $output;
    } else {
        return $output;
    }
}
Example #2
0
 /**
  * @api
  * @param array|string $args
  * @return array|string
  */
 function get_items($args = null)
 {
     global $wpdb;
     $defaults = array('type' => 'monthly-nested', 'limit' => '', 'show_post_count' => false, 'order' => 'DESC', 'post_type' => 'post', 'show_year' => false, 'nested' => false);
     $args = wp_parse_args($args, $defaults);
     $post_type = $args['post_type'];
     $order = $args['order'];
     $nested = $args['nested'];
     $type = $args['type'];
     $limit = '';
     if ($type == 'yearlymonthly' || $type == 'yearmonth') {
         $type = 'monthly-nested';
     }
     if ($type == 'monthly-nested') {
         $nested = true;
     }
     if (!empty($args['limit'])) {
         $limit = absint($limit);
         $limit = ' LIMIT ' . $limit;
     }
     $order = strtoupper($order);
     if ($order !== 'ASC') {
         $order = 'DESC';
     }
     // this is what will separate dates on weekly archive links
     $archive_week_separator = '&#8211;';
     // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
     $archive_date_format_over_ride = 0;
     // options for daily archive (only if you over-ride the general date format)
     $archive_day_date_format = 'Y/m/d';
     // options for weekly archive (only if you over-ride the general date format)
     $archive_week_start_date_format = 'Y/m/d';
     $archive_week_end_date_format = 'Y/m/d';
     if (!$archive_date_format_over_ride) {
         $archive_day_date_format = get_option('date_format');
         $archive_week_start_date_format = get_option('date_format');
         $archive_week_end_date_format = get_option('date_format');
     }
     $where = $wpdb->prepare('WHERE post_type = "%s" AND post_status = "publish"', $post_type);
     $where = apply_filters('getarchives_where', $where, $args);
     $join = apply_filters('getarchives_join', '', $args);
     $output = array();
     $last_changed = wp_cache_get('last_changed', 'posts');
     if (!$last_changed) {
         $last_changed = microtime();
         wp_cache_set('last_changed', $last_changed, 'posts');
     }
     if ('monthly' == $type) {
         $output = $this->get_items_monthly($args, $last_changed, $join, $where, $order, $limit, $nested);
     } elseif ('yearly' == $type) {
         $output = $this->get_items_yearly($args, $last_changed, $join, $where, $order, $limit);
     } elseif ('monthly-nested' == $type) {
         $years = $this->get_items_yearly($args, $last_changed, $join, $where, $order, $limit);
         foreach ($years as &$year) {
             $args = array('show_year' => false);
             $year['children'] = $this->get_items_monthly($args, $last_changed, $join, $where, $order, $limit);
         }
         $output = $years;
     } elseif ('daily' == $type) {
         $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date {$order} {$limit}";
         $key = md5($query);
         $key = "wp_get_archives:{$key}:{$last_changed}";
         if (!($results = wp_cache_get($key, 'posts'))) {
             $results = $wpdb->get_results($query);
             $cache = array();
             $cache[$key] = $results;
             wp_cache_set($key, $results, 'posts');
         }
         if ($results) {
             foreach ((array) $results as $result) {
                 $url = get_day_link($result->year, $result->month, $result->dayofmonth);
                 $date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $result->year, $result->month, $result->dayofmonth);
                 $text = mysql2date($archive_day_date_format, $date);
                 $output[] = $this->get_archives_link($url, $text);
             }
         }
     } elseif ('weekly' == $type) {
         $week = _wp_mysql_week('`post_date`');
         $query = "SELECT DISTINCT {$week} AS `week`, YEAR( `post_date` ) AS `yr`, DATE_FORMAT( `post_date`, '%Y-%m-%d' ) AS `yyyymmdd`, " . "count( `ID` ) AS `posts` FROM `{$wpdb->posts}` {$join} {$where} GROUP BY {$week}, YEAR( `post_date` ) ORDER BY `post_date` {$order} {$limit}";
         $key = md5($query);
         $key = "wp_get_archives:{$key}:{$last_changed}";
         if (!($results = wp_cache_get($key, 'posts'))) {
             $results = $wpdb->get_results($query);
             wp_cache_set($key, $results, 'posts');
         }
         $arc_w_last = '';
         if ($results) {
             foreach ((array) $results as $result) {
                 if ($result->week != $arc_w_last) {
                     $arc_year = $result->yr;
                     $arc_w_last = $result->week;
                     $arc_week = get_weekstartend($result->yyyymmdd, get_option('start_of_week'));
                     $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
                     $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
                     $url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', home_url(), '', '?', '=', $arc_year, '&amp;', '=', $result->week);
                     $text = $arc_week_start . $archive_week_separator . $arc_week_end;
                     $output[] = $this->get_archives_link($url, $text);
                 }
             }
         }
     } elseif ('postbypost' == $type || 'alpha' == $type) {
         $orderby = 'alpha' == $type ? 'post_title ASC ' : 'post_date DESC ';
         $query = "SELECT * FROM {$wpdb->posts} {$join} {$where} ORDER BY {$orderby} {$limit}";
         $key = md5($query);
         $key = "wp_get_archives:{$key}:{$last_changed}";
         if (!($results = wp_cache_get($key, 'posts'))) {
             $results = $wpdb->get_results($query);
             wp_cache_set($key, $results, 'posts');
         }
         if ($results) {
             foreach ((array) $results as $result) {
                 if ($result->post_date != '0000-00-00 00:00:00') {
                     $url = get_permalink($result);
                     if ($result->post_title) {
                         /** This filter is documented in wp-includes/post-template.php */
                         $text = strip_tags(apply_filters('the_title', $result->post_title, $result->ID));
                     } else {
                         $text = $result->ID;
                     }
                     $output[] = $this->get_archives_link($url, $text);
                 }
             }
         }
     }
     return $output;
 }
Example #3
0
/**
 * Display archive links based on type and format.
 *
 * The 'type' argument offers a few choices and by default will display monthly
 * archive links. The other options for values are 'daily', 'weekly', 'monthly',
 * 'yearly', 'postbypost' or 'alpha'. Both 'postbypost' and 'alpha' display the
 * same archive link list, the difference between the two is that 'alpha'
 * will order by post title and 'postbypost' will order by post date.
 *
 * The date archives will logically display dates with links to the archive post
 * page. The 'postbypost' and 'alpha' values for 'type' argument will display
 * the post titles.
 *
 * The 'limit' argument will only display a limited amount of links, specified
 * by the 'limit' integer value. By default, there is no limit. The
 * 'show_post_count' argument will show how many posts are within the archive.
 * By default, the 'show_post_count' argument is set to false.
 *
 * For the 'format', 'before', and 'after' arguments, see {@link
 * get_archives_link()}. The values of these arguments have to do with that
 * function.
 *
 * @since 1.2.0
 *
 * @param string|array $args Optional. Override defaults.
 */
function wp_get_archives($args = '')
{
    global $wpdb, $wp_locale;
    $defaults = array('type' => 'monthly', 'limit' => '', 'format' => 'html', 'before' => '', 'after' => '', 'show_post_count' => false, 'echo' => 1);
    $r = wp_parse_args($args, $defaults);
    extract($r, EXTR_SKIP);
    if ('' == $type) {
        $type = 'monthly';
    }
    if ('' != $limit) {
        $limit = absint($limit);
        $limit = ' LIMIT ' . $limit;
    }
    // this is what will separate dates on weekly archive links
    $archive_week_separator = '&#8211;';
    // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
    $archive_date_format_over_ride = 0;
    // options for daily archive (only if you over-ride the general date format)
    $archive_day_date_format = 'Y/m/d';
    // options for weekly archive (only if you over-ride the general date format)
    $archive_week_start_date_format = 'Y/m/d';
    $archive_week_end_date_format = 'Y/m/d';
    if (!$archive_date_format_over_ride) {
        $archive_day_date_format = get_option('date_format');
        $archive_week_start_date_format = get_option('date_format');
        $archive_week_end_date_format = get_option('date_format');
    }
    //filters
    $where = apply_filters('getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r);
    $join = apply_filters('getarchives_join', '', $r);
    $output = '';
    if ('monthly' == $type) {
        $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC {$limit}";
        $key = md5($query);
        $cache = wp_cache_get('wp_get_archives', 'general');
        if (!isset($cache[$key])) {
            $arcresults = $wpdb->get_results($query);
            $cache[$key] = $arcresults;
            wp_cache_set('wp_get_archives', $cache, 'general');
        } else {
            $arcresults = $cache[$key];
        }
        if ($arcresults) {
            $afterafter = $after;
            foreach ((array) $arcresults as $arcresult) {
                $url = get_month_link($arcresult->year, $arcresult->month);
                /* translators: 1: month name, 2: 4-digit year */
                $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);
                if ($show_post_count) {
                    $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                }
                $output .= get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('yearly' == $type) {
        $query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date) ORDER BY post_date DESC {$limit}";
        $key = md5($query);
        $cache = wp_cache_get('wp_get_archives', 'general');
        if (!isset($cache[$key])) {
            $arcresults = $wpdb->get_results($query);
            $cache[$key] = $arcresults;
            wp_cache_set('wp_get_archives', $cache, 'general');
        } else {
            $arcresults = $cache[$key];
        }
        if ($arcresults) {
            $afterafter = $after;
            foreach ((array) $arcresults as $arcresult) {
                $url = get_year_link($arcresult->year);
                $text = sprintf('%d', $arcresult->year);
                if ($show_post_count) {
                    $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                }
                $output .= get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('daily' == $type) {
        $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date DESC {$limit}";
        $key = md5($query);
        $cache = wp_cache_get('wp_get_archives', 'general');
        if (!isset($cache[$key])) {
            $arcresults = $wpdb->get_results($query);
            $cache[$key] = $arcresults;
            wp_cache_set('wp_get_archives', $cache, 'general');
        } else {
            $arcresults = $cache[$key];
        }
        if ($arcresults) {
            $afterafter = $after;
            foreach ((array) $arcresults as $arcresult) {
                $url = get_day_link($arcresult->year, $arcresult->month, $arcresult->dayofmonth);
                $date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $arcresult->year, $arcresult->month, $arcresult->dayofmonth);
                $text = mysql2date($archive_day_date_format, $date);
                if ($show_post_count) {
                    $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                }
                $output .= get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('weekly' == $type) {
        $week = _wp_mysql_week('`post_date`');
        $query = "SELECT DISTINCT {$week} AS `week`, YEAR( `post_date` ) AS `yr`, DATE_FORMAT( `post_date`, '%Y-%m-%d' ) AS `yyyymmdd`, count( `ID` ) AS `posts` FROM `{$wpdb->posts}` {$join} {$where} GROUP BY {$week}, YEAR( `post_date` ) ORDER BY `post_date` DESC {$limit}";
        $key = md5($query);
        $cache = wp_cache_get('wp_get_archives', 'general');
        if (!isset($cache[$key])) {
            $arcresults = $wpdb->get_results($query);
            $cache[$key] = $arcresults;
            wp_cache_set('wp_get_archives', $cache, 'general');
        } else {
            $arcresults = $cache[$key];
        }
        $arc_w_last = '';
        $afterafter = $after;
        if ($arcresults) {
            foreach ((array) $arcresults as $arcresult) {
                if ($arcresult->week != $arc_w_last) {
                    $arc_year = $arcresult->yr;
                    $arc_w_last = $arcresult->week;
                    $arc_week = get_weekstartend($arcresult->yyyymmdd, get_option('start_of_week'));
                    $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
                    $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
                    $url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', home_url(), '', '?', '=', $arc_year, '&amp;', '=', $arcresult->week);
                    $text = $arc_week_start . $archive_week_separator . $arc_week_end;
                    if ($show_post_count) {
                        $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                    }
                    $output .= get_archives_link($url, $text, $format, $before, $after);
                }
            }
        }
    } elseif ('postbypost' == $type || 'alpha' == $type) {
        $orderby = 'alpha' == $type ? 'post_title ASC ' : 'post_date DESC ';
        $query = "SELECT * FROM {$wpdb->posts} {$join} {$where} ORDER BY {$orderby} {$limit}";
        $key = md5($query);
        $cache = wp_cache_get('wp_get_archives', 'general');
        if (!isset($cache[$key])) {
            $arcresults = $wpdb->get_results($query);
            $cache[$key] = $arcresults;
            wp_cache_set('wp_get_archives', $cache, 'general');
        } else {
            $arcresults = $cache[$key];
        }
        if ($arcresults) {
            foreach ((array) $arcresults as $arcresult) {
                if ($arcresult->post_date != '0000-00-00 00:00:00') {
                    $url = get_permalink($arcresult);
                    if ($arcresult->post_title) {
                        $text = strip_tags(apply_filters('the_title', $arcresult->post_title, $arcresult->ID));
                    } else {
                        $text = $arcresult->ID;
                    }
                    $output .= get_archives_link($url, $text, $format, $before, $after);
                }
            }
        }
    }
    if ($echo) {
        echo $output;
    } else {
        return $output;
    }
}
function get_archives($type='', $limit='', $format='html', $before = '', $after = '', $show_post_count = false) {
    global $month, $wpdb;

    if ('' == $type) {
        $type = 'monthly';
    }

    if ('' != $limit) {
        $limit = (int) $limit;
        $limit = ' LIMIT '.$limit;
    }
    // this is what will separate dates on weekly archive links
    $archive_week_separator = '&#8211;';

    // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
    $archive_date_format_over_ride = 0;

    // options for daily archive (only if you over-ride the general date format)
    $archive_day_date_format = 'Y/m/d';

    // options for weekly archive (only if you over-ride the general date format)
    $archive_week_start_date_format = 'Y/m/d';
    $archive_week_end_date_format   = 'Y/m/d';

    if (!$archive_date_format_over_ride) {
        $archive_day_date_format = get_settings('date_format');
        $archive_week_start_date_format = get_settings('date_format');
        $archive_week_end_date_format = get_settings('date_format');
    }

    $add_hours = intval(get_settings('gmt_offset'));
    $add_minutes = intval(60 * (get_settings('gmt_offset') - $add_hours));

    $now = current_time('mysql');

    if ('monthly' == $type) {
        $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts WHERE post_date < '$now' AND post_status = 'publish' GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC" . $limit);
        if ($arcresults) {
            $afterafter = $after;
            foreach ($arcresults as $arcresult) {
                $url  = get_month_link($arcresult->year,   $arcresult->month);
                if ($show_post_count) {
                    $text = sprintf('%s %d', $month[zeroise($arcresult->month,2)], $arcresult->year);
                    $after = '&nbsp;('.$arcresult->posts.')' . $afterafter;
                } else {
                    $text = sprintf('%s %d', $month[zeroise($arcresult->month,2)], $arcresult->year);
                }
                echo get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('daily' == $type) {
        $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth` FROM $wpdb->posts WHERE post_date < '$now' AND post_status = 'publish' ORDER BY post_date DESC" . $limit);
        if ($arcresults) {
            foreach ($arcresults as $arcresult) {
                $url  = get_day_link($arcresult->year, $arcresult->month, $arcresult->dayofmonth);
                $date = sprintf("%d-%02d-%02d 00:00:00", $arcresult->year, $arcresult->month, $arcresult->dayofmonth);
                $text = mysql2date($archive_day_date_format, $date);
                echo get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('weekly' == $type) {
	$start_of_week = get_settings('start_of_week');
        $arcresults = $wpdb->get_results("SELECT DISTINCT WEEK(post_date, $start_of_week) AS `week`, YEAR(post_date) AS yr, DATE_FORMAT(post_date, '%Y-%m-%d') AS yyyymmdd FROM $wpdb->posts WHERE post_date < '$now' AND post_status = 'publish' ORDER BY post_date DESC" . $limit);
        $arc_w_last = '';
        if ($arcresults) {
            foreach ($arcresults as $arcresult) {
                if ($arcresult->week != $arc_w_last) {
                    $arc_year = $arcresult->yr;
                    $arc_w_last = $arcresult->week;
                    $arc_week = get_weekstartend($arcresult->yyyymmdd, get_settings('start_of_week'));
                    $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
                    $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
                    $url  = sprintf('%s/%s%sm%s%s%sw%s%d', get_settings('home'), '', '?',
                                    '=', $arc_year, '&amp;',
                                    '=', $arcresult->week);
                    $text = $arc_week_start . $archive_week_separator . $arc_week_end;
                    echo get_archives_link($url, $text, $format, $before, $after);
                }
            }
        }
    } elseif ('postbypost' == $type) {
        $arcresults = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_date < '$now' AND post_status = 'publish' ORDER BY post_date DESC" . $limit);
        if ($arcresults) {
            foreach ($arcresults as $arcresult) {
                if ($arcresult->post_date != '0000-00-00 00:00:00') {
                    $url  = get_permalink($arcresult);
                    $arc_title = $arcresult->post_title;
                    if ($arc_title) {
                        $text = strip_tags($arc_title);
                    } else {
                        $text = $arcresult->ID;
                    }
                    echo get_archives_link($url, $text, $format, $before, $after);
                }
            }
        }
    }
}
    function wp_dropdown_weekly($current)
    {
        $archive_week_start_date_format = "Y/m/d";
        $archive_week_end_date_format = "Y/m/d";
        $archive_week_separator = " - ";
        $arc_result = $GLOBALS['wpdb']->geT_results("SELECT DISTINCT YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date), WEEK(post_date) FROM " . wp_table('posts') . " ORDER BY post_date DESC", ARRAY_A);
        $arc_w_last = '';
        foreach ($arc_result as $arc_row) {
            $arc_year = $arc_row["YEAR(post_date)"];
            $arc_w = $arc_row["WEEK(post_date)"];
            if ($arc_w != $arc_w_last) {
                $arc_w_last = $arc_w;
                $arc_ymd = $arc_year . "-" . zeroise($arc_row["MONTH(post_date)"], 2) . "-" . zeroise($arc_row["DAYOFMONTH(post_date)"], 2);
                $arc_week = get_weekstartend($arc_ymd, get_settings('start_of_week'));
                $arc_week_start = date($archive_week_start_date_format, $arc_week['start']);
                $arc_week_end = date($archive_week_end_date_format, $arc_week['end']);
                $week_str = $arc_week_start . $archive_week_separator . $arc_week_end;
                ?>
				<option value="<?php 
                echo $arc_w;
                ?>
"<?php 
                selected($current, $arc_w);
                ?>
><?php 
                echo $week_str;
                ?>
</option>
<?php 
            }
        }
    }
 public function test_start_of_week_should_fall_back_on_sunday_when_option_is_missing()
 {
     delete_option('start_of_week');
     $expected = array('start' => 1454803200, 'end' => 1455407999);
     $this->assertEquals($expected, get_weekstartend('2016-02-12'));
 }
function wp_get_archives($args = '') {
	global $wpdb, $wp_locale;

	$defaults = array(
		'type' => 'monthly', 'limit' => '',
		'format' => 'html', 'before' => '',
		'after' => '', 'show_post_count' => false
	);

	$r = wp_parse_args( $args, $defaults );
	extract( $r, EXTR_SKIP );

	if ( '' == $type )
		$type = 'monthly';

	if ( '' != $limit ) {
		$limit = absint($limit);
		$limit = ' LIMIT '.$limit;
	}

	// this is what will separate dates on weekly archive links
	$archive_week_separator = '&#8211;';

	// over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
	$archive_date_format_over_ride = 0;

	// options for daily archive (only if you over-ride the general date format)
	$archive_day_date_format = 'Y/m/d';

	// options for weekly archive (only if you over-ride the general date format)
	$archive_week_start_date_format = 'Y/m/d';
	$archive_week_end_date_format	= 'Y/m/d';

	if ( !$archive_date_format_over_ride ) {
		$archive_day_date_format = get_option('date_format');
		$archive_week_start_date_format = get_option('date_format');
		$archive_week_end_date_format = get_option('date_format');
	}

	//filters
	$where = apply_filters('getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r );
	$join = apply_filters('getarchives_join', "", $r);

	if ( 'monthly' == $type ) {
		$query = "SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC $limit";
		$key = md5($query);
		$cache = wp_cache_get( 'wp_get_archives' , 'general');
		if ( !isset( $cache[ $key ] ) ) {
			$arcresults = $wpdb->get_results($query);
			$cache[ $key ] = $arcresults;
			wp_cache_add( 'wp_get_archives', $cache, 'general' );
		} else {
			$arcresults = $cache[ $key ];
		}
		if ( $arcresults ) {
			$afterafter = $after;
			foreach ( $arcresults as $arcresult ) {
				$url	= get_month_link($arcresult->year,	$arcresult->month);
				$text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);
				if ( $show_post_count )
					$after = '&nbsp;('.$arcresult->posts.')' . $afterafter;
				echo get_archives_link($url, $text, $format, $before, $after);
			}
		}
	} elseif ('yearly' == $type) {
		$query = "SELECT DISTINCT YEAR(post_date) AS `year`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date) ORDER BY post_date DESC $limit";
		$key = md5($query);
		$cache = wp_cache_get( 'wp_get_archives' , 'general');
		if ( !isset( $cache[ $key ] ) ) {
			$arcresults = $wpdb->get_results($query);
			$cache[ $key ] = $arcresults;
			wp_cache_add( 'wp_get_archives', $cache, 'general' );
		} else {
			$arcresults = $cache[ $key ];
		}
		if ($arcresults) {
			$afterafter = $after;
			foreach ($arcresults as $arcresult) {
				$url = get_year_link($arcresult->year);
				$text = sprintf('%d', $arcresult->year);
				if ($show_post_count)
					$after = '&nbsp;('.$arcresult->posts.')' . $afterafter;
				echo get_archives_link($url, $text, $format, $before, $after);
			}
		}
	} elseif ( 'daily' == $type ) {
		$query = "SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date DESC $limit";
		$key = md5($query);
		$cache = wp_cache_get( 'wp_get_archives' , 'general');
		if ( !isset( $cache[ $key ] ) ) {
			$arcresults = $wpdb->get_results($query);
			$cache[ $key ] = $arcresults;
			wp_cache_add( 'wp_get_archives', $cache, 'general' );
		} else {
			$arcresults = $cache[ $key ];
		}
		if ( $arcresults ) {
			$afterafter = $after;
			foreach ( $arcresults as $arcresult ) {
				$url	= get_day_link($arcresult->year, $arcresult->month, $arcresult->dayofmonth);
				$date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $arcresult->year, $arcresult->month, $arcresult->dayofmonth);
				$text = mysql2date($archive_day_date_format, $date);
				if ($show_post_count)
					$after = '&nbsp;('.$arcresult->posts.')'.$afterafter;
				echo get_archives_link($url, $text, $format, $before, $after);
			}
		}
	} elseif ( 'weekly' == $type ) {
		$start_of_week = get_option('start_of_week');
		$query = "SELECT DISTINCT WEEK(post_date, $start_of_week) AS `week`, YEAR(post_date) AS yr, DATE_FORMAT(post_date, '%Y-%m-%d') AS yyyymmdd, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY WEEK(post_date, $start_of_week), YEAR(post_date) ORDER BY post_date DESC $limit";
		$key = md5($query);
		$cache = wp_cache_get( 'wp_get_archives' , 'general');
		if ( !isset( $cache[ $key ] ) ) {
			$arcresults = $wpdb->get_results($query);
			$cache[ $key ] = $arcresults;
			wp_cache_add( 'wp_get_archives', $cache, 'general' );
		} else {
			$arcresults = $cache[ $key ];
		}
		$arc_w_last = '';
		$afterafter = $after;
		if ( $arcresults ) {
				foreach ( $arcresults as $arcresult ) {
					if ( $arcresult->week != $arc_w_last ) {
						$arc_year = $arcresult->yr;
						$arc_w_last = $arcresult->week;
						$arc_week = get_weekstartend($arcresult->yyyymmdd, get_option('start_of_week'));
						$arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
						$arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
						$url  = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', get_option('home'), '', '?', '=', $arc_year, '&amp;', '=', $arcresult->week);
						$text = $arc_week_start . $archive_week_separator . $arc_week_end;
						if ($show_post_count)
							$after = '&nbsp;('.$arcresult->posts.')'.$afterafter;
						echo get_archives_link($url, $text, $format, $before, $after);
					}
				}
		}
	} elseif ( ( 'postbypost' == $type ) || ('alpha' == $type) ) {
		('alpha' == $type) ? $orderby = "post_title ASC " : $orderby = "post_date DESC ";
		$query = "SELECT * FROM $wpdb->posts $join $where ORDER BY $orderby $limit";
		$key = md5($query);
		$cache = wp_cache_get( 'wp_get_archives' , 'general');
		if ( !isset( $cache[ $key ] ) ) {
			$arcresults = $wpdb->get_results($query);
			$cache[ $key ] = $arcresults;
			wp_cache_add( 'wp_get_archives', $cache, 'general' );
		} else {
			$arcresults = $cache[ $key ];
		}
		if ( $arcresults ) {
			foreach ( $arcresults as $arcresult ) {
				if ( $arcresult->post_date != '0000-00-00 00:00:00' ) {
					$url  = get_permalink($arcresult);
					$arc_title = $arcresult->post_title;
					if ( $arc_title )
						$text = strip_tags(apply_filters('the_title', $arc_title));
					else
						$text = $arcresult->ID;
					echo get_archives_link($url, $text, $format, $before, $after);
				}
			}
		}
	}
}
        echo "</option>\n";
    }
} elseif ($archive_mode == "weekly") {
    echo "<select name=\"w\" style=\"width:120px;\">";
    $archive_week_start_date_format = "Y/m/d";
    $archive_week_end_date_format = "Y/m/d";
    $archive_week_separator = " - ";
    $arc_result = $wpdb->geT_results("SELECT DISTINCT YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date), WEEK(post_date) FROM {$wpdb->posts[$wp_id]} ORDER BY post_date DESC", ARRAY_A);
    $arc_w_last = '';
    foreach ($arc_result as $arc_row) {
        $arc_year = $arc_row["YEAR(post_date)"];
        $arc_w = $arc_row["WEEK(post_date)"];
        if ($arc_w != $arc_w_last) {
            $arc_w_last = $arc_w;
            $arc_ymd = $arc_year . "-" . zeroise($arc_row["MONTH(post_date)"], 2) . "-" . zeroise($arc_row["DAYOFMONTH(post_date)"], 2);
            $arc_week = get_weekstartend($arc_ymd, get_settings('start_of_week'));
            $arc_week_start = date($archive_week_start_date_format, $arc_week['start']);
            $arc_week_end = date($archive_week_end_date_format, $arc_week['end']);
            echo "<option value=\"{$arc_w}\">";
            echo $arc_week_start . $archive_week_separator . $arc_week_end;
            echo "</option>\n";
        }
    }
} elseif ($archive_mode == "postbypost") {
    echo '<input type="hidden" name="more" value="1" />';
    echo '<select name="p" style="width:120px;">';
    $resultarc = $wpdb->get_results("SELECT ID,post_date,post_title FROM {$wpdb->posts[$wp_id]} ORDER BY post_date DESC");
    foreach ($resultarc as $row) {
        if ($row->post_date != "0000-00-00 00:00:00") {
            echo "<option value=\"" . $row->ID . "\">";
            if (strip_tags($row->post_title)) {
/**
 * Sets up the dates used to filter graph data
 *
 * Date sent via $_GET is read first and then modified (if needed) to match the
 * selected date-range (if any)
 *
 * @since 1.3
 * @return array
*/
function edd_get_report_dates()
{
    $dates = array();
    $current_time = current_time('timestamp');
    $dates['range'] = isset($_GET['range']) ? $_GET['range'] : 'this_month';
    if ('custom' !== $dates['range']) {
        $dates['year'] = isset($_GET['year']) ? $_GET['year'] : date('Y');
        $dates['year_end'] = isset($_GET['year_end']) ? $_GET['year_end'] : date('Y');
        $dates['m_start'] = isset($_GET['m_start']) ? $_GET['m_start'] : 1;
        $dates['m_end'] = isset($_GET['m_end']) ? $_GET['m_end'] : 12;
        $dates['day'] = isset($_GET['day']) ? $_GET['day'] : 1;
        $dates['day_end'] = isset($_GET['day_end']) ? $_GET['day_end'] : cal_days_in_month(CAL_GREGORIAN, $dates['m_end'], $dates['year']);
    }
    // Modify dates based on predefined ranges
    switch ($dates['range']) {
        case 'this_month':
            $dates['m_start'] = date('n', $current_time);
            $dates['m_end'] = date('n', $current_time);
            $dates['day'] = 1;
            $dates['day_end'] = cal_days_in_month(CAL_GREGORIAN, $dates['m_end'], $dates['year']);
            $dates['year'] = date('Y');
            $dates['year_end'] = date('Y');
            break;
        case 'last_month':
            if (date('n') == 1) {
                $dates['m_start'] = 12;
                $dates['m_end'] = 12;
                $dates['year'] = date('Y', $current_time) - 1;
                $dates['year_end'] = date('Y', $current_time) - 1;
            } else {
                $dates['m_start'] = date('n') - 1;
                $dates['m_end'] = date('n') - 1;
                $dates['year_end'] = $dates['year'];
            }
            $dates['day_end'] = cal_days_in_month(CAL_GREGORIAN, $dates['m_end'], $dates['year']);
            break;
        case 'today':
            $dates['day'] = date('d', $current_time);
            $dates['m_start'] = date('n', $current_time);
            $dates['m_end'] = date('n', $current_time);
            $dates['year'] = date('Y', $current_time);
            break;
        case 'yesterday':
            $year = date('Y', $current_time);
            $month = date('n', $current_time);
            $day = date('d', $current_time);
            if ($month == 1 && $day == 1) {
                $year -= 1;
                $month = 12;
                $day = cal_days_in_month(CAL_GREGORIAN, $month, $year);
            } elseif ($month > 1 && $day == 1) {
                $month -= 1;
                $day = cal_days_in_month(CAL_GREGORIAN, $month, $year);
            } else {
                $day -= 1;
            }
            $dates['day'] = $day;
            $dates['m_start'] = $month;
            $dates['m_end'] = $month;
            $dates['year'] = $year;
            $dates['year_end'] = $year;
            $dates['day_end'] = $day;
            break;
        case 'this_week':
        case 'last_week':
            $base_time = $dates['range'] === 'this_week' ? current_time('mysql') : date('Y-m-d h:i:s', current_time('timestamp') - WEEK_IN_SECONDS);
            $start_end = get_weekstartend($base_time, get_option('start_of_week'));
            $dates['day'] = date('d', $start_end['start']);
            $dates['m_start'] = date('n', $start_end['start']);
            $dates['year'] = date('Y', $start_end['start']);
            $dates['day_end'] = date('d', $start_end['end']);
            $dates['m_end'] = date('n', $start_end['end']);
            $dates['year_end'] = date('Y', $start_end['end']);
            break;
        case 'this_quarter':
            $month_now = date('n', $current_time);
            $dates['year'] = date('Y', $current_time);
            $dates['year_end'] = $dates['year'];
            if ($month_now <= 3) {
                $dates['m_start'] = 1;
                $dates['m_end'] = 3;
            } else {
                if ($month_now <= 6) {
                    $dates['m_start'] = 4;
                    $dates['m_end'] = 6;
                } else {
                    if ($month_now <= 9) {
                        $dates['m_start'] = 7;
                        $dates['m_end'] = 9;
                    } else {
                        $dates['m_start'] = 10;
                        $dates['m_end'] = 12;
                    }
                }
            }
            $dates['day_end'] = cal_days_in_month(CAL_GREGORIAN, $dates['m_end'], $dates['year']);
            break;
        case 'last_quarter':
            $month_now = date('n');
            if ($month_now <= 3) {
                $dates['m_start'] = 10;
                $dates['m_end'] = 12;
                $dates['year'] = date('Y', $current_time) - 1;
                // Previous year
            } else {
                if ($month_now <= 6) {
                    $dates['m_start'] = 1;
                    $dates['m_end'] = 3;
                    $dates['year'] = date('Y', $current_time);
                } else {
                    if ($month_now <= 9) {
                        $dates['m_start'] = 4;
                        $dates['m_end'] = 6;
                        $dates['year'] = date('Y', $current_time);
                    } else {
                        $dates['m_start'] = 7;
                        $dates['m_end'] = 9;
                        $dates['year'] = date('Y', $current_time);
                    }
                }
            }
            $dates['day_end'] = cal_days_in_month(CAL_GREGORIAN, $dates['m_end'], $dates['year']);
            $dates['year_end'] = $dates['year'];
            break;
        case 'this_year':
            $dates['m_start'] = 1;
            $dates['m_end'] = 12;
            $dates['year'] = date('Y', $current_time);
            $dates['year_end'] = $dates['year'];
            break;
        case 'last_year':
            $dates['m_start'] = 1;
            $dates['m_end'] = 12;
            $dates['year'] = date('Y', $current_time) - 1;
            $dates['year_end'] = date('Y', $current_time) - 1;
            break;
    }
    return apply_filters('edd_report_dates', $dates);
}
 /**
  * Construct the date queries for pre-defined periods in the Sales Log.
  *
  * Supports pre-defined periods for the purchase log, including today, yesterday, this week,
  * last week, this month, last month, last two months + month to date (this quarter),
  * prior 3 months, this year, last year. You can insert your own custom periods by filtering
  * either based on the $period_flag or just filter the final query setup.
  *
  * @since 4.0
  *
  * @param array $period_flag The period requested from $_REQUEST['m'].
  *
  * @return array formatted to pass to WP_Date_Query.
  */
 private function assemble_predefined_periods_query($period_flag)
 {
     // warning: period flag is unsanitized user input directly from $_REQUEST - only compare against actual values
     /**
      *	date functions
      */
     $now_string = current_time('mysql');
     $week_start_end = get_weekstartend($now_string);
     // returns array with start/end
     $blog_time_zone = get_option('timezone_string');
     if (empty($blog_time_zone)) {
         $blog_time_zone = date_default_timezone_get();
     }
     $timezone = new DateTimeZone($blog_time_zone);
     $now = new DateTime('now', $timezone);
     // Based on $_REQUEST['m']
     switch ($period_flag) {
         // Today
         case 1:
             $date_query = array('year' => $now->format('Y'), 'monthnum' => $now->format('n'), 'day' => $now->format('d'));
             break;
             // Yesterday
         // Yesterday
         case 2:
             $yesterday = new DateTime(date('Y-m-d', strtotime('yesterday')), $timezone);
             $date_query = array('year' => $yesterday->format('Y'), 'monthnum' => $yesterday->format('n'), 'day' => $yesterday->format('d'));
             break;
             // This Week-to-date
         // This Week-to-date
         case 3:
             $start_of_this_week = new DateTime(date('Y-m-d 00:00:00', $week_start_end['start']), $timezone);
             $date_query = array('date_query' => array('after' => $start_of_this_week->format('Y-m-d 00:00:00'), 'compare' => '>', 'inclusive' => true));
             break;
             // Last Week
         // Last Week
         case 4:
             $start_of_last_week = new DateTime(date('Y-m-d 00:00:00', $week_start_end['start'] - DAY_IN_SECONDS * 7), $timezone);
             $start = $start_of_last_week->format('Y-m-d 00:00:00');
             $start_of_last_week->modify('+7 days');
             $date_query = array('date_query' => array('after' => $start, 'before' => $start_of_last_week->format('Y-m-d 00:00:00'), 'inclusive' => false));
             break;
             // This Month-to-Date (Same as choosing the explicit month on selector)
         // This Month-to-Date (Same as choosing the explicit month on selector)
         case 5:
             $date_query = array('year' => $now->format('Y'), 'monthnum' => $now->format('n'));
             break;
             // Last Month (Same as choosing the explicit month on selector)
         // Last Month (Same as choosing the explicit month on selector)
         case 6:
             $now->modify('-1 month');
             $date_query = array('year' => $now->format('Y'), 'monthnum' => $now->format('n'));
             break;
             // This Quarter (last three months inclusive)
         // This Quarter (last three months inclusive)
         case 7:
             $date_query = array('date_query' => array('after' => 'first day of -2 months'), 'compare' => '>', 'inclusive' => true);
             break;
             // Prior Three Months
         // Prior Three Months
         case 8:
             $date_query = array('date_query' => array('after' => 'first day of -2 months', 'before' => 'last day of -1 month', 'inclusive' => true));
             break;
             // This Year
         // This Year
         case 9:
             $date_query = array('date_query' => array('after' => '1/1 this year', 'compare' => '>', 'inclusive' => true));
             break;
             // Last year
         // Last year
         case 10:
             $date_query = array('date_query' => array('after' => '1/1 last year', 'before' => '12/31 last year', 'inclusive' => true));
             break;
             // default - return empty where clause
         // default - return empty where clause
         default:
             /**
              * Return a custom date query for custom period_flag's.
              *
              * This filter extends the functionality allowing for custom periods if a new value
              * is passed via $_REQUEST['m']. {@see 'purchase_log_special_periods'}.
              *
              * @since 4.1.0
              *
              * @param array Empty array to be filled with a valid query {@see WP_Date_Query}.
              */
             $date_query = apply_filters('wpsc_purchase_log_predefined_periods_' . $period_flag, array());
     }
     /**
      * Filter the parsed date query.
      *
      * This filter can be used to override the constructed date_query.
      *
      * @since 4.1.0
      *
      * @param array $date_query    Empty array to be filled with a valid date query {@see WP_Date_Query}
      * @param string $period_flag  Value passed from $_REQUEST['m'].
      */
     return apply_filters('wpsc_purchase_log_predefined_periods', $date_query, $period_flag);
 }
Example #11
0
    /**
     * Display the calendar.
     *
     * @todo If a specific day (mode == month) or month (mode == year) is selected, apply another class (default to some border)
     */
    function display()
    {
        global $DB;
        global $weekday, $weekday_abbrev, $weekday_letter, $month, $month_abbrev;
        global $time_difference;
        if ($this->mode == 'month') {
            $end_of_week = (locale_startofweek() + 7) % 7;
            // fplanque>> note: I am removing the searchframe thing because 1) I don't think it's of any use
            // and 2) it's brutally inefficient! If someone needs this it should be implemented with A SINGLE
            // QUERY which gets the last available post (BTW, I think there is already a function for that somwhere)
            // walter>> As we are just counting items, the ORDER BY db_prefix . date_start doesn't matter. And a side effect
            // of that is make queries standart compatible (compatible with other databases than MySQL)
            $arc_sql = 'SELECT COUNT(DISTINCT ' . $this->dbIDname . ') AS item_count,
													EXTRACT(DAY FROM ' . $this->dbprefix . 'datestart) AS myday
									FROM (' . $this->dbtable . ' INNER JOIN T_postcats ON ' . $this->dbIDname . ' = postcat_post_ID)
										INNER JOIN T_categories ON postcat_cat_ID = cat_ID
									WHERE EXTRACT(YEAR FROM ' . $this->dbprefix . 'datestart) = \'' . $this->year . '\'
										AND EXTRACT(MONTH FROM ' . $this->dbprefix . 'datestart) = \'' . $this->month . '\'
										' . $this->ItemQuery->get_where(' AND ') . '
									GROUP BY myday ' . $this->ItemQuery->get_group_by(', ');
            // echo $this->ItemQuery->where;
            $arc_result = $DB->get_results($arc_sql, ARRAY_A);
            foreach ($arc_result as $arc_row) {
                if (!isset($daysinmonthwithposts[$arc_row['myday']])) {
                    $daysinmonthwithposts[$arc_row['myday']] = 0;
                }
                // The '+' situation actually only happens when we have a complex GROUP BY above
                // (multiple categories wcombined with "ALL")
                $daysinmonthwithposts[$arc_row['myday']] += $arc_row['item_count'];
            }
            $daysinmonth = intval(date('t', mktime(0, 0, 0, $this->month, 1, $this->year)));
            // echo 'days in month=', $daysinmonth;
            // caution: offset bug inside (??)
            $datestartofmonth = mktime(0, 0, 0, $this->month, 1, $this->year);
            // echo date( locale_datefmt(), $datestartofmonth );
            $calendarblah = get_weekstartend($datestartofmonth, locale_startofweek());
            $calendarfirst = $calendarblah['start'];
            $dateendofmonth = mktime(0, 0, 0, $this->month, $daysinmonth, $this->year);
            // echo 'end of month: '.date( 'Y-m-d H:i:s', $dateendofmonth );
            $calendarblah = get_weekstartend($dateendofmonth, locale_startofweek());
            $calendarlast = $calendarblah['end'];
            // echo date( ' Y-m-d H:i:s', $calendarlast );
            // here the offset bug is corrected
            if (intval(date('d', $calendarfirst)) > 1 && intval(date('m', $calendarfirst)) == intval($this->month)) {
                #pre_dump( 'with offset bug', date('Y-m-d', $calendarfirst) );
                $calendarfirst = $calendarfirst - 604800;
                #pre_dump( 'without offset bug', date('Y-m-d', $calendarfirst) );
            }
        } else {
            // mode is 'year'
            // Find months with posts
            $arc_sql = '
				SELECT COUNT(DISTINCT ' . $this->dbIDname . ') AS item_count, EXTRACT(MONTH FROM ' . $this->dbprefix . 'datestart) AS mymonth
				  FROM (' . $this->dbtable . ' INNER JOIN T_postcats ON ' . $this->dbIDname . ' = postcat_post_ID)
				 INNER JOIN T_categories ON postcat_cat_ID = cat_ID
				 WHERE EXTRACT(YEAR FROM ' . $this->dbprefix . 'datestart) = \'' . $this->year . '\' ' . $this->ItemQuery->get_where(' AND ') . '
				 GROUP BY mymonth ' . $this->ItemQuery->get_group_by(', ');
            $arc_result = $DB->get_results($arc_sql, ARRAY_A);
            if ($DB->num_rows > 0) {
                // OK we have a month with posts! // fp>dh why did you removed that?
                foreach ($arc_result as $arc_row) {
                    $monthswithposts[$arc_row['mymonth']] = $arc_row['item_count'];
                }
            }
        }
        // ** display everything **
        echo $this->tablestart;
        // CAPTION :
        if ($this->displaycaption) {
            // caption:
            echo $this->monthstart;
            if ($this->navigation == 'caption') {
                echo implode('&nbsp;', $this->getNavLinks('prev')) . '&nbsp;';
            }
            if ($this->mode == 'month') {
                // MONTH CAPTION:
                $text = date_i18n($this->monthformat, mktime(0, 0, 0, $this->month, 1, $this->year));
                if ($this->linktomontharchive) {
                    // chosen month with link to archives
                    echo $this->archive_link($text, T_('View monthly archive'), $this->year, $this->month);
                } else {
                    echo $text;
                }
            } else {
                // YEAR CAPTION:
                echo date_i18n('Y', mktime(0, 0, 0, 1, 1, $this->year));
                // display year
            }
            if ($this->navigation == 'caption') {
                echo '&nbsp;' . implode('&nbsp;', $this->getNavLinks('next'));
            }
            echo $this->monthend;
        }
        // HEADER :
        if (!empty($this->headerdisplay) && $this->mode == 'month') {
            // Weekdays:
            echo $this->headerrowstart;
            for ($i = locale_startofweek(), $j = $i + 7; $i < $j; $i = $i + 1) {
                echo str_replace('[abbr]', T_($weekday[$i % 7]), $this->headercellstart);
                switch ($this->headerdisplay) {
                    case 'e':
                        // e => 'F'
                        echo T_($weekday_letter[$i % 7]);
                        break;
                    case 'l':
                        // l (lowercase l) => 'Friday'
                        echo T_($weekday[$i % 7]);
                        break;
                    default:
                        // Backward compatibility: any non emty value will display this
                        // D => 'Fri'
                        echo T_($weekday_abbrev[$i % 7]);
                }
                echo $this->headercellend;
            }
            echo $this->headerrowend;
        }
        // FOOTER :
        if ($this->navigation == 'tfoot') {
            // We want to display navigation in the table footer:
            echo "<tfoot>\n";
            echo "<tr>\n";
            echo '<td colspan="' . (($this->mode == 'month' ? 2 : 1) + (int) $this->today_is_visible) . '" id="prev">';
            echo implode('&nbsp;', $this->getNavLinks('prev'));
            echo "</td>\n";
            if ($this->today_is_visible) {
                if ($this->mode == 'month') {
                    echo '<td class="pad">&nbsp;</td>' . "\n";
                }
            } else {
                echo '<td colspan="' . ($this->mode == 'month' ? '3' : '2') . '" class="center">' . $this->archive_link(T_('Current'), '', date('Y'), $this->mode == 'month' ? date('m') : NULL) . '</td>';
            }
            echo '<td colspan="' . (($this->mode == 'month' ? 2 : 1) + (int) $this->today_is_visible) . '" id="next">';
            echo implode('&nbsp;', $this->getNavLinks('next'));
            echo "</td>\n";
            echo "</tr>\n";
            echo "</tfoot>\n";
        }
        // REAL TABLE DATA :
        echo '<tbody>' . $this->rowstart;
        if ($this->mode == 'year') {
            // DISPLAY MONTHS:
            for ($i = 1; $i < 13; $i = $i + 1) {
                // For each month:
                if (isset($monthswithposts[$i])) {
                    if ($this->month == $i) {
                        echo $this->todaycellstartpost;
                    } else {
                        echo $this->linkpostcellstart;
                    }
                    if ($monthswithposts[$i] > 1 && !empty($this->postcount_year_atitle)) {
                        // display postcount
                        $title = sprintf($this->postcount_year_atitle, $monthswithposts[$i]);
                    } elseif (!empty($this->postcount_year_atitle_one)) {
                        // display postcount for one post
                        $title = sprintf($this->postcount_year_atitle_one, 1);
                    } else {
                        $title = '';
                    }
                    echo $this->archive_link(T_($month_abbrev[zeroise($i, 2)]), $title, $this->year, $i);
                } elseif ($this->month == $i) {
                    // current month
                    echo $this->todaycellstart;
                    echo T_($month_abbrev[zeroise($i, 2)]);
                } else {
                    echo $this->cellstart;
                    echo T_($month_abbrev[zeroise($i, 2)]);
                }
                echo $this->cellend;
                if ($i == 4 || $i == 8) {
                    // new row
                    echo $this->rowend . $this->rowstart;
                }
            }
        } else {
            // DISPLAY DAYS of current month:
            $dow = 0;
            $last_day = -1;
            $dom_displayed = 0;
            // days of month displayed
            for ($i = $calendarfirst; $i <= $calendarlast; $i = $i + 86400) {
                // loop day by day (86400 seconds = 24 hours; but not on days where daylight saving changes!)
                if ($dow == 7) {
                    // We need to start a new row:
                    if ($dom_displayed >= $daysinmonth) {
                        // Last day already displayed!
                        break;
                    }
                    echo $this->rowend;
                    echo $this->rowstart;
                    $dow = 0;
                }
                $dow++;
                // correct daylight saving ("last day"+86400 would lead to "last day at 23:00")
                // fp> TODO: use mkdate()
                while (date('j', $i) == $last_day) {
                    $i += 3600;
                }
                $last_day = date('j', $i);
                if (date('m', $i) != $this->month) {
                    // empty cell
                    echo $this->emptycellstart;
                    echo $this->emptycellcontent;
                    echo $this->emptycellend;
                } else {
                    // This day is in this month
                    $dom_displayed++;
                    $calendartoday = date('Ymd', $i) == date('Ymd', time() + $time_difference);
                    if (isset($daysinmonthwithposts[date('j', $i)])) {
                        if ($calendartoday) {
                            echo $this->todaycellstartpost;
                        } else {
                            echo $this->linkpostcellstart;
                        }
                        if ($daysinmonthwithposts[date('j', $i)] > 1 && !empty($this->postcount_month_atitle)) {
                            // display postcount
                            $title = sprintf($this->postcount_month_atitle, $daysinmonthwithposts[date('j', $i)]);
                        } elseif (!empty($this->postcount_month_atitle_one)) {
                            // display postcount for one post
                            $title = sprintf($this->postcount_month_atitle_one, 1);
                        } else {
                            $title = '';
                        }
                        echo $this->archive_link(date('j', $i), $title, $this->year, $this->month, date('d', $i));
                    } elseif ($calendartoday) {
                        echo $this->todaycellstart;
                        echo date('j', $i);
                    } else {
                        echo $this->cellstart;
                        echo date('j', $i);
                    }
                    echo $this->cellend;
                }
            }
            // loop day by day
        }
        // mode == 'month'
        echo $this->rowend . "</tbody>\n";
        echo $this->tableend;
    }
 function get_archives($type = '', $limit = '', $format = 'html', $before = "", $after = "", $show_post_count = false, $selvalue = '', $echo = true)
 {
     $get_archives = '';
     if (!$type) {
         $type = get_settings('archive_mode');
     }
     // this is what will separate dates on weekly archive links
     $archive_week_separator = '&#8211;';
     // archive link url
     $archive_link_m = wp_siteurl() . '/index.php?m=';
     # monthly archive;
     $archive_link_w = wp_siteurl() . '/index.php?w=';
     # weekly archive;
     $archive_link_p = wp_siteurl() . '/index.php?p=';
     # post-by-post archive;
     // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
     $archive_date_format_over_ride = 0;
     // options for daily archive (only if you over-ride the general date format)
     $archive_day_date_format = 'Y/m/d';
     // options for weekly archive (only if you over-ride the general date format)
     $archive_week_start_date_format = 'Y/m/d';
     $archive_week_end_date_format = 'Y/m/d';
     if (!$archive_date_format_over_ride) {
         $archive_day_date_format = $GLOBALS['dateformat'];
         $archive_week_start_date_format = $GLOBALS['dateformat'];
         $archive_week_end_date_format = $GLOBALS['dateformat'];
     }
     $now = current_time('mysql');
     $postHandler =& wp_handler('Post');
     if ('monthly' == $type) {
         $criteria =& new CriteriaCompo(new Criteria('post_date', $now, '<'));
         $criteria->add(new Criteria('post_status', 'publish'));
         $criteria->setSort('post_date');
         $criteria->setOrder('DESC');
         $criteria->setGroupby('YEAR(post_date), MONTH(post_date)');
         if ($limit) {
             $criteria->setLimit($limit);
         }
         $postObjects =& $postHandler->getObjects($criteria, false, 'DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts');
         if ($postObjects) {
             foreach ($postObjects as $postObject) {
                 $this_year = $postObject->getExtraVar('year');
                 $this_month = $postObject->getExtraVar('month');
                 $url = get_month_link($this_year, $this_month);
                 if ($show_post_count) {
                     $text = format_month(sprintf("%d", $this_year), $GLOBALS['month'][zeroise($this_month, 2)]);
                     $after = "&nbsp;(" . $postObject->getExtraVar('posts') . ")";
                 } else {
                     $text = format_month(sprintf("%d", $this_year), $GLOBALS['month'][zeroise($this_month, 2)]);
                 }
                 $selected = $selvalue == $this_year . zeroise($this_month, 2);
                 $get_archives .= get_archives_link($url, $text, $format, $before, $after, $selected);
             }
         }
     } elseif ('daily' == $type) {
         $criteria =& new CriteriaCompo(new Criteria('post_date', $now, '<'));
         $criteria->add(new Criteria('post_status', 'publish'));
         $criteria->setSort('post_date');
         $criteria->setOrder('DESC');
         if ($limit) {
             $criteria->setLimit($limit);
         }
         $postObjects =& $postHandler->getObjects($criteria, false, 'DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`');
         if ($postObjects) {
             foreach ($postObjects as $postObject) {
                 $this_year = $postObject->getExtraVar('year');
                 $this_month = $postObject->getExtraVar('month');
                 $this_day = $postObject->getExtraVar('dayofmonth');
                 $url = get_day_link($this_year, $this_month, $this_day);
                 $date = sprintf("%d-%02d-%02d 00:00:00", $this_year, $this_month, $this_day);
                 $text = mysql2date($archive_day_date_format, $date);
                 $get_archives .= get_archives_link($url, $text, $format, $before, $after);
             }
         }
     } elseif ('weekly' == $type) {
         $criteria =& new CriteriaCompo(new Criteria('post_date', $now, '<'));
         $criteria->add(new Criteria('post_status', 'publish'));
         $criteria->setSort('post_date');
         $criteria->setOrder('DESC');
         if ($limit) {
             $criteria->setLimit($limit);
         }
         $postObjects =& $postHandler->getObjects($criteria, false, "DISTINCT WEEK(post_date, " . get_settings('start_of_week') . ") AS `week`, YEAR(post_date) AS yr, DATE_FORMAT(post_date, '%Y-%m-%d') AS yyyymmdd");
         $arc_w_last = '';
         if ($postObjects) {
             foreach ($postObjects as $postObject) {
                 $arc_week = $postObject->getExtraVar('week');
                 $arc_year = $postObject->getExtraVar('yr');
                 $arc_date = $postObject->getExtraVar('yyyymmdd');
                 if ($arc_week != $arc_w_last) {
                     $arc_w_last = $arc_week;
                     $arc_week_days = get_weekstartend($arc_date, get_settings('start_of_week'));
                     $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week_days['start']);
                     $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week_days['end']);
                     $url = sprintf("%s/index.php?m=%s&amp;w=%d", wp_siteurl(), $arc_year, $arc_week);
                     $text = $arc_week_start . $archive_week_separator . $arc_week_end;
                     $get_archives .= get_archives_link($url, $text, $format, $before, $after);
                 }
             }
         }
     } elseif ('postbypost' == $type) {
         $criteria =& new CriteriaCompo(new Criteria('post_date', $now, '<'));
         $criteria->add(new Criteria('post_status', 'publish'));
         $criteria->setSort('post_date');
         $criteria->setOrder('DESC');
         if ($limit) {
             $criteria->setLimit($limit);
         }
         $postObjects =& $postHandler->getObjects($criteria, false, 'ID, post_date, post_title');
         if ($postObjects) {
             foreach ($postObjects as $postObject) {
                 if ($postObject->getVar('post_date') != '0000-00-00 00:00:00') {
                     $url = get_permalink($postObject->getVar('ID'));
                     $arc_title = $postObject->getVar('post_title');
                     if ($arc_title) {
                         $text = strip_tags($arc_title);
                     } else {
                         $text = _WP_POST_NOTITLE;
                     }
                     $get_archives .= get_archives_link($url, $text, $format, $before, $after);
                 }
             }
         }
     }
     return _echo($get_archives, $echo);
 }
Example #13
0
 function test_get_weekstartend_start_of_week_set_to_monday()
 {
     $expected = array('start' => strtotime('2016-02-08 00:00:00'), 'end' => strtotime('2016-02-14 23:59:59'));
     $this->assertEquals($expected, get_weekstartend('2016-02-14'));
 }
function wp_get_archives($args = '')
{
    global $wp_locale, $wpdb;
    if (is_array($args)) {
        $r =& $args;
    } else {
        parse_str($args, $r);
    }
    $defaults = array('type' => 'monthly', 'limit' => '', 'format' => 'html', 'before' => '', 'after' => '', 'show_post_count' => false);
    $r = array_merge($defaults, $r);
    extract($r);
    if ('' == $type) {
        $type = 'monthly';
    }
    if ('' != $limit) {
        $limit = (int) $limit;
        $limit = ' LIMIT ' . $limit;
    }
    // this is what will separate dates on weekly archive links
    $archive_week_separator = '&#8211;';
    // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
    $archive_date_format_over_ride = 0;
    // options for daily archive (only if you over-ride the general date format)
    $archive_day_date_format = 'Y/m/d';
    // options for weekly archive (only if you over-ride the general date format)
    $archive_week_start_date_format = 'Y/m/d';
    $archive_week_end_date_format = 'Y/m/d';
    if (!$archive_date_format_over_ride) {
        $archive_day_date_format = get_option('date_format');
        $archive_week_start_date_format = get_option('date_format');
        $archive_week_end_date_format = get_option('date_format');
    }
    $add_hours = intval(get_option('gmt_offset'));
    $add_minutes = intval(60 * (get_option('gmt_offset') - $add_hours));
    if ('monthly' == $type) {
        $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC" . $limit);
        if ($arcresults) {
            $afterafter = $after;
            foreach ($arcresults as $arcresult) {
                $url = get_month_link($arcresult->year, $arcresult->month);
                $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);
                if ($show_post_count) {
                    $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                }
                echo get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('yearly' == $type) {
        $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, count(ID) as posts FROM {$wpdb->posts} WHERE post_type ='post' AND post_status = 'publish' GROUP BY YEAR(post_date) ORDER BY post_date DESC" . $limit);
        if ($arcresults) {
            $afterafter = $after;
            foreach ($arcresults as $arcresult) {
                $url = get_year_link($arcresult->year);
                $text = sprintf('%d', $arcresult->year);
                if ($show_post_count) {
                    $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                }
                echo get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('daily' == $type) {
        $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date DESC" . $limit);
        if ($arcresults) {
            $afterafter = $after;
            foreach ($arcresults as $arcresult) {
                $url = get_day_link($arcresult->year, $arcresult->month, $arcresult->dayofmonth);
                $date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $arcresult->year, $arcresult->month, $arcresult->dayofmonth);
                $text = mysql2date($archive_day_date_format, $date);
                if ($show_post_count) {
                    $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                }
                echo get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('weekly' == $type) {
        $start_of_week = get_option('start_of_week');
        $arcresults = $wpdb->get_results("SELECT DISTINCT WEEK(post_date, {$start_of_week}) AS `week`, YEAR(post_date) AS yr, DATE_FORMAT(post_date, '%Y-%m-%d') AS yyyymmdd, count(ID) as posts FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' GROUP BY WEEK(post_date, {$start_of_week}), YEAR(post_date) ORDER BY post_date DESC" . $limit);
        $arc_w_last = '';
        $afterafter = $after;
        if ($arcresults) {
            foreach ($arcresults as $arcresult) {
                if ($arcresult->week != $arc_w_last) {
                    $arc_year = $arcresult->yr;
                    $arc_w_last = $arcresult->week;
                    $arc_week = get_weekstartend($arcresult->yyyymmdd, get_option('start_of_week'));
                    $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
                    $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
                    $url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', get_option('home'), '', '?', '=', $arc_year, '&amp;', '=', $arcresult->week);
                    $text = $arc_week_start . $archive_week_separator . $arc_week_end;
                    if ($show_post_count) {
                        $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                    }
                    echo get_archives_link($url, $text, $format, $before, $after);
                }
            }
        }
    } elseif ('postbypost' == $type || 'alpha' == $type) {
        'alpha' == $type ? $orderby = "post_title ASC " : ($orderby = "post_date DESC ");
        $arcresults = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY {$orderby} {$limit}");
        if ($arcresults) {
            foreach ($arcresults as $arcresult) {
                if ($arcresult->post_date != '0000-00-00 00:00:00') {
                    $url = get_permalink($arcresult);
                    $arc_title = $arcresult->post_title;
                    if ($arc_title) {
                        $text = strip_tags($arc_title);
                    } else {
                        $text = $arcresult->ID;
                    }
                    echo get_archives_link($url, $text, $format, $before, $after);
                }
            }
        }
    }
}
Example #15
0
        $start_of_week = 1;
    }
    $archive_week_start_date_format = "Y/m/d";
    $archive_week_end_date_format = "Y/m/d";
    $archive_week_separator = " - ";
    $arc_sql = "SELECT DISTINCT YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date), WEEK(post_date) FROM {$tableposts} ORDER BY post_date DESC";
    $querycount++;
    $arc_result = mysql_query($arc_sql) or die($arc_sql . "<br />" . mysql_error());
    $arc_w_last = '';
    while ($arc_row = mysql_fetch_array($arc_result)) {
        $arc_year = $arc_row["YEAR(post_date)"];
        $arc_w = $arc_row["WEEK(post_date)"];
        if ($arc_w != $arc_w_last) {
            $arc_w_last = $arc_w;
            $arc_ymd = $arc_year . "-" . zeroise($arc_row["MONTH(post_date)"], 2) . "-" . zeroise($arc_row["DAYOFMONTH(post_date)"], 2);
            $arc_week = get_weekstartend($arc_ymd, $start_of_week);
            $arc_week_start = date($archive_week_start_date_format, $arc_week['start']);
            $arc_week_end = date($archive_week_end_date_format, $arc_week['end']);
            echo "<option value=\"{$arc_w}\">";
            echo $arc_week_start . $archive_week_separator . $arc_week_end;
            echo "</option>\n";
        }
    }
} elseif ($archive_mode == "postbypost") {
    echo '<input type="hidden" name="more" value="1" />';
    echo '<select name="p" style="width:120px;">';
    $requestarc = " SELECT ID,post_date,post_title FROM {$tableposts} ORDER BY post_date DESC";
    $querycount++;
    $resultarc = mysql_query($requestarc);
    while ($row = mysql_fetch_object($resultarc)) {
        if ($row->post_date != "0000-00-00 00:00:00") {
Example #16
0
    /**
     * Renders the order stats widget
     *
     * @author Jonathan Davis
     * @since 1.0
     *
     * @return void
     **/
    public static function stats_widget($args = false)
    {
        $ranges = array('today' => __('Today', 'Shopp'), 'week' => __('This Week', 'Shopp'), 'month' => __('This Month', 'Shopp'), 'quarter' => __('This Quarter', 'Shopp'), 'year' => __('This Year', 'Shopp'), 'yesterday' => __('Yesterday', 'Shopp'), 'lastweek' => __('Last Week', 'Shopp'), 'last30' => __('Last 30 Days', 'Shopp'), 'last90' => __('Last 3 Months', 'Shopp'), 'lastmonth' => __('Last Month', 'Shopp'), 'lastquarter' => __('Last Quarter', 'Shopp'), 'lastyear' => __('Last Year', 'Shopp'));
        $defaults = array('before_widget' => '', 'before_title' => '', 'widget_name' => '', 'after_title' => '', 'after_widget' => '', 'range' => isset($_GET['shopp-stats-range']) ? $_GET['shopp-stats-range'] : '');
        $args = array_merge($defaults, (array) $args);
        extract($args, EXTR_SKIP);
        if (!$range || !isset($ranges[strtolower($range)])) {
            $range = 'last30';
        }
        $purchasetable = ShoppDatabaseObject::tablename(ShoppPurchase::$table);
        $now = current_time('timestamp');
        // $offset = get_option( 'gmt_offset' ) * 3600;
        $daytimes = 86400;
        $day = date('j', $now);
        $month = date('n', $now);
        $year = date('Y', $now);
        $end = $now;
        list($weekstart, $weekend) = array_values(get_weekstartend(current_time('mysql')));
        switch ($range) {
            case 'today':
                $start = mktime(0, 0, 0, $month, $day, $year);
                break;
            case 'week':
                $start = $weekstart;
                $end = $weekend;
                break;
            case 'month':
                $start = mktime(0, 0, 0, $month, 1, $year);
                break;
            case 'quarter':
                $start = mktime(0, 0, 0, $month - (3 - $month % 3), 1, $year);
                break;
            case 'year':
                $start = mktime(0, 0, 0, 1, 1, $year);
                break;
            case 'yesterday':
                $start = mktime(0, 0, 0, $month, $day - 1, $year);
                $end = mktime(23, 59, 59, $month, $day - 1, $year);
                break;
            case 'lastweek':
                $start = $weekstart - 7 * $daytimes;
                $end = $weekstart - 1;
                break;
            case 'last7':
                $start = $now - 7 * $daytimes;
                break;
            case 'last30':
                $start = $now - 30 * $daytimes;
                break;
            case 'last90':
                $start = $now - 90 * $daytimes;
                break;
            case 'lastmonth':
                $start = mktime(0, 0, 0, $month - 1, 1, $year);
                $end = mktime(0, 0, 0, $month, 0, $year);
                break;
            case 'lastquarter':
                $start = mktime(0, 0, 0, $month - (3 - $month % 3) - 3, 1, $year);
                $end = mktime(23, 59, 59, date('n', $start) + 3, 0, $year);
                break;
            case 'lastyear':
                $start = mktime(0, 0, 0, $month, 1, $year - 1);
                $end = mktime(23, 59, 59, 1, 0, $year);
                break;
        }
        // Include authorizations, captures and old 1.1 tranaction status CHARGED in sales data
        $salestatus = array("'authed'", "'captured'", "'CHARGED'");
        $txnstatus = "txnstatus IN (" . join(',', $salestatus) . ")";
        $daterange = "created BETWEEN '" . sDB::mkdatetime($start) . "' AND '" . sDB::mkdatetime($end) . "'";
        $query = "SELECT count(id) AS orders,\n\t\t\t\t\t\tSUM(total) AS sales,\n\t\t\t\t\t\tAVG(total) AS average,\n\t\t \t\t\t\tSUM(IF({$daterange},1,0)) AS wkorders,\n\t\t\t\t\t\tSUM(IF({$daterange},total,0)) AS wksales,\n\t\t\t\t\t\tAVG(IF({$daterange},total,null)) AS wkavg\n \t\t\t\t\tFROM {$purchasetable} WHERE {$txnstatus}";
        $cached = get_transient('shopp_dashboard_stats_' . $range);
        if (empty($cached)) {
            $results = sDB::query($query);
            $RecentBestsellers = new BestsellerProducts(array('range' => array($start, $end), 'show' => 5));
            $RecentBestsellers->load(array('pagination' => false));
            $RecentBestsellers->maxsold = 0;
            foreach ($RecentBestsellers as $product) {
                $RecentBestsellers->maxsold = max($RecentBestsellers->maxsold, $product->sold);
            }
            $LifeBestsellers = new BestsellerProducts(array('show' => 5));
            $LifeBestsellers->load(array('pagination' => false));
            $LifeBestsellers->maxsold = 0;
            foreach ($LifeBestsellers as $product) {
                $LifeBestsellers->maxsold = max($LifeBestsellers->maxsold, $product->sold);
            }
            set_transient('shopp_dashboard_stats_' . $range, array($results, $RecentBestsellers, $LifeBestsellers), 300);
        } else {
            list($results, $RecentBestsellers, $LifeBestsellers) = $cached;
        }
        echo $before_widget;
        echo $before_title;
        echo $widget_name;
        echo $after_title;
        $orderscreen = add_query_arg('page', ShoppAdmin::pagename('orders'), admin_url('admin.php'));
        $productscreen = add_query_arg(array('page' => ShoppAdmin::pagename('products')), admin_url('admin.php'));
        ?>
		<div class="table"><table>
		<tr><th colspan="2"><form action="<?php 
        echo admin_url('index.php');
        ?>
">
			<select name="shopp-stats-range" id="shopp-stats-range">
				<?php 
        echo menuoptions($ranges, $range, true);
        ?>
			</select>
			<button type="submit" id="filter-button" name="filter" value="order" class="button-secondary hide-if-js"><?php 
        _e('Filter', 'Shopp');
        ?>
</button>
		</form>
		</th><th colspan="2"><?php 
        _e('Lifetime', 'Shopp');
        ?>
</th></tr>

		<tbody>
		<tr><td class="amount"><a href="<?php 
        echo esc_url($orderscreen);
        ?>
"><?php 
        echo (int) $results->wkorders;
        ?>
</a></td><td class="label"><?php 
        echo _n('Order', 'Orders', (int) $results->wkorders, 'Shopp');
        ?>
</td>
		<td class="amount"><a href="<?php 
        echo esc_url($orderscreen);
        ?>
"><?php 
        echo (int) $results->orders;
        ?>
</a></td><td class="label"><?php 
        echo _n('Order', 'Orders', (int) $results->orders, 'Shopp');
        ?>
</td></tr>

		<tr><td class="amount"><a href="<?php 
        echo esc_url($orderscreen);
        ?>
"><?php 
        echo money($results->wksales);
        ?>
</a></td><td class="label"><?php 
        _e('Sales', 'Shopp');
        ?>
</td>
		<td class="amount"><a href="<?php 
        echo esc_url($orderscreen);
        ?>
"><?php 
        echo money($results->sales);
        ?>
</a></td><td class="label"><?php 
        _e('Sales', 'Shopp');
        ?>
</td></tr>

		<tr><td class="amount"><a href="<?php 
        echo esc_url($orderscreen);
        ?>
"><?php 
        echo money($results->wkavg);
        ?>
</a></td><td class="label"><?php 
        _e('Average Order', 'Shopp');
        ?>
</td>
		<td class="amount"><a href="<?php 
        echo esc_url($orderscreen);
        ?>
"><?php 
        echo money($results->average);
        ?>
</a></td><td class="label"><?php 
        _e('Average Order', 'Shopp');
        ?>
</td></tr>

		<?php 
        if (!empty($RecentBestsellers->products) || !empty($LifeBestsellers->products)) {
            ?>
		<tr>
			<th colspan="2"><?php 
            printf(__('Bestsellers %s', 'Shopp'), $ranges[$range]);
            ?>
</th>
			<th colspan="2"><?php 
            printf(__('Lifetime Bestsellers', 'Shopp'), $ranges[$range]);
            ?>
</th>
		</tr>
		<?php 
            reset($RecentBestsellers);
            reset($LifeBestsellers);
            $firstrun = true;
            while (true) {
                list($recentid, $recent) = each($RecentBestsellers->products);
                list($lifetimeid, $lifetime) = each($LifeBestsellers->products);
                if (!$recent && !$lifetime) {
                    break;
                }
                ?>
			<tr>
				<?php 
                if (empty($RecentBestsellers->products) && $firstrun) {
                    echo '<td colspan="2" rowspan="5">' . __('None', 'Shopp') . '</td>';
                }
                ?>
				<?php 
                if (!empty($recent->id)) {
                    ?>
				<td class="salesgraph">
					<div class="bar" style="width:<?php 
                    echo $recent->sold / $RecentBestsellers->maxsold * 100;
                    ?>
%;"><?php 
                    echo $recent->sold;
                    ?>
</div>
				</td>
				<td>
				<a href="<?php 
                    echo esc_url(add_query_arg('view', 'bestselling', $productscreen));
                    ?>
"><?php 
                    echo esc_html($recent->name);
                    ?>
</a>
				</td>
				<?php 
                }
                ?>
				<?php 
                if (empty($LifeBestsellers->products) && $firstrun) {
                    echo '<td colspan="2" rowspan="5">' . __('None', 'Shopp') . '</td>';
                }
                ?>
				<?php 
                if (!empty($lifetime->id)) {
                    ?>
				<td class="salesgraph">
					<div class="bar" style="width:<?php 
                    echo $lifetime->sold / $LifeBestsellers->maxsold * 100;
                    ?>
%;"><?php 
                    echo $lifetime->sold;
                    ?>
</div>
				</td>
				<td>
				<a href="<?php 
                    echo esc_url(add_query_arg('view', 'bestselling', $productscreen));
                    ?>
"><?php 
                    echo esc_html($lifetime->name);
                    ?>
</a>
				</td>
				<?php 
                }
                ?>
			</tr>
		<?php 
                $firstrun = false;
            }
            ?>
		<?php 
        }
        ?>
		</tbody></table></div>
		<script type="text/javascript">
		jQuery(document).ready(function($){$('#shopp-stats-range').change(function(){$(this).parents('form').submit();});});
		</script>
		<?php 
        echo $after_widget;
    }
function get_archives($type = '', $limit = '', $format = 'html', $before = "", $after = "", $show_post_count = false)
{
    global $dateformat, $time_difference, $siteurl, $wp_id;
    global $month, $wpdb, $wp_month_format;
    if ('' == $type) {
        $type = get_settings('archive_mode');
    }
    if ('' != $limit) {
        $limit = (int) $limit;
        $limit = " LIMIT {$limit}";
    }
    // this is what will separate dates on weekly archive links
    $archive_week_separator = '&#8211;';
    // archive link url
    $archive_link_m = $siteurl . '/index.php?m=';
    # monthly archive;
    $archive_link_w = $siteurl . '/index.php?w=';
    # weekly archive;
    $archive_link_p = $siteurl . '/index.php?p=';
    # post-by-post archive;
    // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
    $archive_date_format_over_ride = 0;
    // options for daily archive (only if you over-ride the general date format)
    $archive_day_date_format = 'Y/m/d';
    // options for weekly archive (only if you over-ride the general date format)
    $archive_week_start_date_format = 'Y/m/d';
    $archive_week_end_date_format = 'Y/m/d';
    if (!$archive_date_format_over_ride) {
        $archive_day_date_format = $dateformat;
        $archive_week_start_date_format = $dateformat;
        $archive_week_end_date_format = $dateformat;
    }
    $now = date('Y-m-d H:i:s', time() + $time_difference * 3600);
    if ('monthly' == $type) {
        $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM {$wpdb->posts[$wp_id]} WHERE post_date < '{$now}' AND post_status = 'publish' GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC" . $limit);
        if ($arcresults) {
            foreach ($arcresults as $arcresult) {
                $url = get_month_link($arcresult->year, $arcresult->month);
                if ($show_post_count) {
                    $text = ereg_replace('%MONTH', $month[zeroise($arcresult->month, 2)], $wp_month_format);
                    $text = ereg_replace('%YEAR', sprintf("%d", $arcresult->year), $text);
                    $after = "&nbsp;({$arcresult->posts})";
                } else {
                    $text = ereg_replace('%MONTH', $month[zeroise($arcresult->month, 2)], $wp_month_format);
                    $text = ereg_replace('%YEAR', sprintf("%d", $arcresult->year), $text);
                }
                echo get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('daily' == $type) {
        $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth` FROM {$wpdb->posts[$wp_id]} WHERE post_date < '{$now}' AND post_status = 'publish' ORDER BY post_date DESC" . $limit);
        if ($arcresults) {
            foreach ($arcresults as $arcresult) {
                $url = get_day_link($arcresult->year, $arcresult->month, $arcresult->dayofmonth);
                $date = sprintf("%d-%02d-%02d 00:00:00", $arcresult->year, $arcresult->month, $arcresult->dayofmonth);
                $text = mysql2date($archive_day_date_format, $date);
                echo get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('weekly' == $type) {
        $arcresults = $wpdb->get_results("SELECT DISTINCT WEEK(post_date, " . get_settings('start_of_week') . ") AS `week`, YEAR(post_date) AS yr, DATE_FORMAT(post_date, '%Y-%m-%d') AS yyyymmdd FROM {$wpdb->posts[$wp_id]} WHERE post_date < '{$now}' AND post_status = 'publish' ORDER BY post_date DESC" . $limit);
        $arc_w_last = '';
        if ($arcresults) {
            foreach ($arcresults as $arcresult) {
                if ($arcresult->week != $arc_w_last) {
                    $arc_year = $arcresult->yr;
                    $arc_w_last = $arcresult->week;
                    $arc_week = get_weekstartend($arcresult->yyyymmdd, get_settings('start_of_week'));
                    $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
                    $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
                    $url = sprintf("%s/index.php?m=%s&amp;w=%d", $siteurl, $arc_year, $arcresult->week);
                    $text = $arc_week_start . $archive_week_separator . $arc_week_end;
                    echo get_archives_link($url, $text, $format, $before, $after);
                }
            }
        }
    } elseif ('postbypost' == $type) {
        $arcresults = $wpdb->get_results("SELECT ID, post_date, post_title FROM {$wpdb->posts[$wp_id]} WHERE post_date < '{$now}' AND post_status = 'publish' ORDER BY post_date DESC" . $limit);
        if ($arcresults) {
            foreach ($arcresults as $arcresult) {
                if ($arcresult->post_date != '0000-00-00 00:00:00') {
                    $url = get_permalink($arcresult->ID);
                    $arc_title = stripslashes($arcresult->post_title);
                    if ($arc_title) {
                        $text = strip_tags($arc_title);
                    } else {
                        $text = $arcresult->ID;
                    }
                    echo get_archives_link($url, $text, $format, $before, $after);
                }
            }
        }
    }
}
Example #18
0
        }
    }
}
$daysinmonth = intval(date('t', mktime(0, 0, 0, $thismonth, 1, $thisyear)));
$datestartofmonth = $thisyear . '-' . $thismonth . '-01';
$dateendofmonth = $thisyear . '-' . $thismonth . '-' . $daysinmonth;
// caution: offset bug inside
$calendarblah = get_weekstartend($datestartofmonth, $start_of_week);
if (mysql2date('w', $datestartofmonth) == $start_of_week) {
    $calendarfirst = $calendarblah['start'] + 1 + 3600;
    //	adjust for daylight savings time
} else {
    $calendarfirst = $calendarblah['end'] - 604799 + 3600;
    //	adjust for daylight savings time
}
$calendarblah = get_weekstartend($dateendofmonth, $end_of_week);
if (mysql2date('w', $dateendofmonth) == $end_of_week) {
    $calendarlast = $calendarblah['start'] + 1;
} else {
    $calendarlast = $calendarblah['end'] + 10000;
}
$beforethismonth = zeroise(intval($thismonth) - 1, 2);
$afterthismonth = zeroise(intval($thismonth) - 1, 2);
// here the offset bug is corrected
if (intval(date('d', $calendarfirst)) > 1 && intval(date('m', $calendarfirst)) == intval($thismonth)) {
    $calendarfirst = $calendarfirst - 604800;
}
// displays everything
echo $calendartablestart . "\n";
if ($calendarmonthdisplay) {
    echo $calendarmonthstart;