wp-polls.php 91.8 KB
Newer Older
Lester Chan's avatar
EOL    
Lester Chan committed
1
2
3
<?php
/*
Plugin Name: WP-Polls
4
Plugin URI: https://lesterchan.net/portfolio/programming/php/
Lester Chan's avatar
EOL    
Lester Chan committed
5
Description: Adds an AJAX poll system to your WordPress blog. You can easily include a poll into your WordPress's blog post/page. WP-Polls is extremely customizable via templates and css styles and there are tons of options for you to choose to ensure that WP-Polls runs the way you wanted. It now supports multiple selection of answers.
6
Version: 2.75.5
Lester Chan's avatar
EOL    
Lester Chan committed
7
Author: Lester 'GaMerZ' Chan
8
Author URI: https://lesterchan.net
Lester Chan's avatar
EOL    
Lester Chan committed
9
10
11
12
13
Text Domain: wp-polls
*/


/*
Lester Chan's avatar
Lester Chan committed
14
	Copyright 2020  Lester Chan  (email : lesterchan@gmail.com)
Lester Chan's avatar
EOL    
Lester Chan committed
15

16
17
18
19
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.
David Ajnered's avatar
David Ajnered committed
20

21
22
23
24
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
David Ajnered's avatar
David Ajnered committed
25

26
27
28
	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
Lester Chan's avatar
EOL    
Lester Chan committed
29
30
*/

31
### Version
32
define( 'WP_POLLS_VERSION', '2.75.5' );
33
34


Lester Chan's avatar
EOL    
Lester Chan committed
35
### Create Text Domain For Translations
Lester Chan's avatar
Lester Chan committed
36
add_action( 'plugins_loaded', 'polls_textdomain' );
Lester Chan's avatar
EOL    
Lester Chan committed
37
function polls_textdomain() {
38
	load_plugin_textdomain( 'wp-polls' );
Lester Chan's avatar
EOL    
Lester Chan committed
39
40
41
42
43
}


### Polls Table Name
global $wpdb;
44
45
46
$wpdb->pollsq   = $wpdb->prefix.'pollsq';
$wpdb->pollsa   = $wpdb->prefix.'pollsa';
$wpdb->pollsip  = $wpdb->prefix.'pollsip';
Lester Chan's avatar
EOL    
Lester Chan committed
47
48
49


### Function: Poll Administration Menu
50
add_action( 'admin_menu', 'poll_menu' );
Lester Chan's avatar
EOL    
Lester Chan committed
51
function poll_menu() {
52
	add_menu_page( __( 'Polls', 'wp-polls' ), __( 'Polls', 'wp-polls' ), 'manage_polls', 'wp-polls/polls-manager.php', '', 'dashicons-chart-bar' );
Lester Chan's avatar
Lester Chan committed
53

54
55
56
57
	add_submenu_page( 'wp-polls/polls-manager.php', __( 'Manage Polls', 'wp-polls'), __( 'Manage Polls', 'wp-polls' ), 'manage_polls', 'wp-polls/polls-manager.php' );
	add_submenu_page( 'wp-polls/polls-manager.php', __( 'Add Poll', 'wp-polls'), __( 'Add Poll', 'wp-polls' ), 'manage_polls', 'wp-polls/polls-add.php' );
	add_submenu_page( 'wp-polls/polls-manager.php', __( 'Poll Options', 'wp-polls'), __( 'Poll Options', 'wp-polls' ), 'manage_polls', 'wp-polls/polls-options.php' );
	add_submenu_page( 'wp-polls/polls-manager.php', __( 'Poll Templates', 'wp-polls'), __( 'Poll Templates', 'wp-polls' ), 'manage_polls', 'wp-polls/polls-templates.php' );
Lester Chan's avatar
EOL    
Lester Chan committed
58
59
60
61
62
}


### Function: Get Poll
function get_poll($temp_poll_id = 0, $display = true) {
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
	global $wpdb, $polls_loaded;
	// Poll Result Link
	if(isset($_GET['pollresult'])) {
		$pollresult_id = (int) $_GET['pollresult'];
	} else {
		$pollresult_id = 0;
	}
	$temp_poll_id = (int) $temp_poll_id;
	// Check Whether Poll Is Disabled
	if((int) get_option('poll_currentpoll') === -1) {
		if($display) {
			echo removeslashes(get_option('poll_template_disable'));
			return '';
		}

		return removeslashes(get_option('poll_template_disable'));
	// Poll Is Enabled
	} else {
		do_action('wp_polls_get_poll');
		// Hardcoded Poll ID Is Not Specified
		switch($temp_poll_id) {
			// Random Poll
			case -2:
				$poll_id = $wpdb->get_var("SELECT pollq_id FROM $wpdb->pollsq WHERE pollq_active = 1 ORDER BY RAND() LIMIT 1");
				break;
			// Latest Poll
			case 0:
				// Random Poll
				if((int) get_option('poll_currentpoll') === -2) {
					$random_poll_id = $wpdb->get_var("SELECT pollq_id FROM $wpdb->pollsq WHERE pollq_active = 1 ORDER BY RAND() LIMIT 1");
					$poll_id = (int) $random_poll_id;
					if($pollresult_id > 0) {
						$poll_id = $pollresult_id;
					} elseif((int) $_POST['poll_id'] > 0) {
						$poll_id = (int) $_POST['poll_id'];
					}
				// Current Poll ID Is Not Specified
				} elseif((int) get_option('poll_currentpoll') === 0) {
					// Get Lastest Poll ID
					$poll_id = (int) get_option('poll_latestpoll');
				} else {
					// Get Current Poll ID
					$poll_id = (int) get_option('poll_currentpoll');
				}
				break;
			// Take Poll ID From Arguments
			default:
				$poll_id = $temp_poll_id;
		}
	}

	// Assign All Loaded Poll To $polls_loaded
	if(empty($polls_loaded)) {
		$polls_loaded = array();
	}
	if(!in_array($poll_id, $polls_loaded, true)) {
		$polls_loaded[] = $poll_id;
	}

	// User Click on View Results Link
	if($pollresult_id === $poll_id) {
		if($display) {
			echo display_pollresult($poll_id);
		} else {
			return display_pollresult($poll_id);
		}
	// Check Whether User Has Voted
	} else {
		$poll_active = $wpdb->get_var( $wpdb->prepare( "SELECT pollq_active FROM $wpdb->pollsq WHERE pollq_id = %d", $poll_id ) );
Lester Chan's avatar
Lester Chan committed
132
133
134
		$poll_active = (int) $poll_active;
		$check_voted = check_voted( $poll_id );
		$poll_close = 0;
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
		if( $poll_active === 0 ) {
			$poll_close = (int) get_option( 'poll_close' );
		}
		if( $poll_close === 2 ) {
			if( $display ) {
				echo '';
			} else {
				return '';
			}
		}
		if( $poll_close === 1 || (int) $check_voted > 0 || ( is_array( $check_voted ) && count( $check_voted ) > 0 ) ) {
			if($display) {
				echo display_pollresult($poll_id, $check_voted);
			} else {
				return display_pollresult($poll_id, $check_voted);
			}
		} elseif( $poll_close === 3 || ! check_allowtovote() ) {
			$disable_poll_js = '<script type="text/javascript">jQuery("#polls_form_'.$poll_id.' :input").each(function (i){jQuery(this).attr("disabled","disabled")});</script>';
			if($display) {
				echo display_pollvote($poll_id).$disable_poll_js;
			} else {
				return display_pollvote($poll_id).$disable_poll_js;
			}
		} elseif( $poll_active === 1 ) {
			if($display) {
				echo display_pollvote($poll_id);
			} else {
				return display_pollvote($poll_id);
			}
		}
	}
Lester Chan's avatar
EOL    
Lester Chan committed
166
167
168
169
170
171
}


### Function: Enqueue Polls JavaScripts/CSS
add_action('wp_enqueue_scripts', 'poll_scripts');
function poll_scripts() {
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
	if(@file_exists(get_stylesheet_directory().'/polls-css.css')) {
		wp_enqueue_style('wp-polls', get_stylesheet_directory_uri().'/polls-css.css', false, WP_POLLS_VERSION, 'all');
	} else {
		wp_enqueue_style('wp-polls', plugins_url('wp-polls/polls-css.css'), false, WP_POLLS_VERSION, 'all');
	}
	if( is_rtl() ) {
		if(@file_exists(get_stylesheet_directory().'/polls-css-rtl.css')) {
			wp_enqueue_style('wp-polls-rtl', get_stylesheet_directory_uri().'/polls-css-rtl.css', false, WP_POLLS_VERSION, 'all');
		} else {
			wp_enqueue_style('wp-polls-rtl', plugins_url('wp-polls/polls-css-rtl.css'), false, WP_POLLS_VERSION, 'all');
		}
	}
	$pollbar = get_option( 'poll_bar' );
	if( $pollbar['style'] === 'use_css' ) {
		$pollbar_css = '.wp-polls .pollbar {'."\n";
		$pollbar_css .= "\t".'margin: 1px;'."\n";
		$pollbar_css .= "\t".'font-size: '.($pollbar['height']-2).'px;'."\n";
		$pollbar_css .= "\t".'line-height: '.$pollbar['height'].'px;'."\n";
		$pollbar_css .= "\t".'height: '.$pollbar['height'].'px;'."\n";
		$pollbar_css .= "\t".'background: #'.$pollbar['background'].';'."\n";
		$pollbar_css .= "\t".'border: 1px solid #'.$pollbar['border'].';'."\n";
		$pollbar_css .= '}'."\n";
	} else {
		$pollbar_css = '.wp-polls .pollbar {'."\n";
		$pollbar_css .= "\t".'margin: 1px;'."\n";
		$pollbar_css .= "\t".'font-size: '.($pollbar['height']-2).'px;'."\n";
		$pollbar_css .= "\t".'line-height: '.$pollbar['height'].'px;'."\n";
		$pollbar_css .= "\t".'height: '.$pollbar['height'].'px;'."\n";
		$pollbar_css .= "\t".'background-image: url(\''.plugins_url('wp-polls/images/'.$pollbar['style'].'/pollbg.gif').'\');'."\n";
		$pollbar_css .= "\t".'border: 1px solid #'.$pollbar['border'].';'."\n";
		$pollbar_css .= '}'."\n";
	}
	wp_add_inline_style( 'wp-polls', $pollbar_css );
	$poll_ajax_style = get_option('poll_ajax_style');
	wp_enqueue_script('wp-polls', plugins_url('wp-polls/polls-js.js'), array('jquery'), WP_POLLS_VERSION, true);
	wp_localize_script('wp-polls', 'pollsL10n', array(
		'ajax_url' => admin_url('admin-ajax.php'),
		'text_wait' => __('Your last request is still being processed. Please wait a while ...', 'wp-polls'),
		'text_valid' => __('Please choose a valid poll answer.', 'wp-polls'),
		'text_multiple' => __('Maximum number of choices allowed: ', 'wp-polls'),
		'show_loading' => (int) $poll_ajax_style['loading'],
		'show_fading' => (int) $poll_ajax_style['fading']
	));
Lester Chan's avatar
EOL    
Lester Chan committed
215
216
217
218
219
220
}


