View difference between Paste ID: ZhCja8Ga and
SHOW: | | - or go back to the newest paste.
1-
1+
<?php
2
/*
3
Plugin Name: Wordpress Popular Posts
4
Plugin URI: http://wordpress.org/extend/plugins/wordpress-popular-posts
5
Description: Showcases your most popular posts to your visitors on your blog's sidebar. Use Wordpress Popular Posts as a widget or place it anywhere on your theme using  <strong>&lt;?php wpp_get_mostpopular(); ?&gt;</strong>
6
Version: 2.1.4
7
Author: H&eacute;ctor Cabrera
8
Author URI: http://wordpress.org/extend/plugins/wordpress-popular-posts
9
License: GPL2
10
*/
11
12
function wpp_count_js()
13
{
14
	if (!is_admin())
15
	{ ?>
16
		<script type="text/javascript">
17
			//<![CDATA[
18
				var $j = jQuery.noConflict();
19
				$j(window).load(function(){			
20
					
21
					$j('ul.wpp').each(function() {
22
						var count = 1;
23
						$j('li.group', this).each(function(count) {
24
							$j('.number', this).text(count);
25
							count++;
26
						  }
27
						);
28
					});
29
				});	
30
			//]]>  
31
		</script>
32
	<?php
33
	}
34
}
35
add_action('wp_head', 'wpp_count_js');
36
37
38
if (basename($_SERVER['SCRIPT_NAME']) == basename(__FILE__)) exit('Please do not load this page directly');
39
40
/**
41
 * Load Wordpress Popular Posts to widgets_init.
42
 * @since 2.0
43
 */
44
add_action('widgets_init', 'load_wpp');
45
46
function load_wpp() {
47
	register_widget('WordpressPopularPosts');
48
}
49
50
/**
51
 * Wordpress Popular Posts class.
52
 */
