Completed
Push — master ( 09f8b9...697c79 )
by Justin
05:29
created

admin.php ➔ wpsc_admin_include_css_and_js_refac()   F

Complexity

Conditions 23
Paths 288

Size

Total Lines 101
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
eloc 64
nc 288
nop 1
dl 0
loc 101
rs 3.5803
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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.functions.php' );
22
require_once( WPSC_FILE_PATH . '/wpsc-includes/purchaselogs.class.php' );
23
require_once( WPSC_FILE_PATH . '/wpsc-includes/purchaselogs-items.class.php' );
24
require_once( WPSC_FILE_PATH . '/wpsc-includes/theming.class.php' );
25
require_once( WPSC_FILE_PATH . '/wpsc-admin/ajax.php' );
26
require_once( WPSC_FILE_PATH . '/wpsc-admin/init.php' );
27
require_once( WPSC_FILE_PATH . '/wpsc-admin/ajax-and-init.php' );
28
require_once( WPSC_FILE_PATH . '/wpsc-admin/display-options-settings.page.php' );
29
require_once( WPSC_FILE_PATH . '/wpsc-admin/db-upgrades/upgrade.php' );
30
require_once( WPSC_FILE_PATH . '/wpsc-admin/media.php' );
31
32
if ( ! get_option( 'wpsc_checkout_form_sets' ) ) {
33
	$form_sets = array( __( 'Default Checkout Forms', 'wp-e-commerce' ) );
34
	update_option( 'wpsc_checkout_form_sets', $form_sets );
35
}
36
37
// if we add and wpec admin javascript will add the localizations
38
add_filter( 'wpsc_javascript_localizations', '_wpsc_admin_localizations', 1 );
39
40
/**
41
 * wpsc_query_vars_product_list sets the ordering for the edit-products page list
42
 *
43
 * @since 3.8
44
 * @access public
45
 *
46
 * @uses get_option()   Gets option from the DB given key
47
 *
48
 * @param array     $vars  req  Default query arguments
49
 * @return array    $vars       Modified query arguments
50
 */
51
function wpsc_query_vars_product_list( $vars ){
52
53
	if( 'wpsc-product' != $vars['post_type'] || in_array( $vars['orderby'], array( 'meta_value_num', 'meta_value' ) ) )
54
	    return $vars;
55
56
	$vars['posts_per_archive_page'] = 0;
57
58
	if( 'dragndrop' == get_option( 'wpsc_sort_by' ) ){
59
		$vars['orderby'] = 'menu_order title';
60
		$vars['order'] = 'desc';
61
		$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...
62
	}
63
64
    return $vars;
65
}
66
67
/**
68
 * Admin Edit Posts Order
69
 *
70
 * @since 3.8.12
71
 * @access public
72
 *
73
 * @param   string  $orderby_sql  Order by SQL.
74
 * @return  string  Filtered order by SQL.
75
 */
76
function wpsc_admin_edit_posts_orderby( $orderby_sql ) {
77
	global $wp_query, $wpdb;
78
	if ( 'dragndrop' == get_option( 'wpsc_sort_by' ) ) {
79
		if ( function_exists( 'is_main_query' ) && is_main_query() && 'wpsc-product' == get_query_var( 'post_type' ) && is_tax( 'wpsc_product_category' ) ) {
80
			if ( ! empty( $orderby_sql ) )
81
				$orderby_sql = ', ' . $orderby_sql;
82
			$orderby_sql = " {$wpdb->term_relationships}.term_order ASC" . $orderby_sql;
83
			remove_filter( 'posts_orderby', 'wpsc_admin_edit_posts_orderby' );
84
		}
85
	}
86
	return $orderby_sql;
87
}
88
add_filter( 'posts_orderby', 'wpsc_admin_edit_posts_orderby' );
89
90
/**
91
 * setting the product & variations per page screen option to between 1 and 999
92
 *
93
 * @since 3.8
94
 * @access public
95
 *
96
 * @uses update_user_option()   Updates user option given userid, key, value
97
 *
98
 * @param           $status
99
 * @param string    $option     req     Name of option being saved
100
 * @param string    $value      req     Value of option being saved
101
 * @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...
102
 */
103
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...
104
	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...
105
		if ( "edit_wpsc_variation_per_page" == $option ){
106
			global $user_ID;
107
			update_user_option($user_ID,'edit_wpsc-variation_per_page',$value);
108
		}
109
		return $value;
110
	}
111
}
112
add_filter('set-screen-option', 'wpsc_set_screen_option', 99, 3);
113
114
/**
115
 * Limit admin variation dropdown to show variantion sets only.
116
 *
117
 * @param   array   $args      Dropdown args.
118
 * @param   string  $taxonomy  Taxonomy.
119
 * @param   string  $context   Context.
120
 *
121
 * @since  4.0
122
 *
123
 * @return  array              Filtered dropdown args.
124
 */
125
function wpsc_variation_parent_dropdown_args( $args, $taxonomy, $context ) {
126
127
	if ( 'wpsc-variation' == $taxonomy && 'edit' == $context ) {
128
		$args['depth'] = 1;
129
	}
130
131
	return $args;
132
133
}
134
add_filter( 'taxonomy_parent_dropdown_args', 'wpsc_variation_parent_dropdown_args', 10, 3 );
135
136
/**
137
 * When rearranging the products for drag and drop it is easiest to arrange them when they are all on the same page...
138
 * @access public
139
 *
140
 * @since 3.8
141
 * @access public
142
 *
143
 * @uses get_option()   Gets option from the database given key
144
 *
145
 * @param int       $per_page   req     number of products per page
146
 * @param string    $post_type  req     name of current post type
147
 * @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...
148
 */
149
function wpsc_drag_and_drop_ordering($per_page, $post_type){
150
	global $wpdb;
151
	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" ) )
152
		$per_page = $count;
153
	return $per_page;
154
}
155
add_filter( 'request', 'wpsc_query_vars_product_list' );
156
add_filter( 'edit_posts_per_page' , 'wpsc_drag_and_drop_ordering', 10, 2 );
157
158
/**
159
 * Checks whether to display or hide the update wp-e-commerce link
160
 *
161
 * @since 3.8
162
 * @access public
163
 *
164
 * @uses get_option()   Gets option from DB given key
165
 *
166
 * @return boolean true - show link, false- hide link
167
 */
168
function wpsc_show_update_link() {
169
	global $wpdb;
170
	// Check if old product_list table exists
171
	// If it exists AND get_option wpsc_upgrade_complete is not true then return true
172
	$sql = 'SHOW TABLES LIKE "'.$wpdb->prefix.'wpsc_product_list"';
173
	$var = $wpdb->get_var( $sql );
174
	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...
175
		return true;
176
	else
177
		return false;
178
}
179
180
/**
181
 * wpsc_admin_pages function, all the definitons of admin pages are stores here.
182
 * No parameters, returns nothing
183
 *
184
 * Fairly standard wordpress plugin API stuff for adding the admin pages, rearrange the order to rearrange the pages
185
 * 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
186
 * if you find bugs, feel free to fix them.
187
 *
188
 * If the permissions are changed here, they will likewise need to be changed for the other sections of the admin that either use ajax
189
 * or bypass the normal download system.
190
 *
191
 * @access public
192
 *
193
 * @uses wpsc_show_update_link()    Decides whether or not to show the update link
194
 * @uses add_submenu_page()         Adds a WordPress submenu page
195
 * @uses apply_filters()            Calls wpsc_upgrades_cap allows hooking caps for adiministrator
196
 * @uses apply_filters()            Calls wpsc_coupon_cap allows filtering for the coupon caps
197
 * @uses add_options_page()         Adds a submenu to the settings page
198
 * @uses add_action()               Calls 'admin_print_scripts.$edit_options_page prints out WPEC admin scripts
199
 * @uses apply_filters()            Calls 'wpsc_additional_pages' Passes the page_hooks and product_page URL
200
 * @uses do_action()                Calls 'wpsc_add_submenu' Allows you to hook in to the WPEC menu
201
 * @uses update_option()            Updates option given key and value
202
 */