### Function: Enqueue Polls Stylesheets/JavaScripts In WP-Admin
add_action('admin_enqueue_scripts', 'poll_scripts_admin');
function poll_scripts_admin($hook_suffix) {
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
	$poll_admin_pages = array('wp-polls/polls-manager.php', 'wp-polls/polls-add.php', 'wp-polls/polls-options.php', 'wp-polls/polls-templates.php', 'wp-polls/polls-uninstall.php');
	if(in_array($hook_suffix, $poll_admin_pages, true)) {
		wp_enqueue_style('wp-polls-admin', plugins_url('wp-polls/polls-admin-css.css'), false, WP_POLLS_VERSION, 'all');
		wp_enqueue_script('wp-polls-admin', plugins_url('wp-polls/polls-admin-js.js'), array('jquery'), WP_POLLS_VERSION, true);
		wp_localize_script('wp-polls-admin', 'pollsAdminL10n', array(
			'admin_ajax_url' => admin_url('admin-ajax.php'),
			'text_direction' => is_rtl() ? 'right' : 'left',
			'text_delete_poll' => __('Delete Poll', 'wp-polls'),
			'text_no_poll_logs' => __('No poll logs available.', 'wp-polls'),
			'text_delete_all_logs' => __('Delete All Logs', 'wp-polls'),
			'text_checkbox_delete_all_logs' => __('Please check the \\\'Yes\\\' checkbox if you want to delete all logs.', 'wp-polls'),
			'text_delete_poll_logs' => __('Delete Logs For This Poll Only', 'wp-polls'),
			'text_checkbox_delete_poll_logs' => __('Please check the \\\'Yes\\\' checkbox if you want to delete all logs for this poll ONLY.', 'wp-polls'),
			'text_delete_poll_ans' => __('Delete Poll Answer', 'wp-polls'),
			'text_open_poll' => __('Open Poll', 'wp-polls'),
			'text_close_poll' => __('Close Poll', 'wp-polls'),
			'text_answer' => __('Answer', 'wp-polls'),
			'text_remove_poll_answer' => __('Remove', 'wp-polls')
		));
	}
Lester Chan's avatar
EOL    
Lester Chan committed
241
242
243
244
245
246
247
248
249
}


### Function: Displays Polls Footer In WP-Admin
add_action('admin_footer-post-new.php', 'poll_footer_admin');
add_action('admin_footer-post.php', 'poll_footer_admin');
add_action('admin_footer-page-new.php', 'poll_footer_admin');
add_action('admin_footer-page.php', 'poll_footer_admin');
function poll_footer_admin() {
250
?>
251
252
253
254
255
256
257
258
259
260
261
	<script type="text/javascript">
		QTags.addButton('ed_wp_polls', '<?php echo esc_js(__('Poll', 'wp-polls')); ?>', function() {
			var poll_id = jQuery.trim(prompt('<?php echo esc_js(__('Enter Poll ID', 'wp-polls')); ?>'));
			while(isNaN(poll_id)) {
				poll_id = jQuery.trim(prompt("<?php echo esc_js(__('Error: Poll ID must be numeric', 'wp-polls')); ?>\n\n<?php echo esc_js(__('Please enter Poll ID again', 'wp-polls')); ?>"));
			}
			if (poll_id >= -1 && poll_id != null && poll_id != "") {
				QTags.insertContent('[poll id="' + poll_id + '"]');
			}
		});
	</script>
262
<?php
Lester Chan's avatar
EOL    
Lester Chan committed
263
264
265
266
267
}

### Function: Add Quick Tag For Poll In TinyMCE >= WordPress 2.5
add_action('init', 'poll_tinymce_addbuttons');
function poll_tinymce_addbuttons() {
268
269
270
271
272
273
274
275
	if(!current_user_can('edit_posts') && ! current_user_can('edit_pages')) {
		return;
	}
	if(get_user_option('rich_editing') === 'true') {
		add_filter('mce_external_plugins', 'poll_tinymce_addplugin');
		add_filter('mce_buttons', 'poll_tinymce_registerbutton');
		add_filter('wp_mce_translation', 'poll_tinymce_translation');
	}
Lester Chan's avatar
EOL    
Lester Chan committed
276
277
}
function poll_tinymce_registerbutton($buttons) {
278
279
	array_push($buttons, 'separator', 'polls');
	return $buttons;
Lester Chan's avatar
EOL    
Lester Chan committed
280
281
}
function poll_tinymce_addplugin($plugin_array) {
282
283
284
285
286
287
	if(WP_DEBUG) {
		$plugin_array['polls'] = plugins_url( 'wp-polls/tinymce/plugins/polls/plugin.js?v=' . WP_POLLS_VERSION );
	} else {
		$plugin_array['polls'] = plugins_url( 'wp-polls/tinymce/plugins/polls/plugin.min.js?v=' . WP_POLLS_VERSION );
	}
	return $plugin_array;
Lester Chan's avatar
EOL    
Lester Chan committed
288
}
289
function poll_tinymce_translation($mce_translation) {
290
291
292
293
294
	$mce_translation['Enter Poll ID'] = esc_js(__('Enter Poll ID', 'wp-polls'));
	$mce_translation['Error: Poll ID must be numeric'] = esc_js(__('Error: Poll ID must be numeric', 'wp-polls'));
	$mce_translation['Please enter Poll ID again'] = esc_js(__('Please enter Poll ID again', 'wp-polls'));
	$mce_translation['Insert Poll'] = esc_js(__('Insert Poll', 'wp-polls'));
	return $mce_translation;
295
}
Lester Chan's avatar
EOL    
Lester Chan committed
296
297
298
299


### Function: Check Who Is Allow To Vote
function check_allowtovote() {
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
	global $user_ID;
	$user_ID = (int) $user_ID;
	$allow_to_vote = (int) get_option( 'poll_allowtovote' );
	switch($allow_to_vote) {
		// Guests Only
		case 0:
			if($user_ID > 0) {
				return false;
			}
			return true;
			break;
		// Registered Users Only
		case 1:
			if($user_ID === 0) {
				return false;
			}
			return true;
			break;
		// Registered Users And Guests
		case 2:
		default:
			return true;
	}
Lester Chan's avatar
EOL    
Lester Chan committed
323
324
325
326
327
}


### Funcrion: Check Voted By Cookie Or IP
function check_voted($poll_id) {
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
	$poll_logging_method = (int) get_option( 'poll_logging_method' );
	switch($poll_logging_method) {
		// Do Not Log
		case 0:
			return 0;
			break;
		// Logged By Cookie
		case 1:
			return check_voted_cookie($poll_id);
			break;
		// Logged By IP
		case 2:
			return check_voted_ip($poll_id);
			break;
		// Logged By Cookie And IP
		case 3:
			$check_voted_cookie = check_voted_cookie($poll_id);
			if(!empty($check_voted_cookie)) {
				return $check_voted_cookie;
			}
			return check_voted_ip($poll_id);
			break;
		// Logged By Username
		case 4:
			return check_voted_username($poll_id);
			break;
	}
Lester Chan's avatar
EOL    
Lester Chan committed
355
356
357
358
}


### Function: Check Voted By Cookie
359
360
361
362
363
364
365
function check_voted_cookie( $poll_id ) {
	$get_voted_aids = 0;
	if ( ! empty( $_COOKIE[ 'voted_' . $poll_id ] ) ) {
		$get_voted_aids = explode( ',', $_COOKIE[ 'voted_' . $poll_id ] );
		$get_voted_aids = array_map( 'intval', array_map( 'sanitize_key', $get_voted_aids ) );
	}
	return $get_voted_aids;
Lester Chan's avatar
EOL    
Lester Chan committed
366
367
368
369
}


### Function: Check Voted By IP
370
function check_voted_ip( $poll_id ) {
371
372
373
374
	global $wpdb;
	$log_expiry = (int) get_option( 'poll_cookielog_expiry' );
	$log_expiry_sql = '';
	if( $log_expiry > 0 ) {
375
		$log_expiry_sql = ' AND (' . current_time('timestamp') . '-(pollip_timestamp+0)) < ' . $log_expiry;
376
377
	}
	// Check IP From IP Logging Database
378
	$get_voted_aids = $wpdb->get_col( $wpdb->prepare( "SELECT pollip_aid FROM $wpdb->pollsip WHERE pollip_qid = %d AND (pollip_ip = %s OR pollip_ip = %s)", $poll_id, poll_get_ipaddress(), get_ipaddress() ) . $log_expiry_sql );
379
380
381
382
383
	if( $get_voted_aids ) {
		return $get_voted_aids;
	}

	return 0;
Lester Chan's avatar
EOL    
Lester Chan committed
384
385
386
387
388
}