53
54
if ( !class_exists('WordpressPopularPosts') ) {
55
	class WordpressPopularPosts extends WP_Widget {
56
		// plugin global variables
57
		var $version = "2.1.4";
58
		var $qTrans = false;
59
		var $postRating = false;
60
		var $thumb = false;		
61
		var $pluginDir = "";
62
		var $charset = "UTF-8";
63
		var $magicquotes = false;
64
		
65
		// constructor
66
		function WordpressPopularPosts() {
67
			global $wp_version;
68
				
69
			// widget settings
70
			$widget_ops = array( 'classname' => 'popular-posts', 'description' => 'The most Popular Posts on your blog.' );
71
	
72
			// widget control settings
73
			$control_ops = array( 'width' => 250, 'height' => 350, 'id_base' => 'wpp' );
74
	
75
			// create the widget
76
			$this->WP_Widget( 'wpp', 'Wordpress Popular Posts', $widget_ops, $control_ops );
77
			
78
			// set plugin path
79
			if (empty($this->pluginDir)) $this->pluginDir = WP_PLUGIN_URL . '/wordpress-popular-posts';
80
			
81
			// set charset
82
			$this->charset = get_bloginfo('charset');
83
			
84
			// detect PHP magic quotes
85
			$this->magicquotes = get_magic_quotes_gpc();
86
			
87
			// add ajax update to wp_ajax_ hook
88
			add_action('wp_ajax_nopriv_wpp_update', array(&$this, 'wpp_ajax_update'));
89
			add_action('wp_head', array(&$this, 'wpp_print_ajax'));
90
			
91
			// add ajax table truncation to wp_ajax_ hook
92
			add_action('wp_ajax_wpp_clear_cache', array(&$this, 'wpp_clear_data'));
93
			add_action('wp_ajax_wpp_clear_all', array(&$this, 'wpp_clear_data'));
94
			
95
			// print stylesheet
96
			add_action('wp_head', array(&$this, 'wpp_print_stylesheet'));
97
			
98
			// activate textdomain for translations
99
			add_action('init', array(&$this, 'wpp_textdomain'));
100
			
101
			// activate maintenance page
102
			add_action('admin_menu', array(&$this, 'add_wpp_maintenance_page'));
103
							
104
			// database creation
105
			register_activation_hook(__FILE__, $this->wpp_install());
106
			
107
			// cache maintenance schedule
108
			register_deactivation_hook(__FILE__, array(&$this, 'wpp_deactivation'));			
109
			add_action('wpp_cache_event', array(&$this, 'wpp_cache_maintenance'));
110
			if (!wp_next_scheduled('wpp_cache_event')) {
111
				$tomorrow = time() + 86400;
112
				$midnight  = mktime(0, 0, 0, 
113
					date("m", $tomorrow), 
114
					date("d", $tomorrow), 
115
					date("Y", $tomorrow));
116
				wp_schedule_event( $midnight, 'daily', 'wpp_cache_event' );
117
			}
118
			
119
			// Wordpress version check
120
			if (version_compare($wp_version, '2.8.0', '<')) add_action('admin_notices', array(&$this, 'wpp_update_warning'));
121
			
122
			// qTrans plugin support
123
			if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) $this->qTrans = true;
124
			
125
			// WP-Post Ratings plugin support
126
			if (function_exists('the_ratings_results')) $this->postRating = true;
127
			
128
			// Can we create thumbnails?
129
			if (extension_loaded('gd') && function_exists('gd_info') && version_compare(phpversion(), '4.3.0', '>=')) $this->thumb = true;
130
			
131
			// shortcode
132
			if( function_exists('add_shortcode') ){
133
				add_shortcode('wpp', array(&$this, 'wpp_shortcode'));
134
				add_shortcode('WPP', array(&$this, 'wpp_shortcode'));
135
			}
136
			
137
			// set version
138
			$wpp_ver = get_option('wpp_ver');
139
			if (!$wp_ver) {
140
				add_option('wpp_ver', $this->version);
141
			} else if (version_compare($wpp_ver, $this->version, '<')) {
142
				update_option('wpp_ver', $this->version);
143
			}
144
			
145
			// add stats page
146
			add_action('admin_menu', array(&$this, 'wpp_stats'));
147
		}
148
149
		// builds Wordpress Popular Posts' widgets
150
		function widget($args, $instance) {
151
			extract($args);
152
			echo "<!-- Wordpress Popular Posts Plugin v". $this->version ." [W] [".$instance['range']."]". (($instance['markup']['custom_html']) ? ' [custom]' : ' [regular]') ." -->"."\n";
153
			echo $before_widget . "\n";
154
			
155
			// has user set a title?
156
			if ($instance['title'] != '') {
157
				if ($instance['markup']['custom_html'] && $instance['markup']['title-start'] != "" && $instance['markup']['title-end'] != "" ) {
158
					echo htmlspecialchars_decode($instance['markup']['title-start'], ENT_QUOTES) . $instance['title'], ENT_QUOTES . htmlspecialchars_decode($instance['markup']['title-end'], ENT_QUOTES);
159
				} else {
160
					echo $before_title . $instance['title'] . $after_title;
161
				}
162
			}
163
			
164
			echo $this->get_popular_posts($instance, false);			
165
			echo $after_widget . "\n";
166
			echo "<!-- End Wordpress Popular Posts Plugin v". $this->version ." -->"."\n";
167
		}
168
169
		// updates each widget instance when user clicks the "save" button
170
		function update($new_instance, $old_instance) {
171
			
172
			$instance = $old_instance;
173
			
174
			//$instance['title'] = htmlspecialchars( stripslashes(strip_tags( $new_instance['title'] )), ENT_QUOTES, 'UTF-8', FALSE );
175
			$instance['title'] = ($this->magicquotes) ? htmlspecialchars( stripslashes(strip_tags( $new_instance['title'] )), ENT_QUOTES ) : htmlspecialchars( strip_tags( $new_instance['title'] ), ENT_QUOTES );
176
			$instance['limit'] = is_numeric($new_instance['limit']) ? $new_instance['limit'] : 10;
177
			$instance['range'] = $new_instance['range'];
178
			$instance['order_by'] = $new_instance['order_by'];
179
			$instance['pages'] = $new_instance['pages'];
180
			$instance['shorten_title']['active'] = $new_instance['shorten_title-active'];
181
			$instance['shorten_title']['length'] = is_numeric($new_instance['shorten_title-length']) ? $new_instance['shorten_title-length'] : 25;
182
			$instance['post-excerpt']['active'] = $new_instance['post-excerpt-active'];
183
			$instance['post-excerpt']['length'] = is_numeric($new_instance['post-excerpt-length']) ? $new_instance['post-excerpt-length'] : 55;
184
			$instance['post-excerpt']['keep_format'] = $new_instance['post-excerpt-format'];
185
			$instance['exclude-cats']['active'] = $new_instance['exclude-cats'];
186
			$instance['exclude-cats']['cats'] = empty($new_instance['excluded']) ? '' : (ctype_digit(str_replace(",", "", $new_instance['excluded']))) ? $new_instance['excluded'] : '';
187
			if ($this->thumb) { // can create thumbnails
188
				$instance['thumbnail']['active'] = $new_instance['thumbnail-active'];
189
				$instance['thumbnail']['thumb_selection'] = empty($new_instance['thumb_selection']) ? "wppgenerated" : $new_instance['thumb_selection'];
190
				$instance['thumbnail']['width'] = is_numeric($new_instance['thumbnail-width']) ? $new_instance['thumbnail-width'] : 15;
191
				$instance['thumbnail']['height'] = is_numeric($new_instance['thumbnail-height']) ? $new_instance['thumbnail-height'] : 15;
192
			} else { // cannot create thumbnails
193
				$instance['thumbnail']['active'] = false;
194
				$instance['thumbnail']['thumb_selection'] = "wppgenerated";
195
				$instance['thumbnail']['width'] = 15;
196
				$instance['thumbnail']['height'] = 15;
197
			}
198
			
199
			$instance['rating'] = $new_instance['rating'];
200
			$instance['stats_tag']['comment_count'] = $new_instance['comment_count'];
201
			$instance['stats_tag']['views'] = $new_instance['views'];
202
			$instance['stats_tag']['author'] = $new_instance['author'];
203
			$instance['stats_tag']['date']['active'] = $new_instance['date'];
204
			$instance['stats_tag']['date']['format'] = empty($new_instance['date_format']) ? 'F j, Y' : $new_instance['date_format'];
205
			$instance['markup']['custom_html'] = $new_instance['custom_html'];
206
			$instance['markup']['wpp-start'] = empty($new_instance['wpp-start']) ? '&lt;ul&gt;' : htmlspecialchars( $new_instance['wpp-start'], ENT_QUOTES );
207
			$instance['markup']['wpp-end'] = empty($new_instance['wpp-end']) ? '&lt;/ul&gt;' : htmlspecialchars( $new_instance['wpp-end'], ENT_QUOTES );
208
			$instance['markup']['post-start'] = empty ($new_instance['post-start']) ? '&lt;li&gt;' : htmlspecialchars( $new_instance['post-start'], ENT_QUOTES );
209
			$instance['markup']['post-end'] = empty ($new_instance['post-end']) ? '&lt;/li&gt;' : htmlspecialchars( $new_instance['post-end'], ENT_QUOTES );
210
			$instance['markup']['title-start'] = empty($new_instance['title-start']) ? '' : htmlspecialchars( $new_instance['title-start'], ENT_QUOTES );
211
			$instance['markup']['title-end'] = empty($new_instance['title-end']) ? '' : htmlspecialchars( $new_instance['title-end'], ENT_QUOTES );
212
			$instance['markup']['pattern']['active'] = $new_instance['pattern_active'];
213
			$instance['markup']['pattern']['form'] = empty($new_instance['pattern_form']) ? '{image} {title}: {summary} {stats}' : strip_tags( $new_instance['pattern_form'] );
214
	
215
			return $instance;
216
		}
217
218
		// widget's form
219
		function form($instance) {
220
			// set default values			
221
			$defaults = array(
222
				'title' => __('Popular Posts', 'wordpress-popular-posts'),
223
				'limit' => 10,
224
				'range' => 'daily',
225
				'order_by' => 'comments',
226
				'pages' => true,
227
				'shorten_title' => array(
228
					'active' => false,
229
					'length' => 25,
230
					'keep_format' => false
231
				),
232
				'post-excerpt' => array(
233
					'active' => false,
234
					'length' => 55
235
				),
236
				'exclude-cats' => array(
237
					'active' => false,
238
					'cats' => ''
239
				),
240
				'thumbnail' => array(
241
					'active' => false,
242
					'width' => 15,
243
					'height' => 15
244
				),
245
				'rating' => false,
246
				'stats_tag' => array(
247
					'comment_count' => true,
248
					'views' => false,
249
					'author' => false,
250
					'date' => array(
251
						'active' => false,
252
						'format' => 'F j, Y'
253
					)
254
				),
255
				'markup' => array(
256
					'custom_html' => false,
257
					'wpp-start' => '&lt;ul&gt;',
258
					'wpp-end' => '&lt;/ul&gt;',
259
					'post-start' => '&lt;li&gt;',
260
					'post-end' => '&lt;/li&gt;',
261
					'title-start' => '&lt;h2&gt;',
262
					'title-end' => '&lt;/h2&gt;',
263
					'pattern' => array(
264
						'active' => false,
265
						'form' => '{image} {title}: {summary} {stats}'
266
					)
267
				)
268
			);
269
			
270
			// update instance's default options
271
			$instance = wp_parse_args( (array) $instance, $defaults );
272
			
273
			// form
274
			?>            
275
            <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'wordpress-popular-posts'); ?></label>
276
            <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" class="widefat" /></p>
277
            <p><label for="<?php echo $this->get_field_id( 'limit' ); ?>"><?php _e('Show up to:', 'wordpress-popular-posts'); ?></label><br />
278
            <input id="<?php echo $this->get_field_id( 'limit' ); ?>" name="<?php echo $this->get_field_name( 'limit' ); ?>" value="<?php echo $instance['limit']; ?>"  class="widefat" style="width:50px!important" /> <?php _e('posts', 'wordpress-popular-posts'); ?></p>
279
            <p><label for="<?php echo $this->get_field_id( 'range' ); ?>"><?php _e('Time Range:', 'wordpress-popular-posts'); ?></label>
280
            <select id="<?php echo $this->get_field_id( 'range' ); ?>" name="<?php echo $this->get_field_name( 'range' ); ?>" class="widefat">
281
            	<option value="daily" <?php if ( 'daily' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Today', 'wordpress-popular-posts'); ?></option>
282
                <option value="weekly" <?php if ( 'weekly' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Last 7 days', 'wordpress-popular-posts'); ?></option>
283
                <option value="monthly" <?php if ( 'monthly' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('Last 30 days', 'wordpress-popular-posts'); ?></option>
284
                <option value="all" <?php if ( 'all' == $instance['range'] ) echo 'selected="selected"'; ?>><?php _e('All-time', 'wordpress-popular-posts'); ?></option>
285
            </select>
286
            </p>
287
            <p><label for="<?php echo $this->get_field_id( 'order_by' ); ?>"><?php _e('Sort posts by:', 'wordpress-popular-posts'); ?></label>
288
            <select id="<?php echo $this->get_field_id( 'order_by' ); ?>" name="<?php echo $this->get_field_name( 'order_by' ); ?>" class="widefat">
289
            	<option value="comments" <?php if ( 'comments' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Comments', 'wordpress-popular-posts'); ?></option>
290
                <option value="views" <?php if ( 'views' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Total views', 'wordpress-popular-posts'); ?></option>
291
                <option value="avg" <?php if ( 'avg' == $instance['order_by'] ) echo 'selected="selected"'; ?>><?php _e('Avg. daily views', 'wordpress-popular-posts'); ?></option>
292
            </select>
293
            </p>
294
            <input type="checkbox" class="checkbox" <?php echo ($instance['pages']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'pages' ); ?>" name="<?php echo $this->get_field_name( 'pages' ); ?>" /> <label for="<?php echo $this->get_field_id( 'pages' ); ?>"><?php _e('Include pages', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
295
            <?php if ($this->postRating) : ?>
296
            <input type="checkbox" class="checkbox" <?php echo ($instance['rating']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'rating' ); ?>" name="<?php echo $this->get_field_name( 'rating' ); ?>" /> <label for="<?php echo $this->get_field_id( 'rating' ); ?>"><?php _e('Display post rating', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
297
            <?php endif; ?>
298
            <input type="checkbox" class="checkbox" <?php echo ($instance['shorten_title']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'shorten_title-active' ); ?>" name="<?php echo $this->get_field_name( 'shorten_title-active' ); ?>" /> <label for="<?php echo $this->get_field_id( 'shorten_title-active' ); ?>"><?php _e('Shorten title output', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
299
            <?php if ($instance['shorten_title']['active']) : ?>
300
            <label for="<?php echo $this->get_field_id( 'shorten_title-length' ); ?>"><?php _e('Shorten title to', 'wordpress-popular-posts'); ?> <input id="<?php echo $this->get_field_id( 'shorten_title-length' ); ?>" name="<?php echo $this->get_field_name( 'shorten_title-length' ); ?>" value="<?php echo $instance['shorten_title']['length']; ?>" class="widefat" style="width:50px!important" /> <?php _e('characters', 'wordpress-popular-posts'); ?></label><br /><br />
301
			<?php endif; ?>
302
            <input type="checkbox" class="checkbox" <?php echo ($instance['post-excerpt']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'post-excerpt-active' ); ?>" name="<?php echo $this->get_field_name( 'post-excerpt-active' ); ?>" /> <label for="<?php echo $this->get_field_id( 'post-excerpt-active' ); ?>"><?php _e('Display post excerpt', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
303
            <?php if ($instance['post-excerpt']['active']) : ?>
304
            <fieldset class="widefat">
305
                <legend><?php _e('Excerpt Properties', 'wordpress-popular-posts'); ?></legend>
306
            	&nbsp;&nbsp;<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'post-excerpt-format' ); ?>" name="<?php echo $this->get_field_name( 'post-excerpt-format' ); ?>" <?php echo ($instance['post-excerpt']['keep_format']) ? 'checked="checked"' : ''; ?> /> <label for="<?php echo $this->get_field_id( 'post-excerpt-format' ); ?>"><?php _e('Keep text format and links', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
307
            	&nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'post-excerpt-length' ); ?>"><?php _e('Excerpt length:', 'wordpress-popular-posts'); ?> <input id="<?php echo $this->get_field_id( 'post-excerpt-length' ); ?>" name="<?php echo $this->get_field_name( 'post-excerpt-length' ); ?>" value="<?php echo $instance['post-excerpt']['length']; ?>" class="widefat" style="width:30px!important" /> <?php _e('characters', 'wordpress-popular-posts'); ?></label>
308
			</fieldset>
309
			<br />
310
            <?php endif; ?>
311
            <input type="checkbox" class="checkbox" <?php echo ($instance['exclude-cats']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'exclude-cats' ); ?>" name="<?php echo $this->get_field_name( 'exclude-cats' ); ?>" /> <label for="<?php echo $this->get_field_id( 'exclude-cats' ); ?>"><?php _e('Exclude categories', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
312
            <?php if ($instance['exclude-cats']['active']) : ?>
313
            <fieldset class="widefat">
314
                <legend><?php _e('Categories to exclude', 'wordpress-popular-posts'); ?></legend>
315
                &nbsp;&nbsp;<label for="<?php echo $this->get_field_id( 'excluded' ); ?>"><?php _e('ID(s) (comma separated, no spaces):', 'wordpress-popular-posts'); ?></label><br />&nbsp;&nbsp;<input id="<?php echo $this->get_field_id( 'excluded' ); ?>" name="<?php echo $this->get_field_name( 'excluded' ); ?>" value="<?php echo $instance['exclude-cats']['cats']; ?>" class="widefat" style="width:150px" /><br /><br />
316
            </fieldset>            
317
            <?php endif; ?>
318
            <br />
319
			
320
			<fieldset style="width:214px; padding:5px;"  class="widefat">
321
                <legend><?php _e('Thumbnail settings', 'wordpress-popular-posts'); ?></legend>
322
				<input type="checkbox" class="checkbox" <?php echo ($instance['thumbnail']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'thumbnail-active' ); ?>" name="<?php echo $this->get_field_name( 'thumbnail-active' ); ?>" /> <label for="<?php echo $this->get_field_id( 'thumbnail-active' ); ?>"><?php _e('Display post thumbnail', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
323
				<?php if($instance['thumbnail']['active']) : ?>
324
				
325
				<input type="radio" name="<?php echo $this->get_field_name( 'thumb_selection' ); ?>" value="wppgenerated" <?php if ( 'wppgenerated' == $instance['thumbnail']['thumb_selection'] ) echo 'checked="checked"'; ?>> <label for="<?php echo $this->get_field_id( 'thumb_selection' ); ?>"><?php _e('Generate all thumbnails for me', 'wordpress-popular-posts'); ?></label><br />
326
				<input type="radio" name="<?php echo $this->get_field_name( 'thumb_selection' ); ?>" value="usergenerated" <?php if ( 'usergenerated' == $instance['thumbnail']['thumb_selection']) { echo 'checked="checked"'; } if (!function_exists('get_the_post_thumbnail')) { echo 'disabled="disabled"'; } ?>>  <label for="<?php echo $this->get_field_id( 'thumb_selection' ); ?>"><?php _e('Use thumbnails selected by me', 'wordpress-popular-posts'); ?></label>				
327
				
328
				<label for="<?php echo $this->get_field_id( 'thumbnail-width' ); ?>"><?php _e('Width:', 'wordpress-popular-posts'); ?></label> 
329
				<input id="<?php echo $this->get_field_id( 'thumbnail-width' ); ?>" name="<?php echo $this->get_field_name( 'thumbnail-width' ); ?>" value="<?php echo $instance['thumbnail']['width']; ?>"  class="widefat" style="width:30px!important" <?php echo ($this->thumb) ? '' : 'disabled="disabled"' ?> /> <?php _e('px', 'wordpress-popular-posts'); ?> <br />
330
				<label for="<?php echo $this->get_field_id( 'thumbnail-height' ); ?>"><?php _e('Height:', 'wordpress-popular-posts'); ?></label> 
331
				<input id="<?php echo $this->get_field_id( 'thumbnail-height' ); ?>" name="<?php echo $this->get_field_name( 'thumbnail-height' ); ?>" value="<?php echo $instance['thumbnail']['height']; ?>"  class="widefat" style="width:30px!important" <?php echo ($this->thumb) ? '' : 'disabled="disabled"' ?> /> <?php _e('px', 'wordpress-popular-posts'); ?><br />
332
				
333
				<?php endif; ?>
334
			</fieldset>
335
			
336
            <br />
337
            <fieldset style="width:214px; padding:5px;"  class="widefat">
338
                <legend><?php _e('Stats Tag settings', 'wordpress-popular-posts'); ?></legend>
339
                <input type="checkbox" class="checkbox" <?php echo ($instance['stats_tag']['comment_count']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'comment_count' ); ?>" name="<?php echo $this->get_field_name( 'comment_count' ); ?>" /> <label for="<?php echo $this->get_field_id( 'comment_count' ); ?>"><?php _e('Display comment count', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />                
340
                <input type="checkbox" class="checkbox" <?php echo ($instance['stats_tag']['views']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'views' ); ?>" name="<?php echo $this->get_field_name( 'views' ); ?>" /> <label for="<?php echo $this->get_field_id( 'views' ); ?>"><?php _e('Display views', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />            
341
                <input type="checkbox" class="checkbox" <?php echo ($instance['stats_tag']['author']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'author' ); ?>" name="<?php echo $this->get_field_name( 'author' ); ?>" /> <label for="<?php echo $this->get_field_id( 'author' ); ?>"><?php _e('Display author', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />            
342
                <input type="checkbox" class="checkbox" <?php echo ($instance['stats_tag']['date']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'date' ); ?>" name="<?php echo $this->get_field_name( 'date' ); ?>" /> <label for="<?php echo $this->get_field_id( 'date' ); ?>"><?php _e('Display date', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small>
343
				<?php if ($instance['stats_tag']['date']['active']) : ?>                	
344
                	<fieldset class="widefat">
345
                    	<legend><?php _e('Date Format', 'wordpress-popular-posts'); ?></legend>
346
                        <label title='F j, Y'><input type='radio' name='<?php echo $this->get_field_name( 'date_format' ); ?>' value='F j, Y' <?php echo ($instance['stats_tag']['date']['format'] == 'F j, Y') ? 'checked="checked"' : ''; ?> /><?php echo date('F j, Y', time()); ?></label><br />
347
                        <label title='Y/m/d'><input type='radio' name='<?php echo $this->get_field_name( 'date_format' ); ?>' value='Y/m/d' <?php echo ($instance['stats_tag']['date']['format'] == 'Y/m/d') ? 'checked="checked"' : ''; ?> /><?php echo date('Y/m/d', time()); ?></label><br />
348
                        <label title='m/d/Y'><input type='radio' name='<?php echo $this->get_field_name( 'date_format' ); ?>' value='m/d/Y' <?php echo ($instance['stats_tag']['date']['format'] == 'm/d/Y') ? 'checked="checked"' : ''; ?> /><?php echo date('m/d/Y', time()); ?></label><br />
349
                        <label title='d/m/Y'><input type='radio' name='<?php echo $this->get_field_name( 'date_format' ); ?>' value='d/m/Y' <?php echo ($instance['stats_tag']['date']['format'] == 'd/m/Y') ? 'checked="checked"' : ''; ?> /><?php echo date('d/m/Y', time()); ?></label><br />
350
                    </fieldset>
351
                <?php endif; ?>
352
            </fieldset>
353
            <br />
354
			
355
            <fieldset style="width:214px; padding:5px;"  class="widefat">
356
                <legend><?php _e('HTML Markup settings', 'wordpress-popular-posts'); ?></legend>
357
                <input type="checkbox" class="checkbox" <?php echo ($instance['markup']['custom_html']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'custom_html' ); ?>" name="<?php echo $this->get_field_name( 'custom_html' ); ?>" /> <label for="<?php echo $this->get_field_id( 'custom_html' ); ?>"><?php _e('Use custom HTML Markup', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
358
                <?php if ($instance['markup']['custom_html']) : ?>
359
                <br />
360
                <p style="font-size:11px"><label for="<?php echo $this->get_field_id( 'title-start' ); ?>"><?php _e('Before / after title:', 'wordpress-popular-posts'); ?></label> <br />
361
                <input type="text" id="<?php echo $this->get_field_id( 'title-start' ); ?>" name="<?php echo $this->get_field_name( 'title-start' ); ?>" value="<?php echo $instance['markup']['title-start']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /> <input type="text" id="<?php echo $this->get_field_id( 'title-end' ); ?>" name="<?php echo $this->get_field_name( 'title-end' ); ?>" value="<?php echo $instance['markup']['title-end']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /></p>
362
                <p style="font-size:11px"><label for="<?php echo $this->get_field_id( 'wpp_start' ); ?>"><?php _e('Before / after Popular Posts:', 'wordpress-popular-posts'); ?></label> <br />
363
                <input type="text" id="<?php echo $this->get_field_id( 'wpp-start' ); ?>" name="<?php echo $this->get_field_name( 'wpp-start' ); ?>" value="<?php echo $instance['markup']['wpp-start']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /> <input type="text" id="<?php echo $this->get_field_id( 'wpp-end' ); ?>" name="<?php echo $this->get_field_name( 'wpp-end' ); ?>" value="<?php echo $instance['markup']['wpp-end']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /></p>
364
                <p style="font-size:11px"><label for="<?php echo $this->get_field_id( 'post-start' ); ?>"><?php _e('Before / after each post:', 'wordpress-popular-posts'); ?></label> <br />
365
                <input type="text" id="<?php echo $this->get_field_id( 'post-start' ); ?>" name="<?php echo $this->get_field_name( 'post-start' ); ?>" value="<?php echo $instance['markup']['post-start']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /> <input type="text" id="<?php echo $this->get_field_id( 'post-end' ); ?>" name="<?php echo $this->get_field_name( 'post-end' ); ?>" value="<?php echo $instance['markup']['post-end']; ?>" class="widefat" style="width:80px!important" <?php echo ($instance['markup']['custom_html']) ? '' : 'disabled="disabled"' ?> /></p>
366
                <hr />
367
                <?php endif; ?>
368
                <input type="checkbox" class="checkbox" <?php echo ($instance['markup']['pattern']['active']) ? 'checked="checked"' : ''; ?> id="<?php echo $this->get_field_id( 'pattern_active' ); ?>" name="<?php echo $this->get_field_name( 'pattern_active' ); ?>" /> <label for="<?php echo $this->get_field_id( 'pattern_active' ); ?>"><?php _e('Use content formatting tags', 'wordpress-popular-posts'); ?></label> <small>[<a href="<?php echo bloginfo('url'); ?>/wp-admin/options-general.php?page=wordpress-popular-posts/wordpress-popular-posts.php">?</a>]</small><br />
369
                <?php if ($instance['markup']['pattern']['active']) : ?>
370
                <br />
371
                <p style="font-size:11px"><label for="<?php echo $this->get_field_id( 'pattern_form' ); ?>"><?php _e('Content format:', 'wordpress-popular-posts'); ?></label>
372
                <input type="text" id="<?php echo $this->get_field_id( 'pattern_form' ); ?>" name="<?php echo $this->get_field_name( 'pattern_form' ); ?>" value="<?php echo $instance['markup']['pattern']['form']; ?>" style="width:204px" <?php echo ($instance['markup']['pattern']['active']) ? '' : 'disabled="disabled"' ?> /></p>
373
                <?php endif; ?>
374
            </fieldset>
375
            <?php // end form	
376
		}
377
		
378
		// updates popular posts data table
379
		function wpp_ajax_update() {		
380
			$nonce = $_POST['token'];
381
			
382
			// is this a valid request?
383
			if (! wp_verify_nonce($nonce, 'wpp-token') ) die("Oops!");
384
			
385
			if (is_numeric($_POST['id']) && (intval($_POST['id']) == floatval($_POST['id'])) && ($_POST['id'] != '')) {
386
				$id = $_POST['id'];
387
			} else {
388
				die("Invalid ID");
389
			}
390
			
391
			// if we got an ID, let's update the data table
392
						
393
			global $wpdb;
394
			
395
			$wpdb->show_errors();
396
			
397
			$table = $wpdb->prefix . 'popularpostsdata';
398
			
399
			// update popularpostsdata table
400
			$exists = $wpdb->get_results("SELECT postid FROM $table WHERE postid = '$id'");							
401
			if ($exists) {
402
				$result = $wpdb->query("UPDATE $table SET last_viewed = NOW(), pageviews = pageviews + 1 WHERE postid = '$id'");
403
			} else {				
404
				$result = $wpdb->query("INSERT INTO $table (postid, day, last_viewed) VALUES ('".$id."', NOW(), NOW())");
405
			}
406
			
407
			// update popularpostsdatacache table
408
			$isincache = $wpdb->get_results("SELECT id FROM ".$table."cache WHERE id = '".$id."' AND day = CURDATE()");			
409
			if ($isincache) {
410
				$result2 = $wpdb->query("UPDATE ".$table."cache SET pageviews = pageviews + 1 WHERE id = '".$id."' AND day = CURDATE()");
411
			} else {		
412
				$result2 = $wpdb->query("INSERT INTO ".$table."cache (id, day) VALUES ('".$id."', CURDATE())");
413
			}
414
			
415
			if (($result == 1) && ($result2 == 1)) {
416
				die("OK");
417
			} else {
418
				die($wpdb->print_error);
419
			}		
420
			
421
		}
422
		
423
		// clears Wordpress Popular Posts' data
424
		function wpp_clear_data() {
425
			$token = $_POST['token'];
426
			$clear = isset($_POST['clear']) ? $_POST['clear'] : '';
427
			$key = get_option("wpp_rand");
428
			
429
			if (current_user_can('manage_options') && ($token === $key) && !empty($clear)) {
430
				global $wpdb;
431
				// set table name
432
				$table = $wpdb->prefix . "popularpostsdata";
433
				$cache = $wpdb->prefix . "popularpostsdatacache";
434
				
435
				if ($clear == 'cache') {
436
					if ( $wpdb->get_var("SHOW TABLES LIKE '$cache'") == $cache ) {
437
						$wpdb->query("TRUNCATE TABLE $cache;");
438
						_e('Success! The cache table has been cleared!', 'wordpress-popular-posts');
439
					} else {
440
						_e('Error: cache table does not exist.', 'wordpress-popular-posts');
441
					}
442
				} else if ($clear == 'all') {
443
					if ( $wpdb->get_var("SHOW TABLES LIKE '$table'") == $table && $wpdb->get_var("SHOW TABLES LIKE '$cache'") == $cache ) {
444
						$wpdb->query("TRUNCATE TABLE $table;");
445
						$wpdb->query("TRUNCATE TABLE $cache;");
446
						_e('Success! All data have been cleared!', 'wordpress-popular-posts');
447
					} else {
448
						_e('Error: one or both data tables are missing.', 'wordpress-popular-posts');
449
					}
450
				} else {
451
					_e('Invalid action.', 'wordpress-popular-posts');
452
				}
453
			} else {
454
				_e('Sorry, you do not have enough permissions to do this. Please contact the site administrator for support.', 'wordpress-popular-posts');
455
			}
456
			
457
			die();
458
		}
459
		
460
		// database install
461
		function wpp_install() {
462
			global $wpdb;
463
			
464
			// set table name
465
			$table = $wpdb->prefix . "popularpostsdata";
466
			
467
			// does popularpostsdata table exists?
468
			if ( $wpdb->get_var("SHOW TABLES LIKE '$table'") != $table ) { // fresh setup
469
				// create tables popularpostsdata and popularpostsdatacache
470
				$sql = "CREATE TABLE " . $table . " ( UNIQUE KEY id (postid), postid int(10) NOT NULL, day datetime NOT NULL default '0000-00-00 00:00:00', last_viewed datetime NOT NULL default '0000-00-00 00:00:00', pageviews int(10) default 1 ); CREATE TABLE " . $table ."cache ( UNIQUE KEY id (id, day), id int(10) NOT NULL, day date NOT NULL, pageviews int(10) default 1 );";
471
				
472
				require_once(ABSPATH . 'wp-admin/includes/upgrade.php');				
473
				dbDelta($sql);				
474
			} else {
475
				$cache = $table . "cache";
476
				if ( $wpdb->get_var("SHOW TABLES LIKE '$cache'") != $cache ) {
477
					// someone is upgrading from version 1.5.x
478
					$sql = "CREATE TABLE " . $table ."cache ( UNIQUE KEY id (id, day), id int(10) NOT NULL, day date NOT NULL, pageviews int(10) default 1 );";
479
					
480
					require_once(ABSPATH . 'wp-admin/includes/upgrade.php');				
481
					dbDelta($sql);
482
				}
483
			}
484
		}
485
		
486
		// prints ajax script to theme's header
487
		function wpp_print_ajax() {		
488
			// let's add jQuery
489
			wp_print_scripts('jquery');
490
				
491
			// create security token
492
			$nonce = wp_create_nonce('wpp-token');
493
			
494
			// get current post's ID
495
			global $wp_query;
496
			wp_reset_query();
497
			
498
			// if we're on a page or post, load the script
499
			if ( (is_single() || is_page()) && !is_user_logged_in() ) {
500
				$id = $wp_query->post->ID;
501
			?>
502
<!-- Wordpress Popular Posts v<?php echo $this->version; ?> -->
503
<script type="text/javascript" charset="utf-8">
504
    /* <![CDATA[ */				
505
	jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', {action: 'wpp_update', token: '<?php echo $nonce; ?>', id: <?php echo $id; ?>});
506
    /* ]]> */
507
</script>
508
<!-- End Wordpress Popular Posts v<?php echo $this->version; ?> -->
509
            <?php
510
			}
511
		}		
512
		
513
		// prints popular posts
514
		function get_popular_posts($instance, $echo = true) {		
515
			
516
			global $wpdb;
517
			$table = $wpdb->prefix . "popularpostsdata";
518
						
519
			if ( $instance['pages'] ) {
520
				$nopages = '';
521
			} else {
522
				$nopages = "AND $wpdb->posts.post_type = 'post'";
523
			}
524
			
525
			switch( $instance['range'] ) {
526
				case 'all':
527
					$range = "post_date_gmt < '".gmdate("Y-m-d H:i:s")."'";
528
					break;
529
				case 'yesterday':
530
					$range = $table."cache.day >= '".gmdate("Y-m-d")."' - INTERVAL 1 DAY";
531
					break;
532
				case 'daily':
533
					$range = $table."cache.day = CURDATE()";
534
					break;
535
				case 'weekly':
536
					$range = $table."cache.day >= '".gmdate("Y-m-d")."' - INTERVAL 7 DAY";
537
					break;
538
				case 'monthly':
539
					$range = $table."cache.day >= '".gmdate("Y-m-d")."' - INTERVAL 30 DAY";
540
					break;
541
				default:
542
					$range = "post_date_gmt < '".gmdate("Y-m-d H:i:s")."'";
543
					break;
544
			}
545
			
546
			// sorting options
547
			switch( $instance['order_by'] ) {
548
				case 'comments':
549
					$sortby = 'comment_count';
550
					break;
551
				case 'views':
552
					$sortby = 'pageviews';
553
					break;
554
				case 'avg':
555
					$sortby = 'avg_views';
556
					break;
557
				default:
558
					$sortby = 'comment_count';
559
					break;
560
			}
561
			
562
			
563
			// dynamic query fields
564
			$fields = ', ';			
565
			if ( $instance['stats_tag']['views'] || ($sortby != 'comment_count') ) {
566
				if ( $instance['range'] == 'all') {
567
					$fields .= "$table.pageviews AS 'pageviews' ";
568
				} else {
569
					if ( $sortby == 'avg_views' ) {
570
						$fields .= "(SUM(".$table."cache.pageviews)/(IF ( DATEDIFF(CURDATE(), MIN(".$table."cache.day)) > 0, DATEDIFF(CURDATE(), MIN(".$table."cache.day)), 1) )) AS 'avg_views' ";						
571
					} else {
572
						$fields .= "(SUM(".$table."cache.pageviews)) AS 'pageviews' ";
573
					}
574
				}		
575
			}
576
			
577
			if ( $instance['stats_tag']['comment_count'] ) {
578
				if ( $fields != ', ' ) {
579
					$fields .= ", $wpdb->posts.comment_count AS 'comment_count' ";
580
				} else {
581
					$fields .= "$wpdb->posts.comment_count AS 'comment_count' ";
582
				}
583
			}
584
			
585
			if ( $instance['stats_tag']['author'] ) {
586
				if ( $fields != ', ' ) {
587
					$fields .= ", (SELECT $wpdb->users.display_name FROM $wpdb->users WHERE $wpdb->users.ID = $wpdb->posts.post_author ) AS 'display_name'";
588
				} else {
589
					$fields .= "(SELECT $wpdb->users.display_name FROM $wpdb->users WHERE $wpdb->users.ID = $wpdb->posts.post_author ) AS 'display_name'";
590
				}
591
			}
592
			if ( $instance['stats_tag']['date']['active'] ) {
593
				if ( $fields != ', ' ) {
594
					$fields .= ", $wpdb->posts.post_date_gmt AS 'date_gmt'";
595
				} else {
596
					$fields .= "$wpdb->posts.post_date_gmt AS 'date_gmt'";
597
				}
598
			}			
599
			
600
			if (strlen($fields) == 2) $fields = '';
601
602
			if ( $instance['range'] == 'all') {
603
				$join = "LEFT JOIN $table ON $wpdb->posts.ID = $table.postid";
604
				$force_pv = "AND ".$table.".pageviews > 0 ";
605
			} else {
606
				$join = "RIGHT JOIN ".$table."cache ON $wpdb->posts.ID = ".$table."cache.id";
607
				$force_pv = "";
608
			}
609
			
610
			// Category excluding snippet suggested by user raamdev at http://wordpress.org/support/topic/397885
611
			// Thanks, raamdev!
612
			if ( $instance['exclude-cats']['active'] && !empty($instance['exclude-cats']['cats']) ) {
613
				$exclude = " AND $wpdb->posts.ID NOT IN (
614
615
							SELECT  object_id
616
							FROM    $wpdb->term_relationships AS r
617
									JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
618
									JOIN $wpdb->terms AS t ON t.term_id = x.term_id
619
							WHERE   x.taxonomy = 'category'
620
									AND object_id IN
621
									   (
622
										SELECT object_id
623
										FROM $wpdb->term_relationships AS r
624
										JOIN $wpdb->term_taxonomy AS x ON x.term_taxonomy_id = r.term_taxonomy_id
625
										JOIN $wpdb->terms AS t ON t.term_id = x.term_id
626
										WHERE   x.taxonomy = 'category'
627
										AND t.term_id IN  (".$instance['exclude-cats']['cats']."))) ";
628
			} else {
629
				$exclude = "";
630
			}
631
			
632
			$mostpopular = $wpdb->get_results("SELECT $wpdb->posts.ID, $wpdb->posts.post_title $fields FROM $wpdb->posts $join WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_password = '' AND $range $force_pv $nopages $exclude GROUP BY $wpdb->posts.ID ORDER BY $sortby DESC LIMIT " . $instance['limit'] . "");
633
			
634
			$content = '';
635
			
636
			if ( !is_array($mostpopular) || empty($mostpopular) ) {
637
				$content .= "<p>".__('Sorry. No data so far.', 'wordpress-popular-posts')."</p>"."\n";
638
			} else {
639
				
640
				if ($instance['markup']['custom_html']) {
641
					$content .= htmlspecialchars_decode($instance['markup']['wpp-start'], ENT_QUOTES) ."\n";
642
				} else {
643
					$content .= "<ul>" . "\n";
644
				}
645
				$i = 1;
646
				foreach ($mostpopular as $wppost) {					
647
				
648
					$post_stats = "";
649
					$stats = "";
650
					$thumb = "";
651
					$data = array();
652
					
653
					// get post title
654
					/* qTranslate integration check */
655
					($this->qTrans) ? $tit = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($wppost->post_title) : $tit = $wppost->post_title;
656
					
657
					$tit = ($this->magicquotes) ? stripslashes($tit) : $tit;
658
					$title_attr = htmlentities($tit, ENT_QUOTES, $this->charset);
659
					
660
					if ( $instance['shorten_title']['active'] && (strlen($tit) > $instance['shorten_title']['length'])) {
661
						$tit = mb_substr($tit, 0, $instance['shorten_title']['length'], $this->charset) . "...";
662
					}
663
					
664
					$tit = htmlentities($tit, ENT_QUOTES, $this->charset);
665
					
666
					// get post excerpt
667
					if ( $instance['post-excerpt']['active'] ) {
668
						if ($instance['markup']['pattern']['active']) {
669
							$post_content = "<span class=\"wpp-excerpt\">" . $this->get_summary($wppost->ID, $instance) . "</span>";
670
						} else {
671
							$post_content = ": <span class=\"wpp-excerpt\">" . $this->get_summary($wppost->ID, $instance) . "...</span>";
672
						}
673
					} else {
674
						$post_content = "";
675
					}
676
					
677
					// build stats tag
678
					if ( $instance['stats_tag']['comment_count'] ) {
679
						$comment_count = (int) $wppost->comment_count;
680
						$post_stats .= "<span class=\"wpp-comments\">" . $comment_count . " " . __(' comment(s)', 'wordpress-popular-posts') . "</span>";
681
					}
682
					if ( $instance['stats_tag']['views'] ) {
683
						$views_text = __(' view(s)', 'wordpress-popular-posts');
684
						if ($instance['order_by'] == 'views') {
685
							$pageviews = (int) $wppost->pageviews;
686
						} else if ($instance['order_by'] == 'avg') {
687
							$pageviews = ceil($wppost->avg_views);
688
							if ($instance['range'] != 'daily') $views_text = __(' view(s) per day', 'wordpress-popular-posts');
689
						} else {
690
							$pageviews = (int) $wppost->pageviews;
691
						}			
692
						
693
						if ($post_stats != "") {
694
							$post_stats .= " | <span class=\"wpp-views\">$pageviews $views_text</span>";
695
						} else {							
696
							$post_stats .= "<span class=\"wpp-views\">$pageviews $views_text</span>";
697
						}										
698
					}
699
					if ( $instance['stats_tag']['author'] ) {
700
						if ($post_stats != "") {
701
							$post_stats .= " | ".__('by', 'wordpress-popular-posts')." <span class=\"wpp-author\">".$wppost->display_name."</span>";
702
						} else {					
703
							$post_stats .= __('by', 'wordpress-popular-posts')." <span class=\"wpp-author\">".$wppost->display_name."</span>";
704
						}
705
					}
706
					if ( $instance['stats_tag']['date']['active'] ) {
707
						if ($post_stats != "") {
708
							$post_stats .= " | <span class=\"wpp-date\">".__('posted on', 'wordpress-popular-posts')." ".date($instance['stats_tag']['date']['format'], strtotime($wppost->date_gmt))."</span>";
709
						} else {					
710
							$post_stats .= "<span class=\"wpp-date\">".__('posted on', 'wordpress-popular-posts')." ".date($instance['stats_tag']['date']['format'], strtotime($wppost->date_gmt))."</span>";
711
						}
712
					}
713
					
714
					if (!empty($post_stats)) {
715
						$stats = ' <span class="post-stats">' . $post_stats . '</span> ';
716
					}
717
					
718
					// get thumbnail
719
					if ($instance['thumbnail']['active'] && $this->thumb ) {
720
						$tbWidth = $instance['thumbnail']['width'];
721
						$tbHeight = $instance['thumbnail']['height'];
722
						
723
						// default image
724
						$thumb = "<a href=\"".get_permalink($wppost->ID)."\" class=\"wppnothumb\" title=\"". $title_attr ."\"><img src=\"". $this->pluginDir . "/no_thumb.jpg\" alt=\"".$title_attr."\" border=\"0\" class=\"wpp-thumbnail\" width=\"".$tbWidth."\" height=\"".$tbHeight."\" "."/></a>";
725
						
726
						// let's try to retrieve the post thumbnail!
727
						if ($instance['thumbnail']['thumb_selection'] == "usergenerated") { // use thumbnail selected by user
728
							if (function_exists('get_the_post_thumbnail') && has_post_thumbnail( $wppost->ID )) {
729
								$thumb = "<a href=\"".get_permalink($wppost->ID)."\" title=\"". $title_attr ."\">" . get_the_post_thumbnail($wppost->ID, array($tbWidth), array('class' => 'wpp-thumbnail', 'alt' => $title_attr, 'title' => $title_attr) ) ."</a> <!-- $tbWidth $tbHeight-->";
730
							}
731
						} else if ($instance['thumbnail']['thumb_selection'] == "wppgenerated") { // Wordpress Popular Posts should attempt to create a thumbnail by itself
732
							$img = $this->get_img($wppost->ID);
733
							if ( ($img && !empty($img)) ) {
734
								$thumb = "<a href=\"".get_permalink($wppost->ID)."\" class=\"wppgen\" title=\"". $title_attr ."\"><img src=\"". $this->pluginDir . "/scripts/timthumb.php?src=". $img[1] ."&amp;h=".$tbHeight."&amp;w=".$tbWidth."&amp;zc=1\" alt=\"".$title_attr."\" border=\"0\" class=\"wpp-thumbnail\" width=\"".$tbWidth."\" height=\"".$tbHeight."\" "."/></a>";
735
							}
736
						}
737
					}
738
					
739
					// get rating
740
					if ($instance['rating'] && $this->postRating) {
741
						$rating = '<span class="wpp-rating">'.the_ratings_results($wppost->ID).'</span>';
742
					} else {
743
						$rating = '';
744
					}
745
					$data = array(
746
						'title' => '<a href="'.get_permalink($wppost->ID).'" title="'. $title_attr .'"><span class="wpp-post-title">'. $tit .'</span></a>',
747
						'summary' => $post_content,
748
						'stats' => $stats,
749
						'img' => $thumb,
750
						'id' => $wppost->ID
751
					);		
752
					
753
					// build custom layout
754
					if ($instance['markup']['custom_html']) {
755
						if ($instance['markup']['pattern']['active']) {
756
							$content .= htmlspecialchars_decode($instance['markup']['post-start'], ENT_QUOTES) . $this->format_content($instance['markup']['pattern']['form'], $data, $instance['rating']) . htmlspecialchars_decode($instance['markup']['post-end'], ENT_QUOTES) . "\n";
757
						} else {
758
							$content .= htmlspecialchars_decode($instance['markup']['post-start'], ENT_QUOTES) . $thumb . '<a href="'.get_permalink($wppost->ID).'" title="'. $title_attr .'"><span class="wpp-post-title">'. $tit .'</span></a>'.$post_content.' '. $stats . $rating . htmlspecialchars_decode($instance['markup']['post-end'], ENT_QUOTES) . "\n";
759
						}
760
					} else {
761
						$content .= '<li class="group"><div class="number">' . $i . '</div>'. $thumb .'<a href="'. get_permalink($wppost->ID) .'" title="'. $title_attr .'"><span class="wpp-post-title">'. $tit .'</span></a>'. $post_content .' '. $stats . $rating .'</li>' . "\n";
762
					}
763
					$i++;
764
				}			
765
				
766
				if ($instance['markup']['custom_html']) {
767
					$content .= htmlspecialchars_decode($instance['markup']['wpp-end'], ENT_QUOTES) ."\n";
768
				} else {
769
					$content .= "\n"."</ul>"."\n";
770
				}
771
				
772
			}
773
			
774
			if ($echo) { echo "<noscript>" . $content . "</noscript>"; } else { return $content; }
775
		}		
776
		
777
		// builds posts' excerpt
778
		function get_summary($id, $instance){
779
			if (!is_numeric($id)) return false;
780
			global $wpdb;			
781
			$excerpt = "";
782
			$result = "";
783
			
784
			$result = $wpdb->get_results("SELECT post_excerpt FROM $wpdb->posts WHERE ID = " . $id, ARRAY_A);
785
			
786
			if (empty($result[0]['post_excerpt'])) {
787
				// no custom excerpt defined, how lazy of you!				
788
				$result = $wpdb->get_results("SELECT post_content FROM $wpdb->posts WHERE ID = " . $id, ARRAY_A);
789
				$excerpt = preg_replace("/\[caption.*\[\/caption\]/", "", $result[0]['post_content']);
790
			} else {
791
				// user has defined a custom excerpt, yay!
792
				$excerpt = preg_replace("/\[caption.*\[\/caption\]/", "", $result[0]['post_excerpt']);
793
			}
794
			
795
			$excerpt = preg_replace("/<object[0-9 a-z_?*=\":\-\/\.#\,\\n\\r\\t]+/smi", "", $excerpt);
796
			
797
			if ($instance['post-excerpt']['keep_format']) {
798
				$excerpt = strip_tags($excerpt, '<a><b><i><strong><em>');
799
			} else {
800
				$excerpt = strip_tags($excerpt);
801
			}
802
			
803
			if (strlen($excerpt) > $instance['post-excerpt']['length']) {
804
				$excerpt = $this->truncate($excerpt, $instance['post-excerpt']['length'], '', true, true);
805
			}
806
			
807
			return $excerpt;
808
		}
809
		
810
		// gets the first image of post / page
811
		function get_img($id = "", $print = false) {
812
			if ( empty($id) || !is_numeric($id) ) return false;
813
			
814
			// get post attachments
815
			$attachments = get_children(array('post_parent' => $id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order'));
816
			
817
			// no image has been found
818
			if ( ! is_array($attachments) ) return false;
819
			
820
			$count = count($attachments);
821
			$first_attachment = array_shift($attachments);			
822
			$img = wp_get_attachment_image($first_attachment->ID);
823
			
824
			preg_match('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'\s>]*)/i', $img, $imgm);
825
			
826
			if ($print)
827
					echo $imgm[1];
828
				else
829
					return $imgm;
830
831
		}
832
		
833
		// parses content structure defined by user
834
		function format_content ($string, $data = array(), $rating) {
835
			if (empty($string) || (empty($data) || !is_array($data))) return false;
836
			
837
			$params = array();
838
			$pattern = '/\{(summary|stats|title|image|rating)\}/i';		
839
			preg_match_all($pattern, $string, $matches);
840
			
841
			for ($i=0; $i < count($matches[0]); $i++) {		
842
				if (strtolower($matches[0][$i]) == "{title}") {
843
					$params[$matches[0][$i]] = $data['title'];
844
					continue;
845
				}
846
				if (strtolower($matches[0][$i]) == "{stats}") {
847
					$params[$matches[0][$i]] = $data['stats'];
848
					continue;
849
				}
850
				if (strtolower($matches[0][$i]) == "{summary}") {
851
					$params[$matches[0][$i]] = $data['summary'];
852
					continue;
853
				}
854
				if (strtolower($matches[0][$i]) == "{image}") {
855
					$params[$matches[0][$i]] = $data['img'];
856
					continue;
857
				}
858
				// WP-PostRatings check
859
				if ($rating) {
860
					if (strtolower($matches[0][$i]) == "{rating}") {
861
						$params[$matches[0][$i]] = the_ratings_results($data['id']);
862
						continue;
863
					}
864
				}
865
			}
866
			
867
			for ($i=0; $i < count($params); $i++) {		
868
				$string = str_replace($matches[0][$i], $params[$matches[0][$i]], $string);
869
			}
870
			
871
			return $string;
872
		}		
873
		
874
		// code seen at http://www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags/
875
		// Since 2.0.1
876
		/**
877
		 * Truncates text.
878
		 *
879
		 * Cuts a string to the length of $length and replaces the last characters
880
		 * with the ending if the text is longer than length.
881
		 *
882
		 * @param string  $text String to truncate.
883
		 * @param integer $length Length of returned string, including ellipsis.
884
		 * @param string  $ending Ending to be appended to the trimmed string.
885
		 * @param boolean $exact If false, $text will not be cut mid-word
886
		 * @param boolean $considerHtml If true, HTML tags would be handled correctly
887
		 * @return string Trimmed string.
888
		 */		
889
		function truncate($text, $length = 100, $ending = '...', $exact = true, $considerHtml = false) {
890
			if ($considerHtml) {
891
				// if the plain text is shorter than the maximum length, return the whole text
892
				if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
893
					return $text;
894
				}
895
				// splits all html-tags to scanable lines
896
				preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
897
				$total_length = strlen($ending);
898
				$open_tags = array();
899
				$truncate = '';
900
				foreach ($lines as $line_matchings) {
901
					// if there is any html-tag in this line, handle it and add it (uncounted) to the output
902
					if (!empty($line_matchings[1])) {
903
						// if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
904
						if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
905
							// do nothing
906
						// if tag is a closing tag (f.e. </b>)
907
						} else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
908
							// delete tag from $open_tags list
909
							$pos = array_search($tag_matchings[1], $open_tags);
910
							if ($pos !== false) {
911
								unset($open_tags[$pos]);
912
							}
913
						// if tag is an opening tag (f.e. <b>)
914
						} else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
915
							// add tag to the beginning of $open_tags list
916
							array_unshift($open_tags, strtolower($tag_matchings[1]));
917
						}
918
						// add html-tag to $truncate'd text
919
						$truncate .= $line_matchings[1];
920
					}
921
					// calculate the length of the plain text part of the line; handle entities as one character
922
					$content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
923
					if ($total_length+$content_length> $length) {
924
						// the number of characters which are left
925
						$left = $length - $total_length;
926
						$entities_length = 0;
927
						// search for html entities
928
						if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
929
							// calculate the real length of all entities in the legal range
930
							foreach ($entities[0] as $entity) {
931
								if ($entity[1]+1-$entities_length <= $left) {
932
									$left--;
933
									$entities_length += strlen($entity[0]);
934
								} else {
935
									// no more characters left
936
									break;
937
								}
938
							}
939
						}
940
						$truncate .= substr($line_matchings[2], 0, $left+$entities_length);
941
						// maximum lenght is reached, so get off the loop
942
						break;
943
					} else {
944
						$truncate .= $line_matchings[2];
945
						$total_length += $content_length;
946
					}
947
					// if the maximum length is reached, get off the loop
948
					if($total_length>= $length) {
949
						break;
950
					}
951
				}