203
function wpsc_admin_pages() {
204
205
	// Code to enable or disable the debug page
206
	if ( isset( $_GET['wpsc_activate_debug_page'] ) ) {
207
		if ( 'true' == $_GET['wpsc_activate_debug_page'] ) {
208
			$_SESSION['wpsc_activate_debug_page'] = true;
0 ignored issues
show
introduced by
Usage of $_SESSION variable is prohibited.
Loading history...
209
		} else if ( 'false' == $_GET['wpsc_activate_debug_page'] ) {
210
				$_SESSION['wpsc_activate_debug_page'] = false;
0 ignored issues
show
introduced by
Usage of $_SESSION variable is prohibited.
Loading history...
211
			}
212
	}
213
214
	$store_upgrades_cap = apply_filters( 'wpsc_upgrades_cap', 'administrator' );
215
216
	$page_hooks = array();
217
218
	if ( wpsc_show_update_link() ) {
219
		$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' );
220
	}
221
222
	$purchase_logs_cap = apply_filters( 'wpsc_purchase_logs_cap', 'administrator' );
223
	$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' );
224
225
	$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' );
226
227
	// Set the base page for Products
228
	$products_page = 'edit.php?post_type=wpsc-product';
229
230
	$manage_coupon_cap = apply_filters( 'wpsc_coupon_cap', 'administrator' );
231
	$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' );
232
233
	// Add Settings pages
234
	$page_hooks[] = $edit_options_page = add_options_page( __( 'Store Settings', 'wp-e-commerce' ), __( 'Store', 'wp-e-commerce' ), 'administrator', 'wpsc-settings', 'wpsc_display_settings_page' );
235
	add_action( 'admin_print_scripts-' . $edit_options_page , 'wpsc_print_admin_scripts' );
236
237
	$page_hooks = apply_filters( 'wpsc_additional_pages', $page_hooks, $products_page );
238
239
	do_action( 'wpsc_add_submenu' );
240
241
	// Include the javascript and CSS for this page
242
	// This is so important that I can't even express it in one line
243
244
	foreach ( $page_hooks as $page_hook ) {
245
		add_action( 'load-' . $page_hook, 'wpsc_admin_include_css_and_js_refac' );
246
247
		switch ( $page_hook ) {
248
249
		case $edit_options_page :
250
			add_action( 'load-' . $page_hook, 'wpsc_admin_include_optionspage_css_and_js' );
251
			break;
252
253
		case $purchase_logs_page :
254
			add_action( 'admin_head', 'wpsc_product_log_rss_feed' );
255
			add_action( 'load-' . $page_hook, 'wpsc_admin_include_purchase_logs_css_and_js' );
256
			break;
257
258
		case $edit_coupons_page :
259
			add_action( 'load-' . $page_hook, 'wpsc_admin_include_coupon_js' );
260
			break;
261
		}
262
	}
263
264
	// Some updating code is run from here, is as good a place as any, and better than some
265
	if ( ( null == get_option( 'wpsc_trackingid_subject' ) ) && ( null == get_option( 'wpsc_trackingid_message' ) ) ) {
266
		update_option( 'wpsc_trackingid_subject', __( 'Product Tracking Email', 'wp-e-commerce' ) );
267
		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' ) );
268
	}
269
270
	add_action( 'load-' . $edit_options_page, 'wpsc_load_settings_page', 1 );
271
272
	// only load the purchase log list table and page classes when it's necessary
273
	// also, the WPSC_Purchase_Logs_List_Table needs to be initializied before admin_header.php
274
	// is loaded, therefore wpsc_load_purchase_logs_page needs to do this as well
275
	add_action( 'load-' . $purchase_logs_page, 'wpsc_load_purchase_logs_page', 1 );
276
277
	// Help tabs
278
	add_action( 'load-' . $edit_options_page , 'wpsc_add_help_tabs' );
279
	add_action( 'load-' . $purchase_logs_page , 'wpsc_add_help_tabs' );
280
	add_action( 'load-' . $edit_coupons_page , 'wpsc_add_help_tabs' );
281
	add_action( 'load-edit.php'              , 'wpsc_add_help_tabs' );
282
	add_action( 'load-post.php'              , 'wpsc_add_help_tabs' );
283
	add_action( 'load-post-new.php'          , 'wpsc_add_help_tabs' );
284
	add_action( 'load-edit-tags.php'         , 'wpsc_add_help_tabs' );
285
286
	// screen options on Sales Log
287
	add_action( 'load-' . $purchase_logs_page , 'wpsc_add_purchase_logs_screen_option' );
288
}
289
290
/**
291
 * This function adds contextual help to all WPEC screens.
292
 * add_contextual_help() is supported as well as $screen->add_help_tab().
293
 *
294
 * @since 3.8.8
295
 * @access public
296
 *
297
 * @uses get_current_screen()   Returns WordPress admin screen object
298
 * @uses get_bloginfo()         Returns information about the WordPress site
299
 * @uses add_help_tab()         Used to add a tab to the contextual help menu
300
 */
301
function wpsc_add_help_tabs() {
302
	$tabs = array(
303
		// Store Settings Page
304
		'settings_page_wpsc-settings' => array(
305
			'title' => _x( 'Store Settings', 'contextual help tab', 'wp-e-commerce' ),
306
			'links' => array(
307
				'category/configuring-your-store/store-settings/'   => _x( 'Store Settings Overview'          , 'contextual help link', 'wp-e-commerce' ),
308
				'category/configuring-your-store/payment-gateways/' => _x( 'Configuring Your Payment Gateways', 'contextual help link', 'wp-e-commerce' ),
309
				'category/configuring-your-store/shipping/'         => _x( 'Configuring Your Shipping Modules', 'contextual help link', 'wp-e-commerce' ),
310
			),
311
		),
312
313
		// Sales Log Page
314
		'dashboard_page_wpsc-purchase-logs' => array(
315
			'title' => _x( 'Sales Log', 'contextual help tab', 'wp-e-commerce' ),
316
			'links' => array(
317
				'documentation/sales/' => _x( 'Monitor and Manage Your Sales', 'contextual help link', 'wp-e-commerce' ),
318
			),
319
		),
320
321
		// Main Products Listing Admin Page (edit.php?post_type=wpsc-product)
322
		'edit-wpsc-product' => array(
323
			'title' => _x( 'Product Catalog', 'contextual help tab', 'wp-e-commerce' ),
324
			'links' => array(
325
				'category/managing-your-store/' => _x( 'Managing Your Store', 'contextual help link', 'wp-e-commerce' ),
326
			),
327
		),
328
329
		// Add and Edit Product Pages
330
		'wpsc-product' => array(
331
			'title' => _x( 'Add and Edit Product', 'contextual help tab', 'wp-e-commerce' ),
332
			'links' => array(
333
				'category/managing-your-store/'   => _x( 'Managing Your Store'   , 'contextual help link', 'wp-e-commerce' ),
334
				'resource/video-adding-products/' => _x( 'Video: Adding Products', 'contextual help link', 'wp-e-commerce' ),
335
			),
336
		),
337
338
		// Product Tags Page
339
		'edit-product_tag' => array(
340
			'title' => _x( 'Product Tags', 'contextual help tab', 'wp-e-commerce' ),
341
			'links' =>array(
342
				'resource/video-product-tags/' => _x( 'Video: Product Tags', 'contextual help link', 'wp-e-commerce' ),
343
			),
344
		),
345
346
		// Product Category Page
347
		'edit-wpsc_product_category' => array(
348
			'title' => _x( 'Product Categories', 'contextual help tab', 'wp-e-commerce' ),
349
			'links' => array(
350
				'resource/video-creating-product-categories/' => _x( 'Video: Creating Product Categories', 'contextual help link', 'wp-e-commerce' ),
351
			),
352
		),
353
354
		// Product Variations Page
355
		'edit-wpsc-variation' => array(
356
			'title' => _x( 'Product Variations', 'contextual help tab', 'wp-e-commerce' ),
357
			'links' => array(
358
				'category/managing-your-store/' => _x( 'Managing Your Store', 'contextual help link', 'wp-e-commerce' ),
359
			),
360
		),
361
362
		// Coupon Page
363
		'wpsc-product_page_wpsc-edit-coupons' => array(
364
			'title' => _x( 'Coupons', 'contextual help tab', 'wp-e-commerce' ),
365
			'links' => array(
366
				'resource/video-creating-coupons/' => _x( 'Video: Creating Coupons', 'contextual help link', 'wp-e-commerce' ),
367
			),
368
		),
369
	);
370
371
	$screen = get_current_screen();
372
	if ( array_key_exists( $screen->id, $tabs ) ) {
373
		$tab = $tabs[$screen->id];
374
		$content = '<p><strong>' . __( 'For More Information', 'wp-e-commerce' ) . '</strong></p>';
375
		$links = array();
376
		foreach( $tab['links'] as $link => $link_title ) {
377
			$link = 'http://docs.wpecommerce.org/' . $link;
378
			$links[] = '<a target="_blank" href="' . esc_url( $link ) . '">' . esc_html( $link_title ) . '</a>';
379
		}
380
		$content .= '<p>' . implode( '<br />', $links ) . '</p>';
381
382
		$screen->add_help_tab( array(
383
			'id'      => $screen->id . '_help',
384
			'title'   => $tab['title'],
385
			'content' => $content,
386
		) );
387
388
	}
389
}
390
391
/**
392
 * This function allows change in number of purchase logs shown on Sales Log (Screen Options).
393
 *
394
 * @since 3.9
395
 * @access public
396
 *
397
 * @uses add_screen_option()
398
 */
399
function wpsc_add_purchase_logs_screen_option(){
400
401
	// setup Screen Option for purchase logs per page
402
	add_screen_option( 'per_page', array(
403
		'label'		=> __("Sales Orders", 'wp-e-commerce'),
404
		'default'	=> 20,
405
		'option'	=> 'wpsc_purchases_per_page'
406
	) );
407
}
408
409
/**
410
 * Includes purchase logs CSS and JS
411
 *
412
 * @acces public
413
 *
414
 * @uses wp_enqueue_script()    Recommended way of adding scripts in WordPress
415
 * @uses wp_localize_script()   Adds noncing and other data to the logs script
416
 */
417
function wpsc_admin_include_purchase_logs_css_and_js() {
418
419
	_wpsc_enqueue_wp_e_commerce_admin();
420
421
	wp_enqueue_script( 'wp-e-commerce-purchase-logs', WPSC_URL . '/wpsc-admin/js/purchase-logs.js', array( 'jquery' ), WPSC_VERSION . '.' . WPSC_MINOR_VERSION, true );
422
	wp_localize_script( 'wp-e-commerce-purchase-logs', 'WPSC_Purchase_Logs_Admin', array(
423
		'nonce'                                  => wp_create_nonce( 'wpsc_purchase_logs' ),
424
		'change_purchase_log_status_nonce'       => _wpsc_create_ajax_nonce( 'change_purchase_log_status' ),
425
		'purchase_log_save_tracking_id_nonce'    => _wpsc_create_ajax_nonce( 'purchase_log_save_tracking_id' ),
426
		'purchase_log_send_tracking_email_nonce' => _wpsc_create_ajax_nonce( 'purchase_log_send_tracking_email' ),
427
		'remove_log_item_nonce'                  => _wpsc_create_ajax_nonce( 'remove_log_item' ),
428
		'update_log_item_qty_nonce'              => _wpsc_create_ajax_nonce( 'update_log_item_qty' ),
429
		'add_log_item_nonce'                     => _wpsc_create_ajax_nonce( 'add_log_item' ),
430
		'search_products_nonce'                  => _wpsc_create_ajax_nonce( 'search_products' ),
431
		'sending_message'                        => _x( 'sending...', 'sending tracking email for purchase log', 'wp-e-commerce' ),
432
		'sent_message'                           => _x( 'Email Sent!', 'sending tracking email for purchase log', 'wp-e-commerce' ),
433
		'current_view'                           => empty( $_REQUEST['status'] ) ? 'all' : $_REQUEST['status'],
434
		'current_filter'                         => empty( $_REQUEST['m'] ) ? '' : $_REQUEST['m'],
435
		'current_page'                           => empty( $_REQUEST['paged'] ) ? '' : $_REQUEST['paged'],
436
		'strings'                                => array(
437
			'confirm_delete' => esc_html__( 'Are you sure you want to remove this item?', 'wp-e-commerce' ),
438
			'search_head' => esc_html__( 'Search for Products to Add', 'wp-e-commerce' ),
439
		),
440
	) );
441
442
	// Purchase Log Action Links
443
	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, true );