### Function: Check Voted By Username
function check_voted_username($poll_id) {
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
	global $wpdb, $user_ID;
	// Check IP If User Is Guest
	if ( ! is_user_logged_in() ) {
		return 1;
	}
	$pollsip_userid = (int) $user_ID;
	$log_expiry = (int) get_option( 'poll_cookielog_expiry' );
	$log_expiry_sql = '';
	if( $log_expiry > 0 ) {
		$log_expiry_sql = 'AND (' . current_time('timestamp') . '-(pollip_timestamp+0)) < ' . $log_expiry;
	}
	// Check User ID From IP Logging Database
	$get_voted_aids = $wpdb->get_col( $wpdb->prepare( "SELECT pollip_aid FROM $wpdb->pollsip WHERE pollip_qid = %d AND pollip_userid = %d", $poll_id, $pollsip_userid ) . $log_expiry_sql );
	if($get_voted_aids) {
		return $get_voted_aids;
	} else {
		return 0;
	}
Lester Chan's avatar
EOL    
Lester Chan committed
407
408
}

Lester Chan's avatar
Lester Chan committed
409
410
411
add_filter( 'wp_polls_template_voteheader_markup', 'poll_template_vote_markup', 10, 3 );
add_filter( 'wp_polls_template_votebody_markup', 'poll_template_vote_markup', 10, 3 );
add_filter( 'wp_polls_template_votefooter_markup', 'poll_template_vote_markup', 10, 3) ;
412
413
414
415
416
add_filter( 'wp_polls_template_resultheader_markup', 'poll_template_vote_markup', 10, 3) ;
add_filter( 'wp_polls_template_resultbody_markup', 'poll_template_vote_markup', 10, 3) ;
add_filter( 'wp_polls_template_resultbody2_markup', 'poll_template_vote_markup', 10, 3) ;
add_filter( 'wp_polls_template_resultfooter_markup', 'poll_template_vote_markup', 10, 3) ;
add_filter( 'wp_polls_template_resultfooter2_markup', 'poll_template_vote_markup', 10, 3) ;
417

Lester Chan's avatar
Lester Chan committed
418
419
function poll_template_vote_markup( $template, $object, $variables ) {
	return str_replace( array_keys( $variables ), array_values( $variables ), $template ) ;
420
}
Lester Chan's avatar
EOL    
Lester Chan committed
421

422

Lester Chan's avatar
EOL    
Lester Chan committed
423
424
### Function: Display Voting Form
function display_pollvote($poll_id, $display_loading = true) {
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
	do_action('wp_polls_display_pollvote');
	global $wpdb;
	// Temp Poll Result
	$temp_pollvote = '';
	// Get Poll Question Data
	$poll_question = $wpdb->get_row( $wpdb->prepare( "SELECT pollq_id, pollq_question, pollq_totalvotes, pollq_timestamp, pollq_expiry, pollq_multiple, pollq_totalvoters FROM $wpdb->pollsq WHERE pollq_id = %d LIMIT 1", $poll_id ) );

	// Poll Question Variables
	$poll_question_text = wp_kses_post( removeslashes( $poll_question->pollq_question ) );
	$poll_question_id = (int) $poll_question->pollq_id;
	$poll_question_totalvotes = (int) $poll_question->pollq_totalvotes;
	$poll_question_totalvoters = (int) $poll_question->pollq_totalvoters;
	$poll_start_date = mysql2date(sprintf(__('%s @ %s', 'wp-polls'), get_option('date_format'), get_option('time_format')), gmdate('Y-m-d H:i:s', $poll_question->pollq_timestamp));
	$poll_expiry = trim($poll_question->pollq_expiry);
	if(empty($poll_expiry)) {
		$poll_end_date  = __('No Expiry', 'wp-polls');
	} else {
		$poll_end_date  = mysql2date(sprintf(__('%s @ %s', 'wp-polls'), get_option('date_format'), get_option('time_format')), gmdate('Y-m-d H:i:s', $poll_expiry));
	}
	$poll_multiple_ans = (int) $poll_question->pollq_multiple;

	$template_question = removeslashes(get_option('poll_template_voteheader'));

448
	$template_question_variables = array(
Lester Chan's avatar
Lester Chan committed
449
450
451
452
453
454
		'%POLL_QUESTION%'           => $poll_question_text,
		'%POLL_ID%'                 => $poll_question_id,
		'%POLL_TOTALVOTES%'         => $poll_question_totalvotes,
		'%POLL_TOTALVOTERS%'        => $poll_question_totalvoters,
		'%POLL_START_DATE%'         => $poll_start_date,
		'%POLL_END_DATE%'           => $poll_end_date,
455
456
457
458
		'%POLL_MULTIPLE_ANS_MAX%'   => $poll_multiple_ans > 0 ? $poll_multiple_ans : 1
	);
	$template_question_variables = apply_filters( 'wp_polls_template_voteheader_variables', $template_question_variables );
	$template_question  		 = apply_filters( 'wp_polls_template_voteheader_markup', $template_question, $poll_question, $template_question_variables );
Lester Chan's avatar
Lester Chan committed
459

460
461
462
463
464
465
466
467

	// Get Poll Answers Data
	list($order_by, $sort_order) = _polls_get_ans_sort();
	$poll_answers = $wpdb->get_results( $wpdb->prepare( "SELECT polla_aid, polla_qid, polla_answers, polla_votes FROM $wpdb->pollsa WHERE polla_qid = %d ORDER BY $order_by $sort_order", $poll_question_id ) );
	// If There Is Poll Question With Answers
	if($poll_question && $poll_answers) {
		// Display Poll Voting Form
		$temp_pollvote .= "<div id=\"polls-$poll_question_id\" class=\"wp-polls\">\n";
Lester Chan's avatar
Lester Chan committed
468
		$temp_pollvote .= "\t<form id=\"polls_form_$poll_question_id\" class=\"wp-polls-form\" action=\"" . sanitize_text_field( $_SERVER['SCRIPT_NAME'] ) ."\" method=\"post\">\n";
469
470
471
472
473
474
475
		$temp_pollvote .= "\t\t<p style=\"display: none;\"><input type=\"hidden\" id=\"poll_{$poll_question_id}_nonce\" name=\"wp-polls-nonce\" value=\"".wp_create_nonce('poll_'.$poll_question_id.'-nonce')."\" /></p>\n";
		$temp_pollvote .= "\t\t<p style=\"display: none;\"><input type=\"hidden\" name=\"poll_id\" value=\"$poll_question_id\" /></p>\n";
		if($poll_multiple_ans > 0) {
			$temp_pollvote .= "\t\t<p style=\"display: none;\"><input type=\"hidden\" id=\"poll_multiple_ans_$poll_question_id\" name=\"poll_multiple_ans_$poll_question_id\" value=\"$poll_multiple_ans\" /></p>\n";
		}
		// Print Out Voting Form Header Template
		$temp_pollvote .= "\t\t$template_question\n";
Lester Chan's avatar
Lester Chan committed
476
		foreach ( $poll_answers as $poll_answer ) {
477
478
479
480
			// Poll Answer Variables
			$poll_answer_id = (int) $poll_answer->polla_aid;
			$poll_answer_text = wp_kses_post( removeslashes( $poll_answer->polla_answers ) );
			$poll_answer_votes = (int) $poll_answer->polla_votes;
481
			$poll_answer_percentage = $poll_question_totalvotes > 0 ? round( ( $poll_answer_votes / $poll_question_totalvotes ) * 100 ) : 0;
Lester Chan's avatar
Lester Chan committed
482
483
			$poll_multiple_answer_percentage = $poll_question_totalvoters > 0 ? round( ( $poll_answer_votes / $poll_question_totalvoters ) * 100 ) : 0;
			$template_answer = removeslashes( get_option( 'poll_template_votebody' ) );
484

485
			$template_answer_variables = array(
Lester Chan's avatar
Lester Chan committed
486
487
488
489
490
				'%POLL_ID%'                         => $poll_question_id,
				'%POLL_ANSWER_ID%'                  => $poll_answer_id,
				'%POLL_ANSWER%'                     => $poll_answer_text,
				'%POLL_ANSWER_VOTES%'               => number_format_i18n( $poll_answer_votes ),
				'%POLL_ANSWER_PERCENTAGE%'          => $poll_answer_percentage,
Lester Chan's avatar
Lester Chan committed
491
				'%POLL_MULTIPLE_ANSWER_PERCENTAGE%' => $poll_multiple_answer_percentage,
Lester Chan's avatar
Lester Chan committed
492
				'%POLL_CHECKBOX_RADIO%'             => $poll_multiple_ans > 0 ? 'checkbox' : 'radio',
493
			);
Lester Chan's avatar
Lester Chan committed
494

495
			$template_answer_variables = apply_filters( 'wp_polls_template_votebody_variables', $template_answer_variables );
Lester Chan's avatar
Lester Chan committed
496
			$template_answer           = apply_filters( 'wp_polls_template_votebody_markup', $template_answer, $poll_answer, $template_answer_variables );
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513

			// Print Out Voting Form Body Template
			$temp_pollvote .= "\t\t$template_answer\n";
		}
		// Determine Poll Result URL
		$poll_result_url = esc_url_raw( $_SERVER['REQUEST_URI'] );
		$poll_result_url = preg_replace('/pollresult=(\d+)/i', 'pollresult='.$poll_question_id, $poll_result_url);
		if(isset($_GET['pollresult']) && (int) $_GET['pollresult'] === 0) {
			if(strpos($poll_result_url, '?') !== false) {
				$poll_result_url = "$poll_result_url&amp;pollresult=$poll_question_id";
			} else {
				$poll_result_url = "$poll_result_url?pollresult=$poll_question_id";
			}
		}
		// Voting Form Footer Variables
		$template_footer = removeslashes(get_option('poll_template_votefooter'));

514
		$template_footer_variables = array(
Lester Chan's avatar
Lester Chan committed
515
516
517
518
			'%POLL_ID%'               => $poll_question_id,
			'%POLL_RESULT_URL%'       => $poll_result_url,
			'%POLL_START_DATE%'       => $poll_start_date,
			'%POLL_END_DATE%'         => $poll_end_date,
Lester Chan's avatar
Lester Chan committed
519
			'%POLL_MULTIPLE_ANS_MAX%' => $poll_multiple_ans > 0 ? $poll_multiple_ans : 1
520
		);
Lester Chan's avatar
Lester Chan committed
521

522
		$template_footer_variables = apply_filters( 'wp_polls_template_votefooter_variables', $template_footer_variables );
Lester Chan's avatar
Lester Chan committed
523
		$template_footer           = apply_filters( 'wp_polls_template_votefooter_markup', $template_footer, $poll_question, $template_footer_variables );
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539

		// Print Out Voting Form Footer Template
		$temp_pollvote .= "\t\t$template_footer\n";
		$temp_pollvote .= "\t</form>\n";
		$temp_pollvote .= "</div>\n";
		if($display_loading) {
			$poll_ajax_style = get_option('poll_ajax_style');
			if((int) $poll_ajax_style['loading'] === 1) {
				$temp_pollvote .= "<div id=\"polls-$poll_question_id-loading\" class=\"wp-polls-loading\"><img src=\"".plugins_url('wp-polls/images/loading.gif')."\" width=\"16\" height=\"16\" alt=\"".__('Loading', 'wp-polls')." ...\" title=\"".__('Loading', 'wp-polls')." ...\" class=\"wp-polls-image\" />&nbsp;".__('Loading', 'wp-polls')." ...</div>\n";
			}
		}
	} else {
		$temp_pollvote .= removeslashes(get_option('poll_template_disable'));
	}
	// Return Poll Vote Template
	return $temp_pollvote;
Lester Chan's avatar
EOL    
Lester Chan committed
540
541
542
543
}