952
			} else {
953
				if (strlen($text) <= $length) {
954
					return $text;
955
				} else {
956
					$truncate = substr($text, 0, $length - strlen($ending));
957
				}
958
			}
959
			// if the words shouldn't be cut in the middle...
960
			if (!$exact) {
961
				// ...search the last occurance of a space...
962
				$spacepos = strrpos($truncate, ' ');
963
				if (isset($spacepos)) {
964
					// ...and cut the text in this position
965
					$truncate = substr($truncate, 0, $spacepos);
966
				}
967
			}
968
			// add the defined ending to the text
969
			$truncate .= $ending;
970
			if($considerHtml) {
971
				// close all unclosed html-tags
972
				foreach ($open_tags as $tag) {
973
					$truncate .= '</' . $tag . '>';
974
				}				
975
			}
976
			return $truncate;
977
		}
978
		
979
		// plugin localization (Credits: Aleksey Timkov at@uadeveloper.com)
980
		function wpp_textdomain() {
981
			load_plugin_textdomain('wordpress-popular-posts', 'wp-content/plugins/wordpress-popular-posts');
982
		}
983
		
984
		// insert Wordpress Popular Posts' stylesheet in theme's head section, just in case someone needs it
985
		function wpp_print_stylesheet() {
986
			echo "\n"."<!-- Wordpress Popular Posts v". $this->version ." -->"."\n".'<link rel="stylesheet" href="'.$this->pluginDir.'/style/wpp.css" type="text/css" media="screen" />'."\n"."<!-- End Wordpress Popular Posts v". $this->version ." -->"."\n";	
987
		}