444
	wp_localize_script( 'wpsc-purchase-log-action-links', 'WPSC_Purchase_Log_Action_Links', array(
445
		'purchase_log_action_link_nonce' => _wpsc_create_ajax_nonce( 'purchase_log_action_link' ),
446
		'log_id'                         => empty( $_REQUEST['id'] ) ? '' : absint( $_REQUEST['id'] )
447
	) );
448
449
}
450
451
/**
452
 * Loads the WPEC settings page
453
 *
454
 * @access public
455
 *
456
 * @uses WPSC_Settings_Page::get_instance()   Gets instance of WPEC settings page
457
 */
458
function wpsc_load_settings_page() {
459
	require_once('settings-page.php');
460
	WPSC_Settings_Page::get_instance();
461
}
462
463
/**
464
 * Leads the purchase logs page
465
 *
466
 * @uses WPSC_Purchase_Log_Page()     Loads the edit and view sales page
467
 */
468
function wpsc_load_purchase_logs_page() {
469
	require_once( WPSC_FILE_PATH . '/wpsc-admin/includes/purchase-log-list-table-class.php' );
470
	require_once( WPSC_FILE_PATH . '/wpsc-admin/display-sales-logs.php' );
471
	$page = new WPSC_Purchase_Log_Page();
472
}
473
474
/**
475
 * Displays the WPEC purchase logs
476
 *
477
 * @uses do_action()  Calls 'wpsc_display_purchase_logs_page' allows hooking of the sales log page
478
 */
479
function wpsc_display_purchase_logs_page() {
480
	do_action( 'wpsc_display_purchase_logs_page' );
481
}
482
483
/**
484
 * Produces an RSS feed for the product log
485
 *
486
 * @uses add_query_arg()  Allows you to add arguments to the end of a URL
487
 * @uses admin_url()      Retrieves URL to the WordPress admin
488
 */
489
function wpsc_product_log_rss_feed() {
490
	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' />";
491
}
492
493
/**
494
 * Includes and enqueues scripts and styles for coupons
495
 *
496
 * @uses wp_enqueue_style()   Includes and prints styles for WPEC in the WordPress admin
497
 * @uses wp_enqueue_script()  Includes and prints scripts for WPEC in the WordPress admin
498
 */
499
function wpsc_admin_include_coupon_js() {
500
501
	// Variables
502
	$version_identifier = WPSC_VERSION . '.' . WPSC_MINOR_VERSION;
503
504
	// global js
505
	_wpsc_enqueue_wp_e_commerce_admin();
506
507
	// Coupon CSS
508
	wp_enqueue_style( 'wp-e-commerce-admin_2.7',        WPSC_URL         . '/wpsc-admin/css/settingspage.css', false, false,               'all' );
509
	wp_enqueue_style( 'wp-e-commerce-admin',            WPSC_URL         . '/wpsc-admin/css/admin.css',        false, $version_identifier, 'all' );
510
511
	// Coupon JS
512
	wp_enqueue_script( 'jquery-ui-datepicker' );
513
	wp_enqueue_style( 'jquery-ui-datepicker' );
514
515
	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 );
516
517
	$admin_color = get_user_option( 'admin_color' );
518
	$scheme      = 'classic' === $admin_color ? $admin_color : 'fresh';
519
520
	wp_enqueue_style( 'wpsc-jquery-ui-datepicker', WPSC_URL . '/wpsc-admin/css/jquery.ui.datepicker-' . $scheme . '.css', false, $version_identifier );
521
}
522
523
/**
524
 * Includes and enqueues scripts and styles for the WPEC options page
525
 *
526
 * @uses wp_enqueue_script()          Includes and prints out the JS for the WPEC options page
527
 * @uses wp_localize_script()         Sets up the JS vars needed
528
 * @uses _wpsc_create_ajax_nonce()    Alias for wp_create_nonce, creates a random one time use token
529
 * @uses get_current_tab_id()         Returns the current tab id
530
 * @uses wp_enqueue_style()           Includes and prints out the CSS for the WPEC options page
531
 */
532
function wpsc_admin_include_optionspage_css_and_js() {
533
534
	_wpsc_enqueue_wp_e_commerce_admin();
535
536
	$version_identifier = WPSC_VERSION . "." . WPSC_MINOR_VERSION;
537
	wp_enqueue_script( 'wp-e-commerce-admin-settings-page', WPSC_URL . '/wpsc-admin/js/settings-page.js', array( 'jquery-query' ), $version_identifier );
538
539
	wp_localize_script( 'wp-e-commerce-admin-settings-page', 'WPSC_Settings_Page', array(
540
		'navigate_settings_tab_nonce'         => _wpsc_create_ajax_nonce( 'navigate_settings_tab' ),
541
		'payment_gateway_settings_form_nonce' => _wpsc_create_ajax_nonce( 'payment_gateway_settings_form' ),
542
		'shipping_module_settings_form_nonce' => _wpsc_create_ajax_nonce( 'shipping_module_settings_form' ),
543
		'display_region_list_nonce'           => _wpsc_create_ajax_nonce( 'display_region_list' ),
544
		'update_checkout_fields_order_nonce'  => _wpsc_create_ajax_nonce( 'update_checkout_fields_order' ),
545
		'add_tax_rate_nonce'                  => _wpsc_create_ajax_nonce( 'add_tax_rate' ),
546
		'current_tab'                         => WPSC_Settings_Page::get_instance()->get_current_tab_id(),
547
		'before_unload_dialog'                => __( 'The changes you made will be lost if you navigate away from this page.', 'wp-e-commerce' ),
548
		'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' ),
549
		'edit_field_options'                  => __( 'Edit Options', 'wp-e-commerce' ),
550
		'hide_edit_field_options'             => __( 'Hide Options', 'wp-e-commerce' ),
551
		'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' ),
552
	) );
553
554
	wp_enqueue_style( 'wp-e-commerce-admin_2.7', WPSC_URL . '/wpsc-admin/css/settingspage.css', false, false, 'all' );
555
	wp_enqueue_style( 'wp-e-commerce-ui-tabs', WPSC_URL . '/wpsc-admin/css/jquery.ui.tabs.css', false, $version_identifier, 'all' );
556
}
557
558
/**
559
 * Sets up the WPEC metaboxes
560
 *
561
 * @uses remove_meta_box()    Removes the default taxonomy meta box so our own can be added
562
 * @uses add_meta_bax()       Adds metaboxes to the WordPress admin interface
563
 */
564
function wpsc_meta_boxes() {
565
	global $post;
566
	$pagename = 'wpsc-product';
567
	remove_meta_box( 'wpsc-variationdiv', 'wpsc-product', 'side' );
568
569
	//if a variation page do not show these metaboxes
570
	if ( is_object( $post ) && $post->post_parent == 0 ) {
571
		add_meta_box( 'wpsc_product_variation_forms'    , __( 'Variations', 'wp-e-commerce' )           , 'wpsc_product_variation_forms'    , $pagename, 'normal', 'high' );
572
	} else if( is_object( $post ) && $post->post_status == "inherit" ) {
573
		remove_meta_box( 'tagsdiv-product_tag'             , 'wpsc-product', 'core' );
574
		remove_meta_box( 'wpsc_product_categorydiv'        , 'wpsc-product', 'core' );
575
	}
576
577
	add_meta_box( 'wpsc_price_control_forms', __('Product Pricing', 'wp-e-commerce'), 'wpsc_price_control_forms', $pagename, 'side', 'low' );
578
	add_meta_box( 'wpsc_stock_control_forms', __('Stock Inventory', 'wp-e-commerce'), 'wpsc_stock_control_forms', $pagename, 'side', 'low' );
579
	add_meta_box( 'wpsc_product_taxes_forms', __('Taxes', 'wp-e-commerce'), 'wpsc_product_taxes_forms', $pagename, 'side', 'low' );
580
	add_meta_box( 'wpsc_product_delivery_forms', __('Product Delivery', 'wp-e-commerce'), 'wpsc_product_delivery_forms', $pagename, 'normal', 'high' );
581
	add_meta_box( 'wpsc_product_details_forms', __('Product Details', 'wp-e-commerce'), 'wpsc_product_details_forms', $pagename, 'normal', 'high' );
582
}
583
584
add_action( 'admin_footer', 'wpsc_meta_boxes' );
585
add_action( 'admin_enqueue_scripts', 'wpsc_admin_include_css_and_js_refac' );
586
587
/**
588
 * Includes the JS and CSS
589
 *
590
 * @param string    $pagehook     The pagehook for the currently viewing page, provided by the 'admin_enqueue_scripts' action
591
 *
592
 * @uses wp_admin_css()               Enqueues or prints a stylesheet in the admin
593
 * @uses wp_enqueue_script()          Enqueues the specified script
594
 * @uses wp_localize_script()         Sets up the JS vars needed
595
 * @uses wp_enqueue_style()           Enqueues the styles
596
 * @uses wp_dequeue_script()          Removes a previously enqueued script by handle
597
 * @uses _wpsc_create_ajax_nonce()    Alias for wp_create_nonce, creates a random one time use token
598
 */
599
function wpsc_admin_include_css_and_js_refac( $pagehook ) {
600
	global $post_type, $post;
601
602
	$current_screen     = get_current_screen();
603
	$version_identifier = WPSC_VERSION . "." . WPSC_MINOR_VERSION;
604
	$pages              = array( 'index.php', 'options-general.php', 'edit.php', 'post.php', 'post-new.php' );
605
606
	_wpsc_enqueue_wp_e_commerce_admin();
607
608
	if ( ! is_customize_preview() ) {
609
		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 );
610
	}
611
612
	if ( 'dashboard_page_wpsc-sales-logs' == $current_screen->id ) {
613
		// jQuery
614
		wp_enqueue_script( 'jquery' );
615
		wp_enqueue_script( 'jquery-ui-draggable' );
616
		wp_enqueue_script( 'jquery-ui-droppable' );
617
		wp_enqueue_script( 'jquery-ui-sortable' );
618
619
		// Metaboxes
620
		wp_enqueue_script( 'common' );
621
		wp_enqueue_script( 'wp-lists' );
622
		wp_enqueue_script( 'postbox' );
623
	}