### Function: Display Results Form
Lester Chan's avatar
Lester Chan committed
544
function display_pollresult( $poll_id, $user_voted = array(), $display_loading = true ) {
545
	global $wpdb;
Lester Chan's avatar
Lester Chan committed
546
	do_action( 'wp_polls_display_pollresult', $poll_id, $user_voted );
547
548
549
550
551
	$poll_id = (int) $poll_id;
	// User Voted
	if( empty( $user_voted ) ) {
		$user_voted = array();
	}
Lester Chan's avatar
Lester Chan committed
552
553
554
	if ( is_array( $user_voted ) ) {
		$user_voted = array_map( 'intval', $user_voted );
	} else {
Lester Chan's avatar
Lester Chan committed
555
		$user_voted = array( (int) $user_voted );
Lester Chan's avatar
Lester Chan committed
556
	}
Lester Chan's avatar
Lester Chan committed
557

558
559
560
561
562
563
564
565
566
567
568
569
	// Temp Poll Result
	$temp_pollresult = '';
	// Most/Least Variables
	$poll_most_answer = '';
	$poll_most_votes = 0;
	$poll_most_percentage = 0;
	$poll_least_answer = '';
	$poll_least_votes = 0;
	$poll_least_percentage = 0;
	// Get Poll Question Data
	$poll_question = $wpdb->get_row( $wpdb->prepare( "SELECT pollq_id, pollq_question, pollq_totalvotes, pollq_active, pollq_timestamp, pollq_expiry, pollq_multiple, pollq_totalvoters FROM $wpdb->pollsq WHERE pollq_id = %d LIMIT 1", $poll_id ) );
	// No poll could be loaded from the database
Lester Chan's avatar
Lester Chan committed
570
571
	if ( ! $poll_question ) {
		return removeslashes( get_option( 'poll_template_disable' ) );
572
573
574
575
576
577
578
	}
	// Poll Question Variables
	$poll_question_text = wp_kses_post( removeslashes( $poll_question->pollq_question ) );
	$poll_question_id = (int) $poll_question->pollq_id;
	$poll_question_totalvotes = (int) $poll_question->pollq_totalvotes;
	$poll_question_totalvoters = (int) $poll_question->pollq_totalvoters;
	$poll_question_active = (int) $poll_question->pollq_active;
Lester Chan's avatar
Lester Chan committed
579
580
581
582
	$poll_start_date = mysql2date( sprintf( __( '%s @ %s', 'wp-polls' ), get_option( 'date_format' ), get_option( 'time_format' ) ), gmdate( 'Y-m-d H:i:s', $poll_question->pollq_timestamp ) );
	$poll_expiry = trim( $poll_question->pollq_expiry );
	if ( empty( $poll_expiry ) ) {
		$poll_end_date  = __( 'No Expiry', 'wp-polls' );
583
	} else {
Lester Chan's avatar
Lester Chan committed
584
		$poll_end_date  = mysql2date( sprintf( __( '%s @ %s', 'wp-polls' ), get_option( 'date_format' ), get_option( 'time_format' ) ), gmdate( 'Y-m-d H:i:s', $poll_expiry ) );
585
586
	}
	$poll_multiple_ans = (int) $poll_question->pollq_multiple;
Lester Chan's avatar
Lester Chan committed
587
	$template_question = removeslashes( get_option( 'poll_template_resultheader' ) );
588
589
590
591
592
593
594
595
596
	$template_variables = array(
		'%POLL_QUESTION%' => $poll_question_text,
		'%POLL_ID%' => $poll_question_id,
		'%POLL_TOTALVOTES%' => $poll_question_totalvotes,
		'%POLL_TOTALVOTERS%' => $poll_question_totalvoters,
		'%POLL_START_DATE%' => $poll_start_date,
		'%POLL_END_DATE%' => $poll_end_date
	);

597
598
	$template_variables = apply_filters('wp_polls_template_resultheader_variables', $template_variables );
	$template_question  = apply_filters('wp_polls_template_resultheader_markup', $template_question, $poll_question, $template_variables );
599

600
	if($poll_multiple_ans > 0) {
Lester Chan's avatar
Lester Chan committed
601
		$template_question = str_replace( '%POLL_MULTIPLE_ANS_MAX%', $poll_multiple_ans, $template_question );
602
	} else {
Lester Chan's avatar
Lester Chan committed
603
		$template_question = str_replace( '%POLL_MULTIPLE_ANS_MAX%', '1', $template_question );
604
605
	}
	// Get Poll Answers Data
Lester Chan's avatar
Lester Chan committed
606
	list( $order_by, $sort_order ) = _polls_get_ans_result_sort();
607
608
	$poll_answers = $wpdb->get_results( $wpdb->prepare( "SELECT polla_aid, polla_answers, polla_votes FROM $wpdb->pollsa WHERE polla_qid = %d ORDER BY $order_by $sort_order", $poll_question_id ) );
	// If There Is Poll Question With Answers
Lester Chan's avatar
Lester Chan committed
609
	if ( $poll_question && $poll_answers ) {
610
611
		// Store The Percentage Of The Poll
		$poll_answer_percentage_array = array();
Lester Chan's avatar
Lester Chan committed
612
613
614
		// Is The Poll Total Votes or Voters 0?
		$poll_totalvotes_zero = $poll_question_totalvotes <= 0;
		$poll_totalvoters_zero = $poll_question_totalvoters <= 0;
615
616
617
		// Print Out Result Header Template
		$temp_pollresult .= "<div id=\"polls-$poll_question_id\" class=\"wp-polls\">\n";
		$temp_pollresult .= "\t\t$template_question\n";
Lester Chan's avatar
Lester Chan committed
618
		foreach ( $poll_answers as $poll_answer ) {
619
620
			// Poll Answer Variables
			$poll_answer_id = (int) $poll_answer->polla_aid;
Lester Chan's avatar
Lester Chan committed
621
			$poll_answer_text = wp_kses_post( removeslashes( $poll_answer->polla_answers ) );
622
623
			$poll_answer_votes = (int) $poll_answer->polla_votes;
			// Calculate Percentage And Image Bar Width
624
625
626
			$poll_answer_percentage = 0;
			$poll_multiple_answer_percentage = 0;
			$poll_answer_imagewidth = 1;
Lester Chan's avatar
Lester Chan committed
627
			if ( ! $poll_totalvotes_zero && ! $poll_totalvoters_zero && $poll_answer_votes > 0 ) {
628
629
				$poll_answer_percentage = round( ( $poll_answer_votes / $poll_question_totalvotes ) * 100 );
				$poll_multiple_answer_percentage = round( ( $poll_answer_votes / $poll_question_totalvoters ) * 100 );
Lester Chan's avatar
Lester Chan committed
630
631
				$poll_answer_imagewidth = round( $poll_answer_percentage );
				if ( $poll_answer_imagewidth === 100 ) {
632
					$poll_answer_imagewidth = 99;
633
634
635
636
				}
			}
			// Make Sure That Total Percentage Is 100% By Adding A Buffer To The Last Poll Answer
			$round_percentage = apply_filters( 'wp_polls_round_percentage', false );
Lester Chan's avatar
Lester Chan committed
637
638
639
640
641
642
643
			if ( $round_percentage && $poll_multiple_ans === 0 ) {
				$poll_answer_percentage_array[] = $poll_answer_percentage;
				if ( count( $poll_answer_percentage_array ) === count( $poll_answers ) ) {
					$percentage_error_buffer = 100 - array_sum( $poll_answer_percentage_array );
					$poll_answer_percentage += $percentage_error_buffer;
					if ( $poll_answer_percentage < 0 ) {
						$poll_answer_percentage = 0;
644
645
646
647
					}
				}
			}

648
649
650
651
652
653
654
655
656
657
			$template_variables = array(
				'%POLL_ID%' => $poll_question_id,
				'%POLL_ANSWER_ID%' => $poll_answer_id,
				'%POLL_ANSWER%' => $poll_answer_text,
				'%POLL_ANSWER_TEXT%' => htmlspecialchars( wp_strip_all_tags( $poll_answer_text ) ),
				'%POLL_ANSWER_VOTES%' => number_format_i18n( $poll_answer_votes ),
				'%POLL_ANSWER_PERCENTAGE%' => $poll_answer_percentage,
				'%POLL_MULTIPLE_ANSWER_PERCENTAGE%' => $poll_multiple_answer_percentage,
				'%POLL_ANSWER_IMAGEWIDTH%' => $poll_answer_imagewidth
			);
658
659
			$template_variables = apply_filters('wp_polls_template_resultbody_variables', $template_variables);

660
			// Let User See What Options They Voted
661
			if ( in_array( $poll_answer_id, $user_voted, true ) ) {
662
				// Results Body Variables
Lester Chan's avatar
Lester Chan committed
663
				$template_answer = removeslashes( get_option( 'poll_template_resultbody2' ) );
664
				$template_answer = apply_filters('wp_polls_template_resultbody2_markup', $template_answer, $poll_answer, $template_variables);
665
666
			} else {
				// Results Body Variables
Lester Chan's avatar
Lester Chan committed
667
				$template_answer = removeslashes (get_option( 'poll_template_resultbody' ) );
668
				$template_answer = apply_filters('wp_polls_template_resultbody_markup', $template_answer, $poll_answer, $template_variables);
669
			}
670
671
672
673

			// Print Out Results Body Template
			$temp_pollresult .= "\t\t$template_answer\n";

674
			// Get Most Voted Data
Lester Chan's avatar
Lester Chan committed
675
			if ( $poll_answer_votes > $poll_most_votes ) {
676
677
678
679
680
				$poll_most_answer = $poll_answer_text;
				$poll_most_votes = $poll_answer_votes;
				$poll_most_percentage = $poll_answer_percentage;
			}
			// Get Least Voted Data
Lester Chan's avatar
Lester Chan committed
681
			if ( $poll_least_votes === 0 ) {
682
683
				$poll_least_votes = $poll_answer_votes;
			}
Lester Chan's avatar
Lester Chan committed
684
			if ( $poll_answer_votes <= $poll_least_votes ) {
685
686
687
688
689
690
				$poll_least_answer = $poll_answer_text;
				$poll_least_votes = $poll_answer_votes;
				$poll_least_percentage = $poll_answer_percentage;
			}
		}
		// Results Footer Variables
691
692
693
694
695
696
697
698
699
700
701
702
703
		$template_variables = array(
			'%POLL_START_DATE%' => $poll_start_date,
			'%POLL_END_DATE%' => $poll_end_date,
			'%POLL_ID%' => $poll_question_id,
			'%POLL_TOTALVOTES%' => number_format_i18n( $poll_question_totalvotes ),
			'%POLL_TOTALVOTERS%' => number_format_i18n( $poll_question_totalvoters ),
			'%POLL_MOST_ANSWER%' => $poll_most_answer,
			'%POLL_MOST_VOTES%' => number_format_i18n( $poll_most_votes ),
			'%POLL_MOST_PERCENTAGE%' => $poll_most_percentage,
			'%POLL_LEAST_ANSWER%' => $poll_least_answer,
			'%POLL_LEAST_VOTES%' => number_format_i18n( $poll_least_votes ),
			'%POLL_LEAST_PERCENTAGE%' => $poll_least_percentage
		);
704
705
		$template_variables = apply_filters('wp_polls_template_resultfooter_variables', $template_variables );

Lester Chan's avatar
Lester Chan committed
706
707
		if ( ! empty( $user_voted ) || $poll_question_active === 0 || ! check_allowtovote() ) {
			$template_footer = removeslashes( get_option( 'poll_template_resultfooter' ) );
708
			$template_footer = apply_filters('wp_polls_template_resultfooter_markup', $template_footer, $poll_question, $template_variables);
709
		} else {
Lester Chan's avatar
Lester Chan committed
710
			$template_footer = removeslashes( get_option( 'poll_template_resultfooter2' ) );
711
			$template_footer = apply_filters('wp_polls_template_resultfooter2_markup', $template_footer, $poll_question, $template_variables);
712
		}
Lester Chan's avatar
Lester Chan committed
713
714
		if ( $poll_multiple_ans > 0 ) {
			$template_footer = str_replace( '%POLL_MULTIPLE_ANS_MAX%', $poll_multiple_ans, $template_footer );
715
		} else {
Lester Chan's avatar
Lester Chan committed
716
			$template_footer = str_replace( '%POLL_MULTIPLE_ANS_MAX%', '1', $template_footer );
717
718
719
720
721
		}
		// Print Out Results Footer Template
		$temp_pollresult .= "\t\t$template_footer\n";
		$temp_pollresult .= "\t\t<input type=\"hidden\" id=\"poll_{$poll_question_id}_nonce\" name=\"wp-polls-nonce\" value=\"".wp_create_nonce('poll_'.$poll_question_id.'-nonce')."\" />\n";
		$temp_pollresult .= "</div>\n";
Lester Chan's avatar
Lester Chan committed
722
723
724
		if ( $display_loading ) {
			$poll_ajax_style = get_option( 'poll_ajax_style' );
			if ( (int) $poll_ajax_style['loading'] === 1 ) {
725
726
727
728
				$temp_pollresult .= "<div id=\"polls-$poll_question_id-loading\" class=\"wp-polls-loading\"><img src=\"".plugins_url('wp-polls/images/loading.gif')."\" width=\"16\" height=\"16\" alt=\"".__('Loading', 'wp-polls')." ...\" title=\"".__('Loading', 'wp-polls')." ...\" class=\"wp-polls-image\" />&nbsp;".__('Loading', 'wp-polls')." ...</div>\n";
			}
		}
	} else {
Lester Chan's avatar
Lester Chan committed
729
		$temp_pollresult .= removeslashes( get_option ('poll_template_disable' ) );
730
731
	}
	// Return Poll Result
732
	return apply_filters( 'wp_polls_result_markup', $temp_pollresult );
Lester Chan's avatar
EOL    
Lester Chan committed
733
734
735
736
}