988
		
989
		// create Wordpress Popular Posts' maintenance page
990
		function wpp_maintenance_page() {
991
			require (dirname(__FILE__) . '/maintenance.php');
992
		}	
993
		function add_wpp_maintenance_page() {
994
			add_submenu_page('options-general.php', 'Wordpress Popular Posts', 'Wordpress Popular Posts', 10, __FILE__, array(&$this, 'wpp_maintenance_page'));
995
		}
996
		
997
		// version update warning
998
		function wpp_update_warning() {
999
			$msg = '<div id="wpp-message" class="error fade"><p>'.__('Your Wordpress version is too old. Wordpress Popular Posts Plugin requires at least version 2.8 to function correctly. Please update your blog via Tools &gt; Upgrade.', 'wordpress-popular-posts').'</p></div>';
1000
			echo trim($msg);
1001
		}
1002
		
1003
		// cache maintenance
1004
		function wpp_cache_maintenance() {
1005
			global $wpdb;
1006
			$wpdb->query("DELETE FROM ".$wpdb->prefix."popularpostsdatacache WHERE day < DATE_SUB(CURDATE(), INTERVAL 30 DAY);");
1007
		}
1008
		
1009
		// plugin deactivation
1010
		function wpp_deactivation() {
1011
			wp_clear_scheduled_hook('wpp_cache_event');
1012
			remove_shortcode('wpp');
1013
			remove_shortcode('WPP');
1014
			
1015
			delete_option('wpp_ver');
1016
		}