624
625
	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' ) ) {
626
627
		wp_enqueue_script( 'wpsc-sortable-table', WPSC_URL . '/wpsc-admin/js/sortable-table.js', array( 'jquery' ) );
628
629
		if ( in_array( $current_screen->id, array( 'wpsc-product', 'edit-wpsc-variation', 'wpsc-product' ) ) ) {
630
			wp_enqueue_script( 'wp-e-commerce-variations', WPSC_URL . '/wpsc-admin/js/variations.js', array( 'jquery', 'wpsc-sortable-table' ), $version_identifier );
631
			wp_localize_script(
632
				'wp-e-commerce-variations',  // handle
633
				'WPSC_Variations',           // variable name
634
				array(                       // args
635
					'thickbox_title' => __( 'Add Media - %s', 'wp-e-commerce' ),
636
				)
637
			);
638
		}
639
		wp_enqueue_style( 'wp-e-commerce-admin', WPSC_URL . '/wpsc-admin/css/admin.css', false, $version_identifier, 'all' );
640
641
	}
642
643
	static $_wpsc_admin_l10n_loaded;
644
645
	if ( ! $_wpsc_admin_l10n_loaded ) {
646
		// Localize scripts
647
		wp_localize_script( 'wp-e-commerce-admin', 'wpsc_adminL10n', array(
648
			'dragndrop_set'            => ( get_option( 'wpsc_sort_by' ) == 'dragndrop' ? 'true' : 'false' ),
649
			'save_product_order_nonce' => _wpsc_create_ajax_nonce( 'save_product_order' ),
650
			'l10n_print_after'         => 'try{convertEntities(wpsc_adminL10n);}catch(e){};',
651
			'empty_coupon'             => esc_html__( 'Please enter a coupon code.', 'wp-e-commerce' ),
652
			'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' ),
653
			'wpsc_core_images_url'     => WPSC_CORE_IMAGES_URL,
654
			'variation_parent_swap'    => esc_html_x( 'New Variation Set', 'Variation taxonomy parent', 'wp-e-commerce' ),
655
			/* translators             : This string is prepended to the 'New Variation Set' string */
656
			'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' ),
657
			'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' ),
658
			/* translators             : These strings are dynamically inserted as a drop-down for the Coupon comparison conditions */
659
			'coupons_compare_or'       => esc_html_x( 'OR'  , 'Coupon comparison logic', 'wp-e-commerce' ),
660
			'coupons_compare_and'      => esc_html_x( 'AND' , 'Coupon comparison logic', 'wp-e-commerce' ),
661
			'meta_downloads_plural'    => _x( ' downloads', 'live preview for downloads metabox', 'wp-e-commerce' ),
662
			'meta_downloads_singular'  => _x( ' download' , 'live preview for downloads metabox', 'wp-e-commerce' ),
663
			'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' )
664
		) );
665
666
		$_wpsc_admin_l10n_loaded = true;
667
	}
668
669
	if ( $pagehook == 'wpsc-product-variations-iframe' ) {
670
		_wpsc_enqueue_wp_e_commerce_admin();
671
672
		wp_enqueue_script( 'wp-e-commerce-product-variations', WPSC_URL . '/wpsc-admin/js/product-variations.js', array( 'jquery' ), $version_identifier );
673
		wp_localize_script( 'wp-e-commerce-product-variations', 'WPSC_Product_Variations', array(
674
			'product_id'              => absint( $_REQUEST['product_id'] ),
675
			'add_variation_set_nonce' => _wpsc_create_ajax_nonce( 'add_variation_set' ),
676
		) );
677
	}
678
679
	if ( $pagehook == 'media-upload-popup' ) {
680
681
		$post = get_post( $_REQUEST['post_id'] );
0 ignored issues
show
introduced by
Overridding WordPress globals is prohibited
Loading history...
682
		if ( $post->post_type == 'wpsc-product' && $post->post_parent ) {
683
			_wpsc_enqueue_wp_e_commerce_admin();
684
685
			wp_dequeue_script( 'set-post-thumbnail' );
686
			wp_enqueue_script( 'wpsc-set-post-thumbnail', WPSC_URL . '/wpsc-admin/js/set-post-thumbnail.js', array( 'jquery', 'wp-e-commerce-admin' ), $version_identifier );
687
			wp_localize_script( 'wpsc-set-post-thumbnail', 'WPSC_Set_Post_Thumbnail', array(
688
				'link_text' => __( 'Use as Product Thumbnail', 'wp-e-commerce' ),
689
				'saving'    => __( 'Saving...', 'wp-e-commerce' ),
690
				'error'     => __( 'Could not set that as the thumbnail image. Try a different attachment.', 'wp-e-commerce' ),
691
				'done'      => __( 'Done', 'wp-e-commerce' ),
692
				'nonce'     => _wpsc_create_ajax_nonce( 'set_variation_product_thumbnail' ),
693
			) );
694
		}
695
	}
696
697
	if ( 'dashboard_page_wpsc-upgrades' == $pagehook || 'dashboard_page_wpsc-update' == $pagehook )
698
		wp_enqueue_style( 'wp-e-commerce-admin', WPSC_URL . '/wpsc-admin/css/admin.css', false, $version_identifier, 'all' );
699
}
700
701
702
/**
703
 * Adds admin javascript to the wp-e-commerce-admin javascript
704
 *
705
 * @since 3.8.14
706
 *
707
 * @param array  	array containing key value pairs, keys are turned into javascript globals with thier associated values
708
 *
709
 */
710
function _wpsc_admin_localizations( $localizations ) {
711
712
	$hidden_boxes  = get_option( 'wpsc_hidden_box' );
713
	$hidden_boxes  = implode( ',', (array)$hidden_boxes );
714
715
	$form_types_option   = get_option( 'wpsc_checkout_form_fields' );
716
	if ( ! $form_types_option || ! is_array( $form_types_option ) ) {
717
		$form_types_option = array();
718
	}
719
720
	$unique_names_option = get_option( 'wpsc_checkout_unique_names' );
721
	if ( ! $unique_names_option || ! is_array( $unique_names_option ) ) {
722
		$unique_names_option = array();
723
	}
724
725
	$form_types = '';
726
	foreach ( $form_types_option as $form_type ) {
727
		$form_types .= '<option value="' . $form_type . '">' . $form_type . '</option>';
728
	}
729
730
	$unique_names = '<option value="-1">' . __( 'Select a Unique Name', 'wp-e-commerce' ) . '</option>';
731
	foreach ( $unique_names_option as $unique_name ) {
732
		$unique_names .= '<option value="' . $unique_name . '">' . $unique_name . '</option>';
733
	}
734
735
	$localizations['ajaxurl']           = admin_url( 'admin-ajax.php', 'relative' );
736
	$localizations['hidden_boxes']      = '"' . esc_js( $hidden_boxes ) . '"';
737
	$localizations['IS_WP27']           = '"' . esc_js( IS_WP27 ) . '"';
738
	$localizations['TXT_WPSC_DELETE']   = '"' . esc_js( __( 'Delete', 'wp-e-commerce' ) ) . '"';
739
	$localizations['TXT_WPSC_TEXT']     = '"' . esc_js( __( 'Text', 'wp-e-commerce' ) ) . '"';
740
	$localizations['TXT_WPSC_EMAIL']    = '"' . esc_js( __( 'Email', 'wp-e-commerce' ) ) . '"';
741
	$localizations['TXT_WPSC_COUNTRY']  = '"' . esc_js( __( 'Country', 'wp-e-commerce' ) ) . '"';
742
	$localizations['TXT_WPSC_TEXTAREA'] = '"' . esc_js( __( 'Textarea', 'wp-e-commerce' ) ) . '"';
743
	$localizations['TXT_WPSC_HEADING']  = '"' . esc_js( __( 'Heading', 'wp-e-commerce' ) ) . '"';
744
	$localizations['TXT_WPSC_COUPON']   = '"' . esc_js( __( 'Coupon', 'wp-e-commerce' ) ) . '"';
745
746
	$localizations['HTML_FORM_FIELD_TYPES']        = '"' . esc_js( $form_types ) . '"';
747
	$localizations['HTML_FORM_FIELD_UNIQUE_NAMES'] = '"' . esc_js( $unique_names ) . '"';
748
749
	$localizations['TXT_WPSC_LABEL']        = '"' . esc_js( __( 'Label', 'wp-e-commerce' ) ) . '"';
750
	$localizations['TXT_WPSC_LABEL_DESC']   = '"' . esc_js( __( 'Label Description', 'wp-e-commerce' ) ) . '"';
751
	$localizations['TXT_WPSC_ITEM_NUMBER']  = '"' . esc_js( __( 'Item Number', 'wp-e-commerce' ) ) . '"';
752
	$localizations['TXT_WPSC_LIFE_NUMBER']  = '"' . esc_js( __( 'Life Number', 'wp-e-commerce' ) ) . '"';
753
	$localizations['TXT_WPSC_PRODUCT_CODE'] = '"' . esc_js( __( 'Product Code', 'wp-e-commerce' ) ) . '"';
754
	$localizations['TXT_WPSC_PDF']          = '"' . esc_js( __( 'PDF', 'wp-e-commerce' ) ) . '"';
755
756
	$localizations['TXT_WPSC_AND_ABOVE']    = '"' . esc_js( __( ' and above', 'wp-e-commerce' ) ) . '"';
757
	$localizations['TXT_WPSC_IF_PRICE_IS']  = '"' . esc_js( __( 'If price is ', 'wp-e-commerce' ) ) . '"';
758
	$localizations['TXT_WPSC_IF_WEIGHT_IS'] = '"' . esc_js( __( 'If weight is ', 'wp-e-commerce' ) ) . '"';
759
760
	// we only want to add these localizations once, it should happen on the first admin script load
761
	remove_filter( 'wpsc_javascript_localizations', '_wpsc_admin_localizations', 1 );
762
763
	return $localizations;
764
}
765
766
/*
767
 * Enqueue the admin script that applies to applies to all wpsc admin pages
768
 */