### Function: Get IP Address
Lester Chan's avatar
Lester Chan committed
737
if ( ! function_exists( 'get_ipaddress' ) ) {
738
	function get_ipaddress() {
739
		foreach ( array( 'HTTP_CF_CONNECTING_IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR' ) as $key ) {
740
741
742
743
744
745
746
747
748
749
			if ( array_key_exists( $key, $_SERVER ) === true ) {
				foreach ( explode( ',', $_SERVER[$key] ) as $ip ) {
					$ip = trim( $ip );
					if ( filter_var( $ip, FILTER_VALIDATE_IP ) !== false ) {
						return esc_attr( $ip );
					}
				}
			}
		}
	}
Lester Chan's avatar
EOL    
Lester Chan committed
750
}
751
function poll_get_ipaddress() {
752
	return apply_filters( 'wp_polls_ipaddress', wp_hash( get_ipaddress() ) );
753
754
755
756
}
function poll_get_hostname() {
	$hostname = gethostbyaddr( get_ipaddress() );
	if ( $hostname === get_ipaddress() ) {
757
		$hostname = wp_privacy_anonymize_ip( get_ipaddress() );
758
	}
Lester Chan's avatar
EOL    
Lester Chan committed
759

760
	if ( false !== $hostname ) {
761
		$hostname = substr( $hostname, strpos( $hostname, '.' ) + 1 );
762
763
	}

764
	return apply_filters( 'wp_polls_hostname', $hostname );
765
}
Lester Chan's avatar
EOL    
Lester Chan committed
766
767
768
769

### Function: Short Code For Inserting Polls Archive Into Page
add_shortcode('page_polls', 'poll_page_shortcode');
function poll_page_shortcode($atts) {
770
	return polls_archive();
Lester Chan's avatar
EOL    
Lester Chan committed
771
772
773
774
}


### Function: Short Code For Inserting Polls Into Posts
775
add_shortcode( 'poll', 'poll_shortcode' );
776
function poll_shortcode( $atts ) {
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
	$attributes = shortcode_atts( array( 'id' => 0, 'type' => 'vote' ), $atts );
	if( ! is_feed() ) {
		$id = (int) $attributes['id'];

		// To maintain backward compatibility with [poll=1]. Props @tz-ua
		if( ! $id && isset( $atts[0] ) ) {
			$id = (int) trim( $atts[0], '="\'' );
		}

		if( $attributes['type'] === 'vote' ) {
			return get_poll( $id, false );
		} elseif( $attributes['type'] === 'result' ) {
			return display_pollresult( $id );
		}
	} else {
		return __( 'Note: There is a poll embedded within this post, please visit the site to participate in this post\'s poll.', 'wp-polls' );
	}
Lester Chan's avatar
EOL    
Lester Chan committed
794
795
796
797
798
}


### Function: Get Poll Question Based On Poll ID
if(!function_exists('get_poll_question')) {
799
800
801
802
803
804
	function get_poll_question($poll_id) {
		global $wpdb;
		$poll_id = (int) $poll_id;
		$poll_question = $wpdb->get_var( $wpdb->prepare( "SELECT pollq_question FROM $wpdb->pollsq WHERE pollq_id = %d LIMIT 1", $poll_id ) );
		return wp_kses_post( removeslashes( $poll_question ) );
	}
Lester Chan's avatar
EOL    
Lester Chan committed
805
806
807
808
809
}


### Function: Get Poll Total Questions
if(!function_exists('get_pollquestions')) {
810
811
812
813
814
815
816
817
818
	function get_pollquestions($display = true) {
		global $wpdb;
		$totalpollq = (int) $wpdb->get_var("SELECT COUNT(pollq_id) FROM $wpdb->pollsq");
		if($display) {
			echo $totalpollq;
		} else {
			return $totalpollq;
		}
	}
Lester Chan's avatar
EOL    
Lester Chan committed
819
820
821
822
823
}


### Function: Get Poll Total Answers
if(!function_exists('get_pollanswers')) {
824
825
826
827
828
829
830
831
832
	function get_pollanswers($display = true) {
		global $wpdb;
		$totalpolla = (int) $wpdb->get_var("SELECT COUNT(polla_aid) FROM $wpdb->pollsa");
		if($display) {
			echo $totalpolla;
		} else {
			return $totalpolla;
		}
	}
Lester Chan's avatar
EOL    
Lester Chan committed
833
834
835
836
837
}


