Completed
Push — master ( 00af8d...0d3726 )
by Justin
07:13
created

admin.php ➔ wpsc_admin_include_coupon_js()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 11
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 23
rs 9.0856
1
<?php
2
/**
3
 * WP eCommerce Main Admin functions
4
 *
5
 * These are the main WPSC Admin functions
6
 *
7
 * @package wp-e-commerce
8
 * @since 3.7
9
 */
10
11
// admin includes
12
require_once( WPSC_FILE_PATH . '/wpsc-admin/display-update.page.php' );
13
require_once( WPSC_FILE_PATH . '/wpsc-admin/display-items.page.php' );
14
require_once( WPSC_FILE_PATH . '/wpsc-admin/display-upgrades.page.php' );
15
require_once( WPSC_FILE_PATH . '/wpsc-admin/includes/display-items-functions.php' );
16
require_once( WPSC_FILE_PATH . '/wpsc-admin/includes/product-functions.php' );
17
require_once( WPSC_FILE_PATH . '/wpsc-admin/includes/save-data.functions.php' );
18
require_once( WPSC_FILE_PATH . '/wpsc-admin/includes/duplicate-product-class.php' );
19
require_once( WPSC_FILE_PATH . '/wpsc-admin/includes/updating-functions.php' );
20
require_once( WPSC_FILE_PATH . '/wpsc-admin/display-coupons.php' );
21
require_once( WPSC_FILE_PATH . '/wpsc-includes/purchaselogs.class.php' );
22
require_once( WPSC_FILE_PATH . '/wpsc-includes/theming.class.php' );
23
require_once( WPSC_FILE_PATH . '/wpsc-admin/ajax.php' );
24
require_once( WPSC_FILE_PATH . '/wpsc-admin/init.php' );
25
require_once( WPSC_FILE_PATH . '/wpsc-admin/ajax-and-init.php' );
26
require_once( WPSC_FILE_PATH . '/wpsc-admin/display-options-settings.page.php' );
27
require_once( WPSC_FILE_PATH . '/wpsc-admin/db-upgrades/upgrade.php' );
28
require_once( WPSC_FILE_PATH . '/wpsc-admin/media.php' );
29
30
if ( ! get_option( 'wpsc_checkout_form_sets' ) ) {
31
	$form_sets = array( __( 'Default Checkout Forms', 'wp-e-commerce' ) );
32
	update_option( 'wpsc_checkout_form_sets', $form_sets );
33
}
34
35
// if we add and wpec admin javascript will add the localizations
36
add_filter( 'wpsc_javascript_localizations', '_wpsc_admin_localizations', 1 );
37
38
/**
39
 * wpsc_query_vars_product_list sets the ordering for the edit-products page list
40
 *
41
 * @since 3.8
42
 * @access public
43
 *
44
 * @uses get_option()   Gets option from the DB given key
45
 *
46
 * @param array     $vars  req  Default query arguments
47
 * @return array    $vars       Modified query arguments
48
 */
49
function wpsc_query_vars_product_list( $vars ){
50
51
	if( 'wpsc-product' != $vars['post_type'] || in_array( $vars['orderby'], array( 'meta_value_num', 'meta_value' ) ) )
52
	    return $vars;
53
54
	$vars['posts_per_archive_page'] = 0;
55
56
	if( 'dragndrop' == get_option( 'wpsc_sort_by' ) ){
57
		$vars['orderby'] = 'menu_order title';
58
		$vars['order'] = 'desc';
59
		$vars['nopaging'] = true;
0 ignored issues
show
introduced by
Disabling pagination is prohibited in VIP context, do not set nopaging to true ever.
Loading history...
60
	}
61
62
    return $vars;
63
}
64
65
/**
66
 * Admin Edit Posts Order
67
 *
68
 * @since 3.8.12
69
 * @access public
70
 *
71
 * @param   string  $orderby_sql  Order by SQL.
72
 * @return  string  Filtered order by SQL.
73
 */
74
function wpsc_admin_edit_posts_orderby( $orderby_sql ) {
75
	global $wp_query, $wpdb;
76
	if ( 'dragndrop' == get_option( 'wpsc_sort_by' ) ) {
77
		if ( function_exists( 'is_main_query' ) && is_main_query() && 'wpsc-product' == get_query_var( 'post_type' ) && is_tax( 'wpsc_product_category' ) ) {
78
			if ( ! empty( $orderby_sql ) )
79
				$orderby_sql = ', ' . $orderby_sql;
80
			$orderby_sql = " {$wpdb->term_relationships}.term_order ASC" . $orderby_sql;
81
			remove_filter( 'posts_orderby', 'wpsc_admin_edit_posts_orderby' );
82
		}
83
	}
84
	return $orderby_sql;
85
}
86
add_filter( 'posts_orderby', 'wpsc_admin_edit_posts_orderby' );
87
88
/**
89
 * setting the product & variations per page screen option to between 1 and 999
90
 *
91
 * @since 3.8
92
 * @access public
93
 *
94
 * @uses update_user_option()   Updates user option given userid, key, value
95
 *
96
 * @param           $status
97
 * @param string    $option     req     Name of option being saved
98
 * @param string    $value      req     Value of option being saved
99
 * @return $value after changes...
0 ignored issues
show
Documentation introduced by
The doc-type $value could not be parsed: Unknown type name "$value" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
100
 */
101
function wpsc_set_screen_option($status, $option, $value){
0 ignored issues
show
Unused Code introduced by
The parameter $status is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
102
	if( in_array($option, array ("edit_wpsc_variation_per_page","edit_wpsc_product_per_page", "wpsc_purchases_per_page" )) ){
0 ignored issues
show
introduced by
There must be no space between the Array keyword and the opening parenthesis
Loading history...
103
		if ( "edit_wpsc_variation_per_page" == $option ){
104
			global $user_ID;
105
			update_user_option($user_ID,'edit_wpsc-variation_per_page',$value);
106
		}
107
		return $value;
108
	}
109
}
110
add_filter('set-screen-option', 'wpsc_set_screen_option', 99, 3);
111
112
/**
113
 * Limit admin variation dropdown to show variantion sets only.
114
 *
115
 * @param   array   $args      Dropdown args.
116
 * @param   string  $taxonomy  Taxonomy.
117
 * @param   string  $context   Context.
118
 *
119
 * @since  4.0
120
 *
121
 * @return  array              Filtered dropdown args.
122
 */
123
function wpsc_variation_parent_dropdown_args( $args, $taxonomy, $context ) {
124
125
	if ( 'wpsc-variation' == $taxonomy && 'edit' == $context ) {
126
		$args['depth'] = 1;
127
	}
128
129
	return $args;
130
131
}
132
add_filter( 'taxonomy_parent_dropdown_args', 'wpsc_variation_parent_dropdown_args', 10, 3 );
133
134
/**
135
 * When rearranging the products for drag and drop it is easiest to arrange them when they are all on the same page...
136
 * @access public
137
 *
138
 * @since 3.8
139
 * @access public
140
 *
141
 * @uses get_option()   Gets option from the database given key
142
 *
143
 * @param int       $per_page   req     number of products per page
144
 * @param string    $post_type  req     name of current post type
145
 * @return $per_page after changes...
0 ignored issues
show
Documentation introduced by
The doc-type $per_page could not be parsed: Unknown type name "$per_page" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
146
 */