769
function _wpsc_enqueue_wp_e_commerce_admin( ) {
770
	static $already_enqueued = false;
771
	if ( ! $already_enqueued ) {
772
		$version_identifier = WPSC_VERSION . '.' . WPSC_MINOR_VERSION;
773
		wp_enqueue_script( 'wp-e-commerce-admin-js',  WPSC_URL . '/wpsc-admin/js/wp-e-commerce-admin.js', false, false, $version_identifier );
774
		wp_localize_script( 'wp-e-commerce-admin-js', 'wpsc_admin_vars', wpsc_javascript_localizations() );
775
		$already_enqueued = true;
776
	}
777
}
778
779
add_action( 'admin_menu', 'wpsc_admin_pages' );
780
781
/**
782
 * Displays latest activity in the Dashboard widget
783
 *
784
 * @uses $wpdb                          WordPress database object for queries
785
 * @uses get_var()                      Returns single variable from the database
786
 * @uses esc_html__()                   Gets translation of $text and escapes it for HTML output
787
 * @uses wpsc_currency_display()        Displays the currency
788
 * @uses admin_display_total_price()    Displays the total price
789
 * @uses esc_html_x()
790
 * @uses _n()                           Retrieves the singular or plural version
791
 */
792
function wpsc_admin_latest_activity() {
793
	global $wpdb;
794
	$totalOrders = $wpdb->get_var( "SELECT COUNT(*) FROM `" . WPSC_TABLE_PURCHASE_LOGS . "`" );
795
796
	/*
797
	 * This is the right hand side for the past 30 days revenue on the wp dashboard
798
	 */
799
	echo "<div id='leftDashboard'>";
800
	echo "<strong class='dashboardHeading'>" . esc_html__( 'Current Month', 'wp-e-commerce' ) . "</strong><br />";
801
	echo "<p class='dashboardWidgetSpecial'>";
802
	// calculates total amount of orders for the month
803
	$year = date( "Y" );
804
	$month = date( "m" );
805
	$start_timestamp = mktime( 0, 0, 0, $month, 1, $year );
806
	$end_timestamp = mktime( 0, 0, 0, ( $month + 1 ), 0, $year );
807
	$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";
808
	$currentMonthOrders = $wpdb->get_var( $sql );
809
810
	//calculates amount of money made for the month
811
	$currentMonthsSales = wpsc_currency_display( admin_display_total_price( $start_timestamp, $end_timestamp ) );
812
	echo $currentMonthsSales;
813
	echo "<span class='dashboardWidget'>" . esc_html_x( 'Sales', 'the total value of sales in dashboard widget', 'wp-e-commerce' ) . "</span>";
814
	echo "</p>";
815
	echo "<p class='dashboardWidgetSpecial'>";
816
	echo "<span class='pricedisplay'>";
817
	echo $currentMonthOrders;
818
	echo "</span>";
819
	echo "<span class='dashboardWidget'>" . _n( 'Order', 'Orders', $currentMonthOrders, 'wp-e-commerce' ) . "</span>";
820
	echo "</p>";
821
	echo "<p class='dashboardWidgetSpecial'>";
822
	//calculates average sales amount per order for the month
823
	if ( $currentMonthOrders > 0 ) {
824
		$monthsAverage = ( (int)admin_display_total_price( $start_timestamp, $end_timestamp ) / (int)$currentMonthOrders );
825
		echo wpsc_currency_display( $monthsAverage );
826
	}
827
	//echo "</span>";
828
	echo "<span class='dashboardWidget'>" . esc_html__( 'Avg Order', 'wp-e-commerce' ) . "</span>";
829
	echo "</p>";
830
	echo "</div>";
831
	/*
832
	 * This is the left side for the total life time revenue on the wp dashboard
833
	 */
834
835
	echo "<div id='rightDashboard' >";
836
	echo "<strong class='dashboardHeading'>" . esc_html__( 'Total Income', 'wp-e-commerce' ) . "</strong><br />";
837
838
	echo "<p class='dashboardWidgetSpecial'>";
839
	echo wpsc_currency_display( admin_display_total_price() );
840
	echo "<span class='dashboardWidget'>" . esc_html_x( 'Sales', 'the total value of sales in dashboard widget', 'wp-e-commerce' ) . "</span>";
841
	echo "</p>";
842
	echo "<p class='dashboardWidgetSpecial'>";
843
	echo "<span class='pricedisplay'>";
844
	echo $totalOrders;
845
	echo "</span>";
846
	echo "<span class='dashboardWidget'>" . _n( 'Order', 'Orders', $totalOrders, 'wp-e-commerce' ) . "</span>";
847
	echo "</p>";
848
	echo "<p class='dashboardWidgetSpecial'>";
849
	//calculates average sales amount per order for the month
850
	if ( ( admin_display_total_price() > 0 ) && ( $totalOrders > 0 ) ) {
851
		$totalAverage = ( (int)admin_display_total_price() / (int)$totalOrders );
852
	} else {
853
		$totalAverage = 0;
854
	}
855
	echo wpsc_currency_display( $totalAverage );
856
	//echo "</span>";
857
	echo "<span class='dashboardWidget'>" . esc_html__( 'Avg Order', 'wp-e-commerce' ) . "</span>";
858
	echo "</p>";
859
	echo "</div>";
860
	echo "<div style='clear:both'></div>";
861
}
862
add_action( 'wpsc_admin_pre_activity', 'wpsc_admin_latest_activity' );
863
864
/*
865
 * Dashboard Widget Setup
866
 * Adds the dashboard widgets if the user is an admin
867
 *
868
 * Since 3.6
869
 *
870
 * @uses wp_enqueue_style()           Enqueues CSS
871
 * @uses wp_enqueue_script()          Enqueues JS
872
 * @uses wp_add_dashboard_widget()    Adds a new widget to the WordPress admin dashboard
873
 * @uses current_user_can()           Checks the capabilities of the current user
874
 */
875
function wpsc_dashboard_widget_setup() {
876
	$version_identifier = WPSC_VERSION . "." . WPSC_MINOR_VERSION;
877
	// Enqueue the styles and scripts necessary
878
	wp_enqueue_style( 'wp-e-commerce-admin', WPSC_URL . '/wpsc-admin/css/admin.css', false, $version_identifier, 'all' );
879
	wp_enqueue_script( 'datepicker-ui', WPSC_URL . "/wpsc-core/js/ui.datepicker.js", array( 'jquery', 'jquery-ui-core', 'jquery-ui-sortable' ), $version_identifier );
880
881
	$news_cap            = apply_filters( 'wpsc_dashboard_news_cap'           , 'manage_options' );
882
	$sales_cap           = apply_filters( 'wpsc_dashboard_sales_summary_cap'  , 'manage_options' );
883
	$quarterly_sales_cap = apply_filters( 'wpsc_dashboard_quarterly_sales_cap', 'manage_options' );
884
	$monthly_sales_cap   = apply_filters( 'wpsc_dashboard_monthly_sales_cap'  , 'manage_options' );
885
886
	// Add the dashboard widgets
887
	if ( current_user_can( $news_cap ) )
888
		wp_add_dashboard_widget( 'wpsc_dashboard_news', __( 'WP eCommerce News' , 'wp-e-commerce' ), 'wpsc_dashboard_news' );
889
	if ( current_user_can( $sales_cap ) )
890
		wp_add_dashboard_widget( 'wpsc_dashboard_widget', __( 'Sales Summary', 'wp-e-commerce' ), 'wpsc_dashboard_widget' );
891
	if ( current_user_can( $quarterly_sales_cap ) )
892
		wp_add_dashboard_widget( 'wpsc_quarterly_dashboard_widget', __( 'Sales by Quarter', 'wp-e-commerce' ), 'wpsc_quarterly_dashboard_widget' );
893
	if ( current_user_can( $monthly_sales_cap ) )
894
		wp_add_dashboard_widget( 'wpsc_dashboard_4months_widget', __( 'Sales by Month', 'wp-e-commerce' ), 'wpsc_dashboard_4months_widget' );
895
896
	// Sort the Dashboard widgets so ours it at the top
897
	global $wp_meta_boxes;
898
	$boxes  = $wp_meta_boxes['dashboard'];
899
	$normal = isset( $wp_meta_boxes['dashboard']['normal'] ) ? $wp_meta_boxes['dashboard']['normal'] : array();
900
901
	$normal_dashboard   = isset( $normal['core'] ) ? $normal['core'] : array();
902
903
	// Backup and delete our new dashbaord widget from the end of the array
904
	$wpsc_widget_backup = array();
905
	if ( isset( $normal_dashboard['wpsc_dashboard_news'] ) ) {
906
		$wpsc_widget_backup['wpsc_dashboard_news'] = $normal_dashboard['wpsc_dashboard_news'];
907
		unset( $normal_dashboard['wpsc_dashboard_news'] );
908
	}
909
	if ( isset( $normal_dashboard['wpsc_dashboard_widget'] ) ) {
910
		$wpsc_widget_backup['wpsc_dashboard_widget'] = $normal_dashboard['wpsc_dashboard_widget'];
911
		unset( $normal_dashboard['wpsc_dashboard_widget'] );
912
	}
913
	if ( isset( $normal_dashboard['wpsc_quarterly_dashboard_widget'] ) ) {
914
		$wpsc_widget_backup['wpsc_quarterly_dashboard_widget'] = $normal_dashboard['wpsc_quarterly_dashboard_widget'];
915
		unset( $normal_dashboard['wpsc_quarterly_dashboard_widget'] );
916
	}
917
	if ( isset( $normal_dashboard['wpsc_dashboard_4months_widget'] ) ) {
918
		$wpsc_widget_backup['wpsc_dashboard_4months_widget'] = $normal_dashboard['wpsc_dashboard_4months_widget'];
919
		unset( $normal_dashboard['wpsc_dashboard_4months_widget'] );
920
	}
921
922
	// Merge the two arrays together so our widget is at the beginning
923
	$sorted_dashboard = array_merge( $wpsc_widget_backup, $normal_dashboard );
924
925
	// Save the sorted array back into the original metaboxes
926
927
	$wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;
928
}
929
930
/*
931
 * 	Registers the widgets on the WordPress Dashboard
932
 */
933
934
add_action( 'wp_dashboard_setup', 'wpsc_dashboard_widget_setup' );
935
936
/**
937
 * Shows the RSS feed for the WPEC dashboard widget
938
 *
939
 * @uses fetch_feed()             Build SimplePie object based on RSS or Atom feed from URL.
940
 * @uses wp_widget_rss_output()   Display the RSS entries in a list
941
 */