1017
		
1018
		// shortcode handler
1019
		function wpp_shortcode($atts = NULL, $content = NULL) {
1020
			extract( shortcode_atts( array(
1021
				'header' => '',
1022
				'limit' => 10,
1023
				'range' => 'daily',
1024
				'order_by' => 'comments',
1025
				'pages' => true,
1026
				'title_length' => 0,
1027
				'excerpt_length' => 0,
1028
				'excerpt_format' => 0,
1029
				'cats_to_exclude' => '',
1030
				'thumbnail_width' => 0,
1031
				'thumbnail_height' => 0,
1032
				'thumbnail_selection' => 'wppgenerated',
1033
				'rating' => false,
1034
				'stats_comments' => true,
1035
				'stats_views' => false,
1036
				'stats_author' => false,
1037
				'stats_date' => false,
1038
				'stats_date_format' => 'F j, Y',
1039
				'wpp_start' => '<ul class="wpp">',
1040
				'wpp_end' => '</ul>',
1041
				'post_start' => '<li class="group"><div class="number"></div>',
1042
				'post_end' => '</li>',
1043
				'header_start' => '<h2>',
1044
				'header_end' => '</h2>',
1045
				'do_pattern' => false,
1046
				'pattern_form' => '{image} {title}: {summary} {stats}'
1047
			), $atts ) );
1048
			
1049
			// possible values for "Time Range" and "Order by"
1050
			$range_values = array("yesterday", "daily", "weekly", "monthly", "all");
1051
			$order_by_values = array("comments", "views", "avg");
1052
			$thumbnail_selector = array("wppgenerated", "usergenerated");
1053
			
1054
			$shortcode_ops = array(
1055
				'title' => strip_tags($header),
1056
				'limit' => empty($limit) ? 10 : (is_numeric($limit)) ? (($limit > 0) ? $limit : 10) : 10,
1057
				'range' => (in_array($range, $range_values)) ? $range : 'daily',
1058
				'order_by' => (in_array($order_by, $order_by_values)) ? $order_by : 'comments',
1059
				'pages' => empty($pages) ? false : $pages,
1060
				'shorten_title' => array(
1061
					'active' => empty($title_length) ? false : (is_numeric($title_length)) ? (($title_length > 0) ? true : false) : false,
1062
					'length' => empty($title_length) ? 0 : (is_numeric($title_length)) ? $title_length : 0 
1063
				),
1064
				'post-excerpt' => array(
1065
					'active' => empty($excerpt_length) ? false : (is_numeric($excerpt_length)) ? (($excerpt_length > 0) ? true : false) : false,
1066
					'length' => empty($excerpt_length) ? 0 : (is_numeric($excerpt_length)) ? $excerpt_length : 0,
1067
					'keep_format' => empty($excerpt_format) ? false : (is_numeric($excerpt_format)) ? (($excerpt_format > 0) ? true : false) : false,
1068
				),
1069
				'exclude-cats' => array(
1070
					'active' => empty($cats_to_exclude) ? false : (ctype_digit(str_replace(",", "", $cats_to_exclude))) ? true : false,
1071
					'cats' => empty($cats_to_exclude) ? '' : (ctype_digit(str_replace(",", "", $cats_to_exclude))) ? $cats_to_exclude : ''
1072
				),		
1073
				'thumbnail' => array(
1074
					'active' => empty($thumbnail_width) ? false : (is_numeric($thumbnail_width)) ? (($thumbnail_width > 0) ? true : false) : false,
1075
					'thumb_selection' => (in_array($thumbnail_selection, $thumbnail_selector)) ? $thumbnail_selection : 'wppgenerated',
1076
					'width' => empty($thumbnail_width) ? 0 : (is_numeric($thumbnail_width)) ? $thumbnail_width : 0,
1077
					'height' => empty($thumbnail_height) ? 0 : (is_numeric($thumbnail_height)) ? $thumbnail_height : 0
1078
				),
1079
				'rating' => empty($rating) ? false : (bool)$rating,
1080
				'stats_tag' => array(
1081
					'comment_count' => empty($stats_comments) ? false : $stats_comments,
1082
					'views' => empty($stats_views) ? false : $stats_views,
1083
					'author' => empty($stats_author) ? false : $stats_author,
1084
					'date' => array(
1085
						'active' => empty($stats_date) ? false : $stats_date,
1086
						'format' => empty($stats_date_format) ? 'F j, Y' : $stats_date_format
1087
					)
1088
				),
1089
				'markup' => array(
1090
					'custom_html' => true,
1091
					'wpp-start' => empty($wpp_start) ? '<ul>' : $wpp_start,
1092
					'wpp-end' => empty($wpp_end) ? '</ul>' : $wpp_end,
1093
					'post-start' => empty($post_start) ? '<li>;' : $post_start,
1094
					'post-end' => empty($post_end) ? '</li>' : $post_end,
1095
					'title-start' => empty($header_start) ? '' : $header_start,
1096
					'title-end' => empty($header_end) ? '' : $header_end,
1097
					'pattern' => array(
1098
						'active' => empty($do_pattern) ? false : (bool)$do_pattern,
1099
						'form' => empty($pattern_form) ? '{image} {title}: {summary} {stats}' : $pattern_form
1100
					)
1101
				)
1102
			);
1103
			
1104
			$shortcode_content = "";
1105
			
1106
			$shortcode_content .= "<!-- Wordpress Popular Posts Plugin v". $this->version ." [SC] [".$shortcode_ops['range']."]". (($shortcode_ops['markup']['custom_html']) ? ' [custom]' : ' [regular]') ." -->"."\n";
1107
			
1108
			// is there a title defined by user?
1109
			if (!empty($header) && !empty($header_start) && !empty($header_end)) {
1110
				$shortcode_content .= $header_start . $header . $header_end;
1111
			}
1112
			
1113
			// print popular posts list
1114
			$shortcode_content .= $this->get_popular_posts($shortcode_ops, false);
1115
			
1116
			$shortcode_content .= "<!-- End Wordpress Popular Posts Plugin v". $this->version ." -->"."\n";
1117
			
1118
			return $shortcode_content;
1119
		}