### Function: Get Poll Total Votes
if(!function_exists('get_pollvotes')) {
838
839
840
841
842
843
844
845
846
	function get_pollvotes($display = true) {
		global $wpdb;
		$totalvotes = (int) $wpdb->get_var("SELECT SUM(pollq_totalvotes) FROM $wpdb->pollsq");
		if($display) {
			echo $totalvotes;
		} else {
			return $totalvotes;
		}
	}
Lester Chan's avatar
EOL    
Lester Chan committed
847
848
}

Thomas Brace's avatar
Thomas Brace committed
849
850
851
852
853
### Function: Get Poll Votes Based on Poll ID
if(!function_exists('get_pollvotes_by_id')) {
	function get_pollvotes_by_id($poll_id, $display = true) {
		global $wpdb;
		$poll_id = (int) $poll_id;
854
		$totalvotes = (int) $wpdb->get_var( $wpdb->prepare("SELECT pollq_totalvotes FROM $wpdb->pollsq WHERE pollq_id = %d LIMIT 1", $poll_id));
Thomas Brace's avatar
Thomas Brace committed
855
856
857
858
859
860
861
862
		if($display) {
			echo $totalvotes;
		} else {
			return $totalvotes;
		}
	}
}

Lester Chan's avatar
EOL    
Lester Chan committed
863
864
865

### Function: Get Poll Total Voters
if(!function_exists('get_pollvoters')) {
866
867
868
869
870
871
872
873
874
	function get_pollvoters($display = true) {
		global $wpdb;
		$totalvoters = (int) $wpdb->get_var("SELECT SUM(pollq_totalvoters) FROM $wpdb->pollsq");
		if($display) {
			echo $totalvoters;
		} else {
			return $totalvoters;
		}
	}
Lester Chan's avatar
EOL    
Lester Chan committed
875
876
}

877
### Function: Get Poll Time Based on Poll ID and Date Format
Lester Chan's avatar
Lester Chan committed
878
879
if ( ! function_exists( 'get_polltime' ) ) {
	function get_polltime( $poll_id, $date_format = 'd/m/Y', $display = true ) {
Thomas Brace's avatar
Thomas Brace committed
880
881
		global $wpdb;
		$poll_id = (int) $poll_id;
Lester Chan's avatar
Lester Chan committed
882
		$timestamp = (int) $wpdb->get_var( $wpdb->prepare( "SELECT pollq_timestamp FROM $wpdb->pollsq WHERE pollq_id = %d LIMIT 1", $poll_id ) );
Thomas Brace's avatar
Thomas Brace committed
883
		$formatted_date = date( $date_format, $timestamp );
Lester Chan's avatar
Lester Chan committed
884
		if ( $display ) {
885
			echo $formatted_date;
Thomas Brace's avatar
Thomas Brace committed
886
		} else {
887
			return $formatted_date;
Thomas Brace's avatar
Thomas Brace committed
888
889
890
891
		}
	}
}

Lester Chan's avatar
EOL    
Lester Chan committed
892
893
894

### Function: Check Voted To Get Voted Answer
function check_voted_multiple($poll_id, $polls_ips) {
895
896
897
898
899
900
901
902
903
	if(!empty($_COOKIE["voted_$poll_id"])) {
		return explode(',', $_COOKIE["voted_$poll_id"]);
	} else {
		if($polls_ips) {
			return $polls_ips;
		} else {
			return array();
		}
	}
Lester Chan's avatar
EOL    
Lester Chan committed
904
905
906
907
908
}


### Function: Polls Archive Link
function polls_archive_link($page) {
909
910
911
912
913
914
915
916
917
	$polls_archive_url = get_option('poll_archive_url');
	if($page > 0) {
		if(strpos($polls_archive_url, '?') !== false) {
			$polls_archive_url = "$polls_archive_url&amp;poll_page=$page";
		} else {
			$polls_archive_url = "$polls_archive_url?poll_page=$page";
		}
	}
	return $polls_archive_url;
Lester Chan's avatar
EOL    
Lester Chan committed
918
919
920
921
922
}


### Function: Displays Polls Archive Link
function display_polls_archive_link($display = true) {
923
924
925
926
927
928
929
	$template_pollarchivelink = removeslashes(get_option('poll_template_pollarchivelink'));
	$template_pollarchivelink = str_replace("%POLL_ARCHIVE_URL%", get_option('poll_archive_url'), $template_pollarchivelink);
	if($display) {
		echo $template_pollarchivelink;
	} else{
		return $template_pollarchivelink;
	}
Lester Chan's avatar
EOL    
Lester Chan committed
930
931
932
933
934
}