942
function wpsc_dashboard_news() {
943
	$rss = fetch_feed( 'http://wpecommerce.org/feed/?category_name=news' );
944
	$args = array( 'show_author' => 1, 'show_date' => 1, 'show_summary' => 1, 'items' => 3 );
945
	wp_widget_rss_output( $rss, $args );
946
947
}
948
949
/**
950
 * Gets the quarterly summary of revenue
951
 *
952
 * @uses get_option()                 Retrieves an option from the WordPress database
953
 * @uses admin_display_total_price()  Displays the total price
954
 *
955
 * @return array        The array of prices
956
 */
957
function wpsc_get_quarterly_summary() {
958
	$firstquarter = (int)get_option( 'wpsc_first_quart' );
959
	$secondquarter = (int)get_option( 'wpsc_second_quart' );
960
	$thirdquarter = (int)get_option( 'wpsc_third_quart' );
961
	$fourthquarter = (int)get_option( 'wpsc_fourth_quart' );
962
	$finalquarter = (int)get_option( 'wpsc_final_quart' );
963
964
	$results   = array();
965
	$results[] = admin_display_total_price( $thirdquarter + 1, $fourthquarter );
966
	$results[] = admin_display_total_price( $secondquarter + 1, $thirdquarter );
967
	$results[] = admin_display_total_price( $firstquarter + 1, $secondquarter );
968
	$results[] = admin_display_total_price( $finalquarter, $firstquarter );
969
	return $results;
970
}
971
972
/**
973
 * Called by wp_add_dashboard_widget and ads the quarterly revenue reports to the WordPress admin dashboard
974
 *
975
 * @uses get_option()     Gets the specified option from database
976
 * @uses esc_html_e()     Displays translated text that has been escaped for safe use in HTML
977
 */
978
function wpsc_quarterly_dashboard_widget() {
979
	if ( get_option( 'wpsc_business_year_start' ) == false ) {
980
?>
981
		<form action='' method='post'>
982
			<label for='date_start'><?php esc_html_e( 'Financial Year End' , 'wp-e-commerce' ); ?>: </label>
983
			<input id='date_start' type='text' class='pickdate' size='11' value='<?php echo get_option( 'wpsc_last_date' ); ?>' name='add_start' />
984
			   <!--<select name='add_start[day]'>
985
<?php
986
		for ( $i = 1; $i <= 31; ++$i ) {
987
			$selected = '';
988
			if ( $i == date( "d" ) ) {
989
				$selected = "selected='selected'";
990
			}
991
			echo "<option $selected value='$i'>$i</option>";
992
		}
993
?>
994
				   </select>
995
		   <select name='add_start[month]'>
996
	<?php
997
		for ( $i = 1; $i <= 12; ++$i ) {
998
			$selected = '';
999
			if ( $i == (int)date( "m" ) ) {
1000
				$selected = "selected='selected'";
1001
			}
1002
			echo "<option $selected value='$i'>" . date( "M", mktime( 0, 0, 0, $i, 1, date( "Y" ) ) ) . "</option>";
1003
		}
1004
?>
1005
				   </select>
1006
		   <select name='add_start[year]'>
1007
	<?php
1008
		for ( $i = date( "Y" ); $i <= ( date( "Y" ) + 12 ); ++$i ) {
1009
			$selected = '';
1010
			if ( $i == date( "Y" ) ) {
1011
				$selected = "selected='true'";
1012
			}
1013
			echo "<option $selected value='$i'>" . $i . "</option>";
1014
		}
1015
?>
1016
				   </select>-->
1017
		<input type='hidden' name='wpsc_admin_action' value='wpsc_quarterly' />
1018
		<input type='submit' class='button primary' value='Submit' name='wpsc_submit' />
1019
	</form>
1020
<?php
1021
		if ( get_option( 'wpsc_first_quart' ) != '' ) {
1022
			$firstquarter = get_option( 'wpsc_first_quart' );
1023
			$secondquarter = get_option( 'wpsc_second_quart' );
1024
			$thirdquarter = get_option( 'wpsc_third_quart' );
1025
			$fourthquarter = get_option( 'wpsc_fourth_quart' );
1026
			$finalquarter = get_option( 'wpsc_final_quart' );
1027
			$revenue = wpsc_get_quarterly_summary();
1028
			$currsymbol = wpsc_get_currency_symbol();
1029
			foreach ( $revenue as $rev ) {
1030
				if ( $rev == '' ) {
1031
					$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...
1032
				} else {
1033
					$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...
1034
				}
1035
			}
1036
?>
1037
			<div id='box'>
1038
				<p class='atglance'>
1039
					<span class='wpsc_quart_left'><?php esc_html_e( 'At a Glance' , 'wp-e-commerce' ); ?></span>
1040
					<span class='wpsc_quart_right'><?php esc_html_e( 'Revenue' , 'wp-e-commerce' ); ?></span>
1041
				</p>
1042
				<div style='clear:both'></div>
1043
				<p class='quarterly'>
1044
					<span class='wpsc_quart_left'><strong>01</strong>&nbsp; (<?php echo date( 'M Y', $thirdquarter ) . ' - ' . date( 'M Y', $fourthquarter ); ?>)</span>
1045
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[0]; ?></span></p>
1046
				<p class='quarterly'>
1047
					<span class='wpsc_quart_left'><strong>02</strong>&nbsp; (<?php echo date( 'M Y', $secondquarter ) . ' - ' . date( 'M Y', $thirdquarter ); ?>)</span>
1048
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[1]; ?></span></p>
1049
				<p class='quarterly'>
1050
					<span class='wpsc_quart_left'><strong>03</strong>&nbsp; (<?php echo date( 'M Y', $firstquarter ) . ' - ' . date( 'M Y', $secondquarter ); ?>)</span>
1051
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[2]; ?></span></p>
1052
				<p class='quarterly'>
1053
					<span class='wpsc_quart_left'><strong>04</strong>&nbsp; (<?php echo date( 'M Y', $finalquarter ) . ' - ' . date( 'M Y', $firstquarter ); ?>)</span>
1054
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[3]; ?></span>
1055
				</p>
1056
				<div style='clear:both'></div>
1057
			</div>
1058
<?php
1059
		}
1060
	}
1061
}
1062
1063
/**
1064
 * Called by wp_add_dashboard_widget to add the WPSC dashboard widget
1065
 *
1066
 * @uses do_action()    Calls 'wpsc_admin_pre_activity'
1067
 * @uses do_action()    Calls 'wpsc_admin_post_activity'
1068
 */
1069
function wpsc_dashboard_widget() {
1070
	do_action( 'wpsc_admin_pre_activity' );
1071
	do_action( 'wpsc_admin_post_activity' );
1072
}
1073
1074
/*
1075
 * END - Dashboard Widget for 2.7
1076
 */
1077
1078
1079
/*
1080
 * Dashboard Widget Last Four Month Sales.
1081
 *
1082
 * @uses $wpdb                      WordPress database object for queries
1083
 * @uses get_results()              Gets generic multiple row results from the WordPress database
1084
 * @uses get_var()                  Returns a single variable from the database
1085
 * @uses wpsc_currency_display()    Returns the currency with the display options applied
1086
 */
