/** 
 * Widget function: recent posts 
 * Optional parameters can be passed as array in the first argument 
 * to overload default settings: 
 * 
 * title
 * spec_query - specific WP Query (can also be passed as string in 3rd argument)
 * cache_name - a bit deprecated (can also be passed as string in 2nd argument)
 * meta_field
 * title_cut
 * excerpt_cut
 * use_wpexcerpt
 * display_thumb
 * display_post_title
 * display_date
 * date_format
 * display_excerpt
 * bottom_text
 * bottom_link
 * image_style
 * default_image
 * strip_sqbt
 * strip_clbt
 * keep_html
 * display_ul
 * ellipsis_string
 * 
 ***/
function widget_yd_rp($args = TRUE, $cache_name = NULL, $spec_query = NULL)
{
    if (isset($args) && $args === FALSE) {
        $echo = FALSE;
    } else {
        if (is_array($args)) {
            extract($args);
        }
        $echo = TRUE;
    }
    //var_dump( $args );
    global $wpdb;
    global $user_level;
    global $more;
    $plugin_dir = 'yd-recent-posts-widget';
    $options = get_option('widget_yd_rp');
    $default_cutlength = $options[0]['default_cutlength'];
    $current_querycount = get_num_queries();
    $html = '';
    $i = (int) str_replace('wydrp-', '', $args['widget_id']);
    if (!$i) {
        $i = 1;
    }
    if (is_admin()) {
        return;
    }
    if ($spec_query || is_home() || $options[$i]["same_opages"]) {
        //echo "HOME<br/>";
        $title = $options[$i]["home_title"];
        if ($options[$i]["home_tag"]) {
            $wp_query_string = "post_type=post&showposts=" . $options[$i]["home_showposts"] . "&offset=0&tag=" . $options[$i]["home_tag"];
        } else {
            $nb_to_skip = get_option('posts_per_page');
            $my_query = "post_type=post&showposts=" . $options[$i]["home_showposts"];
            if (is_home() && $options[0]["skip_latest"]) {
                $my_query .= "&offset=" . $nb_to_skip;
            }
            $wp_query_string = $my_query;
        }
        if ($options[$i]["home_datemeta"]) {
            $date_type = $options[$i]["home_datemeta"];
        } else {
            $date_type = 'post_date';
        }
        $bottom_text = $options[$i]["home_bottomtext"];
        $bottom_link = $options[$i]["home_bottomlink"];
        $list_type = 'home';
        $title_cutlength = isset($options[$i]["home_title_cutlength"]) && $options[$i]["home_title_cutlength"] != '' ? $options[$i]["home_title_cutlength"] : $default_cutlength;
        $abstract_cutlength = isset($options[$i]["home_abstract_cutlength"]) && $options[$i]["home_abstract_cutlength"] != '' ? $options[$i]["home_abstract_cutlength"] : $default_cutlength;
        $use_wp_excerpt = $options[$i]["home_u_wpabstract"];
        $display_thumb = $options[$i]['home_d_post_thumb'];
        $display_post_title = $options[$i]['home_d_post_title'];
        $display_date = $options[$i]['home_d_post_date'];
        $date_format = $options[$i]['home_date_format'];
        $display_excerpt = $options[$i]['home_d_abstract'];
        if ($options[$i]['home_add_query']) {
            $wp_query_string .= '&' . $options[$i]['home_add_query'];
        }
    } else {
        //echo "PAGE<br/>";
        $title = $options[$i]["opage_title"];
        $wp_query_string = "post_type=post&showposts=" . $options[$i]["opage_showposts"] . "&offset=0&tag=" . $options[$i]["opage_tag"];
        $date_type = 'post_date';
        $bottom_text = $options[$i]["opage_bottomtext"];
        $bottom_link = $options[$i]["opage_bottomlink"];
        $list_type = 'page';
        $title_cutlength = isset($options[$i]["opage_title_cutlength"]) && $options[$i]["opage_title_cutlength"] != '' ? $options[$i]["opage_title_cutlength"] : $default_cutlength;
        $abstract_cutlength = isset($options[$i]["opage_abstract_cutlength"]) && $options[$i]["opage_abstract_cutlength"] != '' ? $options[$i]["opage_abstract_cutlength"] : $default_cutlength;
        $use_wp_excerpt = $options[$i]["opage_u_wpabstract"];
        $display_thumb = $options[$i]['opage_d_post_thumb'];
        $display_post_title = $options[$i]['opage_d_post_title'];
        $display_date = $options[$i]['opage_d_post_date'];
        $date_format = $options[$i]['opage_date_format'];
        $display_excerpt = $options[$i]['opage_d_abstract'];
        if ($options[$i]['opage_add_query']) {
            $wp_query_string .= '&' . $options[$i]['opage_add_query'];
        }
    }
    /** deprecated since v.3.0.0: ** /
    	$title_cutlength = $options[$i]["title_cutlength"] ? $options[$i]["title_cutlength"] : $default_cutlength;
    	$abstract_cutlength = $options[$i]["abstract_cutlength"] ? $options[$i]["abstract_cutlength"] : $default_cutlength;
    	/** **/
    $image_style = $options[$i]["image_style"];
    $default_image = $options[$i]["default_image"];
    $load_css = $options[$i]["load_css"];
    // widget-level option (deprecated in 3.0.0)
    if ($options[0]["load_css"]) {
        $load_css = false;
    }
    // plugin-level option precedes.
    $strip_sqbt = $options[0]['strip_sqbt'];
    $strip_clbt = $options[0]['strip_clbt'];
    $keep_html = $options[0]['keep_html'];
    $display_ul = $options[0]["display_ul"];
    $ellipsis_string = $options[0]['ellipsis_string'];
    /**
     * function parameter overload (new in v.3.0.0)
     * 
     */
    if ($args['title']) {
        $title = $args['title'];
    }
    if ($args['spec_query']) {
        $spec_query = $args['spec_query'];
    }
    if ($args['cache_name']) {
        $cache_name = $args['cache_name'];
    }
    if ($args['meta_field']) {
        $date_type = $args['meta_field'];
    }
    if ($args['title_cut']) {
        $title_cutlength = $args['title_cut'];
    }
    if ($args['excerpt_cut']) {
        $abstract_cutlength = $args['excerpt_cut'];
    }
    if ($args['use_wpexcerpt']) {
        $use_wp_excerpt = $args['use_wpexcerpt'];
    }
    if ($args['display_thumb']) {
        $display_thumb = $args['display_thumb'];
    }
    if ($args['display_post_title']) {
        $display_post_title = $args['display_post_title'];
    }
    if ($args['display_date']) {
        $display_date = $args['display_date'];
    }
    if ($args['date_format']) {
        $date_format = $args['date_format'];
    }
    if ($args['display_excerpt']) {
        $display_excerpt = $args['display_excerpt'];
    }
    if ($args['bottom_text']) {
        $bottom_text = $args['bottom_text'];
    }
    if ($args['bottom_link']) {
        $bottom_link = $args['bottom_link'];
    }
    if ($args['image_style']) {
        $image_style = $args['image_style'];
    }
    if ($args['default_image']) {
        $default_image = $args['default_image'];
    }
    if ($args['strip_sqbt']) {
        $strip_sqbt = $args['strip_sqbt'];
    }
    if ($args['strip_clbt']) {
        $strip_clbt = $args['strip_clbt'];
    }
    if ($args['keep_html']) {
        $keep_html = $args['keep_html'];
    }
    if ($args['display_ul']) {
        $display_ul = $args['display_ul'];
    }
    if ($args['ellipsis_string']) {
        $ellipsis_string = $args['ellipsis_string'];
    }
    if ($spec_query) {
        //echo 'debug: spec_query: <pre>'; var_dump( $spec_query ); echo '</pre>';
        //echo 'debug: echo: ' . $echo . '<br/>';
        $wp_query_string = $spec_query;
    }
    //specific overloaded usage within templates... (new in 0.7) -- deprecated?
    if ($cache_name) {
        $list_type = $cache_name;
        $title = '';
        $date_type = 'post_date';
        $bottom_text = '';
        $bottom_link = '';
    }
    //
    $wp_query_string = apply_filters('yd_rp_query_filter', $wp_query_string);
    //echo "debug: wpqs: " . $wp_query_string . '<br/>';
    //var_dump( $wp_query_string );
    $my_wp_query = new WP_Query($wp_query_string);
    $more = 0;
    if (is_array($wp_query_string)) {
        $wp_query_string = http_build_query((array) $wp_query_string);
    }
    $cache_key = md5($wp_query_string . http_build_query((array) $args));
    //echo 'debug: qu:' . $wp_query_string . '<br/>';
    //echo 'debug: cc:' . $cache_key . '<br/>';
    if (!check_yd_widget_cache('widget_yd_rp_' . $cache_key)) {
        //query_posts( $my_wp_query );
        $html .= $before_widget;
        /** this way of loading the css is deprecated since plugin v.3.0.0 -- we now use enqueue script
         * 	and the option is now a plugin-level option [0] (used to be widget-level [1])
         */
        if ($load_css) {
            $html .= '<link type="text/css" rel="stylesheet" href="' . get_bloginfo('wpurl') . '/wp-content/plugins/' . $plugin_dir . '/css/yd_rp.css" />';
        }
        if ($title) {
            $html .= $before_title . $title . $after_title;
        }
        $html .= '<div class="yd_rp_widget">';
        if ($my_wp_query->have_posts()) {
            //echo 'debug: have posts!<br/>';
            if ($display_ul) {
                $html .= '<ul>';
            }
            while ($my_wp_query->have_posts()) {
                $my_wp_query->the_post();
                /** new in 0.7: make sure not to display private posts **/
                if (get_post_status() != 'publish') {
                    continue;
                }
                $post = get_post(get_the_id());
                if ($post->post_password != '') {
                    continue;
                }
                // -- thumbnails ! --
                $link = '<a href="' . get_permalink() . '" rel="bookmark" title="' . __('Permanent link to:', 'yd-recent-posts-widget') . ' ' . get_the_title('', '', FALSE) . '">';
                $tn_url = false;
                if ($display_thumb) {
                    //WP2.9+
                    // If WordPress 2.9 or above and a Post Thumbnail has been specified
                    if ($options[0]['use_wpthumb'] && function_exists('has_post_thumbnail') && has_post_thumbnail($post->ID)) {
                        $tn = get_the_post_thumbnail($post->ID);
                        if (preg_match('/src="([^"]+)"/i', $tn, $matches)) {
                            $tn_url = $matches[1];
                        }
                    }
                    //WP2.7 (?)
                    if (!$tn_url) {
                        $values = get_post_custom_values("thumb");
                        $tn_url = $values[0];
                    }
                    //Get first attachment
                    if (!$tn_url) {
                        $tn_url = $wpdb->get_var("SELECT guid FROM " . $wpdb->posts . " WHERE post_type='attachment' and post_mime_type like 'image/%' and post_parent = " . get_the_id() . " and guid != '' LIMIT 1");
                    }
                    //Try to find first image in html
                    if (!$tn_url) {
                        preg_match('/<img[^>]+src=[\'"]([^\'"]+)[\'"]/', get_the_content(), $matches);
                        $tn_url = $matches[1];
                    }
                    if ($options[0]['use_timthumb']) {
                        if ($tn_url) {
                            $tn_url = preg_replace("|^http://[^\\/]+|", '', $tn_url);
                            // strip original domain (timthumb does not do external fetches)
                            $tn_url = $options[0]['timthumb_path'] . '?src=' . $tn_url . '&amp;h=' . $options[0]['timthumb_height'] . '&amp;w=' . $options[0]['timthumb_width'] . '&amp;zc=1&amp;q=100';
                        }
                    } else {
                        //WP2.0+ (wp-admin/includes/image.php:71-:75) .thumbnail file extension
                        $extension = '.thumbnail';
                        $tn_url = yd_check_thumbpath($tn_url, $extension);
                        //WP2.5+
                        $extension = "-" . get_option('thumbnail_size_w') . 'x' . get_option('thumbnail_size_h');
                        $tn_url = yd_check_thumbpath($tn_url, $extension);
                    }
                    if (!$tn_url) {
                        $tn_url = $default_image;
                    }
                }
                // if( $display_thumb )
                if ($display_ul) {
                    $html .= '<li>';
                }
                $html .= '<h4>';
                $html .= $link;
                if ($display_thumb) {
                    $html .= '<img src="' . $tn_url . '" style="' . $image_style . '" alt="' . get_the_title() . '" />';
                }
                //$html .= '</a>';
                if ($use_wp_excerpt && function_exists('get_the_excerpt') && get_the_excerpt()) {
                    $cont = get_the_excerpt();
                } else {
                    $cont = get_the_content('', '');
                }
                if ($strip_sqbt) {
                    $cont = preg_replace("/\\[[^\\]]+\\]/", '', $cont);
                }
                if ($strip_clbt) {
                    $cont = preg_replace("/{[^}]+}/", '', $cont);
                }
                if ($keep_html) {
                    $cont = preg_replace("/<img[^>]+>/i", '', $cont);
                    // get rid of images in excerpt
                    if ($abstract_cutlength === 0 || $abstract_cutlength === '0') {
                        $summary = $cont;
                    } else {
                        $summary = yd_cake_truncate($cont, $abstract_cutlength, '', false, true);
                    }
                } else {
                    if ($abstract_cutlength === 0 || $abstract_cutlength === '0') {
                        $summary = strip_tags($cont);
                    } else {
                        $summary = yd_clean_cut($cont, $abstract_cutlength);
                    }
                }
                if ($display_date) {
                    if ($date_type != 'post_date') {
                        $date = get_post_meta(get_the_id(), $date_type, true);
                    } else {
                        $date = get_the_time($date_format);
                    }
                    $date .= __(':', 'yd-recent-posts-widget') . ' ';
                } else {
                    $date = '';
                }
                if ($display_post_title) {
                    $post_title = get_the_title();
                } else {
                    $post_title = '';
                }
                //$html .= '<a href="' . get_permalink() . '" rel="bookmark" title="' . get_the_title() . '">';
                if ($title_cutlength === 0 || $title_cutlength === '0') {
                    $html .= $date . strip_tags($post_title);
                } else {
                    $html .= yd_clean_cut($date . $post_title, $title_cutlength);
                }
                $html .= '</a></h4>';
                if ($display_excerpt) {
                    $html .= '<div class="yd_rp_excerpt">' . $summary . $link . $ellipsis_string . '</a></div>';
                }
                if ($display_ul) {
                    $html .= '</li>';
                } else {
                    $html .= '<br clear="all" />';
                }
            }
            if ($display_ul) {
                $html .= '</ul>';
            }
        } else {
            //echo 'debug: no posts found for: ' . $wp_query_string . '<br/>';
        }
        $html .= '<a class="rpw_bottom_link" href="' . $bottom_link . '">' . $bottom_text . '</a>';
        $html .= '</div>' . $after_widget;
        update_yd_widget_cache('widget_yd_rp_' . $cache_key, $html);
    } else {
        //echo "debug: FROM CACHE<br/>";
        $html = get_yd_widget_cache('widget_yd_rp_' . $cache_key);
    }
    //if( $user_level > 0 ) $html .= ( get_num_queries() - $current_querycount ) . '&nbsp;queries.<br />';
    if ($echo) {
        echo $html;
    } else {
        return $html;
    }
}
/** Widget function: recent posts **/
function widget_yd_rp($args, $cache_name = NULL, $spec_query = NULL)
{
    if (isset($args) && $args === FALSE) {
        $echo = FALSE;
    } else {
        if (is_array($args)) {
            extract($args);
        }
        $echo = TRUE;
    }
    $default_cutlength = 128;
    global $wpdb;
    global $user_level;
    $plugin_dir = 'yd-recent-posts-widget';
    $options = get_option('widget_yd_rp');
    $current_querycount = get_num_queries();
    $html = '';
    $i = 1;
    if (is_admin()) {
        return;
    }
    if ($spec_query) {
        $my_wp_query = new WP_Query($spec_query);
    } else {
        if (is_home()) {
            //echo "HOME<br/>";
            $title = $options[$i]["home_title"];
            if ($options[$i]["home_tag"]) {
                $my_wp_query = new WP_Query("post_type=post&showposts=" . $options[$i]["home_showposts"] . "&offset=0&tag=" . $options[$i]["home_tag"]);
            } else {
                $nb_to_skip = get_option('posts_per_page');
                $my_wp_query = new WP_Query("post_type=post&showposts=" . $options[$i]["home_showposts"] . "&offset=" . $nb_to_skip);
            }
            if ($options[$i]["home_datemeta"]) {
                $date_type = $options[$i]["home_datemeta"];
            } else {
                $date_type = 'post_date';
            }
            $bottom_text = $options[$i]["home_bottomtext"];
            $bottom_link = $options[$i]["home_bottomlink"];
            $list_type = 'home';
        } else {
            //echo "PAGE<br/>";
            $title = $options[$i]["opage_title"];
            $my_wp_query = new WP_Query("post_type=post&showposts=" . $options[$i]["opage_showposts"] . "&offset=0&tag=" . $options[$i]["opage_tag"]);
            $date_type = 'post_date';
            $bottom_text = $options[$i]["opage_bottomtext"];
            $bottom_link = $options[$i]["opage_bottomlink"];
            $list_type = 'page';
        }
    }
    //specific overloaded usage within templates... (new in 0.7)
    if ($cache_name) {
        $list_type = $cache_name;
        $title = '';
        $date_type = 'post_date';
        $bottom_text = '';
        $bottom_link = '';
    }
    //
    $title_cutlength = $options[$i]["title_cutlength"] ? $options[$i]["title_cutlength"] : $default_cutlength;
    $abstract_cutlength = $options[$i]["abstract_cutlength"] ? $options[$i]["abstract_cutlength"] : $default_cutlength;
    $image_style = $options[$i]["image_style"];
    $default_image = $options[$i]["default_image"];
    $load_css = $options[$i]["load_css"];
    if (!check_yd_widget_cache('widget_yd_rp_' . $list_type)) {
        //query_posts( $my_wp_query );
        $html .= $before_widget;
        if ($load_css) {
            $html .= '<link type="text/css" rel="stylesheet" href="' . get_bloginfo('wpurl') . '/wp-content/plugins/' . $plugin_dir . '/css/yd_rp.css" />';
        }
        if ($title) {
            //$html .= $before_title . $title . $after_title;
            $html .= '<h2>' . $title . '</h2>';
        }
        $html .= '<div class="yd_rp_widget">';
        if ($my_wp_query->have_posts()) {
            $post_cnt = 0;
            if ($options[0]["display_ul"]) {
                $html .= '<ul>';
            }
            while ($my_wp_query->have_posts() && $post_cnt < 3) {
                $post_cnt++;
                $my_wp_query->the_post();
                /** new in 0.7: make sure not to display private posts **/
                if (get_post_status() != 'publish') {
                    continue;
                }
                $post = get_post(get_the_id());
                if ($post->post_password != '') {
                    continue;
                }
                // -- thumbnails ! --
                $link = '<a href="' . get_permalink() . '" rel="bookmark" title="' . __('Permanent link to:', 'yd-recent-posts-widget') . ' ' . get_the_title('', '', FALSE) . '" class="latest_post_link">';
                //WP2.7 (?)
                $values = get_post_custom_values("thumb");
                $tn_url = $values[0];
                //Get first attachment
                if (!$tn_url) {
                    $tn_url = $wpdb->get_var("SELECT guid FROM " . $wpdb->posts . " WHERE post_type='attachment' and post_mime_type like 'image/%' and post_parent = " . get_the_id() . " and guid != '' LIMIT 1");
                }
                //Try to find first image in html
                if (!$tn_url) {
                    preg_match('/<img[^>]+src=[\'"]([^\'"]+)[\'"]/', get_the_content(), $matches);
                    $tn_url = $matches[1];
                }
                //WP2.0+ (wp-admin/includes/image.php:71-:75) .thumbnail file extension
                $extension = '.thumbnail';
                $tn_url = yd_check_thumbpath($tn_url, $extension);
                //WP2.5+
                $extension = "-" . get_option('thumbnail_size_w') . 'x' . get_option('thumbnail_size_h');
                $tn_url = yd_check_thumbpath($tn_url, $extension);
                if (!$tn_url) {
                    $tn_url = $default_image;
                }
                if ($options[0]["display_ul"]) {
                    $html .= '<li>';
                }
                $html .= '<p>';
                $html .= '<img src="' . $tn_url . '" style="' . $image_style . '" alt="' . get_the_title() . '" /><span class="latest_post_title">' . $link;
                //$html .= '</a>';
                $cont = get_the_content();
                if ($options[0]['strip_sqbt']) {
                    $cont = preg_replace("/\\[[^\\]]+\\]/", '', $cont);
                }
                if ($options[0]['strip_clbt']) {
                    $cont = preg_replace("/{[^}]+}/", '', $cont);
                }
                if ($options[0]['keep_html']) {
                    $cont = preg_replace("/<img[^>]+>/i", '', $cont);
                    // get rid of images in excerpt
                    $summary = yd_cake_truncate($cont, $abstract_cutlength, '', false, true);
                } else {
                    $summary = yd_clean_cut($cont, $abstract_cutlength);
                }
                if ($options[$i]["display_date"]) {
                    if ($date_type != 'post_date') {
                        $date = get_post_meta(get_the_id(), $date_type, true);
                    } else {
                        $date = get_the_time($options[$i]["date_format"]);
                    }
                    $date .= __('', 'yd-recent-posts-widget') . ' ';
                } else {
                    $date = '';
                }
                //$html .= '<a href="' . get_permalink() . '" rel="bookmark" title="' . get_the_title() . '">';
                //$html .= yd_clean_cut( ( $date . get_the_title() ), $title_cutlength );
                $html .= yd_clean_cut(get_the_title(), $title_cutlength);
                $html .= '</a><br />' . $date . '</span><div class="clear"></div></p>';
                //$html .= '<div class="yd_rp_excerpt">' . $summary . $link . '...&nbsp;&raquo;</a></div>';
                if ($options[0]["display_ul"]) {
                    $html .= '</li>';
                } else {
                    $html .= '<br clear="all" />';
                }
            }
            if ($options[0]["display_ul"]) {
                $html .= '</ul>';
            }
        }
        $html .= '<a href="' . $bottom_link . '">' . $bottom_text . '</a>';
        $html .= '</div>' . $after_widget;
        update_yd_widget_cache('widget_yd_rp_' . $list_type, $html);
    } else {
        //echo "FROM CACHE<br/>";
        $html = get_yd_widget_cache('widget_yd_rp_' . $list_type);
    }
    //if( $user_level > 0 ) $html .= ( get_num_queries() - $current_querycount ) . '&nbsp;queries.<br />';
    if ($echo) {
        echo $html;
    } else {
        return $html;
    }
}