### Function: Display Polls Archive
function polls_archive() {
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
	do_action('wp_polls_polls_archive');
	global $wpdb, $in_pollsarchive;
	// Polls Variables
	$in_pollsarchive = true;
	$page = isset($_GET['poll_page']) ? (int) sanitize_key( $_GET['poll_page'] ) : 0;
	$polls_questions = array();
	$polls_answers = array();
	$polls_ips = array();
	$polls_perpage = (int) get_option('poll_archive_perpage');
	$poll_questions_ids = '0';
	$poll_voted = false;
	$poll_voted_aid = 0;
	$poll_id = 0;
	$pollsarchive_output_archive = '';
	$polls_type = (int) get_option('poll_archive_displaypoll');
	$polls_type_sql = '';
	// Determine What Type Of Polls To Show
	switch($polls_type) {
		case 1:
			$polls_type_sql = 'pollq_active = 0';
			break;
		case 2:
			$polls_type_sql = 'pollq_active = 1';
			break;
		case 3:
			$polls_type_sql = 'pollq_active IN (0,1)';
			break;
	}
	// Get Total Polls
	$total_polls = $wpdb->get_var("SELECT COUNT(pollq_id) FROM $wpdb->pollsq WHERE $polls_type_sql AND pollq_active != -1");

	// Calculate Paging
	$numposts = $total_polls;
	$perpage = $polls_perpage;
	$max_page = ceil($numposts/$perpage);
	if(empty($page) || $page == 0) {
		$page = 1;
	}
	$offset = ($page-1) * $perpage;
	$pages_to_show = 10;
	$pages_to_show_minus_1 = $pages_to_show-1;
	$half_page_start = floor($pages_to_show_minus_1/2);
	$half_page_end = ceil($pages_to_show_minus_1/2);
	$start_page = $page - $half_page_start;
	if($start_page <= 0) {
		$start_page = 1;
	}
	$end_page = $page + $half_page_end;
	if(($end_page - $start_page) !== $pages_to_show_minus_1) {
		$end_page = $start_page + $pages_to_show_minus_1;
	}
	if($end_page > $max_page) {
		$start_page = $max_page - $pages_to_show_minus_1;
		$end_page = $max_page;
	}
	if($start_page <= 0) {
		$start_page = 1;
	}
	if(($offset + $perpage) > $numposts) {
		$max_on_page = $numposts;
	} else {
		$max_on_page = ($offset + $perpage);
	}
	if (($offset + 1) > ($numposts)) {
		$display_on_page = $numposts;
	} else {
		$display_on_page = ($offset + 1);
	}

	// Get Poll Questions
	$questions = $wpdb->get_results("SELECT * FROM $wpdb->pollsq WHERE $polls_type_sql ORDER BY pollq_id DESC LIMIT $offset, $polls_perpage");
	if($questions) {
		foreach($questions as $question) {
			$polls_questions[] = array( 'id' => (int) $question->pollq_id, 'question' => wp_kses_post( removeslashes( $question->pollq_question ) ), 'timestamp' => $question->pollq_timestamp, 'totalvotes' => (int) $question->pollq_totalvotes, 'start' => $question->pollq_timestamp, 'end' => trim( $question->pollq_expiry ), 'multiple' => (int) $question->pollq_multiple, 'totalvoters' => (int) $question->pollq_totalvoters );
			$poll_questions_ids .= (int) $question->pollq_id . ', ';
		}
		$poll_questions_ids = substr($poll_questions_ids, 0, -2);
	}

	// Get Poll Answers
	list($order_by, $sort_order) = _polls_get_ans_result_sort();
	$answers = $wpdb->get_results("SELECT polla_aid, polla_qid, polla_answers, polla_votes FROM $wpdb->pollsa WHERE polla_qid IN ($poll_questions_ids) ORDER BY $order_by $sort_order");
	if($answers) {
		foreach($answers as $answer) {
			$polls_answers[(int)$answer->polla_qid][] = array( 'aid' => (int)$answer->polla_aid, 'qid' => (int) $answer->polla_qid, 'answers' => wp_kses_post( removeslashes( $answer->polla_answers ) ), 'votes' => (int) $answer->polla_votes );
		}
	}

	// Get Poll IPs
1024
	$ips = $wpdb->get_results( "SELECT pollip_qid, pollip_aid FROM $wpdb->pollsip WHERE pollip_qid IN ($poll_questions_ids) AND pollip_ip = '" . poll_get_ipaddress() . "' ORDER BY pollip_qid ASC" );
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
	if($ips) {
		foreach($ips as $ip) {
			$polls_ips[(int) $ip->pollip_qid][] = (int) $ip->pollip_aid;
		}
	}
	// Poll Archives
	$pollsarchive_output_archive .= "<div class=\"wp-polls wp-polls-archive\">\n";
	foreach($polls_questions as $polls_question) {
		// Most/Least Variables
		$poll_most_answer = '';
		$poll_most_votes = 0;
		$poll_most_percentage = 0;
		$poll_least_answer = '';
		$poll_least_votes = 0;
		$poll_least_percentage = 0;
		// Is The Poll Total Votes 0?
Lester Chan's avatar
Lester Chan committed
1041
1042
		$poll_totalvotes_zero = $polls_question['totalvotes'] <= 0;
		$poll_totalvoters_zero = $polls_question['totalvoters'] <= 0;
Lester Chan's avatar
Lester Chan committed
1043
1044
1045
1046
1047
1048
		$poll_start_date = mysql2date(sprintf(__('%s @ %s', 'wp-polls'), get_option('date_format'), get_option('time_format')), gmdate('Y-m-d H:i:s', $polls_question['start']));
		if(empty($polls_question['end'])) {
			$poll_end_date  = __('No Expiry', 'wp-polls');
		} else {
			$poll_end_date  = mysql2date(sprintf(__('%s @ %s', 'wp-polls'), get_option('date_format'), get_option('time_format')), gmdate('Y-m-d H:i:s', $polls_question['end']));
		}
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
		// Archive Poll Header
		$template_archive_header = removeslashes(get_option('poll_template_pollarchiveheader'));
		// Poll Question Variables
		$template_question = removeslashes(get_option('poll_template_resultheader'));
		$template_question = str_replace("%POLL_QUESTION%", $polls_question['question'], $template_question);
		$template_question = str_replace("%POLL_ID%", $polls_question['id'], $template_question);
		$template_question = str_replace("%POLL_TOTALVOTES%", number_format_i18n($polls_question['totalvotes']), $template_question);
		$template_question = str_replace("%POLL_TOTALVOTERS%", number_format_i18n($polls_question['totalvoters']), $template_question);
		$template_question = str_replace("%POLL_START_DATE%", $poll_start_date, $template_question);
		$template_question = str_replace("%POLL_END_DATE%", $poll_end_date, $template_question);
		if($polls_question['multiple'] > 0) {
			$template_question = str_replace("%POLL_MULTIPLE_ANS_MAX%", $polls_question['multiple'], $template_question);
		} else {
			$template_question = str_replace("%POLL_MULTIPLE_ANS_MAX%", '1', $template_question);
		}
		// Print Out Result Header Template
		$pollsarchive_output_archive .= $template_archive_header;
		$pollsarchive_output_archive .= $template_question;
		// Store The Percentage Of The Poll
		$poll_answer_percentage_array = array();
		foreach($polls_answers[$polls_question['id']] as $polls_answer) {
			// Calculate Percentage And Image Bar Width
1071
1072
1073
			$poll_answer_percentage = 0;
			$poll_multiple_answer_percentage = 0;
			$poll_answer_imagewidth = 1;
Lester Chan's avatar
Lester Chan committed
1074
			if ( ! $poll_totalvotes_zero && ! $poll_totalvoters_zero && $polls_answer['votes'] > 0 ) {
1075
1076
1077
				$poll_answer_percentage = round( ( $polls_answer['votes'] / $polls_question['totalvotes'] ) * 100 );
				$poll_multiple_answer_percentage = round( ( $polls_answer['votes'] / $polls_question['totalvoters'] ) * 100 );
				$poll_answer_imagewidth = round( $poll_answer_percentage * 0.9 );
1078
1079
1080
1081
1082
1083
			}
			// Make Sure That Total Percentage Is 100% By Adding A Buffer To The Last Poll Answer
			if($polls_question['multiple'] === 0) {
				$poll_answer_percentage_array[] = $poll_answer_percentage;
				if(count($poll_answer_percentage_array) === count($polls_answers[$polls_question['id']])) {
					$percentage_error_buffer = 100 - array_sum($poll_answer_percentage_array);
1084
					$poll_answer_percentage += $percentage_error_buffer;
1085
1086
1087
1088
1089
1090
1091
					if($poll_answer_percentage < 0) {
						$poll_answer_percentage = 0;
					}
				}
			}
			$polls_answer['answers'] = wp_kses_post( $polls_answer['answers'] );
			// Let User See What Options They Voted
1092
			if (isset( $polls_ips[$polls_question['id']] ) && in_array( $polls_answer['aid'], check_voted_multiple( $polls_question['id'], $polls_ips[$polls_question['id']] ), true ) ) {
1093
1094
1095
1096
				$template_answer = removeslashes(get_option('poll_template_resultbody2'));
			} else {
				$template_answer = removeslashes(get_option('poll_template_resultbody'));
			}
1097

Lester Chan's avatar
Lester Chan committed
1098
			$template_answer = str_replace( array(
1099
1100
1101
				'%POLL_ID%',
				'%POLL_ANSWER_ID%',
				'%POLL_ANSWER%',
1102
				'%POLL_ANSWER_TEXT%',
1103
				'%POLL_ANSWER_VOTES%',
1104
				'%POLL_ANSWER_PERCENTAGE%',
1105
1106
				'%POLL_MULTIPLE_ANSWER_PERCENTAGE%',
				'%POLL_ANSWER_IMAGEWIDTH%',
Lester Chan's avatar
Lester Chan committed
1107
			), array(
1108
1109
1110
1111
1112
1113
1114
1115
				$polls_question['id'],
				$polls_answer['aid'],
				$polls_answer['answers'],
				htmlspecialchars( wp_strip_all_tags( $polls_answer['answers'] ) ),
				number_format_i18n( $polls_answer['votes'] ),
				$poll_answer_percentage,
				$poll_multiple_answer_percentage,
				$poll_answer_imagewidth,
Lester Chan's avatar
Lester Chan committed
1116
			),
1117
1118
1119
1120
1121
				$template_answer );

			// Print Out Results Body Template
			$pollsarchive_output_archive .= $template_answer;

1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
			// Get Most Voted Data
			if($polls_answer['votes'] > $poll_most_votes) {
				$poll_most_answer = $polls_answer['answers'];
				$poll_most_votes = $polls_answer['votes'];
				$poll_most_percentage = $poll_answer_percentage;
			}
			// Get Least Voted Data
			if($poll_least_votes === 0) {
				$poll_least_votes = $polls_answer['votes'];
			}
			if($polls_answer['votes'] <= $poll_least_votes) {
				$poll_least_answer = $polls_answer['answers'];
				$poll_least_votes = $polls_answer['votes'];
				$poll_least_percentage = $poll_answer_percentage;
			}
		}
		// Results Footer Variables
		$template_footer = removeslashes(get_option('poll_template_resultfooter'));
		$template_footer = str_replace("%POLL_ID%", $polls_question['id'], $template_footer);
		$template_footer = str_replace("%POLL_START_DATE%", $poll_start_date, $template_footer);
		$template_footer = str_replace("%POLL_END_DATE%", $poll_end_date, $template_footer);
		$template_footer = str_replace("%POLL_TOTALVOTES%", number_format_i18n($polls_question['totalvotes']), $template_footer);
		$template_footer = str_replace("%POLL_TOTALVOTERS%", number_format_i18n($polls_question['totalvoters']), $template_footer);
		$template_footer = str_replace("%POLL_MOST_ANSWER%", $poll_most_answer, $template_footer);
		$template_footer = str_replace("%POLL_MOST_VOTES%", number_format_i18n($poll_most_votes), $template_footer);
		$template_footer = str_replace("%POLL_MOST_PERCENTAGE%", $poll_most_percentage, $template_footer);
		$template_footer = str_replace("%POLL_LEAST_ANSWER%", $poll_least_answer, $template_footer);
		$template_footer = str_replace("%POLL_LEAST_VOTES%", number_format_i18n($poll_least_votes), $template_footer);
		$template_footer = str_replace("%POLL_LEAST_PERCENTAGE%", $poll_least_percentage, $template_footer);
		if($polls_question['multiple'] > 0) {
			$template_footer  = str_replace("%POLL_MULTIPLE_ANS_MAX%", $polls_question['multiple'], $template_footer);
		} else {
			$template_footer  = str_replace("%POLL_MULTIPLE_ANS_MAX%", '1', $template_footer);
		}
		// Archive Poll Footer
		$template_archive_footer = removeslashes(get_option('poll_template_pollarchivefooter'));
		$template_archive_footer = str_replace("%POLL_START_DATE%", $poll_start_date, $template_archive_footer);
		$template_archive_footer = str_replace("%POLL_END_DATE%", $poll_end_date, $template_archive_footer);
		$template_archive_footer = str_replace("%POLL_TOTALVOTES%", number_format_i18n($polls_question['totalvotes']), $template_archive_footer);
		$template_archive_footer = str_replace("%POLL_TOTALVOTERS%", number_format_i18n($polls_question['totalvoters']), $template_archive_footer);
		$template_archive_footer = str_replace("%POLL_MOST_ANSWER%", $poll_most_answer, $template_archive_footer);
		$template_archive_footer = str_replace("%POLL_MOST_VOTES%", number_format_i18n($poll_most_votes), $template_archive_footer);
		$template_archive_footer = str_replace("%POLL_MOST_PERCENTAGE%", $poll_most_percentage, $template_archive_footer);
		$template_archive_footer = str_replace("%POLL_LEAST_ANSWER%", $poll_least_answer, $template_archive_footer);
		$template_archive_footer = str_replace("%POLL_LEAST_VOTES%", number_format_i18n($poll_least_votes), $template_archive_footer);
		$template_archive_footer = str_replace("%POLL_LEAST_PERCENTAGE%", $poll_least_percentage, $template_archive_footer);
		if($polls_question['multiple'] > 0) {
			$template_archive_footer  = str_replace("%POLL_MULTIPLE_ANS_MAX%", $polls_question['multiple'], $template_archive_footer);
		} else {
			$template_archive_footer  = str_replace("%POLL_MULTIPLE_ANS_MAX%", '1', $template_archive_footer);
		}
		// Print Out Results Footer Template
		$pollsarchive_output_archive .= $template_footer;
		// Print Out Archive Poll Footer Template
		$pollsarchive_output_archive .= $template_archive_footer;
	}
	$pollsarchive_output_archive .= "</div>\n";

	// Polls Archive Paging
	if($max_page > 1) {
		$pollsarchive_output_archive .= removeslashes(get_option('poll_template_pollarchivepagingheader'));
		if(function_exists('wp_pagenavi')) {
			$pollsarchive_output_archive .= '<div class="wp-pagenavi">'."\n";
		} else {
			$pollsarchive_output_archive .= '<div class="wp-polls-paging">'."\n";
		}
		$pollsarchive_output_archive .= '<span class="pages">&#8201;'.sprintf(__('Page %s of %s', 'wp-polls'), number_format_i18n($page), number_format_i18n($max_page)).'&#8201;</span>';
		if ($start_page >= 2 && $pages_to_show < $max_page) {
			$pollsarchive_output_archive .= '<a href="'.polls_archive_link(1).'" title="'.__('&laquo; First', 'wp-polls').'">&#8201;'.__('&laquo; First', 'wp-polls').'&#8201;</a>';
			$pollsarchive_output_archive .= '<span class="extend">...</span>';
		}
		if($page > 1) {
			$pollsarchive_output_archive .= '<a href="'.polls_archive_link(($page-1)).'" title="'.__('&laquo;', 'wp-polls').'">&#8201;'.__('&laquo;', 'wp-polls').'&#8201;</a>';
		}
		for($i = $start_page; $i  <= $end_page; $i++) {
			if($i === $page) {
				$pollsarchive_output_archive .= '<span class="current">&#8201;'.number_format_i18n($i).'&#8201;</span>';
			} else {
				$pollsarchive_output_archive .= '<a href="'.polls_archive_link($i).'" title="'.number_format_i18n($i).'">&#8201;'.number_format_i18n($i).'&#8201;</a>';
			}
		}
		if(empty($page) || ($page+1) <= $max_page) {
			$pollsarchive_output_archive .= '<a href="'.polls_archive_link(($page+1)).'" title="'.__('&raquo;', 'wp-polls').'">&#8201;'.__('&raquo;', 'wp-polls').'&#8201;</a>';
		}
		if ($end_page < $max_page) {
			$pollsarchive_output_archive .= '<span class="extend">...</span>';
			$pollsarchive_output_archive .= '<a href="'.polls_archive_link($max_page).'" title="'.__('Last &raquo;', 'wp-polls').'">&#8201;'.__('Last &raquo;', 'wp-polls').'&#8201;</a>';
		}
		$pollsarchive_output_archive .= '</div>';
		$pollsarchive_output_archive .= removeslashes(get_option('poll_template_pollarchivepagingfooter'));
	}

	// Output Polls Archive Page
1215
	return apply_filters( 'wp_polls_archive', $pollsarchive_output_archive );
Lester Chan's avatar
EOL    
Lester Chan committed
1216
1217
1218
1219
1220
}