1087
function wpsc_dashboard_4months_widget() {
1088
	global $wpdb;
1089
1090
	$this_year = date( "Y" ); //get current year and month
1091
	$this_month = date( "n" );
1092
1093
	$months   = array();
1094
	$months[] = mktime( 0, 0, 0, $this_month - 3, 1, $this_year ); //generate  unix time stamps fo 4 last months
1095
	$months[] = mktime( 0, 0, 0, $this_month - 2, 1, $this_year );
1096
	$months[] = mktime( 0, 0, 0, $this_month - 1, 1, $this_year );
1097
	$months[] = mktime( 0, 0, 0, $this_month, 1, $this_year );
1098
1099
	$products = $wpdb->get_results( "SELECT `cart`.`prodid`,
1100
	 `cart`.`name`
1101
	 FROM `" . WPSC_TABLE_CART_CONTENTS . "` AS `cart`
1102
	 INNER JOIN `" . WPSC_TABLE_PURCHASE_LOGS . "` AS `logs`
1103
	 ON `cart`.`purchaseid` = `logs`.`id`
1104
	 WHERE `logs`.`processed` >= 2
1105
	 AND `logs`.`date` >= " . $months[0] . "
1106
	 GROUP BY `cart`.`prodid`
1107
	 ORDER BY SUM(`cart`.`price` * `cart`.`quantity`) DESC
1108
	 LIMIT 4", ARRAY_A ); //get 4 products with top income in 4 last months.
1109
1110
	$timeranges = array();
1111
	$timeranges[0]["start"] = mktime( 0, 0, 0, $this_month - 3, 1, $this_year ); //make array of time ranges
1112
	$timeranges[0]["end"] = mktime( 0, 0, 0, $this_month - 2, 1, $this_year );
1113
	$timeranges[1]["start"] = mktime( 0, 0, 0, $this_month - 2, 1, $this_year );
1114
	$timeranges[1]["end"] = mktime( 0, 0, 0, $this_month - 1, 1, $this_year );
1115
	$timeranges[2]["start"] = mktime( 0, 0, 0, $this_month - 1, 1, $this_year );
1116
	$timeranges[2]["end"] = mktime( 0, 0, 0, $this_month, 1, $this_year );
1117
	$timeranges[3]["start"] = mktime( 0, 0, 0, $this_month, 1, $this_year );
1118
	$timeranges[3]["end"] = time(); // using mktime here can generate a php runtime warning
1119
1120
	$prod_data = array( );
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
1121
	foreach ( (array)$products as $product ) { //run through products and get each product income amounts and name
1122
		$sale_totals = array( );
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
1123
		foreach ( $timeranges as $timerange ) { //run through time ranges of product, and get its income over each time range
1124
			$prodsql = "SELECT
1125
			SUM(`cart`.`price` * `cart`.`quantity`) AS sum
1126
			FROM `" . WPSC_TABLE_CART_CONTENTS . "` AS `cart`
1127
			INNER JOIN `" . WPSC_TABLE_PURCHASE_LOGS . "` AS `logs`
1128
				ON `cart`.`purchaseid` = `logs`.`id`
1129
			WHERE `logs`.`processed` >= 2
1130
				AND `logs`.`date` >= " . $timerange["start"] . "
1131
				AND `logs`.`date` < " . $timerange["end"] . "
1132
				AND `cart`.`prodid` = " . $product['prodid'] . "
1133
			GROUP BY `cart`.`prodid`"; //get the amount of income that current product has generaterd over current time range
1134
			$sale_totals[] = $wpdb->get_var( $prodsql ); //push amount to array
1135
		}
1136
		$prod_data[] = array(
1137
			'sale_totals' => $sale_totals,
1138
			'product_name' => $product['name'] ); //result: array of 2: $prod_data[0] = array(income)
1139
		$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...
1140
	}
1141
1142
	$tablerow = 1;
1143
	ob_start();
1144
	?>
1145
	<div style="padding-bottom:15px; "><?php esc_html_e( 'Last four months of sales on a per product basis:', 'wp-e-commerce' ); ?></div>
1146
    <table style="width:100%" border="0" cellspacing="0">
1147
    	<tr style="font-style:italic; color:#666;" height="20">
1148
    		<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>
1149
			<?php foreach ( $months as $mnth ): ?>
1150
			<td align="center" style=" font-family:\'Times New Roman\'; font-size:15px; border-bottom:solid 1px #000;"><?php echo date( "M", $mnth ); ?></td>
1151
			<?php endforeach; ?>
1152
		</tr>
1153
	<?php foreach ( (array)$prod_data as $sales_data ): ?>
1154
		<tr height="20">
1155
			<td width="20" style="font-weight:bold; color:#008080; border-bottom:solid 1px #000;"><?php echo $tablerow; ?></td>
1156
			<td style="border-bottom:solid 1px #000;width:60px"><?php echo $sales_data['product_name']; ?></td>
1157
			<?php foreach ( $sales_data['sale_totals'] as $amount ): ?>
1158
				<td align="center" style="border-bottom:solid 1px #000;"><?php echo wpsc_currency_display($amount); ?></td>
1159
			<?php endforeach; ?>
1160
		</tr>
1161
		<?php
1162
		$tablerow++;
1163
		endforeach; ?>
1164
	</table>
1165
	<?php
1166
	ob_end_flush();
1167
}
1168
1169
1170
//Modification to allow for multiple column layout
1171
1172
/**
1173
 * @todo docs
1174
 * @param $columns
1175
 * @param $screen
1176
 * @return mixed
1177
 */
1178
function wpec_two_columns( $columns, $screen ) {
1179
	if ( $screen == 'toplevel_page_wpsc-edit-products' )
1180
		$columns['toplevel_page_wpsc-edit-products'] = 2;
1181
1182
	return $columns;
1183
}
1184
add_filter( 'screen_layout_columns', 'wpec_two_columns', 10, 2 );
1185
1186
/**
1187
 * @todo docs
1188
 * @param $actions
1189
 * @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...
1190
 */
1191
function wpsc_fav_action( $actions ) {
1192
	$actions['post-new.php?post_type=wpsc-product'] = array( 'New Product', 'manage_options' );
1193
	return $actions;
1194
}
1195
add_filter( 'favorite_actions', 'wpsc_fav_action' );
1196
1197
/**
1198
 * Enqueue the admin scripts
1199
 *
1200
 * @uses wp_enqueue_script()      Enqueues scripts
1201
 * @uses home_url()               Returns the base url for the site
1202
 */
1203
function wpsc_print_admin_scripts() {
1204
	$version_identifier = WPSC_VERSION . '.' . WPSC_MINOR_VERSION;
1205
	wp_enqueue_script( 'wp-e-commerce-admin', WPSC_CORE_JS_URL . '/wp-e-commerce.js', array( 'jquery' ), $version_identifier );
1206
	wp_localize_script( 'wp-e-commerce-admin', 'wpsc_ajax', wpsc_javascript_localizations() );
1207
}
1208
1209
/**
1210
 * wpsc_ajax_ie_save save changes made using inline edit
1211
 *
1212
 * @since  3.8
1213
 * @access public
1214
 *
1215
 * @uses get_post_type_object()       Gets post object for given registered post type name
1216
 * @uses current_user_can()           Checks the capabilities of the current user
1217
 * @uses absint()                     Converts to a nonnegative integer
1218
 * @uses get_post()                   Gets the post object given post id
1219
 * @uses wp_get_object_terms()        Gets terms for given post object
1220
 * @uses wp_update_post()             Updates the post in the database
1221
 * @uses get_product_meta()           An alias for get_post_meta prefixes with the WPSC key
1222
 * @uses wpsc_convert_weight()        Converts to weight format specified by user
1223
 * @uses json_encode()                Encodes array for JS
1224
 * @uses esc_js()                     Escape single quotes, htmlspecialchar " < > &, and fix line endings.
1225
 *
1226
 * @returns nothing
1227
 */
1228
function wpsc_ajax_ie_save() {
1229
1230
	$product_post_type = get_post_type_object( 'wpsc-product' );
1231
1232
	if ( !current_user_can( $product_post_type->cap->edit_posts ) ) {
1233
		echo '({"error":"' . __( 'Error: you don\'t have required permissions to edit this product', 'wp-e-commerce' ) . '", "id": "'. esc_js( $_POST['id'] ) .'"})';
1234
		die();
1235
	}
1236
1237
	$id = absint( $_POST['id'] );
1238
	$post = get_post( $_POST['id'] );
0 ignored issues
show
introduced by
Overridding WordPress globals is prohibited
Loading history...
1239
	$parent = get_post( $post->post_parent );
1240
	$terms = wpsc_get_product_terms( $id, 'wpsc-variation', 'name' );
1241
1242
	$product = array(
1243
		'ID' => $_POST['id'],
1244
		'post_title' => $parent->post_title . ' (' . implode( ', ', $terms ) . ')',
1245
	);
1246
1247
	$id = wp_update_post( $product );
1248
	if ( $id > 0 ) {
1249
		//need parent meta to know which weight unit we are using
1250
		$parent_meta = get_product_meta($post->post_parent, 'product_metadata', true );
1251
		$product_meta = get_product_meta( $product['ID'], 'product_metadata', true );
1252
		if ( is_numeric( $_POST['weight'] ) || empty( $_POST['weight'] ) ){
1253
			$product_meta['weight'] = wpsc_convert_weight($_POST['weight'], $parent_meta['weight_unit'], 'pound', true);
1254
			$product_meta['weight_unit'] = $parent_meta['weight_unit'];
1255
		}
1256
1257
		update_product_meta( $product['ID'], 'product_metadata', $product_meta );
1258
		update_product_meta( $product['ID'], 'price', (float)$_POST['price'] );
1259
		update_product_meta( $product['ID'], 'special_price', (float)$_POST['special_price'] );
1260
		update_product_meta( $product['ID'], 'sku', sanitize_text_field( $_POST['sku'] ) );
1261
1262
		if ( !is_numeric($_POST['stock']) )
1263
			update_product_meta( $product['ID'], 'stock', '' );
1264
		else
1265
			update_product_meta( $product['ID'], 'stock', absint( $_POST['stock'] ) );
1266
1267
		$meta = get_product_meta( $id, 'product_metadata', true );
1268
		$price = get_product_meta( $id, 'price', true );
1269
		$special_price = get_product_meta( $id, 'special_price', true );
1270
		$sku = get_product_meta( $id, 'sku', true );
1271
		$sku = ( $sku )?$sku:__('N/A', 'wp-e-commerce');
1272
		$stock = get_product_meta( $id, 'stock', true );
1273
		$stock = ( $stock === '' )?__('N/A', 'wp-e-commerce'):$stock;
1274
		$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 );
1275
		echo '(' . json_encode( $results ) . ')';
1276
		die();
1277
	} else {
1278
		echo '({"error":"' . __( 'Error updating product', 'wp-e-commerce' ) . '", "id": "'. esc_js( $_POST['id'] ) .'"})';
1279
	}
1280
	die();
1281
}
1282
1283
/**
1284
 * @todo docs
1285
 *
1286
 * @uses add_meta_box  Allows addition of metaboxes to the wpsc_add_meta_boxes admin
1287
 */
1288
function wpsc_add_meta_boxes(){
1289
	add_meta_box( 'dashboard_right_now', __( 'Current Month', 'wp-e-commerce' ), 'wpsc_right_now', 'dashboard_page_wpsc-sales-logs', 'top' );
1290
}
1291
1292
/**
1293
 * Displays notice if user has Great Britain selected as their base country
1294
 * Since 3.8.9, we have deprecated Great Britain in favor of the UK
1295
 *
1296
 * @since 3.8.9
1297
 * @access private
1298
 * @link http://code.google.com/p/wp-e-commerce/issues/detail?id=1079
1299
 *
1300
 * @uses get_option()             Retrieves option from the WordPress database
1301
 * @uses get_outdate_isocodes()   Returns outdated isocodes
1302
 * @uses admin_url()              Returns admin_url of the site
1303
 *
1304
 * @return string  The admin notices for deprecated countries
1305
 */
1306
function _wpsc_action_admin_notices_deprecated_countries_notice() {
1307
	$base_country = get_option( 'base_country' );
1308
1309
	if ( ! in_array( $base_country, WPSC_Country::get_outdated_isocodes() ) )
1310
		return;
1311
1312
	switch ( $base_country ) {
1313
		case 'YU':
1314
			$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' );
1315
			break;
1316
		case 'UK':
1317
			$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' );
1318
			break;
1319
		case 'AN':
1320
			$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' );
1321
		case 'TP':
1322
			$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' );
1323
			break;
1324
	}
1325
1326
	$message = sprintf(
1327
		/* 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...
1328
		/* %1$s    */ 'http://en.wikipedia.org/wiki/ISO_3166-1',
1329
		/* %2$s    */ admin_url( 'options-general.php?page=wpsc-settings&tab=general' ),
1330
		/* %3$s    */ WPSC_VERSION
1331
	);
1332
	echo '<div id="wpsc-warning" class="error"><p>' . $message . '</p></div>';
1333
}
1334
1335
add_action( 'admin_notices'               , '_wpsc_action_admin_notices_deprecated_countries_notice' );
1336
add_action( 'wp_ajax_category_sort_order' , 'wpsc_ajax_set_category_order' );
1337
add_action( 'wp_ajax_variation_sort_order', 'wpsc_ajax_set_variation_order' );
1338
add_action( 'wp_ajax_wpsc_ie_save'        , 'wpsc_ajax_ie_save' );
1339
add_action( 'in_admin_header'             , 'wpsc_add_meta_boxes' );
1340
1341
/**
1342
 * Deletes file associated with a product.
1343
 *
1344
 * @access private
1345
 *
1346
 * @uses $wpdb              WordPress database object for queries
1347
 * @uses prepare()          Prepares a database query by escaping
1348
 * @uses wp_delete_post()   Removes a post attachment or page*
1349
 *
1350
 * @param int       $product_id     req        The id of the product
1351
 * @param string    $file_name      req        The string
1352
 *
1353
 * @return mixed
1354
 *
1355
 */