1120
		
1121
		// stats page
1122
		// Since 2.0.3
1123
		function wpp_stats() {
1124
			if ( function_exists('add_submenu_page') ) add_submenu_page('index.php', __('Wordpress Popular Posts Stats'), __('Wordpress Popular Posts Stats'), 'manage_options', 'wpp-stats-display', array(&$this, 'wpp_stats_display'));
1125
		}
1126
		
1127
		function wpp_stats_display() {
1128
			require (dirname(__FILE__) . '/stats.php');
1129
        }
1130
	}
1131
}
1132
1133
/**
1134
 * Wordpress Popular Posts template tags for use in themes.
1135
 */
1136
1137
// gets views count
1138
// Since 2.0.0
1139
function wpp_get_views($id = NULL) {
1140
	// have we got an id?
1141
	if ( empty($id) || is_null($id) || !is_numeric($id) ) {
1142
		return "-1";
1143
	} else {		
1144
		global $wpdb;
1145
		
1146
		$table_name = $wpdb->prefix . "popularpostsdata";		
1147
		$result = $wpdb->get_results("SELECT pageviews FROM $table_name WHERE postid = '$id'", ARRAY_A);
1148
		
1149
		if ( !is_array($result) || empty($result) ) {
1150
			return "0";
1151
		} else {
1152
			return $result[0]['pageviews'];
1153
		}
1154
	}
1155
}
1156
1157
// gets popular posts
1158
// Since 2.0.3
1159
function wpp_get_mostpopular($args = NULL) {
1160
1161
	if (is_null($args)) {
1162
		echo do_shortcode('[wpp]');
1163
	} else {
1164
		$atts = trim(str_replace("&", " ", $args));
1165
		echo do_shortcode('[wpp '.$atts.']');
1166
	}
1167
}
1168
1169
// gets popular posts
1170
/**
1171
 * Deprecated in 2.0.3.
1172
 * Use wpp_get_mostpopular instead.
1173
 */
1174
function get_mostpopular($args = NULL) {
1175
	return wpp_get_mostpopular($args);
1176
}
1177
1178
1179
/**
1180
 * Wordpress Popular Posts 2.1.4 Changelog.
1181
 */
1182
1183
/*
1184
 = 2.1.4 =
1185
 * Added charset detection.
1186
*/