// Edit Timestamp Options
function poll_timestamp($poll_timestamp, $fieldname = 'pollq_timestamp', $display = 'block') {
1221
1222
	global $month;
	echo '<div id="'.$fieldname.'" style="display: '.$display.'">'."\n";
Lester Chan's avatar
Lester Chan committed
1223
	$day = (int) gmdate('j', $poll_timestamp);
1224
1225
1226
1227
1228
1229
1230
1231
1232
	echo '<select name="'.$fieldname.'_day" size="1">'."\n";
	for($i = 1; $i <=31; $i++) {
		if($day === $i) {
			echo "<option value=\"$i\" selected=\"selected\">$i</option>\n";
		} else {
			echo "<option value=\"$i\">$i</option>\n";
		}
	}
	echo '</select>&nbsp;&nbsp;'."\n";
Lester Chan's avatar
Lester Chan committed
1233
	$month2 = (int) gmdate('n', $poll_timestamp);
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
	echo '<select name="'.$fieldname.'_month" size="1">'."\n";
	for($i = 1; $i <= 12; $i++) {
		if ($i < 10) {
			$ii = '0'.$i;
		} else {
			$ii = $i;
		}
		if($month2 === $i) {
			echo "<option value=\"$i\" selected=\"selected\">$month[$ii]</option>\n";
		} else {
			echo "<option value=\"$i\">$month[$ii]</option>\n";
		}
	}
	echo '</select>&nbsp;&nbsp;'."\n";
Lester Chan's avatar
Lester Chan committed
1248
	$year = (int) gmdate('Y', $poll_timestamp);
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
	echo '<select name="'.$fieldname.'_year" size="1">'."\n";
	for($i = 2000; $i <= ($year+10); $i++) {
		if($year === $i) {
			echo "<option value=\"$i\" selected=\"selected\">$i</option>\n";
		} else {
			echo "<option value=\"$i\">$i</option>\n";
		}
	}
	echo '</select>&nbsp;@'."\n";
	echo '<span dir="ltr">'."\n";
Lester Chan's avatar
Lester Chan committed
1259
	$hour = (int) gmdate('H', $poll_timestamp);
1260
1261
1262
1263
1264
1265
1266
1267
1268
	echo '<select name="'.$fieldname.'_hour" size="1">'."\n";
	for($i = 0; $i < 24; $i++) {
		if($hour === $i) {
			echo "<option value=\"$i\" selected=\"selected\">$i</option>\n";
		} else {
			echo "<option value=\"$i\">$i</option>\n";
		}
	}
	echo '</select>&nbsp;:'."\n";
Lester Chan's avatar
Lester Chan committed
1269
	$minute = (int) gmdate('i', $poll_timestamp);
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
	echo '<select name="'.$fieldname.'_minute" size="1">'."\n";
	for($i = 0; $i < 60; $i++) {
		if($minute === $i) {
			echo "<option value=\"$i\" selected=\"selected\">$i</option>\n";
		} else {
			echo "<option value=\"$i\">$i</option>\n";
		}
	}

	echo '</select>&nbsp;:'."\n";
Lester Chan's avatar
Lester Chan committed
1280
	$second = (int) gmdate('s', $poll_timestamp);
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
	echo '<select name="'.$fieldname.'_second" size="1">'."\n";
	for($i = 0; $i <= 60; $i++) {
		if($second === $i) {
			echo "<option value=\"$i\" selected=\"selected\">$i</option>\n";
		} else {
			echo "<option value=\"$i\">$i</option>\n";
		}
	}
	echo '</select>'."\n";
	echo '</span>'."\n";
	echo '</div>'."\n";
Lester Chan's avatar
EOL    
Lester Chan committed
1292
1293
1294
1295
1296
}


### Function: Place Cron
function cron_polls_place() {
1297
1298
1299
1300
	wp_clear_scheduled_hook('polls_cron');
	if (!wp_next_scheduled('polls_cron')) {
		wp_schedule_event(time(), 'hourly', 'polls_cron');
	}
Lester Chan's avatar
EOL    
Lester Chan committed
1301
1302
1303
1304
1305
}

### Funcion: Check All Polls Status To Check If It Expires
add_action('polls_cron', 'cron_polls_status');
function cron_polls_status() {
1306
1307
	global $wpdb;
	// Close Poll
1308
	$close_polls = $wpdb->query("UPDATE $wpdb->pollsq SET pollq_active = 0 WHERE pollq_expiry < '".current_time('timestamp')."' AND pollq_expiry != 0 AND pollq_active != 0");
1309
1310
1311
1312
1313
1314
1315
	// Open Future Polls
	$active_polls = $wpdb->query("UPDATE $wpdb->pollsq SET pollq_active = 1 WHERE pollq_timestamp <= '".current_time('timestamp')."' AND pollq_active = -1");
	// Update Latest Poll If Future Poll Is Opened
	if($active_polls) {
		$update_latestpoll = update_option('poll_latestpoll', polls_latest_id());
	}
	return;
Lester Chan's avatar
EOL    
Lester Chan committed
1316
1317
1318
1319
1320
}


### Funcion: Get Latest Poll ID
function polls_latest_id() {
1321
1322
1323
	global $wpdb;
	$poll_id = $wpdb->get_var("SELECT pollq_id FROM $wpdb->pollsq WHERE pollq_active = 1 ORDER BY pollq_timestamp DESC LIMIT 1");
	return (int) $poll_id;
Lester Chan's avatar
EOL    
Lester Chan committed
1324
1325
1326
1327
1328
}


### Check If In Poll Archive Page
function in_pollarchive() {
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
	$poll_archive_url = get_option('poll_archive_url');
	$poll_archive_url_array = explode('/', $poll_archive_url);
	$poll_archive_url = $poll_archive_url_array[count($poll_archive_url_array)-1];
	if(empty($poll_archive_url)) {
		$poll_archive_url = $poll_archive_url_array[count($poll_archive_url_array)-2];
	}
	$current_url = esc_url_raw( $_SERVER['REQUEST_URI'] );
	if(strpos($current_url, $poll_archive_url) === false) {
		return false;
	}

	return true;
Lester Chan's avatar
EOL    
Lester Chan committed
1341
1342
}

1343
1344
1345
1346
1347
1348
1349
1350
function vote_poll_process($poll_id, $poll_aid_array = [])
{
	global $wpdb, $user_identity, $user_ID;

	do_action('wp_polls_vote_poll');

	$polla_aids = $wpdb->get_col( $wpdb->prepare( "SELECT polla_aid FROM $wpdb->pollsa WHERE polla_qid = %d", $poll_id ) );
	$is_real = count( array_intersect( $poll_aid_array, $polla_aids ) ) === count( $poll_aid_array );
Lester Chan's avatar
Lester Chan committed
1351

1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
	if( !$is_real ) {
		throw new InvalidArgumentException(sprintf(__('Invalid Answer to Poll ID #%s', 'wp-polls'), $poll_id));
	}

	if (!check_allowtovote()) {
		throw new InvalidArgumentException(sprintf(__('User is not allowed to vote for Poll ID #%s', 'wp-polls'), $poll_id));
	}

	if (empty($poll_aid_array)) {
		throw new InvalidArgumentException(sprintf(__('No anwsers given for Poll ID #%s', 'wp-polls'), $poll_id));
	}

	if($poll_id === 0) {
		throw new InvalidArgumentException(sprintf(__('Invalid Poll ID. Poll ID #%s', 'wp-polls'), $poll_id));
	}

	$is_poll_open = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->pollsq WHERE pollq_id = %d AND pollq_active = 1", $poll_id ) );
Lester Chan's avatar
Lester Chan committed
1369

1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428