1356
function _wpsc_delete_file( $product_id, $file_name ) {
1357
	global $wpdb;
1358
1359
	$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 );
1360
	$product_id_to_delete = $wpdb->get_var( $sql );
1361
1362
	//Delete wpsc_download_status entry for this file
1363
	$wpdb->query( $wpdb->prepare( "DELETE FROM `".WPSC_TABLE_DOWNLOAD_STATUS."` WHERE `fileid`=%d AND `product_id` = %d", $product_id_to_delete, $product_id ) );
1364
1365
	return wp_delete_post( $product_id_to_delete, true );
1366
}
1367
1368
/**
1369
 * @todo docs
1370
 *
1371
 * @access private
1372
 *
1373
 * @uses add_query_arg()      Adds argument to the WordPress query
1374
 * @uses update_option()      Updates an option in the WordPress database given string and value
1375
 * @uses get_option()         Gets option from the database given string
1376
 */
1377
function _wpsc_admin_notices_3dot8dot9() {
1378
	$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>';
1379
	$message .= "\n<p>" . __( '<a href="%2$s">Hide this warning</a>', 'wp-e-commerce' ) . '</p>';
1380
	$message = sprintf(
1381
		$message,
1382
		'https://wpecommerce.org/wp-e-commerce-3-8-9-compatibility-issues/',
1383
		esc_url( add_query_arg( 'dismiss_389_upgrade_notice', 1 ) )
1384
	);
1385
1386
	echo '<div id="wpsc-3.8.9-notice" class="error">' . $message . '</div>';
1387
}
1388
1389
/**
1390
 * Checks to ensure that shipping is enabled, and one or both of the shipping/billing states are not displayed.
1391
 * If those condtions are met, and the user has not previously dismissed the notice, then we notify them
1392
 * that the shipping calculator now depend on those fields.
1393
 *
1394
 * @access private
1395
 *
1396
 * @uses add_query_arg()      Adds argument to the WordPress query
1397
 * @uses update_option()      Updates an option in the WordPress database given string and value
1398
 * @uses get_option()         Gets option from the database given string
1399
 */
1400
function _wpsc_admin_notices_3_8_14_1() {
1401
1402
	if ( get_option( 'do_not_use_shipping' ) ) {
1403
		return;
1404
	}
1405
1406
	global $wpdb;
1407
1408
	$state_visibility = $wpdb->get_var( "SELECT COUNT(active) FROM " . WPSC_TABLE_CHECKOUT_FORMS . " WHERE unique_name IN ( 'billingstate', 'shippingstate' ) AND active = '1'" );
1409
1410
	if ( '2' === $state_visibility ) {
1411
		return;
1412
	}
1413
1414
	$message = '<p>' . __( 'WP eCommerce has been updated, please confirm the checkout field display
1415
settings are correct for your store.<br><br><i>The visibility of the checkout billing and shipping
1416
drop downs that show states and provinces is now controlled by the "billingstate" and "shippingstate"
1417
options set in the <b>Store Settings</b> on the <b>Checkout</b> tab.  Prior versions used
1418
the "billingcountry" and "shippingcountry" settings to control the visibility of the drop downs.</i>' , 'wp-e-commerce' ) . '</p>';
1419
	$message .= "\n<p>" . __( '<a href="%s">Hide this warning</a>', 'wp-e-commerce' ) . '</p>';
1420
	$message = sprintf(
1421
		$message,
1422
		esc_url( add_query_arg( 'dismiss_3_8_14_1_upgrade_notice', 1 ) )
1423
	);
1424
1425
	echo '<div id="wpsc-3-8-14-1-notice" class="error">' . $message . '</div>';
1426
}
1427
1428
if ( ! get_option( 'wpsc_hide_3_8_14_1_notices' ) ) {
1429
	add_action( 'admin_notices', '_wpsc_admin_notices_3_8_14_1' );
1430
1431
  if ( isset( $_REQUEST['dismiss_3_8_14_1_upgrade_notice'] ) ) {
1432
    update_option( 'wpsc_hide_3_8_14_1_notices', true );
1433
  }
1434
}
1435
1436
/**
1437
 * @todo docs
1438
 * @access private
1439
 *
1440
 * @uses add_query_arg()      Adds argument to the WordPress query
1441
 * @uses update_option()      Updates an option in the WordPress database given string and value
1442
 * @uses get_option()         Gets option from the database given string
1443
 */
1444
function _wpsc_admin_notices_3dot8dot11() {
1445
	$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>';
1446
	$message .= "\n<p>" . __( '<a href="%4$s">Hide this warning</a>', 'wp-e-commerce' ) . '</p>';
1447
	$message  = sprintf(
1448
		$message,
1449
		WPSC_VERSION,
1450
		'https://github.com/wp-e-commerce/WP-e-Commerce/issues/359',
1451
		'http://docs.wpecommerce.org/documentation/3-8-11-user-logs',
1452
		esc_url( add_query_arg( 'dismiss_3811_upgrade_notice', 1 ) )
1453
	);
1454
1455
	echo '<div id="wpsc-3.8.11-notice" class="error">' . $message . '</div>';
1456
}
1457
1458
if ( isset( $_REQUEST['dismiss_3811_upgrade_notice'] ) )
1459
	update_option( '_wpsc_3811_user_log_notice', false );
1460
1461
if ( get_option( '_wpsc_3811_user_log_notice' ) )
1462
	add_action( 'admin_notices', '_wpsc_admin_notices_3dot8dot11' );
1463
1464
function _wpsc_notify_google_checkout_deprecation() {
1465
	$gateways = get_option( 'custom_gateway_options', array() );
1466
1467
	if ( false !== ( $key = array_search( 'google', $gateways ) ) ) {
1468
		unset( $gateways[ $key ] );
1469
	}
1470
1471
	if ( empty( $gateways ) ) {
1472
		$gateways[] = 'wpsc_merchant_testmode';
1473
	}
1474
1475
	update_option( 'custom_gateway_options', $gateways );
1476
1477
	$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>';
1478
1479
	echo '<div id="wpsc-3.8.11-notice" class="error">' . $message . '</div>';
1480
}
1481
1482
if ( in_array( 'google', get_option( 'custom_gateway_options', array() ) ) ) {
1483
	add_action( 'admin_notices', '_wpsc_notify_google_checkout_deprecation' );
1484
}
1485
1486
/**
1487
 * Adds links to premium support and documentation on WPeCommerce.org
1488
 *
1489
 * @since  3.9.0
1490
 *
1491
 * @param  array $links Original links
1492
 * @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...
1493
 */
1494
function wpsc_support_links( $links ) {
1495
	$links[] = sprintf( '<a href="%s">%s</a>', _x( 'https://wpecommerce.org/support/', 'Support URL', 'wp-e-commerce' ),  __( 'Support', 'wp-e-commerce' ) );
1496
	$links[] = sprintf( '<a href="%s">%s</a>', _x( 'http://docs.wpecommerce.org/', 'Documentation URL', 'wp-e-commerce' ),  __( 'Documentation', 'wp-e-commerce' ) );
1497
1498
	return $links;
1499
}
1500
1501
add_filter( 'plugin_action_links_' . WPSC_PLUGIN_BASENAME, 'wpsc_support_links' );
1502
1503
/**
1504
 * Adds removable query args, for compatibility with dismissable notices.
1505
 *
1506
 * @param  array $args Array of removable query args.
1507
 *
1508
 * @since  4.0
1509
 *
1510
 * @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...
1511
 */
1512
function wpsc_removable_query_args( $args ) {
1513
	$args[] = 'shipping_disabled';
1514
	return $args;
1515
}
1516
1517
add_filter( 'removable_query_args', 'wpsc_removable_query_args' );
1518
1519
/**
1520
 * Modify bulk post messages.
1521
 *
1522
 * @param  array $bulk_messages Array of bulk messages.
1523
 * @param  int   $bulk_counts   The amount of messages affected.
1524
 *
1525
 * @since  4.0
1526
 *
1527
 * @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...
1528
 */
1529
function wpsc_bulk_updated_messages( $bulk_messages, $bulk_counts ) {
1530
	$bulk_messages['wpsc-product'] = array(
1531
		'updated'   => _n( '%s product updated.', '%s products updated.', $bulk_counts['updated'], 'wp-e-commerce' ),
1532
		'locked'    => ( 1 == $bulk_counts['locked'] ) ? __( '1 product not updated, somebody is editing it.', 'wp-e-commerce' ) :
1533
		                   _n( '%s product not updated, somebody is editing it.', '%s products not updated, somebody is editing them.', $bulk_counts['locked'], 'wp-e-commerce' ),
1534
		'deleted'   => _n( '%s product permanently deleted.', '%s products permanently deleted.', $bulk_counts['deleted'], 'wp-e-commerce' ),
1535
		'trashed'   => _n( '%s product moved to the Trash.', '%s products moved to the Trash.', $bulk_counts['trashed'], 'wp-e-commerce' ),
1536
		'untrashed' => _n( '%s product restored from the Trash.', '%s products restored from the Trash.', $bulk_counts['untrashed'], 'wp-e-commerce' ),
1537
	);
1538
1539
	return $bulk_messages;
1540
}
1541
1542
add_filter( 'bulk_post_updated_messages', 'wpsc_bulk_updated_messages', 10, 2 );
1543