147
function wpsc_drag_and_drop_ordering($per_page, $post_type){
148
	global $wpdb;
149
	if ( 'wpsc-product' == $post_type && 'dragndrop' == get_option( 'wpsc_sort_by' ) && $count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE `post_type`='wpsc-product' AND `post_parent`=0" ) )
150
		$per_page = $count;
151
	return $per_page;
152
}
153
add_filter( 'request', 'wpsc_query_vars_product_list' );
154
add_filter( 'edit_posts_per_page' , 'wpsc_drag_and_drop_ordering', 10, 2 );
155
156
/**
157
 * Checks whether to display or hide the update wp-e-commerce link
158
 *
159
 * @since 3.8
160
 * @access public
161
 *
162
 * @uses get_option()   Gets option from DB given key
163
 *
164
 * @return boolean true - show link, false- hide link
165
 */
166
function wpsc_show_update_link() {
167
	global $wpdb;
168
	// Check if old product_list table exists
169
	// If it exists AND get_option wpsc_upgrade_complete is not true then return true
170
	$sql = 'SHOW TABLES LIKE "'.$wpdb->prefix.'wpsc_product_list"';
171
	$var = $wpdb->get_var( $sql );
172
	if ( !empty( $var ) && false == get_option( 'wpsc_hide_update' ) )
0 ignored issues
show
Coding Style introduced by
The if-else statement can be simplified to return !empty($var) && f...on('wpsc_hide_update');.
Loading history...
173
		return true;
174
	else
175
		return false;
176
}
177
178
/**
179
 * wpsc_admin_pages function, all the definitons of admin pages are stores here.
180
 * No parameters, returns nothing
181
 *
182
 * Fairly standard wordpress plugin API stuff for adding the admin pages, rearrange the order to rearrange the pages
183
 * The bits to display the options page first on first use may be buggy, but tend not to stick around long enough to be identified and fixed
184
 * if you find bugs, feel free to fix them.
185
 *
186
 * If the permissions are changed here, they will likewise need to be changed for the other sections of the admin that either use ajax
187
 * or bypass the normal download system.
188
 *
189
 * @access public
190
 *
191
 * @uses wpsc_show_update_link()    Decides whether or not to show the update link
192
 * @uses add_submenu_page()         Adds a WordPress submenu page
193
 * @uses apply_filters()            Calls wpsc_upgrades_cap allows hooking caps for adiministrator
194
 * @uses apply_filters()            Calls wpsc_coupon_cap allows filtering for the coupon caps
195
 * @uses add_options_page()         Adds a submenu to the settings page
196
 * @uses add_action()               Calls 'admin_print_scripts.$edit_options_page prints out WPEC admin scripts
197
 * @uses apply_filters()            Calls 'wpsc_additional_pages' Passes the page_hooks and product_page URL
198
 * @uses do_action()                Calls 'wpsc_add_submenu' Allows you to hook in to the WPEC menu
199
 * @uses update_option()            Updates option given key and value
200
 */
201
function wpsc_admin_pages() {
202
203
	// Code to enable or disable the debug page
204
	if ( isset( $_GET['wpsc_activate_debug_page'] ) ) {
205
		if ( 'true' == $_GET['wpsc_activate_debug_page'] ) {
206
			$_SESSION['wpsc_activate_debug_page'] = true;
0 ignored issues
show
introduced by
Usage of $_SESSION variable is prohibited.
Loading history...
207
		} else if ( 'false' == $_GET['wpsc_activate_debug_page'] ) {
208
				$_SESSION['wpsc_activate_debug_page'] = false;
0 ignored issues
show
introduced by
Usage of $_SESSION variable is prohibited.
Loading history...
209
			}
210
	}
211
212
	$store_upgrades_cap = apply_filters( 'wpsc_upgrades_cap', 'administrator' );
213
214
	$page_hooks = array();
215
216
	if ( wpsc_show_update_link() ) {
217
		$page_hooks[] = add_submenu_page( 'index.php', __( 'Update Store', 'wp-e-commerce' ), __( 'Store Update', 'wp-e-commerce' ), $store_upgrades_cap, 'wpsc-update', 'wpsc_display_update_page' );
218
	}
219
220
	$purchase_logs_cap = apply_filters( 'wpsc_purchase_logs_cap', 'administrator' );
221
	$page_hooks[] = $purchase_logs_page = add_submenu_page( 'index.php', __( 'Store Sales', 'wp-e-commerce' ), __( 'Store Sales', 'wp-e-commerce' ), $purchase_logs_cap, 'wpsc-purchase-logs', 'wpsc_display_purchase_logs_page' );
222
223
	$page_hooks[] = add_submenu_page( 'index.php', __( 'WPeC License', 'wp-e-commerce' ), __( 'WPeC Licensing', 'wp-e-commerce' ), $store_upgrades_cap, 'wpsc-upgrades', 'wpsc_display_upgrades_page' );
224
225
	// Set the base page for Products
226
	$products_page = 'edit.php?post_type=wpsc-product';
227
228
	$manage_coupon_cap = apply_filters( 'wpsc_coupon_cap', 'administrator' );
229
	$page_hooks[] = $edit_coupons_page = add_submenu_page( $products_page , __( 'Coupons', 'wp-e-commerce' ), __( 'Coupons', 'wp-e-commerce' ), $manage_coupon_cap, 'wpsc-edit-coupons', 'wpsc_display_coupons_page' );
230
231
	// Add Settings pages
232
	$page_hooks[] = $edit_options_page = add_options_page( __( 'Store Settings', 'wp-e-commerce' ), __( 'Store', 'wp-e-commerce' ), 'administrator', 'wpsc-settings', 'wpsc_display_settings_page' );
233
	add_action( 'admin_print_scripts-' . $edit_options_page , 'wpsc_print_admin_scripts' );
234
235
	$page_hooks = apply_filters( 'wpsc_additional_pages', $page_hooks, $products_page );
236
237
	do_action( 'wpsc_add_submenu' );
238
239
	// Include the javascript and CSS for this page
240
	// This is so important that I can't even express it in one line
241
242
	foreach ( $page_hooks as $page_hook ) {
243
		add_action( 'load-' . $page_hook, 'wpsc_admin_include_css_and_js_refac' );
244
245
		switch ( $page_hook ) {
246
247
		case $edit_options_page :
248
			add_action( 'load-' . $page_hook, 'wpsc_admin_include_optionspage_css_and_js' );
249
			break;
250
251
		case $purchase_logs_page :
252
			add_action( 'admin_head', 'wpsc_product_log_rss_feed' );
253
			add_action( 'load-' . $page_hook, 'wpsc_admin_include_purchase_logs_css_and_js' );
254
			break;
255
256
		case $edit_coupons_page :
257
			add_action( 'load-' . $page_hook, 'wpsc_admin_include_coupon_js' );
258
			break;
259
		}
260
	}
261
262
	// Some updating code is run from here, is as good a place as any, and better than some
263
	if ( ( null == get_option( 'wpsc_trackingid_subject' ) ) && ( null == get_option( 'wpsc_trackingid_message' ) ) ) {
264
		update_option( 'wpsc_trackingid_subject', __( 'Product Tracking Email', 'wp-e-commerce' ) );
265
		update_option( 'wpsc_trackingid_message', __( "Track & Trace means you may track the progress of your parcel with our online parcel tracker, just login to our website and enter the following Tracking ID to view the status of your order.\n\nTracking ID: %trackid%\n", 'wp-e-commerce' ) );
266
	}
267
268
	add_action( 'load-' . $edit_options_page, 'wpsc_load_settings_page', 1 );
269
270
	// only load the purchase log list table and page classes when it's necessary
271
	// also, the WPSC_Purchase_Logs_List_Table needs to be initializied before admin_header.php
272
	// is loaded, therefore wpsc_load_purchase_logs_page needs to do this as well
273
	add_action( 'load-' . $purchase_logs_page, 'wpsc_load_purchase_logs_page', 1 );
274
275
	// Help tabs
276
	add_action( 'load-' . $edit_options_page , 'wpsc_add_help_tabs' );
277
	add_action( 'load-' . $purchase_logs_page , 'wpsc_add_help_tabs' );
278
	add_action( 'load-' . $edit_coupons_page , 'wpsc_add_help_tabs' );
279
	add_action( 'load-edit.php'              , 'wpsc_add_help_tabs' );
280
	add_action( 'load-post.php'              , 'wpsc_add_help_tabs' );
281
	add_action( 'load-post-new.php'          , 'wpsc_add_help_tabs' );
282
	add_action( 'load-edit-tags.php'         , 'wpsc_add_help_tabs' );
283
284
	// screen options on Sales Log
285
	add_action( 'load-' . $purchase_logs_page , 'wpsc_add_purchase_logs_screen_option' );
286
}
287
288
/**
289
 * This function adds contextual help to all WPEC screens.
290
 * add_contextual_help() is supported as well as $screen->add_help_tab().
291
 *
292
 * @since 3.8.8
293
 * @access public
294
 *
295
 * @uses get_current_screen()   Returns WordPress admin screen object
296
 * @uses get_bloginfo()         Returns information about the WordPress site
297
 * @uses add_help_tab()         Used to add a tab to the contextual help menu
298
 */
299
function wpsc_add_help_tabs() {
300
	$tabs = array(
301
		// Store Settings Page
302
		'settings_page_wpsc-settings' => array(
303
			'title' => _x( 'Store Settings', 'contextual help tab', 'wp-e-commerce' ),
304
			'links' => array(
305
				'category/configuring-your-store/store-settings/'   => _x( 'Store Settings Overview'          , 'contextual help link', 'wp-e-commerce' ),
306
				'category/configuring-your-store/payment-gateways/' => _x( 'Configuring Your Payment Gateways', 'contextual help link', 'wp-e-commerce' ),
307
				'category/configuring-your-store/shipping/'         => _x( 'Configuring Your Shipping Modules', 'contextual help link', 'wp-e-commerce' ),
308
			),
309
		),
310
311
		// Sales Log Page
312
		'dashboard_page_wpsc-purchase-logs' => array(
313
			'title' => _x( 'Sales Log', 'contextual help tab', 'wp-e-commerce' ),
314
			'links' => array(
315
				'documentation/sales/' => _x( 'Monitor and Manage Your Sales', 'contextual help link', 'wp-e-commerce' ),
316
			),
317
		),
318
319
		// Main Products Listing Admin Page (edit.php?post_type=wpsc-product)
320
		'edit-wpsc-product' => array(
321
			'title' => _x( 'Product Catalog', 'contextual help tab', 'wp-e-commerce' ),
322
			'links' => array(
323
				'category/managing-your-store/' => _x( 'Managing Your Store', 'contextual help link', 'wp-e-commerce' ),
324
			),
325
		),
326
327
		// Add and Edit Product Pages
328
		'wpsc-product' => array(
329
			'title' => _x( 'Add and Edit Product', 'contextual help tab', 'wp-e-commerce' ),
330
			'links' => array(
331
				'category/managing-your-store/'   => _x( 'Managing Your Store'   , 'contextual help link', 'wp-e-commerce' ),
332
				'resource/video-adding-products/' => _x( 'Video: Adding Products', 'contextual help link', 'wp-e-commerce' ),
333
			),
334
		),
335
336
		// Product Tags Page
337
		'edit-product_tag' => array(
338
			'title' => _x( 'Product Tags', 'contextual help tab', 'wp-e-commerce' ),
339
			'links' =>array(
340
				'resource/video-product-tags/' => _x( 'Video: Product Tags', 'contextual help link', 'wp-e-commerce' ),
341
			),
342
		),
343
344
		// Product Category Page
345
		'edit-wpsc_product_category' => array(
346
			'title' => _x( 'Product Categories', 'contextual help tab', 'wp-e-commerce' ),
347
			'links' => array(
348
				'resource/video-creating-product-categories/' => _x( 'Video: Creating Product Categories', 'contextual help link', 'wp-e-commerce' ),
349
			),
350
		),
351
352
		// Product Variations Page
353
		'edit-wpsc-variation' => array(
354
			'title' => _x( 'Product Variations', 'contextual help tab', 'wp-e-commerce' ),
355
			'links' => array(
356
				'category/managing-your-store/' => _x( 'Managing Your Store', 'contextual help link', 'wp-e-commerce' ),
357
			),
358
		),
359
360
		// Coupon Page
361
		'wpsc-product_page_wpsc-edit-coupons' => array(
362
			'title' => _x( 'Coupons', 'contextual help tab', 'wp-e-commerce' ),
363
			'links' => array(
364
				'resource/video-creating-coupons/' => _x( 'Video: Creating Coupons', 'contextual help link', 'wp-e-commerce' ),
365
			),
366
		),
367
	);
368
369
	$screen = get_current_screen();
370
	if ( array_key_exists( $screen->id, $tabs ) ) {
371
		$tab = $tabs[$screen->id];
372
		$content = '<p><strong>' . __( 'For More Information', 'wp-e-commerce' ) . '</strong></p>';
373
		$links = array();
374
		foreach( $tab['links'] as $link => $link_title ) {
375
			$link = 'http://docs.wpecommerce.org/' . $link;
376
			$links[] = '<a target="_blank" href="' . esc_url( $link ) . '">' . esc_html( $link_title ) . '</a>';
377
		}
378
		$content .= '<p>' . implode( '<br />', $links ) . '</p>';
379
380
		$screen->add_help_tab( array(
381
			'id'      => $screen->id . '_help',
382
			'title'   => $tab['title'],
383
			'content' => $content,
384
		) );
385
386
	}
387
}
388
389
/**
390
 * This function allows change in number of purchase logs shown on Sales Log (Screen Options).
391
 *
392
 * @since 3.9
393
 * @access public
394
 *
395
 * @uses add_screen_option()
396
 */
397
function wpsc_add_purchase_logs_screen_option(){
398
399
	// setup Screen Option for purchase logs per page
400
	add_screen_option( 'per_page', array(
401
		'label'		=> __("Sales Orders", 'wp-e-commerce'),
402
		'default'	=> 20,
403
		'option'	=> 'wpsc_purchases_per_page'
404
	) );
405
}
406
407
/**
408
 * Includes purchase logs CSS and JS
409
 *
410
 * @acces public
411
 *
412
 * @uses wp_enqueue_script()    Recommended way of adding scripts in WordPress
413
 * @uses wp_localize_script()   Adds noncing and other data to the logs script
414
 */
415
function wpsc_admin_include_purchase_logs_css_and_js() {
416
417
	_wpsc_enqueue_wp_e_commerce_admin();
418
419
	wp_enqueue_script( 'wp-e-commerce-purchase-logs', WPSC_URL . '/wpsc-admin/js/purchase-logs.js', array( 'jquery' ), WPSC_VERSION . '.' . WPSC_MINOR_VERSION );
420
	wp_localize_script( 'wp-e-commerce-purchase-logs', 'WPSC_Purchase_Logs_Admin', array(
421
		'nonce'                                  => wp_create_nonce( 'wpsc_purchase_logs' ),
422
		'change_purchase_log_status_nonce'       => _wpsc_create_ajax_nonce( 'change_purchase_log_status' ),
423
		'purchase_log_save_tracking_id_nonce'    => _wpsc_create_ajax_nonce( 'purchase_log_save_tracking_id' ),
424
		'purchase_log_send_tracking_email_nonce' => _wpsc_create_ajax_nonce( 'purchase_log_send_tracking_email' ),
425
		'sending_message'                        => _x( 'sending...', 'sending tracking email for purchase log', 'wp-e-commerce' ),
426
		'sent_message'                           => _x( 'Email Sent!', 'sending tracking email for purchase log', 'wp-e-commerce' ),
427
		'current_view'                           => empty( $_REQUEST['status'] ) ? 'all' : $_REQUEST['status'],
428
		'current_filter'                         => empty( $_REQUEST['m'] ) ? '' : $_REQUEST['m'],
429
		'current_page'                           => empty( $_REQUEST['paged'] ) ? '' : $_REQUEST['paged'],
430
	) );
431
432
	// Purchase Log Action Links
433
	wp_enqueue_script( 'wpsc-purchase-log-action-links', WPSC_URL . '/wpsc-admin/js/purchase-log-action-links.js', array( 'jquery' ), WPSC_VERSION . '.' . WPSC_MINOR_VERSION );
434
	wp_localize_script( 'wpsc-purchase-log-action-links', 'WPSC_Purchase_Log_Action_Links', array(
435
		'purchase_log_action_link_nonce' => _wpsc_create_ajax_nonce( 'purchase_log_action_link' ),
436
		'log_id'                         => empty( $_REQUEST['id'] ) ? '' : absint( $_REQUEST['id'] )
437
	) );
438
439
}
440
441
/**
442
 * Loads the WPEC settings page
443
 *
444
 * @access public
445
 *
446
 * @uses WPSC_Settings_Page::get_instance()   Gets instance of WPEC settings page
447
 */
448
function wpsc_load_settings_page() {
449
	require_once('settings-page.php');
450
	WPSC_Settings_Page::get_instance();
451
}
452
453
/**
454
 * Leads the purchase logs page
455
 *
456
 * @uses WPSC_Purchase_Log_Page()     Loads the edit and view sales page
457
 */
458
function wpsc_load_purchase_logs_page() {
459
	require_once( WPSC_FILE_PATH . '/wpsc-admin/includes/purchase-log-list-table-class.php' );
460
	require_once( WPSC_FILE_PATH . '/wpsc-admin/display-sales-logs.php' );
461
	$page = new WPSC_Purchase_Log_Page();
462
}
463
464
/**
465
 * Displays the WPEC purchase logs
466
 *
467
 * @uses do_action()  Calls 'wpsc_display_purchase_logs_page' allows hooking of the sales log page
468
 */
469
function wpsc_display_purchase_logs_page() {
470
	do_action( 'wpsc_display_purchase_logs_page' );
471
}
472
473
/**
474
 * Produces an RSS feed for the product log
475
 *
476
 * @uses add_query_arg()  Allows you to add arguments to the end of a URL
477
 * @uses admin_url()      Retrieves URL to the WordPress admin
478
 */
479
function wpsc_product_log_rss_feed() {
480
	echo "<link type='application/rss+xml' href='" . add_query_arg( array( 'rss' => 'true', 'rss_key' => 'key', 'action' => 'purchase_log', 'type' => 'rss' ), admin_url( 'index.php' ) ) . "' title='" . esc_attr__( 'WP eCommerce Purchase Log RSS', 'wp-e-commerce' ) . "' rel='alternate' />";
481
}
482
483
/**
484
 * Includes and enqueues scripts and styles for coupons
485
 *
486
 * @uses wp_enqueue_style()   Includes and prints styles for WPEC in the WordPress admin
487
 * @uses wp_enqueue_script()  Includes and prints scripts for WPEC in the WordPress admin
488
 */
489
function wpsc_admin_include_coupon_js() {
490
491
	// Variables
492
	$version_identifier = WPSC_VERSION . '.' . WPSC_MINOR_VERSION;
493
494
	// global js
495
	_wpsc_enqueue_wp_e_commerce_admin();
496
497
	// Coupon CSS
498
	wp_enqueue_style( 'wp-e-commerce-admin_2.7',        WPSC_URL         . '/wpsc-admin/css/settingspage.css', false, false,               'all' );
499
	wp_enqueue_style( 'wp-e-commerce-admin',            WPSC_URL         . '/wpsc-admin/css/admin.css',        false, $version_identifier, 'all' );
500
501
	// Coupon JS
502
	wp_enqueue_script( 'jquery-ui-datepicker' );
503
	wp_enqueue_style( 'jquery-ui-datepicker' );
504
505
	wp_enqueue_script( 'wp-e-commerce-admin_legacy',    WPSC_URL         . '/wpsc-admin/js/admin-legacy.js',                 array( 'jquery', 'jquery-ui-core', 'jquery-ui-sortable', 'jquery-ui-datepicker' ), $version_identifier );
506
507
	$admin_color = get_user_option( 'admin_color' );
508
	$scheme      = 'classic' === $admin_color ? $admin_color : 'fresh';
509
510
	wp_enqueue_style( 'wpsc-jquery-ui-datepicker', WPSC_URL . '/wpsc-admin/css/jquery.ui.datepicker-' . $scheme . '.css', false, $version_identifier );
511
}
512
513
/**
514
 * Includes and enqueues scripts and styles for the WPEC options page
515
 *
516
 * @uses wp_enqueue_script()          Includes and prints out the JS for the WPEC options page
517
 * @uses wp_localize_script()         Sets up the JS vars needed
518
 * @uses _wpsc_create_ajax_nonce()    Alias for wp_create_nonce, creates a random one time use token
519
 * @uses get_current_tab_id()         Returns the current tab id
520
 * @uses wp_enqueue_style()           Includes and prints out the CSS for the WPEC options page
521
 */
522
function wpsc_admin_include_optionspage_css_and_js() {
523
524
	_wpsc_enqueue_wp_e_commerce_admin();
525
526
	$version_identifier = WPSC_VERSION . "." . WPSC_MINOR_VERSION;
527
	wp_enqueue_script( 'wp-e-commerce-admin-settings-page', WPSC_URL . '/wpsc-admin/js/settings-page.js', array( 'jquery-query' ), $version_identifier );
528
529
	wp_localize_script( 'wp-e-commerce-admin-settings-page', 'WPSC_Settings_Page', array(
530
		'navigate_settings_tab_nonce'         => _wpsc_create_ajax_nonce( 'navigate_settings_tab' ),
531
		'payment_gateway_settings_form_nonce' => _wpsc_create_ajax_nonce( 'payment_gateway_settings_form' ),
532
		'shipping_module_settings_form_nonce' => _wpsc_create_ajax_nonce( 'shipping_module_settings_form' ),
533
		'display_region_list_nonce'           => _wpsc_create_ajax_nonce( 'display_region_list' ),
534
		'update_checkout_fields_order_nonce'  => _wpsc_create_ajax_nonce( 'update_checkout_fields_order' ),
535
		'add_tax_rate_nonce'                  => _wpsc_create_ajax_nonce( 'add_tax_rate' ),
536
		'current_tab'                         => WPSC_Settings_Page::get_instance()->get_current_tab_id(),
537
		'before_unload_dialog'                => __( 'The changes you made will be lost if you navigate away from this page.', 'wp-e-commerce' ),
538
		'ajax_navigate_confirm_dialog'        => __( 'The changes you made will be lost if you navigate away from this page.', 'wp-e-commerce' ) . "\n\n" . __( 'Click OK to discard your changes, or Cancel to remain on this page.', 'wp-e-commerce' ),
539
		'edit_field_options'                  => __( 'Edit Options', 'wp-e-commerce' ),
540
		'hide_edit_field_options'             => __( 'Hide Options', 'wp-e-commerce' ),
541
		'delete_form_set_confirm'             => __( 'Are you sure you want to delete %s? Submitted data of this form set will also be removed from sales logs.', 'wp-e-commerce' ),
542
	) );
543
544
	wp_enqueue_style( 'wp-e-commerce-admin_2.7', WPSC_URL . '/wpsc-admin/css/settingspage.css', false, false, 'all' );
545
	wp_enqueue_style( 'wp-e-commerce-ui-tabs', WPSC_URL . '/wpsc-admin/css/jquery.ui.tabs.css', false, $version_identifier, 'all' );
546
}
547
548
/**
549
 * Sets up the WPEC metaboxes
550
 *
551
 * @uses remove_meta_box()    Removes the default taxonomy meta box so our own can be added
552
 * @uses add_meta_bax()       Adds metaboxes to the WordPress admin interface
553
 */
554
function wpsc_meta_boxes() {
555
	global $post;
556
	$pagename = 'wpsc-product';
557
	remove_meta_box( 'wpsc-variationdiv', 'wpsc-product', 'side' );
558
559
	//if a variation page do not show these metaboxes
560
	if ( is_object( $post ) && $post->post_parent == 0 ) {
561
		add_meta_box( 'wpsc_product_variation_forms'    , __( 'Variations', 'wp-e-commerce' )           , 'wpsc_product_variation_forms'    , $pagename, 'normal', 'high' );
562
	} else if( is_object( $post ) && $post->post_status == "inherit" ) {
563
		remove_meta_box( 'tagsdiv-product_tag'             , 'wpsc-product', 'core' );
564
		remove_meta_box( 'wpsc_product_categorydiv'        , 'wpsc-product', 'core' );
565
	}
566
567
	add_meta_box( 'wpsc_price_control_forms', __('Product Pricing', 'wp-e-commerce'), 'wpsc_price_control_forms', $pagename, 'side', 'low' );
568
	add_meta_box( 'wpsc_stock_control_forms', __('Stock Inventory', 'wp-e-commerce'), 'wpsc_stock_control_forms', $pagename, 'side', 'low' );
569
	add_meta_box( 'wpsc_product_taxes_forms', __('Taxes', 'wp-e-commerce'), 'wpsc_product_taxes_forms', $pagename, 'side', 'low' );
570
	add_meta_box( 'wpsc_product_delivery_forms', __('Product Delivery', 'wp-e-commerce'), 'wpsc_product_delivery_forms', $pagename, 'normal', 'high' );
571
	add_meta_box( 'wpsc_product_details_forms', __('Product Details', 'wp-e-commerce'), 'wpsc_product_details_forms', $pagename, 'normal', 'high' );
572
}
573
574
add_action( 'admin_footer', 'wpsc_meta_boxes' );
575
add_action( 'admin_enqueue_scripts', 'wpsc_admin_include_css_and_js_refac' );
576
577
/**
578
 * Includes the JS and CSS
579
 *
580
 * @param string    $pagehook     The pagehook for the currently viewing page, provided by the 'admin_enqueue_scripts' action
581
 *
582
 * @uses wp_admin_css()               Enqueues or prints a stylesheet in the admin
583
 * @uses wp_enqueue_script()          Enqueues the specified script
584
 * @uses wp_localize_script()         Sets up the JS vars needed
585
 * @uses wp_enqueue_style()           Enqueues the styles
586
 * @uses wp_dequeue_script()          Removes a previously enqueued script by handle
587
 * @uses _wpsc_create_ajax_nonce()    Alias for wp_create_nonce, creates a random one time use token
588
 */
589
function wpsc_admin_include_css_and_js_refac( $pagehook ) {
590
	global $post_type, $post;
591
592
	$current_screen     = get_current_screen();
593
	$version_identifier = WPSC_VERSION . "." . WPSC_MINOR_VERSION;
594
	$pages              = array( 'index.php', 'options-general.php', 'edit.php', 'post.php', 'post-new.php' );
595
596
	_wpsc_enqueue_wp_e_commerce_admin();
597
	wp_enqueue_script( 'wp-e-commerce-admin', WPSC_URL . '/wpsc-admin/js/admin.js', array( 'jquery', 'jquery-ui-core', 'jquery-ui-sortable' ), $version_identifier, false );
598
599
	if ( 'dashboard_page_wpsc-sales-logs' == $current_screen->id ) {
600
		// jQuery
601
		wp_enqueue_script( 'jquery' );
602
		wp_enqueue_script( 'jquery-ui-draggable' );
603
		wp_enqueue_script( 'jquery-ui-droppable' );
604
		wp_enqueue_script( 'jquery-ui-sortable' );
605
606
		// Metaboxes
607
		wp_enqueue_script( 'common' );
608
		wp_enqueue_script( 'wp-lists' );
609
		wp_enqueue_script( 'postbox' );
610
	}
611
612
	if ( ( in_array( $pagehook, $pages ) && $post_type == 'wpsc-product' )  || $current_screen->id == 'edit-wpsc_product_category' || $current_screen->id == 'dashboard_page_wpsc-sales-logs' || $current_screen->id == 'dashboard_page_wpsc-purchase-logs' || $current_screen->id == 'settings_page_wpsc-settings' || $current_screen->id == 'wpsc-product_page_wpsc-edit-coupons' || $current_screen->id == 'edit-wpsc-variation' || $current_screen->id == 'wpsc-product-variations-iframe' || ( $pagehook == 'media-upload-popup' && get_post_type( $_REQUEST['post_id'] ) == 'wpsc-product' ) ) {
613
614
		wp_enqueue_script( 'wpsc-sortable-table', WPSC_URL . '/wpsc-admin/js/sortable-table.js', array( 'jquery' ) );
615
616
		if ( in_array( $current_screen->id, array( 'wpsc-product', 'edit-wpsc-variation', 'wpsc-product' ) ) ) {
617
			wp_enqueue_script( 'wp-e-commerce-variations', WPSC_URL . '/wpsc-admin/js/variations.js', array( 'jquery', 'wpsc-sortable-table' ), $version_identifier );
618
			wp_localize_script(
619
				'wp-e-commerce-variations',  // handle
620
				'WPSC_Variations',           // variable name
621
				array(                       // args
622
					'thickbox_title' => __( 'Add Media - %s', 'wp-e-commerce' ),
623
				)
624
			);
625
		}
626
		wp_enqueue_style( 'wp-e-commerce-admin', WPSC_URL . '/wpsc-admin/css/admin.css', false, $version_identifier, 'all' );
627
628
	}
629
630
	static $_wpsc_admin_l10n_loaded;
631
632
	if ( ! $_wpsc_admin_l10n_loaded ) {
633
		// Localize scripts
634
		wp_localize_script( 'wp-e-commerce-admin', 'wpsc_adminL10n', array(
635
			'dragndrop_set'            => ( get_option( 'wpsc_sort_by' ) == 'dragndrop' ? 'true' : 'false' ),
636
			'save_product_order_nonce' => _wpsc_create_ajax_nonce( 'save_product_order' ),
637
			'l10n_print_after'         => 'try{convertEntities(wpsc_adminL10n);}catch(e){};',
638
			'empty_coupon'             => esc_html__( 'Please enter a coupon code.', 'wp-e-commerce' ),
639
			'bulk_edit_no_vars'        => esc_html__( 'Quick Edit options are limited when editing products that have variations. You will need to edit the variations themselves.', 'wp-e-commerce' ),
640
			'wpsc_core_images_url'     => WPSC_CORE_IMAGES_URL,
641
			'variation_parent_swap'    => esc_html_x( 'New Variation Set', 'Variation taxonomy parent', 'wp-e-commerce' ),
642
			/* translators             : This string is prepended to the 'New Variation Set' string */
643
			'variation_helper_text'    => esc_html_x( 'Choose the Variation Set you want to add variants to. If you\'re creating a new variation set, then select', 'Variation helper text', 'wp-e-commerce' ),
644
			'variations_tutorial'      => esc_html__( 'Variations allow you to create options for your products. For example, if you\'re selling T-Shirts, they will generally have a "Size" option. Size will be the Variation Set name, and it will be a "New Variant Set". You will then create variants (small, medium, large) which will have the "Variation Set" of Size. Once you have made your set you can use the table on the right to manage them (edit, delete). You will be able to order your variants by dragging and dropping them within their Variation Set.', 'wp-e-commerce' ),
645
			/* translators             : These strings are dynamically inserted as a drop-down for the Coupon comparison conditions */
646
			'coupons_compare_or'       => esc_html_x( 'OR'  , 'Coupon comparison logic', 'wp-e-commerce' ),
647
			'coupons_compare_and'      => esc_html_x( 'AND' , 'Coupon comparison logic', 'wp-e-commerce' ),
648
			'meta_downloads_plural'    => _x( ' downloads', 'live preview for downloads metabox', 'wp-e-commerce' ),
649
			'meta_downloads_singular'  => _x( ' download' , 'live preview for downloads metabox', 'wp-e-commerce' ),
650
			'wpsc_inline_css_error'    => __( 'It is not possible to change the state of the inline CSS without also changing the common CSS.', 'wp-e-commerce' )
651
		) );
652
653
		$_wpsc_admin_l10n_loaded = true;
654
	}
655
656
	if ( $pagehook == 'wpsc-product-variations-iframe' ) {
657
		_wpsc_enqueue_wp_e_commerce_admin();
658
659
		wp_enqueue_script( 'wp-e-commerce-product-variations', WPSC_URL . '/wpsc-admin/js/product-variations.js', array( 'jquery' ), $version_identifier );
660
		wp_localize_script( 'wp-e-commerce-product-variations', 'WPSC_Product_Variations', array(
661
			'product_id'              => absint( $_REQUEST['product_id'] ),
662
			'add_variation_set_nonce' => _wpsc_create_ajax_nonce( 'add_variation_set' ),
663
		) );
664
	}
665
666
	if ( $pagehook == 'media-upload-popup' ) {
667
668
		$post = get_post( $_REQUEST['post_id'] );
0 ignored issues
show
introduced by
Overridding WordPress globals is prohibited
Loading history...
669
		if ( $post->post_type == 'wpsc-product' && $post->post_parent ) {
670
			_wpsc_enqueue_wp_e_commerce_admin();
671
672
			wp_dequeue_script( 'set-post-thumbnail' );
673
			wp_enqueue_script( 'wpsc-set-post-thumbnail', WPSC_URL . '/wpsc-admin/js/set-post-thumbnail.js', array( 'jquery', 'wp-e-commerce-admin' ), $version_identifier );
674
			wp_localize_script( 'wpsc-set-post-thumbnail', 'WPSC_Set_Post_Thumbnail', array(
675
				'link_text' => __( 'Use as Product Thumbnail', 'wp-e-commerce' ),
676
				'saving'    => __( 'Saving...', 'wp-e-commerce' ),
677
				'error'     => __( 'Could not set that as the thumbnail image. Try a different attachment.', 'wp-e-commerce' ),
678
				'done'      => __( 'Done', 'wp-e-commerce' ),
679
				'nonce'     => _wpsc_create_ajax_nonce( 'set_variation_product_thumbnail' ),
680
			) );
681
		}
682
	}
683
684
	if ( 'dashboard_page_wpsc-upgrades' == $pagehook || 'dashboard_page_wpsc-update' == $pagehook )
685
		wp_enqueue_style( 'wp-e-commerce-admin', WPSC_URL . '/wpsc-admin/css/admin.css', false, $version_identifier, 'all' );
686
}
687
688
689
/**
690
 * Adds admin javascript to the wp-e-commerce-admin javascript
691
 *
692
 * @since 3.8.14
693
 *
694
 * @param array  	array containing key value pairs, keys are turned into javascript globals with thier associated values
695
 *
696
 */
697
function _wpsc_admin_localizations( $localizations ) {
698
699
	$hidden_boxes  = get_option( 'wpsc_hidden_box' );
700
	$hidden_boxes  = implode( ',', (array)$hidden_boxes );
701
702
	$form_types_option   = get_option( 'wpsc_checkout_form_fields' );
703
	if ( ! $form_types_option || ! is_array( $form_types_option ) ) {
704
		$form_types_option = array();
705
	}
706
707
	$unique_names_option = get_option( 'wpsc_checkout_unique_names' );
708
	if ( ! $unique_names_option || ! is_array( $unique_names_option ) ) {
709
		$unique_names_option = array();
710
	}
711
712
	$form_types = '';
713
	foreach ( $form_types_option as $form_type ) {
714
		$form_types .= '<option value="' . $form_type . '">' . $form_type . '</option>';
715
	}
716
717
	$unique_names = '<option value="-1">' . __( 'Select a Unique Name', 'wp-e-commerce' ) . '</option>';
718
	foreach ( $unique_names_option as $unique_name ) {
719
		$unique_names .= '<option value="' . $unique_name . '">' . $unique_name . '</option>';
720
	}
721
722
	$localizations['ajaxurl']           = admin_url( 'admin-ajax.php', 'relative' );
723
	$localizations['hidden_boxes']      = '"' . esc_js( $hidden_boxes ) . '"';
724
	$localizations['IS_WP27']           = '"' . esc_js( IS_WP27 ) . '"';
725
	$localizations['TXT_WPSC_DELETE']   = '"' . esc_js( __( 'Delete', 'wp-e-commerce' ) ) . '"';
726
	$localizations['TXT_WPSC_TEXT']     = '"' . esc_js( __( 'Text', 'wp-e-commerce' ) ) . '"';
727
	$localizations['TXT_WPSC_EMAIL']    = '"' . esc_js( __( 'Email', 'wp-e-commerce' ) ) . '"';
728
	$localizations['TXT_WPSC_COUNTRY']  = '"' . esc_js( __( 'Country', 'wp-e-commerce' ) ) . '"';
729
	$localizations['TXT_WPSC_TEXTAREA'] = '"' . esc_js( __( 'Textarea', 'wp-e-commerce' ) ) . '"';
730
	$localizations['TXT_WPSC_HEADING']  = '"' . esc_js( __( 'Heading', 'wp-e-commerce' ) ) . '"';
731
	$localizations['TXT_WPSC_COUPON']   = '"' . esc_js( __( 'Coupon', 'wp-e-commerce' ) ) . '"';
732
733
	$localizations['HTML_FORM_FIELD_TYPES']        = '"' . esc_js( $form_types ) . '"';
734
	$localizations['HTML_FORM_FIELD_UNIQUE_NAMES'] = '"' . esc_js( $unique_names ) . '"';
735
736
	$localizations['TXT_WPSC_LABEL']        = '"' . esc_js( __( 'Label', 'wp-e-commerce' ) ) . '"';
737
	$localizations['TXT_WPSC_LABEL_DESC']   = '"' . esc_js( __( 'Label Description', 'wp-e-commerce' ) ) . '"';
738
	$localizations['TXT_WPSC_ITEM_NUMBER']  = '"' . esc_js( __( 'Item Number', 'wp-e-commerce' ) ) . '"';
739
	$localizations['TXT_WPSC_LIFE_NUMBER']  = '"' . esc_js( __( 'Life Number', 'wp-e-commerce' ) ) . '"';
740
	$localizations['TXT_WPSC_PRODUCT_CODE'] = '"' . esc_js( __( 'Product Code', 'wp-e-commerce' ) ) . '"';
741
	$localizations['TXT_WPSC_PDF']          = '"' . esc_js( __( 'PDF', 'wp-e-commerce' ) ) . '"';
742
743
	$localizations['TXT_WPSC_AND_ABOVE']    = '"' . esc_js( __( ' and above', 'wp-e-commerce' ) ) . '"';
744
	$localizations['TXT_WPSC_IF_PRICE_IS']  = '"' . esc_js( __( 'If price is ', 'wp-e-commerce' ) ) . '"';
745
	$localizations['TXT_WPSC_IF_WEIGHT_IS'] = '"' . esc_js( __( 'If weight is ', 'wp-e-commerce' ) ) . '"';
746
747
	// we only want to add these localizations once, it should happen on the first admin script load
748
	remove_filter( 'wpsc_javascript_localizations', '_wpsc_admin_localizations', 1 );
749
750
	return $localizations;
751
}
752
753
/*
754
 * Enqueue the admin script that applies to applies to all wpsc admin pages
755
 */
756
function _wpsc_enqueue_wp_e_commerce_admin( ) {
757
	static $already_enqueued = false;
758
	if ( ! $already_enqueued ) {
759
		$version_identifier = WPSC_VERSION . '.' . WPSC_MINOR_VERSION;
760
		wp_enqueue_script( 'wp-e-commerce-admin-js',  WPSC_URL . '/wpsc-admin/js/wp-e-commerce-admin.js', false, false, $version_identifier );
761
		wp_localize_script( 'wp-e-commerce-admin-js', 'wpsc_admin_vars', wpsc_javascript_localizations() );
762
		$already_enqueued = true;
763
	}
764
}
765
766
add_action( 'admin_menu', 'wpsc_admin_pages' );
767
768
/**
769
 * Displays latest activity in the Dashboard widget
770
 *
771
 * @uses $wpdb                          WordPress database object for queries
772
 * @uses get_var()                      Returns single variable from the database
773
 * @uses esc_html__()                   Gets translation of $text and escapes it for HTML output
774
 * @uses wpsc_currency_display()        Displays the currency
775
 * @uses admin_display_total_price()    Displays the total price
776
 * @uses esc_html_x()
777
 * @uses _n()                           Retrieves the singular or plural version
778
 */
779
function wpsc_admin_latest_activity() {
780
	global $wpdb;
781
	$totalOrders = $wpdb->get_var( "SELECT COUNT(*) FROM `" . WPSC_TABLE_PURCHASE_LOGS . "`" );
782
783
	/*
784
	 * This is the right hand side for the past 30 days revenue on the wp dashboard
785
	 */
786
	echo "<div id='leftDashboard'>";
787
	echo "<strong class='dashboardHeading'>" . esc_html__( 'Current Month', 'wp-e-commerce' ) . "</strong><br />";
788
	echo "<p class='dashboardWidgetSpecial'>";
789
	// calculates total amount of orders for the month
790
	$year = date( "Y" );
791
	$month = date( "m" );
792
	$start_timestamp = mktime( 0, 0, 0, $month, 1, $year );
793
	$end_timestamp = mktime( 0, 0, 0, ( $month + 1 ), 0, $year );
794
	$sql = "SELECT COUNT(*) FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `date` BETWEEN '$start_timestamp' AND '$end_timestamp' AND `processed` IN (2,3,4) ORDER BY `date` DESC";
795
	$currentMonthOrders = $wpdb->get_var( $sql );
796
797
	//calculates amount of money made for the month
798
	$currentMonthsSales = wpsc_currency_display( admin_display_total_price( $start_timestamp, $end_timestamp ) );
799
	echo $currentMonthsSales;
800
	echo "<span class='dashboardWidget'>" . esc_html_x( 'Sales', 'the total value of sales in dashboard widget', 'wp-e-commerce' ) . "</span>";
801
	echo "</p>";
802
	echo "<p class='dashboardWidgetSpecial'>";
803
	echo "<span class='pricedisplay'>";
804
	echo $currentMonthOrders;
805
	echo "</span>";
806
	echo "<span class='dashboardWidget'>" . _n( 'Order', 'Orders', $currentMonthOrders, 'wp-e-commerce' ) . "</span>";
807
	echo "</p>";
808
	echo "<p class='dashboardWidgetSpecial'>";
809
	//calculates average sales amount per order for the month
810
	if ( $currentMonthOrders > 0 ) {
811
		$monthsAverage = ( (int)admin_display_total_price( $start_timestamp, $end_timestamp ) / (int)$currentMonthOrders );
812
		echo wpsc_currency_display( $monthsAverage );
813
	}
814
	//echo "</span>";
815
	echo "<span class='dashboardWidget'>" . esc_html__( 'Avg Order', 'wp-e-commerce' ) . "</span>";
816
	echo "</p>";
817
	echo "</div>";
818
	/*
819
	 * This is the left side for the total life time revenue on the wp dashboard
820
	 */
821
822
	echo "<div id='rightDashboard' >";
823
	echo "<strong class='dashboardHeading'>" . esc_html__( 'Total Income', 'wp-e-commerce' ) . "</strong><br />";
824
825
	echo "<p class='dashboardWidgetSpecial'>";
826
	echo wpsc_currency_display( admin_display_total_price() );
827
	echo "<span class='dashboardWidget'>" . esc_html_x( 'Sales', 'the total value of sales in dashboard widget', 'wp-e-commerce' ) . "</span>";
828
	echo "</p>";
829
	echo "<p class='dashboardWidgetSpecial'>";
830
	echo "<span class='pricedisplay'>";
831
	echo $totalOrders;
832
	echo "</span>";
833
	echo "<span class='dashboardWidget'>" . _n( 'Order', 'Orders', $totalOrders, 'wp-e-commerce' ) . "</span>";
834
	echo "</p>";
835
	echo "<p class='dashboardWidgetSpecial'>";
836
	//calculates average sales amount per order for the month
837
	if ( ( admin_display_total_price() > 0 ) && ( $totalOrders > 0 ) ) {
838
		$totalAverage = ( (int)admin_display_total_price() / (int)$totalOrders );
839
	} else {
840
		$totalAverage = 0;
841
	}
842
	echo wpsc_currency_display( $totalAverage );
843
	//echo "</span>";
844
	echo "<span class='dashboardWidget'>" . esc_html__( 'Avg Order', 'wp-e-commerce' ) . "</span>";
845
	echo "</p>";
846
	echo "</div>";
847
	echo "<div style='clear:both'></div>";
848
}
849
add_action( 'wpsc_admin_pre_activity', 'wpsc_admin_latest_activity' );
850
851
/*
852
 * Dashboard Widget Setup
853
 * Adds the dashboard widgets if the user is an admin
854
 *
855
 * Since 3.6
856
 *
857
 * @uses wp_enqueue_style()           Enqueues CSS
858
 * @uses wp_enqueue_script()          Enqueues JS
859
 * @uses wp_add_dashboard_widget()    Adds a new widget to the WordPress admin dashboard
860
 * @uses current_user_can()           Checks the capabilities of the current user
861
 */
862
function wpsc_dashboard_widget_setup() {
863
	$version_identifier = WPSC_VERSION . "." . WPSC_MINOR_VERSION;
864
	// Enqueue the styles and scripts necessary
865
	wp_enqueue_style( 'wp-e-commerce-admin', WPSC_URL . '/wpsc-admin/css/admin.css', false, $version_identifier, 'all' );
866
	wp_enqueue_script( 'datepicker-ui', WPSC_URL . "/wpsc-core/js/ui.datepicker.js", array( 'jquery', 'jquery-ui-core', 'jquery-ui-sortable' ), $version_identifier );
867
868
	$news_cap            = apply_filters( 'wpsc_dashboard_news_cap'           , 'manage_options' );
869
	$sales_cap           = apply_filters( 'wpsc_dashboard_sales_summary_cap'  , 'manage_options' );
870
	$quarterly_sales_cap = apply_filters( 'wpsc_dashboard_quarterly_sales_cap', 'manage_options' );
871
	$monthly_sales_cap   = apply_filters( 'wpsc_dashboard_monthly_sales_cap'  , 'manage_options' );
872
873
	// Add the dashboard widgets
874
	if ( current_user_can( $news_cap ) )
875
		wp_add_dashboard_widget( 'wpsc_dashboard_news', __( 'WP eCommerce News' , 'wp-e-commerce' ), 'wpsc_dashboard_news' );
876
	if ( current_user_can( $sales_cap ) )
877
		wp_add_dashboard_widget( 'wpsc_dashboard_widget', __( 'Sales Summary', 'wp-e-commerce' ), 'wpsc_dashboard_widget' );
878
	if ( current_user_can( $quarterly_sales_cap ) )
879
		wp_add_dashboard_widget( 'wpsc_quarterly_dashboard_widget', __( 'Sales by Quarter', 'wp-e-commerce' ), 'wpsc_quarterly_dashboard_widget' );
880
	if ( current_user_can( $monthly_sales_cap ) )
881
		wp_add_dashboard_widget( 'wpsc_dashboard_4months_widget', __( 'Sales by Month', 'wp-e-commerce' ), 'wpsc_dashboard_4months_widget' );
882
883
	// Sort the Dashboard widgets so ours it at the top
884
	global $wp_meta_boxes;
885
	$boxes  = $wp_meta_boxes['dashboard'];
886
	$normal = isset( $wp_meta_boxes['dashboard']['normal'] ) ? $wp_meta_boxes['dashboard']['normal'] : array();
887
888
	$normal_dashboard   = isset( $normal['core'] ) ? $normal['core'] : array();
889
890
	// Backup and delete our new dashbaord widget from the end of the array
891
	$wpsc_widget_backup = array();
892
	if ( isset( $normal_dashboard['wpsc_dashboard_news'] ) ) {
893
		$wpsc_widget_backup['wpsc_dashboard_news'] = $normal_dashboard['wpsc_dashboard_news'];
894
		unset( $normal_dashboard['wpsc_dashboard_news'] );
895
	}
896
	if ( isset( $normal_dashboard['wpsc_dashboard_widget'] ) ) {
897
		$wpsc_widget_backup['wpsc_dashboard_widget'] = $normal_dashboard['wpsc_dashboard_widget'];
898
		unset( $normal_dashboard['wpsc_dashboard_widget'] );
899
	}
900
	if ( isset( $normal_dashboard['wpsc_quarterly_dashboard_widget'] ) ) {
901
		$wpsc_widget_backup['wpsc_quarterly_dashboard_widget'] = $normal_dashboard['wpsc_quarterly_dashboard_widget'];
902
		unset( $normal_dashboard['wpsc_quarterly_dashboard_widget'] );
903
	}
904
	if ( isset( $normal_dashboard['wpsc_dashboard_4months_widget'] ) ) {
905
		$wpsc_widget_backup['wpsc_dashboard_4months_widget'] = $normal_dashboard['wpsc_dashboard_4months_widget'];
906
		unset( $normal_dashboard['wpsc_dashboard_4months_widget'] );
907
	}
908
909
	// Merge the two arrays together so our widget is at the beginning
910
	$sorted_dashboard = array_merge( $wpsc_widget_backup, $normal_dashboard );
911
912
	// Save the sorted array back into the original metaboxes
913
914
	$wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;
915
}
916
917
/*
918
 * 	Registers the widgets on the WordPress Dashboard
919
 */
920
921
add_action( 'wp_dashboard_setup', 'wpsc_dashboard_widget_setup' );
922
923
/**
924
 * Shows the RSS feed for the WPEC dashboard widget
925
 *
926
 * @uses fetch_feed()             Build SimplePie object based on RSS or Atom feed from URL.
927
 * @uses wp_widget_rss_output()   Display the RSS entries in a list
928
 */
929
function wpsc_dashboard_news() {
930
	$rss = fetch_feed( 'http://wpecommerce.org/feed/?category_name=news' );
931
	$args = array( 'show_author' => 1, 'show_date' => 1, 'show_summary' => 1, 'items' => 3 );
932
	wp_widget_rss_output( $rss, $args );
933
934
}
935
936
/**
937
 * Gets the quarterly summary of revenue
938
 *
939
 * @uses get_option()                 Retrieves an option from the WordPress database
940
 * @uses admin_display_total_price()  Displays the total price
941
 *
942
 * @return array        The array of prices
943
 */
944
function wpsc_get_quarterly_summary() {
945
	$firstquarter = (int)get_option( 'wpsc_first_quart' );
946
	$secondquarter = (int)get_option( 'wpsc_second_quart' );
947
	$thirdquarter = (int)get_option( 'wpsc_third_quart' );
948
	$fourthquarter = (int)get_option( 'wpsc_fourth_quart' );
949
	$finalquarter = (int)get_option( 'wpsc_final_quart' );
950
951
	$results   = array();
952
	$results[] = admin_display_total_price( $thirdquarter + 1, $fourthquarter );
953
	$results[] = admin_display_total_price( $secondquarter + 1, $thirdquarter );
954
	$results[] = admin_display_total_price( $firstquarter + 1, $secondquarter );
955
	$results[] = admin_display_total_price( $finalquarter, $firstquarter );
956
	return $results;
957
}
958
959
/**
960
 * Called by wp_add_dashboard_widget and ads the quarterly revenue reports to the WordPress admin dashboard
961
 *
962
 * @uses get_option()     Gets the specified option from database
963
 * @uses esc_html_e()     Displays translated text that has been escaped for safe use in HTML
964
 */
965
function wpsc_quarterly_dashboard_widget() {
966
	if ( get_option( 'wpsc_business_year_start' ) == false ) {
967
?>
968
		<form action='' method='post'>
969
			<label for='date_start'><?php esc_html_e( 'Financial Year End' , 'wp-e-commerce' ); ?>: </label>
970
			<input id='date_start' type='text' class='pickdate' size='11' value='<?php echo get_option( 'wpsc_last_date' ); ?>' name='add_start' />
971
			   <!--<select name='add_start[day]'>
972
<?php
973
		for ( $i = 1; $i <= 31; ++$i ) {
974
			$selected = '';
975
			if ( $i == date( "d" ) ) {
976
				$selected = "selected='selected'";
977
			}
978
			echo "<option $selected value='$i'>$i</option>";
979
		}
980
?>
981
				   </select>
982
		   <select name='add_start[month]'>
983
	<?php
984
		for ( $i = 1; $i <= 12; ++$i ) {
985
			$selected = '';
986
			if ( $i == (int)date( "m" ) ) {
987
				$selected = "selected='selected'";
988
			}
989
			echo "<option $selected value='$i'>" . date( "M", mktime( 0, 0, 0, $i, 1, date( "Y" ) ) ) . "</option>";
990
		}
991
?>
992
				   </select>
993
		   <select name='add_start[year]'>
994
	<?php
995
		for ( $i = date( "Y" ); $i <= ( date( "Y" ) + 12 ); ++$i ) {
996
			$selected = '';
997
			if ( $i == date( "Y" ) ) {
998
				$selected = "selected='true'";
999
			}
1000
			echo "<option $selected value='$i'>" . $i . "</option>";
1001
		}
1002
?>
1003
				   </select>-->
1004
		<input type='hidden' name='wpsc_admin_action' value='wpsc_quarterly' />
1005
		<input type='submit' class='button primary' value='Submit' name='wpsc_submit' />
1006
	</form>
1007
<?php
1008
		if ( get_option( 'wpsc_first_quart' ) != '' ) {
1009
			$firstquarter = get_option( 'wpsc_first_quart' );
1010
			$secondquarter = get_option( 'wpsc_second_quart' );
1011
			$thirdquarter = get_option( 'wpsc_third_quart' );
1012
			$fourthquarter = get_option( 'wpsc_fourth_quart' );
1013
			$finalquarter = get_option( 'wpsc_final_quart' );
1014
			$revenue = wpsc_get_quarterly_summary();
1015
			$currsymbol = wpsc_get_currency_symbol();
1016
			foreach ( $revenue as $rev ) {
1017
				if ( $rev == '' ) {
1018
					$totals[] = '0.00';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$totals was never initialized. Although not strictly required by PHP, it is generally a good practice to add $totals = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1019
				} else {
1020
					$totals[] = $rev;
0 ignored issues
show
Bug introduced by
The variable $totals does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1021
				}
1022
			}
1023
?>
1024
			<div id='box'>
1025
				<p class='atglance'>
1026
					<span class='wpsc_quart_left'><?php esc_html_e( 'At a Glance' , 'wp-e-commerce' ); ?></span>
1027
					<span class='wpsc_quart_right'><?php esc_html_e( 'Revenue' , 'wp-e-commerce' ); ?></span>
1028
				</p>
1029
				<div style='clear:both'></div>
1030
				<p class='quarterly'>
1031
					<span class='wpsc_quart_left'><strong>01</strong>&nbsp; (<?php echo date( 'M Y', $thirdquarter ) . ' - ' . date( 'M Y', $fourthquarter ); ?>)</span>
1032
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[0]; ?></span></p>
1033
				<p class='quarterly'>
1034
					<span class='wpsc_quart_left'><strong>02</strong>&nbsp; (<?php echo date( 'M Y', $secondquarter ) . ' - ' . date( 'M Y', $thirdquarter ); ?>)</span>
1035
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[1]; ?></span></p>
1036
				<p class='quarterly'>
1037
					<span class='wpsc_quart_left'><strong>03</strong>&nbsp; (<?php echo date( 'M Y', $firstquarter ) . ' - ' . date( 'M Y', $secondquarter ); ?>)</span>
1038
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[2]; ?></span></p>
1039
				<p class='quarterly'>
1040
					<span class='wpsc_quart_left'><strong>04</strong>&nbsp; (<?php echo date( 'M Y', $finalquarter ) . ' - ' . date( 'M Y', $firstquarter ); ?>)</span>
1041
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[3]; ?></span>
1042
				</p>
1043
				<div style='clear:both'></div>
1044
			</div>
1045
<?php
1046
		}
1047
	}
1048
}
1049
1050
/**
1051
 * Called by wp_add_dashboard_widget to add the WPSC dashboard widget
1052
 *
1053
 * @uses do_action()    Calls 'wpsc_admin_pre_activity'
1054
 * @uses do_action()    Calls 'wpsc_admin_post_activity'
1055
 */
1056
function wpsc_dashboard_widget() {
1057
	do_action( 'wpsc_admin_pre_activity' );
1058
	do_action( 'wpsc_admin_post_activity' );
1059
}
1060
1061
/*
1062
 * END - Dashboard Widget for 2.7
1063
 */
1064
1065
1066
/*
1067
 * Dashboard Widget Last Four Month Sales.
1068
 *
1069
 * @uses $wpdb                      WordPress database object for queries
1070
 * @uses get_results()              Gets generic multiple row results from the WordPress database
1071
 * @uses get_var()                  Returns a single variable from the database
1072
 * @uses wpsc_currency_display()    Returns the currency with the display options applied
1073
 */
1074
function wpsc_dashboard_4months_widget() {
1075
	global $wpdb;
1076
1077
	$this_year = date( "Y" ); //get current year and month
1078
	$this_month = date( "n" );
1079
1080
	$months   = array();
1081
	$months[] = mktime( 0, 0, 0, $this_month - 3, 1, $this_year ); //generate  unix time stamps fo 4 last months
1082
	$months[] = mktime( 0, 0, 0, $this_month - 2, 1, $this_year );
1083
	$months[] = mktime( 0, 0, 0, $this_month - 1, 1, $this_year );
1084
	$months[] = mktime( 0, 0, 0, $this_month, 1, $this_year );
1085
1086
	$products = $wpdb->get_results( "SELECT `cart`.`prodid`,
1087
	 `cart`.`name`
1088
	 FROM `" . WPSC_TABLE_CART_CONTENTS . "` AS `cart`
1089
	 INNER JOIN `" . WPSC_TABLE_PURCHASE_LOGS . "` AS `logs`
1090
	 ON `cart`.`purchaseid` = `logs`.`id`
1091
	 WHERE `logs`.`processed` >= 2
1092
	 AND `logs`.`date` >= " . $months[0] . "
1093
	 GROUP BY `cart`.`prodid`
1094
	 ORDER BY SUM(`cart`.`price` * `cart`.`quantity`) DESC
1095
	 LIMIT 4", ARRAY_A ); //get 4 products with top income in 4 last months.
1096
1097
	$timeranges = array();
1098
	$timeranges[0]["start"] = mktime( 0, 0, 0, $this_month - 3, 1, $this_year ); //make array of time ranges
1099
	$timeranges[0]["end"] = mktime( 0, 0, 0, $this_month - 2, 1, $this_year );
1100
	$timeranges[1]["start"] = mktime( 0, 0, 0, $this_month - 2, 1, $this_year );
1101
	$timeranges[1]["end"] = mktime( 0, 0, 0, $this_month - 1, 1, $this_year );
1102
	$timeranges[2]["start"] = mktime( 0, 0, 0, $this_month - 1, 1, $this_year );
1103
	$timeranges[2]["end"] = mktime( 0, 0, 0, $this_month, 1, $this_year );
1104
	$timeranges[3]["start"] = mktime( 0, 0, 0, $this_month, 1, $this_year );
1105
	$timeranges[3]["end"] = time(); // using mktime here can generate a php runtime warning
1106
1107
	$prod_data = array( );
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
1108
	foreach ( (array)$products as $product ) { //run through products and get each product income amounts and name
1109
		$sale_totals = array( );
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
1110
		foreach ( $timeranges as $timerange ) { //run through time ranges of product, and get its income over each time range
1111
			$prodsql = "SELECT
1112
			SUM(`cart`.`price` * `cart`.`quantity`) AS sum
1113
			FROM `" . WPSC_TABLE_CART_CONTENTS . "` AS `cart`
1114
			INNER JOIN `" . WPSC_TABLE_PURCHASE_LOGS . "` AS `logs`
1115
				ON `cart`.`purchaseid` = `logs`.`id`
1116
			WHERE `logs`.`processed` >= 2
1117
				AND `logs`.`date` >= " . $timerange["start"] . "
1118
				AND `logs`.`date` < " . $timerange["end"] . "
1119
				AND `cart`.`prodid` = " . $product['prodid'] . "
1120
			GROUP BY `cart`.`prodid`"; //get the amount of income that current product has generaterd over current time range
1121
			$sale_totals[] = $wpdb->get_var( $prodsql ); //push amount to array
1122
		}
1123
		$prod_data[] = array(
1124
			'sale_totals' => $sale_totals,
1125
			'product_name' => $product['name'] ); //result: array of 2: $prod_data[0] = array(income)
1126
		$sums = array( ); //reset array    //$prod_data[1] = product name
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
1127
	}
1128
1129
	$tablerow = 1;
1130
	ob_start();
1131
	?>
1132
	<div style="padding-bottom:15px; "><?php esc_html_e( 'Last four months of sales on a per product basis:', 'wp-e-commerce' ); ?></div>
1133
    <table style="width:100%" border="0" cellspacing="0">
1134
    	<tr style="font-style:italic; color:#666;" height="20">
1135
    		<td colspan="2" style=" font-family:\'Times New Roman\', Times, serif; font-size:15px; border-bottom:solid 1px #000;"><?php esc_html_e( 'At a Glance', 'wp-e-commerce' ); ?></td>
1136
			<?php foreach ( $months as $mnth ): ?>
1137
			<td align="center" style=" font-family:\'Times New Roman\'; font-size:15px; border-bottom:solid 1px #000;"><?php echo date( "M", $mnth ); ?></td>
1138
			<?php endforeach; ?>
1139
		</tr>
1140
	<?php foreach ( (array)$prod_data as $sales_data ): ?>
1141
		<tr height="20">
1142
			<td width="20" style="font-weight:bold; color:#008080; border-bottom:solid 1px #000;"><?php echo $tablerow; ?></td>
1143
			<td style="border-bottom:solid 1px #000;width:60px"><?php echo $sales_data['product_name']; ?></td>
1144
			<?php foreach ( $sales_data['sale_totals'] as $amount ): ?>
1145
				<td align="center" style="border-bottom:solid 1px #000;"><?php echo wpsc_currency_display($amount); ?></td>
1146
			<?php endforeach; ?>
1147
		</tr>
1148
		<?php
1149
		$tablerow++;
1150
		endforeach; ?>
1151
	</table>
1152
	<?php
1153
	ob_end_flush();
1154
}
1155
1156
1157
//Modification to allow for multiple column layout
1158
1159
/**
1160
 * @todo docs
1161
 * @param $columns
1162
 * @param $screen
1163
 * @return mixed
1164
 */
1165
function wpec_two_columns( $columns, $screen ) {
1166
	if ( $screen == 'toplevel_page_wpsc-edit-products' )
1167
		$columns['toplevel_page_wpsc-edit-products'] = 2;
1168
1169
	return $columns;
1170
}
1171
add_filter( 'screen_layout_columns', 'wpec_two_columns', 10, 2 );
1172
1173
/**
1174
 * @todo docs
1175
 * @param $actions
1176
 * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,string[]>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
1177
 */
1178
function wpsc_fav_action( $actions ) {
1179
	$actions['post-new.php?post_type=wpsc-product'] = array( 'New Product', 'manage_options' );
1180
	return $actions;
1181
}
1182
add_filter( 'favorite_actions', 'wpsc_fav_action' );
1183
1184
/**
1185
 * Enqueue the admin scripts
1186
 *
1187
 * @uses wp_enqueue_script()      Enqueues scripts
1188
 * @uses home_url()               Returns the base url for the site
1189
 */
1190
function wpsc_print_admin_scripts() {
1191
	$version_identifier = WPSC_VERSION . '.' . WPSC_MINOR_VERSION;
1192
	wp_enqueue_script( 'wp-e-commerce-admin', WPSC_CORE_JS_URL . '/wp-e-commerce.js', array( 'jquery' ), $version_identifier );
1193
	wp_localize_script( 'wp-e-commerce-admin', 'wpsc_ajax', wpsc_javascript_localizations() );
1194
}
1195
1196
/**
1197
 * wpsc_ajax_ie_save save changes made using inline edit
1198
 *
1199
 * @since  3.8
1200
 * @access public
1201
 *
1202
 * @uses get_post_type_object()       Gets post object for given registered post type name
1203
 * @uses current_user_can()           Checks the capabilities of the current user
1204
 * @uses absint()                     Converts to a nonnegative integer
1205
 * @uses get_post()                   Gets the post object given post id
1206
 * @uses wp_get_object_terms()        Gets terms for given post object
1207
 * @uses wp_update_post()             Updates the post in the database
1208
 * @uses get_product_meta()           An alias for get_post_meta prefixes with the WPSC key
1209
 * @uses wpsc_convert_weight()        Converts to weight format specified by user
1210
 * @uses json_encode()                Encodes array for JS
1211
 * @uses esc_js()                     Escape single quotes, htmlspecialchar " < > &, and fix line endings.
1212
 *
1213
 * @returns nothing
1214
 */
1215
function wpsc_ajax_ie_save() {
1216
1217
	$product_post_type = get_post_type_object( 'wpsc-product' );
1218
1219
	if ( !current_user_can( $product_post_type->cap->edit_posts ) ) {
1220
		echo '({"error":"' . __( 'Error: you don\'t have required permissions to edit this product', 'wp-e-commerce' ) . '", "id": "'. esc_js( $_POST['id'] ) .'"})';
1221
		die();
1222
	}
1223
1224
	$id = absint( $_POST['id'] );
1225
	$post = get_post( $_POST['id'] );
0 ignored issues
show
introduced by
Overridding WordPress globals is prohibited
Loading history...
1226
	$parent = get_post( $post->post_parent );
1227
	$terms = wpsc_get_product_terms( $id, 'wpsc-variation', 'name' );
1228
1229
	$product = array(
1230
		'ID' => $_POST['id'],
1231
		'post_title' => $parent->post_title . ' (' . implode( ', ', $terms ) . ')',
1232
	);
1233
1234
	$id = wp_update_post( $product );
1235
	if ( $id > 0 ) {
1236
		//need parent meta to know which weight unit we are using
1237
		$parent_meta = get_product_meta($post->post_parent, 'product_metadata', true );
1238
		$product_meta = get_product_meta( $product['ID'], 'product_metadata', true );
1239
		if ( is_numeric( $_POST['weight'] ) || empty( $_POST['weight'] ) ){
1240
			$product_meta['weight'] = wpsc_convert_weight($_POST['weight'], $parent_meta['weight_unit'], 'pound', true);
1241
			$product_meta['weight_unit'] = $parent_meta['weight_unit'];
1242
		}
1243
1244
		update_product_meta( $product['ID'], 'product_metadata', $product_meta );
1245
		update_product_meta( $product['ID'], 'price', (float)$_POST['price'] );
1246
		update_product_meta( $product['ID'], 'special_price', (float)$_POST['special_price'] );
1247
		update_product_meta( $product['ID'], 'sku', sanitize_text_field( $_POST['sku'] ) );
1248
1249
		if ( !is_numeric($_POST['stock']) )
1250
			update_product_meta( $product['ID'], 'stock', '' );
1251
		else
1252
			update_product_meta( $product['ID'], 'stock', absint( $_POST['stock'] ) );
1253
1254
		$meta = get_product_meta( $id, 'product_metadata', true );
1255
		$price = get_product_meta( $id, 'price', true );
1256
		$special_price = get_product_meta( $id, 'special_price', true );
1257
		$sku = get_product_meta( $id, 'sku', true );
1258
		$sku = ( $sku )?$sku:__('N/A', 'wp-e-commerce');
1259
		$stock = get_product_meta( $id, 'stock', true );
1260
		$stock = ( $stock === '' )?__('N/A', 'wp-e-commerce'):$stock;
1261
		$results = array( 'id' => $id, 'title' => $post->post_title, 'weight' => wpsc_convert_weight($meta['weight'], 'pound', $parent_meta['weight_unit']), 'price' => wpsc_currency_display( $price ), 'special_price' => wpsc_currency_display( $special_price ), 'sku' => $sku, 'stock' => $stock );
1262
		echo '(' . json_encode( $results ) . ')';
1263
		die();
1264
	} else {
1265
		echo '({"error":"' . __( 'Error updating product', 'wp-e-commerce' ) . '", "id": "'. esc_js( $_POST['id'] ) .'"})';
1266
	}
1267
	die();
1268
}
1269
1270
/**
1271
 * @todo docs
1272
 *
1273
 * @uses add_meta_box  Allows addition of metaboxes to the wpsc_add_meta_boxes admin
1274
 */
1275
function wpsc_add_meta_boxes(){
1276
	add_meta_box( 'dashboard_right_now', __( 'Current Month', 'wp-e-commerce' ), 'wpsc_right_now', 'dashboard_page_wpsc-sales-logs', 'top' );
1277
}
1278
1279
/**
1280
 * Displays notice if user has Great Britain selected as their base country
1281
 * Since 3.8.9, we have deprecated Great Britain in favor of the UK
1282
 *
1283
 * @since 3.8.9
1284
 * @access private
1285
 * @link http://code.google.com/p/wp-e-commerce/issues/detail?id=1079
1286
 *
1287
 * @uses get_option()             Retrieves option from the WordPress database
1288
 * @uses get_outdate_isocodes()   Returns outdated isocodes
1289
 * @uses admin_url()              Returns admin_url of the site
1290
 *
1291
 * @return string  The admin notices for deprecated countries
1292
 */
1293
function _wpsc_action_admin_notices_deprecated_countries_notice() {
1294
	$base_country = get_option( 'base_country' );
1295
1296
	if ( ! in_array( $base_country, WPSC_Country::get_outdated_isocodes() ) )
1297
		return;
1298
1299
	switch ( $base_country ) {
1300
		case 'YU':
1301
			$message = __( 'Yugoslavia is no longer a valid official country name according to <a href="%1$s">ISO 3166</a> while both Serbia and Montenegro have been added to the country list.<br /> As a result, we highly recommend changing your <em>Base Country</em> to reflect this change on the <a href="%2$s">General Settings</a> page.', 'wp-e-commerce' );
1302
			break;
1303
		case 'UK':
1304
			$message = __( 'Prior to WP eCommerce 3.8.9, in your database, United Kingdom\'s country code is UK and you have already selected that country code as the base country. However, now that you\'re using WP eCommerce version %3$s, it is recommended that you change your base country to the official "GB" country code, according to <a href="%1$s">ISO 3166</a>.<br /> Please go to <a href="%2$s">General Settings</a> page to make this change.<br />The legacy "UK" item will be marked as "U.K. (legacy)" on the country drop down list. Simply switch to the official "United Kingdom (ISO 3166)" to use the "GB" country code.' , 'wp-e-commerce' );
1305
			break;
1306
		case 'AN':
1307
			$message = __( 'Netherlands Antilles is no longer a valid official country name according to <a href="%1$s">ISO 3166</a>.<br />Please consider changing your <em>Base Country</em> to reflect this change on the <a href="%2$s">General Settings</a> page.', 'wp-e-commerce' );
1308
		case 'TP':
1309
			$message = __( 'Prior to WP eCommerce 3.8.9, in your database, East Timor\'s country code is TP and you have already selected that country code as the base country. However, now that you\'re using WP eCommerce version %3$s, it is recommended that you change your base country to the official "TL" country code, according to <a href="%1$s">ISO 3166</a>.<br /> Please go to <a href="%2$s">General Settings</a> page to make this change.<br />The legacy "TP" item will be marked as "East Timor (legacy)" on the country drop down list. Simply switch to the official "Timor-Leste (ISO 3166)" to use the "TL" country code.' , 'wp-e-commerce' );
1310
			break;
1311
	}
1312
1313
	$message = sprintf(
1314
		/* message */ $message,
0 ignored issues
show
Bug introduced by
The variable $message does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1315
		/* %1$s    */ 'http://en.wikipedia.org/wiki/ISO_3166-1',
1316
		/* %2$s    */ admin_url( 'options-general.php?page=wpsc-settings&tab=general' ),
1317
		/* %3$s    */ WPSC_VERSION
1318
	);
1319
	echo '<div id="wpsc-warning" class="error"><p>' . $message . '</p></div>';
1320
}
1321
1322
add_action( 'admin_notices'               , '_wpsc_action_admin_notices_deprecated_countries_notice' );
1323
add_action( 'wp_ajax_category_sort_order' , 'wpsc_ajax_set_category_order' );
1324
add_action( 'wp_ajax_variation_sort_order', 'wpsc_ajax_set_variation_order' );
1325
add_action( 'wp_ajax_wpsc_ie_save'        , 'wpsc_ajax_ie_save' );
1326
add_action( 'in_admin_header'             , 'wpsc_add_meta_boxes' );
1327
1328
/**
1329
 * Deletes file associated with a product.
1330
 *
1331
 * @access private
1332
 *
1333
 * @uses $wpdb              WordPress database object for queries
1334
 * @uses prepare()          Prepares a database query by escaping
1335
 * @uses wp_delete_post()   Removes a post attachment or page*
1336
 *
1337
 * @param int       $product_id     req        The id of the product
1338
 * @param string    $file_name      req        The string
1339
 *
1340
 * @return mixed
1341
 *
1342
 */
1343
function _wpsc_delete_file( $product_id, $file_name ) {
1344
	global $wpdb;
1345
1346
	$sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_parent = %d AND post_type ='wpsc-product-file'", $file_name, $product_id );
1347
	$product_id_to_delete = $wpdb->get_var( $sql );
1348
1349
	//Delete wpsc_download_status entry for this file
1350
	$wpdb->query( $wpdb->prepare( "DELETE FROM `".WPSC_TABLE_DOWNLOAD_STATUS."` WHERE `fileid`=%d AND `product_id` = %d", $product_id_to_delete, $product_id ) );
1351
1352
	return wp_delete_post( $product_id_to_delete, true );
1353
}
1354
1355
/**
1356
 * @todo docs
1357
 *
1358
 * @access private
1359
 *
1360
 * @uses add_query_arg()      Adds argument to the WordPress query
1361
 * @uses update_option()      Updates an option in the WordPress database given string and value
1362
 * @uses get_option()         Gets option from the database given string
1363
 */
1364
function _wpsc_admin_notices_3dot8dot9() {
1365
	$message = '<p>' . __( 'You are currently using WP eCommerce. There have been major changes in WP eCommerce 3.8.9, so backward-compatibility with existing plugins might not always be guaranteed. If you are unsure, please roll back to 3.8.8.5, and set up a test site with 3.8.9 to make sure WP eCommerce 3.8.9 is compatible with your existing themes and plugins.<br />If you find any incompatibility issues, please <a href="%1$s">report them to us</a> as well as the other plugins or themes\' developers.' , 'wp-e-commerce' ) . '</p>';
1366
	$message .= "\n<p>" . __( '<a href="%2$s">Hide this warning</a>', 'wp-e-commerce' ) . '</p>';
1367
	$message = sprintf(
1368
		$message,
1369
		'https://wpecommerce.org/wp-e-commerce-3-8-9-compatibility-issues/',
1370
		esc_url( add_query_arg( 'dismiss_389_upgrade_notice', 1 ) )
1371
	);
1372
1373
	echo '<div id="wpsc-3.8.9-notice" class="error">' . $message . '</div>';
1374
}
1375
1376
/**
1377
 * Checks to ensure that shipping is enabled, and one or both of the shipping/billing states are not displayed.
1378
 * If those condtions are met, and the user has not previously dismissed the notice, then we notify them
1379
 * that the shipping calculator now depend on those fields.
1380
 *
1381
 * @access private
1382
 *
1383
 * @uses add_query_arg()      Adds argument to the WordPress query
1384
 * @uses update_option()      Updates an option in the WordPress database given string and value
1385
 * @uses get_option()         Gets option from the database given string
1386
 */
1387
function _wpsc_admin_notices_3_8_14_1() {
1388
1389
	if ( get_option( 'do_not_use_shipping' ) ) {
1390
		return;
1391
	}
1392
1393
	global $wpdb;
1394
1395
	$state_visibility = $wpdb->get_var( "SELECT COUNT(active) FROM " . WPSC_TABLE_CHECKOUT_FORMS . " WHERE unique_name IN ( 'billingstate', 'shippingstate' ) AND active = '1'" );
1396
1397
	if ( '2' === $state_visibility ) {
1398
		return;
1399
	}
1400
1401
	$message = '<p>' . __( 'WP eCommerce has been updated, please confirm the checkout field display
1402
settings are correct for your store.<br><br><i>The visibility of the checkout billing and shipping
1403
drop downs that show states and provinces is now controlled by the "billingstate" and "shippingstate"
1404
options set in the <b>Store Settings</b> on the <b>Checkout</b> tab.  Prior versions used
1405
the "billingcountry" and "shippingcountry" settings to control the visibility of the drop downs.</i>' , 'wp-e-commerce' ) . '</p>';
1406
	$message .= "\n<p>" . __( '<a href="%s">Hide this warning</a>', 'wp-e-commerce' ) . '</p>';
1407
	$message = sprintf(
1408
		$message,
1409
		esc_url( add_query_arg( 'dismiss_3_8_14_1_upgrade_notice', 1 ) )
1410
	);
1411
1412
	echo '<div id="wpsc-3-8-14-1-notice" class="error">' . $message . '</div>';
1413
}
1414
1415
if ( ! get_option( 'wpsc_hide_3_8_14_1_notices' ) ) {
1416
	add_action( 'admin_notices', '_wpsc_admin_notices_3_8_14_1' );
1417
1418
  if ( isset( $_REQUEST['dismiss_3_8_14_1_upgrade_notice'] ) ) {
1419
    update_option( 'wpsc_hide_3_8_14_1_notices', true );
1420
  }
1421
}
1422
1423
/**
1424
 * @todo docs
1425
 * @access private
1426
 *
1427
 * @uses add_query_arg()      Adds argument to the WordPress query
1428
 * @uses update_option()      Updates an option in the WordPress database given string and value
1429
 * @uses get_option()         Gets option from the database given string
1430
 */
1431
function _wpsc_admin_notices_3dot8dot11() {
1432
	$message  = '<p>' . __( 'You are currently using WPeC %1$s.  We introduced a regression in WPeC 3.8.10 which affects your customer user account page. We have included a fix for a <a href="%2$s">bug on the User Account management page</a>. We are able to fix this automatically on most sites, but it appears that you have made changes to your wpsc-user-log.php page.  For that reason, we have some <a href="%3$s">simple instructions for you to follow</a> to resolve the issue.  We are sorry for the inconvenience.' , 'wp-e-commerce' ) . '</p>';
1433
	$message .= "\n<p>" . __( '<a href="%4$s">Hide this warning</a>', 'wp-e-commerce' ) . '</p>';
1434
	$message  = sprintf(
1435
		$message,
1436
		WPSC_VERSION,
1437
		'https://github.com/wp-e-commerce/WP-e-Commerce/issues/359',
1438
		'http://docs.wpecommerce.org/documentation/3-8-11-user-logs',
1439
		esc_url( add_query_arg( 'dismiss_3811_upgrade_notice', 1 ) )
1440
	);
1441
1442
	echo '<div id="wpsc-3.8.11-notice" class="error">' . $message . '</div>';
1443
}
1444
1445
if ( isset( $_REQUEST['dismiss_3811_upgrade_notice'] ) )
1446
	update_option( '_wpsc_3811_user_log_notice', false );
1447
1448
if ( get_option( '_wpsc_3811_user_log_notice' ) )
1449
	add_action( 'admin_notices', '_wpsc_admin_notices_3dot8dot11' );
1450
1451
function _wpsc_notify_google_checkout_deprecation() {
1452
	$gateways = get_option( 'custom_gateway_options', array() );
1453
1454
	if ( false !== ( $key = array_search( 'google', $gateways ) ) ) {
1455
		unset( $gateways[ $key ] );
1456
	}
1457
1458
	if ( empty( $gateways ) ) {
1459
		$gateways[] = 'wpsc_merchant_testmode';
1460
	}
1461
1462
	update_option( 'custom_gateway_options', $gateways );
1463
1464
	$message  = '<p>' . __( 'Effective November 20th, 2013, Google Checkout was shut down and is no longer processing payments.  You are seeing this warning because it appears that Google Checkout was your payment gateway processor.  If it was your sole processor, we have enabled the Test Gateway to ensure that orders are coming through on your site, but we highly recommend enabling a proper gateway.  If you have no preference, we highly recommend Stripe.' , 'wp-e-commerce' ) . '</p>';
1465
1466
	echo '<div id="wpsc-3.8.11-notice" class="error">' . $message . '</div>';
1467
}
1468
1469
if ( in_array( 'google', get_option( 'custom_gateway_options', array() ) ) ) {
1470
	add_action( 'admin_notices', '_wpsc_notify_google_checkout_deprecation' );
1471
}
1472
1473
/**
1474
 * Adds links to premium support and documentation on WPeCommerce.org
1475
 *
1476
 * @since  3.9.0
1477
 *
1478
 * @param  array $links Original links
1479
 * @return array $links Updated links
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string[].

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
1480
 */
1481
function wpsc_support_links( $links ) {
1482
	$links[] = sprintf( '<a href="%s">%s</a>', _x( 'https://wpecommerce.org/support/', 'Support URL', 'wp-e-commerce' ),  __( 'Support', 'wp-e-commerce' ) );
1483
	$links[] = sprintf( '<a href="%s">%s</a>', _x( 'http://docs.wpecommerce.org/', 'Documentation URL', 'wp-e-commerce' ),  __( 'Documentation', 'wp-e-commerce' ) );
1484
1485
	return $links;
1486
}
1487
1488
add_filter( 'plugin_action_links_' . WPSC_PLUGIN_BASENAME, 'wpsc_support_links' );
1489
1490
/**
1491
 * Adds removable query args, for compatibility with dismissable notices.
1492
 *
1493
 * @param  array $args Array of removable query args.
1494
 *
1495
 * @since  4.0
1496
 *
1497
 * @return array $args Array of removable query args.
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string[].

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
1498
 */
1499
function wpsc_removable_query_args( $args ) {
1500
	$args[] = 'shipping_disabled';
1501
	return $args;
1502
}
1503
1504
add_filter( 'removable_query_args', 'wpsc_removable_query_args' );
1505
1506
/**
1507
 * Modify bulk post messages.
1508
 *
1509
 * @param  array $bulk_messages Array of bulk messages.
1510
 * @param  int   $bulk_counts   The amount of messages affected.
1511
 *
1512
 * @since  4.0
1513
 *
1514
 * @return array                Array of bulk messages.
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,array>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
1515
 */
1516
function wpsc_bulk_updated_messages( $bulk_messages, $bulk_counts ) {
1517
	$bulk_messages['wpsc-product'] = array(
1518
		'updated'   => _n( '%s product updated.', '%s products updated.', $bulk_counts['updated'], 'wp-e-commerce' ),
1519
		'locked'    => ( 1 == $bulk_counts['locked'] ) ? __( '1 product not updated, somebody is editing it.', 'wp-e-commerce' ) :
1520
		                   _n( '%s product not updated, somebody is editing it.', '%s products not updated, somebody is editing them.', $bulk_counts['locked'], 'wp-e-commerce' ),
1521
		'deleted'   => _n( '%s product permanently deleted.', '%s products permanently deleted.', $bulk_counts['deleted'], 'wp-e-commerce' ),
1522
		'trashed'   => _n( '%s product moved to the Trash.', '%s products moved to the Trash.', $bulk_counts['trashed'], 'wp-e-commerce' ),
1523
		'untrashed' => _n( '%s product restored from the Trash.', '%s products restored from the Trash.', $bulk_counts['untrashed'], 'wp-e-commerce' ),
1524
	);
1525
1526
	return $bulk_messages;
1527
}
1528
1529
add_filter( 'bulk_post_updated_messages', 'wpsc_bulk_updated_messages', 10, 2 );
1530