Completed
Pull Request — master (#2165)
by Justin
05:48
created

admin.php ➔ wpsc_admin_include_purchase_logs_css_and_js()   C

Complexity

Conditions 8
Paths 2

Size

Total Lines 46
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 34
nc 2
nop 0
dl 0
loc 46
rs 5.5555
c 0
b 0
f 0
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
	$dependencies = array( 'jquery' );
422
423
	if ( isset( $_REQUEST['id'] ) && is_numeric( $_REQUEST['id'] ) ) {
424
		wp_enqueue_style( 'wp-admin' );
425
		$dependencies[] = 'postbox';
426
	}
427
428
	wp_enqueue_script( 'wp-e-commerce-purchase-logs', WPSC_URL . '/wpsc-admin/js/purchase-logs.js', $dependencies, WPSC_VERSION . '.' . WPSC_MINOR_VERSION, true );
429
	wp_localize_script( 'wp-e-commerce-purchase-logs', 'WPSC_Purchase_Logs_Admin', array(
430
		'nonce'                                  => wp_create_nonce( 'wpsc_purchase_logs' ),
431
		'change_purchase_log_status_nonce'       => _wpsc_create_ajax_nonce( 'change_purchase_log_status' ),
432
		'purchase_log_save_tracking_id_nonce'    => _wpsc_create_ajax_nonce( 'purchase_log_save_tracking_id' ),
433
		'purchase_log_send_tracking_email_nonce' => _wpsc_create_ajax_nonce( 'purchase_log_send_tracking_email' ),
434
		'remove_log_item_nonce'                  => _wpsc_create_ajax_nonce( 'remove_log_item' ),
435
		'update_log_item_qty_nonce'              => _wpsc_create_ajax_nonce( 'update_log_item_qty' ),
436
		'add_log_item_nonce'                     => _wpsc_create_ajax_nonce( 'add_log_item' ),
437
		'edit_contact_details_nonce'             => _wpsc_create_ajax_nonce( 'edit_contact_details' ),
438
		'add_note_nonce'                         => _wpsc_create_ajax_nonce( 'add_note' ),
439
		'delete_note_nonce'                      => _wpsc_create_ajax_nonce( 'delete_note' ),
440
		'search_products_nonce'                  => _wpsc_create_ajax_nonce( 'search_products' ),
441
		'sending_message'                        => _x( 'sending...', 'sending tracking email for purchase log', 'wp-e-commerce' ),
442
		'sent_message'                           => _x( 'Email Sent!', 'sending tracking email for purchase log', 'wp-e-commerce' ),
443
		'current_view'                           => empty( $_REQUEST['status'] ) ? 'all' : $_REQUEST['status'],
444
		'current_filter'                         => empty( $_REQUEST['m'] ) ? '' : $_REQUEST['m'],
445
		'current_page'                           => empty( $_REQUEST['paged'] ) ? '' : $_REQUEST['paged'],
446
		'log_id'                                 => isset( $_REQUEST['id'] ) ? absint( $_REQUEST['id'] ) : 0,
447
		'strings'                                => array(
448
			'confirm_delete_item' => esc_html__( 'Are you sure you want to remove this item?', 'wp-e-commerce' ),
449
			'confirm_delete_note' => esc_html__( 'Are you sure you want to delete this note?', 'wp-e-commerce' ),
450
			'search_head' => esc_html__( 'Search for Products to Add', 'wp-e-commerce' ),
451
			'cancel_btn' => esc_html__( 'Cancel', 'wp-e-commerce' ),
452
		),
453
	) );
454
455
	// Purchase Log Action Links
456
	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 );
457
	wp_localize_script( 'wpsc-purchase-log-action-links', 'WPSC_Purchase_Log_Action_Links', array(
458
		'purchase_log_action_link_nonce' => _wpsc_create_ajax_nonce( 'purchase_log_action_link' ),
459
		'log_id'                         => empty( $_REQUEST['id'] ) ? '' : absint( $_REQUEST['id'] )
460
	) );
461
462
}
463
464
/**
465
 * Loads the WPEC settings page
466
 *
467
 * @access public
468
 *
469
 * @uses WPSC_Settings_Page::get_instance()   Gets instance of WPEC settings page
470
 */
471
function wpsc_load_settings_page() {
472
	require_once('settings-page.php');
473
	WPSC_Settings_Page::get_instance();
474
}
475
476
/**
477
 * Leads the purchase logs page
478
 *
479
 * @uses WPSC_Purchase_Log_Page()     Loads the edit and view sales page
480
 */
481
function wpsc_load_purchase_logs_page() {
482
	require_once( WPSC_FILE_PATH . '/wpsc-admin/includes/purchase-log-list-table-class.php' );
483
	require_once( WPSC_FILE_PATH . '/wpsc-admin/display-sales-logs.php' );
484
	$page = new WPSC_Purchase_Log_Page();
485
}
486
487
/**
488
 * Displays the WPEC purchase logs
489
 *
490
 * @uses do_action()  Calls 'wpsc_display_purchase_logs_page' allows hooking of the sales log page
491
 */
492
function wpsc_display_purchase_logs_page() {
493
	do_action( 'wpsc_display_purchase_logs_page' );
494
}
495
496
/**
497
 * Produces an RSS feed for the product log
498
 *
499
 * @uses add_query_arg()  Allows you to add arguments to the end of a URL
500
 * @uses admin_url()      Retrieves URL to the WordPress admin
501
 */
502
function wpsc_product_log_rss_feed() {
503
	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' />";
504
}
505
506
/**
507
 * Includes and enqueues scripts and styles for coupons
508
 *
509
 * @uses wp_enqueue_style()   Includes and prints styles for WPEC in the WordPress admin
510
 * @uses wp_enqueue_script()  Includes and prints scripts for WPEC in the WordPress admin
511
 */
512
function wpsc_admin_include_coupon_js() {
513
514
	// Variables
515
	$version_identifier = WPSC_VERSION . '.' . WPSC_MINOR_VERSION;
516
517
	// global js
518
	_wpsc_enqueue_wp_e_commerce_admin();
519
520
	// Coupon CSS
521
	wp_enqueue_style( 'wp-e-commerce-admin_2.7',        WPSC_URL         . '/wpsc-admin/css/settingspage.css', false, false,               'all' );
522
	wp_enqueue_style( 'wp-e-commerce-admin',            WPSC_URL         . '/wpsc-admin/css/admin.css',        false, $version_identifier, 'all' );
523
524
	// Coupon JS
525
	wp_enqueue_script( 'jquery-ui-datepicker' );
526
	wp_enqueue_style( 'jquery-ui-datepicker' );
527
528
	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 );
529
530
	$admin_color = get_user_option( 'admin_color' );
531
	$scheme      = 'classic' === $admin_color ? $admin_color : 'fresh';
532
533
	wp_enqueue_style( 'wpsc-jquery-ui-datepicker', WPSC_URL . '/wpsc-admin/css/jquery.ui.datepicker-' . $scheme . '.css', false, $version_identifier );
534
}
535
536
/**
537
 * Includes and enqueues scripts and styles for the WPEC options page
538
 *
539
 * @uses wp_enqueue_script()          Includes and prints out the JS for the WPEC options page
540
 * @uses wp_localize_script()         Sets up the JS vars needed
541
 * @uses _wpsc_create_ajax_nonce()    Alias for wp_create_nonce, creates a random one time use token
542
 * @uses get_current_tab_id()         Returns the current tab id
543
 * @uses wp_enqueue_style()           Includes and prints out the CSS for the WPEC options page
544
 */
545
function wpsc_admin_include_optionspage_css_and_js() {
546
547
	_wpsc_enqueue_wp_e_commerce_admin();
548
549
	$version_identifier = WPSC_VERSION . "." . WPSC_MINOR_VERSION;
550
	wp_enqueue_script( 'wp-e-commerce-admin-settings-page', WPSC_URL . '/wpsc-admin/js/settings-page.js', array( 'jquery-query' ), $version_identifier );
551
552
	wp_localize_script( 'wp-e-commerce-admin-settings-page', 'WPSC_Settings_Page', array(
553
		'navigate_settings_tab_nonce'         => _wpsc_create_ajax_nonce( 'navigate_settings_tab' ),
554
		'payment_gateway_settings_form_nonce' => _wpsc_create_ajax_nonce( 'payment_gateway_settings_form' ),
555
		'shipping_module_settings_form_nonce' => _wpsc_create_ajax_nonce( 'shipping_module_settings_form' ),
556
		'display_region_list_nonce'           => _wpsc_create_ajax_nonce( 'display_region_list' ),
557
		'update_checkout_fields_order_nonce'  => _wpsc_create_ajax_nonce( 'update_checkout_fields_order' ),
558
		'add_tax_rate_nonce'                  => _wpsc_create_ajax_nonce( 'add_tax_rate' ),
559
		'current_tab'                         => WPSC_Settings_Page::get_instance()->get_current_tab_id(),
560
		'before_unload_dialog'                => __( 'The changes you made will be lost if you navigate away from this page.', 'wp-e-commerce' ),
561
		'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' ),
562
		'edit_field_options'                  => __( 'Edit Options', 'wp-e-commerce' ),
563
		'hide_edit_field_options'             => __( 'Hide Options', 'wp-e-commerce' ),
564
		'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' ),
565
	) );
566
567
	wp_enqueue_style( 'wp-e-commerce-admin_2.7', WPSC_URL . '/wpsc-admin/css/settingspage.css', false, false, 'all' );
568
	wp_enqueue_style( 'wp-e-commerce-ui-tabs', WPSC_URL . '/wpsc-admin/css/jquery.ui.tabs.css', false, $version_identifier, 'all' );
569
}
570
571
/**
572
 * Sets up the WPEC metaboxes
573
 *
574
 * @uses remove_meta_box()    Removes the default taxonomy meta box so our own can be added
575
 * @uses add_meta_bax()       Adds metaboxes to the WordPress admin interface
576
 */
577
function wpsc_meta_boxes() {
578
	global $post;
579
	$pagename = 'wpsc-product';
580
	remove_meta_box( 'wpsc-variationdiv', 'wpsc-product', 'side' );
581
582
	//if a variation page do not show these metaboxes
583
	if ( is_object( $post ) && $post->post_parent == 0 ) {
584
		add_meta_box( 'wpsc_product_variation_forms'    , __( 'Variations', 'wp-e-commerce' )           , 'wpsc_product_variation_forms'    , $pagename, 'normal', 'high' );
585
	} else if( is_object( $post ) && $post->post_status == "inherit" ) {
586
		remove_meta_box( 'tagsdiv-product_tag'             , 'wpsc-product', 'core' );
587
		remove_meta_box( 'wpsc_product_categorydiv'        , 'wpsc-product', 'core' );
588
	}
589
590
	add_meta_box( 'wpsc_price_control_forms', __('Product Pricing', 'wp-e-commerce'), 'wpsc_price_control_forms', $pagename, 'side', 'low' );
591
	add_meta_box( 'wpsc_stock_control_forms', __('Stock Inventory', 'wp-e-commerce'), 'wpsc_stock_control_forms', $pagename, 'side', 'low' );
592
	add_meta_box( 'wpsc_product_taxes_forms', __('Taxes', 'wp-e-commerce'), 'wpsc_product_taxes_forms', $pagename, 'side', 'low' );
593
	add_meta_box( 'wpsc_product_delivery_forms', __('Product Delivery', 'wp-e-commerce'), 'wpsc_product_delivery_forms', $pagename, 'normal', 'high' );
594
	add_meta_box( 'wpsc_product_details_forms', __('Product Details', 'wp-e-commerce'), 'wpsc_product_details_forms', $pagename, 'normal', 'high' );
595
}
596
597
add_action( 'admin_footer', 'wpsc_meta_boxes' );
598
add_action( 'admin_enqueue_scripts', 'wpsc_admin_include_css_and_js_refac' );
599
600
/**
601
 * Includes the JS and CSS
602
 *
603
 * @param string    $pagehook     The pagehook for the currently viewing page, provided by the 'admin_enqueue_scripts' action
604
 *
605
 * @uses wp_admin_css()               Enqueues or prints a stylesheet in the admin
606
 * @uses wp_enqueue_script()          Enqueues the specified script
607
 * @uses wp_localize_script()         Sets up the JS vars needed
608
 * @uses wp_enqueue_style()           Enqueues the styles
609
 * @uses wp_dequeue_script()          Removes a previously enqueued script by handle
610
 * @uses _wpsc_create_ajax_nonce()    Alias for wp_create_nonce, creates a random one time use token
611
 */
612
function wpsc_admin_include_css_and_js_refac( $pagehook ) {
613
	global $post_type, $post;
614
615
	$current_screen     = get_current_screen();
616
	$version_identifier = WPSC_VERSION . "." . WPSC_MINOR_VERSION;
617
	$pages              = array( 'index.php', 'options-general.php', 'edit.php', 'post.php', 'post-new.php' );
618
619
	_wpsc_enqueue_wp_e_commerce_admin();
620
621
	if ( ! is_customize_preview() ) {
622
		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 );
623
	}
624
625
	if ( 'dashboard_page_wpsc-sales-logs' == $current_screen->id ) {
626
		// jQuery
627
		wp_enqueue_script( 'jquery' );
628
		wp_enqueue_script( 'jquery-ui-draggable' );
629
		wp_enqueue_script( 'jquery-ui-droppable' );
630
		wp_enqueue_script( 'jquery-ui-sortable' );
631
632
		// Metaboxes
633
		wp_enqueue_script( 'common' );
634
		wp_enqueue_script( 'wp-lists' );
635
		wp_enqueue_script( 'postbox' );
636
	}
637
638
	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' ) ) {
639
640
		wp_enqueue_script( 'wpsc-sortable-table', WPSC_URL . '/wpsc-admin/js/sortable-table.js', array( 'jquery' ) );
641
642
		if ( in_array( $current_screen->id, array( 'wpsc-product', 'edit-wpsc-variation', 'wpsc-product' ) ) ) {
643
			wp_enqueue_script( 'wp-e-commerce-variations', WPSC_URL . '/wpsc-admin/js/variations.js', array( 'jquery', 'wpsc-sortable-table' ), $version_identifier );
644
			wp_localize_script(
645
				'wp-e-commerce-variations',  // handle
646
				'WPSC_Variations',           // variable name
647
				array(                       // args
648
					'thickbox_title' => __( 'Add Media - %s', 'wp-e-commerce' ),
649
				)
650
			);
651
		}
652
		wp_enqueue_style( 'wp-e-commerce-admin', WPSC_URL . '/wpsc-admin/css/admin.css', false, $version_identifier, 'all' );
653
654
	}
655
656
	static $_wpsc_admin_l10n_loaded;
657
658
	if ( ! $_wpsc_admin_l10n_loaded ) {
659
		// Localize scripts
660
		wp_localize_script( 'wp-e-commerce-admin', 'wpsc_adminL10n', array(
661
			'dragndrop_set'            => ( get_option( 'wpsc_sort_by' ) == 'dragndrop' ? 'true' : 'false' ),
662
			'save_product_order_nonce' => _wpsc_create_ajax_nonce( 'save_product_order' ),
663
			'l10n_print_after'         => 'try{convertEntities(wpsc_adminL10n);}catch(e){};',
664
			'empty_coupon'             => esc_html__( 'Please enter a coupon code.', 'wp-e-commerce' ),
665
			'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' ),
666
			'wpsc_core_images_url'     => WPSC_CORE_IMAGES_URL,
667
			'variation_parent_swap'    => esc_html_x( 'New Variation Set', 'Variation taxonomy parent', 'wp-e-commerce' ),
668
			/* translators             : This string is prepended to the 'New Variation Set' string */
669
			'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' ),
670
			'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' ),
671
			/* translators             : These strings are dynamically inserted as a drop-down for the Coupon comparison conditions */
672
			'coupons_compare_or'       => esc_html_x( 'OR'  , 'Coupon comparison logic', 'wp-e-commerce' ),
673
			'coupons_compare_and'      => esc_html_x( 'AND' , 'Coupon comparison logic', 'wp-e-commerce' ),
674
			'meta_downloads_plural'    => _x( ' downloads', 'live preview for downloads metabox', 'wp-e-commerce' ),
675
			'meta_downloads_singular'  => _x( ' download' , 'live preview for downloads metabox', 'wp-e-commerce' ),
676
			'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' )
677
		) );
678
679
		$_wpsc_admin_l10n_loaded = true;
680
	}
681
682
	if ( $pagehook == 'wpsc-product-variations-iframe' ) {
683
		_wpsc_enqueue_wp_e_commerce_admin();
684
685
		wp_enqueue_script( 'wp-e-commerce-product-variations', WPSC_URL . '/wpsc-admin/js/product-variations.js', array( 'jquery' ), $version_identifier );
686
		wp_localize_script( 'wp-e-commerce-product-variations', 'WPSC_Product_Variations', array(
687
			'product_id'              => absint( $_REQUEST['product_id'] ),
688
			'add_variation_set_nonce' => _wpsc_create_ajax_nonce( 'add_variation_set' ),
689
		) );
690
	}
691
692
	if ( $pagehook == 'media-upload-popup' ) {
693
694
		$post = get_post( $_REQUEST['post_id'] );
0 ignored issues
show
introduced by
Overridding WordPress globals is prohibited
Loading history...
695
		if ( $post->post_type == 'wpsc-product' && $post->post_parent ) {
696
			_wpsc_enqueue_wp_e_commerce_admin();
697
698
			wp_dequeue_script( 'set-post-thumbnail' );
699
			wp_enqueue_script( 'wpsc-set-post-thumbnail', WPSC_URL . '/wpsc-admin/js/set-post-thumbnail.js', array( 'jquery', 'wp-e-commerce-admin' ), $version_identifier );
700
			wp_localize_script( 'wpsc-set-post-thumbnail', 'WPSC_Set_Post_Thumbnail', array(
701
				'link_text' => __( 'Use as Product Thumbnail', 'wp-e-commerce' ),
702
				'saving'    => __( 'Saving...', 'wp-e-commerce' ),
703
				'error'     => __( 'Could not set that as the thumbnail image. Try a different attachment.', 'wp-e-commerce' ),
704
				'done'      => __( 'Done', 'wp-e-commerce' ),
705
				'nonce'     => _wpsc_create_ajax_nonce( 'set_variation_product_thumbnail' ),
706
			) );
707
		}
708
	}
709
710
	if ( 'dashboard_page_wpsc-upgrades' == $pagehook || 'dashboard_page_wpsc-update' == $pagehook )
711
		wp_enqueue_style( 'wp-e-commerce-admin', WPSC_URL . '/wpsc-admin/css/admin.css', false, $version_identifier, 'all' );
712
}
713
714
715
/**
716
 * Adds admin javascript to the wp-e-commerce-admin javascript
717
 *
718
 * @since 3.8.14
719
 *
720
 * @param array  	array containing key value pairs, keys are turned into javascript globals with thier associated values
721
 *
722
 */
723
function _wpsc_admin_localizations( $localizations ) {
724
725
	$hidden_boxes  = get_option( 'wpsc_hidden_box' );
726
	$hidden_boxes  = implode( ',', (array)$hidden_boxes );
727
728
	$form_types_option   = get_option( 'wpsc_checkout_form_fields' );
729
	if ( ! $form_types_option || ! is_array( $form_types_option ) ) {
730
		$form_types_option = array();
731
	}
732
733
	$unique_names_option = get_option( 'wpsc_checkout_unique_names' );
734
	if ( ! $unique_names_option || ! is_array( $unique_names_option ) ) {
735
		$unique_names_option = array();
736
	}
737
738
	$form_types = '';
739
	foreach ( $form_types_option as $form_type ) {
740
		$form_types .= '<option value="' . $form_type . '">' . $form_type . '</option>';
741
	}
742
743
	$unique_names = '<option value="-1">' . __( 'Select a Unique Name', 'wp-e-commerce' ) . '</option>';
744
	foreach ( $unique_names_option as $unique_name ) {
745
		$unique_names .= '<option value="' . $unique_name . '">' . $unique_name . '</option>';
746
	}
747
748
	$localizations['ajaxurl']           = admin_url( 'admin-ajax.php', 'relative' );
749
	$localizations['hidden_boxes']      = '"' . esc_js( $hidden_boxes ) . '"';
750
	$localizations['IS_WP27']           = '"' . esc_js( IS_WP27 ) . '"';
751
	$localizations['TXT_WPSC_DELETE']   = '"' . esc_js( __( 'Delete', 'wp-e-commerce' ) ) . '"';
752
	$localizations['TXT_WPSC_TEXT']     = '"' . esc_js( __( 'Text', 'wp-e-commerce' ) ) . '"';
753
	$localizations['TXT_WPSC_EMAIL']    = '"' . esc_js( __( 'Email', 'wp-e-commerce' ) ) . '"';
754
	$localizations['TXT_WPSC_COUNTRY']  = '"' . esc_js( __( 'Country', 'wp-e-commerce' ) ) . '"';
755
	$localizations['TXT_WPSC_TEXTAREA'] = '"' . esc_js( __( 'Textarea', 'wp-e-commerce' ) ) . '"';
756
	$localizations['TXT_WPSC_HEADING']  = '"' . esc_js( __( 'Heading', 'wp-e-commerce' ) ) . '"';
757
	$localizations['TXT_WPSC_COUPON']   = '"' . esc_js( __( 'Coupon', 'wp-e-commerce' ) ) . '"';
758
759
	$localizations['HTML_FORM_FIELD_TYPES']        = '"' . esc_js( $form_types ) . '"';
760
	$localizations['HTML_FORM_FIELD_UNIQUE_NAMES'] = '"' . esc_js( $unique_names ) . '"';
761
762
	$localizations['TXT_WPSC_LABEL']        = '"' . esc_js( __( 'Label', 'wp-e-commerce' ) ) . '"';
763
	$localizations['TXT_WPSC_LABEL_DESC']   = '"' . esc_js( __( 'Label Description', 'wp-e-commerce' ) ) . '"';
764
	$localizations['TXT_WPSC_ITEM_NUMBER']  = '"' . esc_js( __( 'Item Number', 'wp-e-commerce' ) ) . '"';
765
	$localizations['TXT_WPSC_LIFE_NUMBER']  = '"' . esc_js( __( 'Life Number', 'wp-e-commerce' ) ) . '"';
766
	$localizations['TXT_WPSC_PRODUCT_CODE'] = '"' . esc_js( __( 'Product Code', 'wp-e-commerce' ) ) . '"';
767
	$localizations['TXT_WPSC_PDF']          = '"' . esc_js( __( 'PDF', 'wp-e-commerce' ) ) . '"';
768
769
	$localizations['TXT_WPSC_AND_ABOVE']    = '"' . esc_js( __( ' and above', 'wp-e-commerce' ) ) . '"';
770
	$localizations['TXT_WPSC_IF_PRICE_IS']  = '"' . esc_js( __( 'If price is ', 'wp-e-commerce' ) ) . '"';
771
	$localizations['TXT_WPSC_IF_WEIGHT_IS'] = '"' . esc_js( __( 'If weight is ', 'wp-e-commerce' ) ) . '"';
772
773
	// we only want to add these localizations once, it should happen on the first admin script load
774
	remove_filter( 'wpsc_javascript_localizations', '_wpsc_admin_localizations', 1 );
775
776
	return $localizations;
777
}
778
779
/*
780
 * Enqueue the admin script that applies to applies to all wpsc admin pages
781
 */
782
function _wpsc_enqueue_wp_e_commerce_admin( ) {
783
	static $already_enqueued = false;
784
	if ( ! $already_enqueued ) {
785
		$version_identifier = WPSC_VERSION . '.' . WPSC_MINOR_VERSION;
786
		wp_enqueue_script( 'wp-e-commerce-admin-js',  WPSC_URL . '/wpsc-admin/js/wp-e-commerce-admin.js', false, false, $version_identifier );
787
		wp_localize_script( 'wp-e-commerce-admin-js', 'wpsc_admin_vars', wpsc_javascript_localizations() );
788
		$already_enqueued = true;
789
	}
790
}
791
792
add_action( 'admin_menu', 'wpsc_admin_pages' );
793
794
/**
795
 * Displays latest activity in the Dashboard widget
796
 *
797
 * @uses $wpdb                          WordPress database object for queries
798
 * @uses get_var()                      Returns single variable from the database
799
 * @uses esc_html__()                   Gets translation of $text and escapes it for HTML output
800
 * @uses wpsc_currency_display()        Displays the currency
801
 * @uses admin_display_total_price()    Displays the total price
802
 * @uses esc_html_x()
803
 * @uses _n()                           Retrieves the singular or plural version
804
 */
805
function wpsc_admin_latest_activity() {
806
	global $wpdb;
807
	$totalOrders = $wpdb->get_var( "SELECT COUNT(*) FROM `" . WPSC_TABLE_PURCHASE_LOGS . "`" );
808
809
	/*
810
	 * This is the right hand side for the past 30 days revenue on the wp dashboard
811
	 */
812
	echo "<div id='leftDashboard'>";
813
	echo "<strong class='dashboardHeading'>" . esc_html__( 'Current Month', 'wp-e-commerce' ) . "</strong><br />";
814
	echo "<p class='dashboardWidgetSpecial'>";
815
	// calculates total amount of orders for the month
816
	$year = date( "Y" );
817
	$month = date( "m" );
818
	$start_timestamp = mktime( 0, 0, 0, $month, 1, $year );
819
	$end_timestamp = mktime( 0, 0, 0, ( $month + 1 ), 0, $year );
820
	$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";
821
	$currentMonthOrders = $wpdb->get_var( $sql );
822
823
	//calculates amount of money made for the month
824
	$currentMonthsSales = wpsc_currency_display( admin_display_total_price( $start_timestamp, $end_timestamp ) );
825
	echo $currentMonthsSales;
826
	echo "<span class='dashboardWidget'>" . esc_html_x( 'Sales', 'the total value of sales in dashboard widget', 'wp-e-commerce' ) . "</span>";
827
	echo "</p>";
828
	echo "<p class='dashboardWidgetSpecial'>";
829
	echo "<span class='pricedisplay'>";
830
	echo $currentMonthOrders;
831
	echo "</span>";
832
	echo "<span class='dashboardWidget'>" . _n( 'Order', 'Orders', $currentMonthOrders, 'wp-e-commerce' ) . "</span>";
833
	echo "</p>";
834
	echo "<p class='dashboardWidgetSpecial'>";
835
	//calculates average sales amount per order for the month
836
	if ( $currentMonthOrders > 0 ) {
837
		$monthsAverage = ( (int)admin_display_total_price( $start_timestamp, $end_timestamp ) / (int)$currentMonthOrders );
838
		echo wpsc_currency_display( $monthsAverage );
839
	}
840
	//echo "</span>";
841
	echo "<span class='dashboardWidget'>" . esc_html__( 'Avg Order', 'wp-e-commerce' ) . "</span>";
842
	echo "</p>";
843
	echo "</div>";
844
	/*
845
	 * This is the left side for the total life time revenue on the wp dashboard
846
	 */
847
848
	echo "<div id='rightDashboard' >";
849
	echo "<strong class='dashboardHeading'>" . esc_html__( 'Total Income', 'wp-e-commerce' ) . "</strong><br />";
850
851
	echo "<p class='dashboardWidgetSpecial'>";
852
	echo wpsc_currency_display( admin_display_total_price() );
853
	echo "<span class='dashboardWidget'>" . esc_html_x( 'Sales', 'the total value of sales in dashboard widget', 'wp-e-commerce' ) . "</span>";
854
	echo "</p>";
855
	echo "<p class='dashboardWidgetSpecial'>";
856
	echo "<span class='pricedisplay'>";
857
	echo $totalOrders;
858
	echo "</span>";
859
	echo "<span class='dashboardWidget'>" . _n( 'Order', 'Orders', $totalOrders, 'wp-e-commerce' ) . "</span>";
860
	echo "</p>";
861
	echo "<p class='dashboardWidgetSpecial'>";
862
	//calculates average sales amount per order for the month
863
	if ( ( admin_display_total_price() > 0 ) && ( $totalOrders > 0 ) ) {
864
		$totalAverage = ( (int)admin_display_total_price() / (int)$totalOrders );
865
	} else {
866
		$totalAverage = 0;
867
	}
868
	echo wpsc_currency_display( $totalAverage );
869
	//echo "</span>";
870
	echo "<span class='dashboardWidget'>" . esc_html__( 'Avg Order', 'wp-e-commerce' ) . "</span>";
871
	echo "</p>";
872
	echo "</div>";
873
	echo "<div style='clear:both'></div>";
874
}
875
add_action( 'wpsc_admin_pre_activity', 'wpsc_admin_latest_activity' );
876
877
/*
878
 * Dashboard Widget Setup
879
 * Adds the dashboard widgets if the user is an admin
880
 *
881
 * Since 3.6
882
 *
883
 * @uses wp_enqueue_style()           Enqueues CSS
884
 * @uses wp_enqueue_script()          Enqueues JS
885
 * @uses wp_add_dashboard_widget()    Adds a new widget to the WordPress admin dashboard
886
 * @uses current_user_can()           Checks the capabilities of the current user
887
 */
888
function wpsc_dashboard_widget_setup() {
889
	$version_identifier = WPSC_VERSION . "." . WPSC_MINOR_VERSION;
890
	// Enqueue the styles and scripts necessary
891
	wp_enqueue_style( 'wp-e-commerce-admin', WPSC_URL . '/wpsc-admin/css/admin.css', false, $version_identifier, 'all' );
892
	wp_enqueue_script( 'datepicker-ui', WPSC_URL . "/wpsc-core/js/ui.datepicker.js", array( 'jquery', 'jquery-ui-core', 'jquery-ui-sortable' ), $version_identifier );
893
894
	$news_cap            = apply_filters( 'wpsc_dashboard_news_cap'           , 'manage_options' );
895
	$sales_cap           = apply_filters( 'wpsc_dashboard_sales_summary_cap'  , 'manage_options' );
896
	$quarterly_sales_cap = apply_filters( 'wpsc_dashboard_quarterly_sales_cap', 'manage_options' );
897
	$monthly_sales_cap   = apply_filters( 'wpsc_dashboard_monthly_sales_cap'  , 'manage_options' );
898
899
	// Add the dashboard widgets
900
	if ( current_user_can( $news_cap ) )
901
		wp_add_dashboard_widget( 'wpsc_dashboard_news', __( 'WP eCommerce News' , 'wp-e-commerce' ), 'wpsc_dashboard_news' );
902
	if ( current_user_can( $sales_cap ) )
903
		wp_add_dashboard_widget( 'wpsc_dashboard_widget', __( 'Sales Summary', 'wp-e-commerce' ), 'wpsc_dashboard_widget' );
904
	if ( current_user_can( $quarterly_sales_cap ) )
905
		wp_add_dashboard_widget( 'wpsc_quarterly_dashboard_widget', __( 'Sales by Quarter', 'wp-e-commerce' ), 'wpsc_quarterly_dashboard_widget' );
906
	if ( current_user_can( $monthly_sales_cap ) )
907
		wp_add_dashboard_widget( 'wpsc_dashboard_4months_widget', __( 'Sales by Month', 'wp-e-commerce' ), 'wpsc_dashboard_4months_widget' );
908
909
	// Sort the Dashboard widgets so ours it at the top
910
	global $wp_meta_boxes;
911
	$boxes  = $wp_meta_boxes['dashboard'];
912
	$normal = isset( $wp_meta_boxes['dashboard']['normal'] ) ? $wp_meta_boxes['dashboard']['normal'] : array();
913
914
	$normal_dashboard   = isset( $normal['core'] ) ? $normal['core'] : array();
915
916
	// Backup and delete our new dashbaord widget from the end of the array
917
	$wpsc_widget_backup = array();
918
	if ( isset( $normal_dashboard['wpsc_dashboard_news'] ) ) {
919
		$wpsc_widget_backup['wpsc_dashboard_news'] = $normal_dashboard['wpsc_dashboard_news'];
920
		unset( $normal_dashboard['wpsc_dashboard_news'] );
921
	}
922
	if ( isset( $normal_dashboard['wpsc_dashboard_widget'] ) ) {
923
		$wpsc_widget_backup['wpsc_dashboard_widget'] = $normal_dashboard['wpsc_dashboard_widget'];
924
		unset( $normal_dashboard['wpsc_dashboard_widget'] );
925
	}
926
	if ( isset( $normal_dashboard['wpsc_quarterly_dashboard_widget'] ) ) {
927
		$wpsc_widget_backup['wpsc_quarterly_dashboard_widget'] = $normal_dashboard['wpsc_quarterly_dashboard_widget'];
928
		unset( $normal_dashboard['wpsc_quarterly_dashboard_widget'] );
929
	}
930
	if ( isset( $normal_dashboard['wpsc_dashboard_4months_widget'] ) ) {
931
		$wpsc_widget_backup['wpsc_dashboard_4months_widget'] = $normal_dashboard['wpsc_dashboard_4months_widget'];
932
		unset( $normal_dashboard['wpsc_dashboard_4months_widget'] );
933
	}
934
935
	// Merge the two arrays together so our widget is at the beginning
936
	$sorted_dashboard = array_merge( $wpsc_widget_backup, $normal_dashboard );
937
938
	// Save the sorted array back into the original metaboxes
939
940
	$wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;
941
}
942
943
/*
944
 * 	Registers the widgets on the WordPress Dashboard
945
 */
946
947
add_action( 'wp_dashboard_setup', 'wpsc_dashboard_widget_setup' );
948
949
/**
950
 * Shows the RSS feed for the WPEC dashboard widget
951
 *
952
 * @uses fetch_feed()             Build SimplePie object based on RSS or Atom feed from URL.
953
 * @uses wp_widget_rss_output()   Display the RSS entries in a list
954
 */
955
function wpsc_dashboard_news() {
956
	$rss = fetch_feed( 'http://wpecommerce.org/feed/?category_name=news' );
957
	$args = array( 'show_author' => 1, 'show_date' => 1, 'show_summary' => 1, 'items' => 3 );
958
	wp_widget_rss_output( $rss, $args );
959
960
}
961
962
/**
963
 * Gets the quarterly summary of revenue
964
 *
965
 * @uses get_option()                 Retrieves an option from the WordPress database
966
 * @uses admin_display_total_price()  Displays the total price
967
 *
968
 * @return array        The array of prices
969
 */
970
function wpsc_get_quarterly_summary() {
971
	$firstquarter = (int)get_option( 'wpsc_first_quart' );
972
	$secondquarter = (int)get_option( 'wpsc_second_quart' );
973
	$thirdquarter = (int)get_option( 'wpsc_third_quart' );
974
	$fourthquarter = (int)get_option( 'wpsc_fourth_quart' );
975
	$finalquarter = (int)get_option( 'wpsc_final_quart' );
976
977
	$results   = array();
978
	$results[] = admin_display_total_price( $thirdquarter + 1, $fourthquarter );
979
	$results[] = admin_display_total_price( $secondquarter + 1, $thirdquarter );
980
	$results[] = admin_display_total_price( $firstquarter + 1, $secondquarter );
981
	$results[] = admin_display_total_price( $finalquarter, $firstquarter );
982
	return $results;
983
}
984
985
/**
986
 * Called by wp_add_dashboard_widget and ads the quarterly revenue reports to the WordPress admin dashboard
987
 *
988
 * @uses get_option()     Gets the specified option from database
989
 * @uses esc_html_e()     Displays translated text that has been escaped for safe use in HTML
990
 */
991
function wpsc_quarterly_dashboard_widget() {
992
	if ( get_option( 'wpsc_business_year_start' ) == false ) {
993
?>
994
		<form action='' method='post'>
995
			<label for='date_start'><?php esc_html_e( 'Financial Year End' , 'wp-e-commerce' ); ?>: </label>
996
			<input id='date_start' type='text' class='pickdate' size='11' value='<?php echo get_option( 'wpsc_last_date' ); ?>' name='add_start' />
997
			   <!--<select name='add_start[day]'>
998
<?php
999
		for ( $i = 1; $i <= 31; ++$i ) {
1000
			$selected = '';
1001
			if ( $i == date( "d" ) ) {
1002
				$selected = "selected='selected'";
1003
			}
1004
			echo "<option $selected value='$i'>$i</option>";
1005
		}
1006
?>
1007
				   </select>
1008
		   <select name='add_start[month]'>
1009
	<?php
1010
		for ( $i = 1; $i <= 12; ++$i ) {
1011
			$selected = '';
1012
			if ( $i == (int)date( "m" ) ) {
1013
				$selected = "selected='selected'";
1014
			}
1015
			echo "<option $selected value='$i'>" . date( "M", mktime( 0, 0, 0, $i, 1, date( "Y" ) ) ) . "</option>";
1016
		}
1017
?>
1018
				   </select>
1019
		   <select name='add_start[year]'>
1020
	<?php
1021
		for ( $i = date( "Y" ); $i <= ( date( "Y" ) + 12 ); ++$i ) {
1022
			$selected = '';
1023
			if ( $i == date( "Y" ) ) {
1024
				$selected = "selected='true'";
1025
			}
1026
			echo "<option $selected value='$i'>" . $i . "</option>";
1027
		}
1028
?>
1029
				   </select>-->
1030
		<input type='hidden' name='wpsc_admin_action' value='wpsc_quarterly' />
1031
		<input type='submit' class='button primary' value='Submit' name='wpsc_submit' />
1032
	</form>
1033
<?php
1034
		if ( get_option( 'wpsc_first_quart' ) != '' ) {
1035
			$firstquarter = get_option( 'wpsc_first_quart' );
1036
			$secondquarter = get_option( 'wpsc_second_quart' );
1037
			$thirdquarter = get_option( 'wpsc_third_quart' );
1038
			$fourthquarter = get_option( 'wpsc_fourth_quart' );
1039
			$finalquarter = get_option( 'wpsc_final_quart' );
1040
			$revenue = wpsc_get_quarterly_summary();
1041
			$currsymbol = wpsc_get_currency_symbol();
1042
			foreach ( $revenue as $rev ) {
1043
				if ( $rev == '' ) {
1044
					$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...
1045
				} else {
1046
					$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...
1047
				}
1048
			}
1049
?>
1050
			<div id='box'>
1051
				<p class='atglance'>
1052
					<span class='wpsc_quart_left'><?php esc_html_e( 'At a Glance' , 'wp-e-commerce' ); ?></span>
1053
					<span class='wpsc_quart_right'><?php esc_html_e( 'Revenue' , 'wp-e-commerce' ); ?></span>
1054
				</p>
1055
				<div style='clear:both'></div>
1056
				<p class='quarterly'>
1057
					<span class='wpsc_quart_left'><strong>01</strong>&nbsp; (<?php echo date( 'M Y', $thirdquarter ) . ' - ' . date( 'M Y', $fourthquarter ); ?>)</span>
1058
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[0]; ?></span></p>
1059
				<p class='quarterly'>
1060
					<span class='wpsc_quart_left'><strong>02</strong>&nbsp; (<?php echo date( 'M Y', $secondquarter ) . ' - ' . date( 'M Y', $thirdquarter ); ?>)</span>
1061
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[1]; ?></span></p>
1062
				<p class='quarterly'>
1063
					<span class='wpsc_quart_left'><strong>03</strong>&nbsp; (<?php echo date( 'M Y', $firstquarter ) . ' - ' . date( 'M Y', $secondquarter ); ?>)</span>
1064
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[2]; ?></span></p>
1065
				<p class='quarterly'>
1066
					<span class='wpsc_quart_left'><strong>04</strong>&nbsp; (<?php echo date( 'M Y', $finalquarter ) . ' - ' . date( 'M Y', $firstquarter ); ?>)</span>
1067
					<span class='wpsc_quart_right'><?php echo $currsymbol . ' ' . $totals[3]; ?></span>
1068
				</p>
1069
				<div style='clear:both'></div>
1070
			</div>
1071
<?php
1072
		}
1073
	}
1074
}
1075
1076
/**
1077
 * Called by wp_add_dashboard_widget to add the WPSC dashboard widget
1078
 *
1079
 * @uses do_action()    Calls 'wpsc_admin_pre_activity'
1080
 * @uses do_action()    Calls 'wpsc_admin_post_activity'
1081
 */
1082
function wpsc_dashboard_widget() {
1083
	do_action( 'wpsc_admin_pre_activity' );
1084
	do_action( 'wpsc_admin_post_activity' );
1085
}
1086
1087
/*
1088
 * END - Dashboard Widget for 2.7
1089
 */
1090
1091
1092
/*
1093
 * Dashboard Widget Last Four Month Sales.
1094
 *
1095
 * @uses $wpdb                      WordPress database object for queries
1096
 * @uses get_results()              Gets generic multiple row results from the WordPress database
1097
 * @uses get_var()                  Returns a single variable from the database
1098
 * @uses wpsc_currency_display()    Returns the currency with the display options applied
1099
 */
1100
function wpsc_dashboard_4months_widget() {
1101
	global $wpdb;
1102
1103
	$this_year = date( "Y" ); //get current year and month
1104
	$this_month = date( "n" );
1105
1106
	$months   = array();
1107
	$months[] = mktime( 0, 0, 0, $this_month - 3, 1, $this_year ); //generate  unix time stamps fo 4 last months
1108
	$months[] = mktime( 0, 0, 0, $this_month - 2, 1, $this_year );
1109
	$months[] = mktime( 0, 0, 0, $this_month - 1, 1, $this_year );
1110
	$months[] = mktime( 0, 0, 0, $this_month, 1, $this_year );
1111
1112
	$products = $wpdb->get_results( "SELECT `cart`.`prodid`,
1113
	 `cart`.`name`
1114
	 FROM `" . WPSC_TABLE_CART_CONTENTS . "` AS `cart`
1115
	 INNER JOIN `" . WPSC_TABLE_PURCHASE_LOGS . "` AS `logs`
1116
	 ON `cart`.`purchaseid` = `logs`.`id`
1117
	 WHERE `logs`.`processed` >= 2
1118
	 AND `logs`.`date` >= " . $months[0] . "
1119
	 GROUP BY `cart`.`prodid`
1120
	 ORDER BY SUM(`cart`.`price` * `cart`.`quantity`) DESC
1121
	 LIMIT 4", ARRAY_A ); //get 4 products with top income in 4 last months.
1122
1123
	$timeranges = array();
1124
	$timeranges[0]["start"] = mktime( 0, 0, 0, $this_month - 3, 1, $this_year ); //make array of time ranges
1125
	$timeranges[0]["end"] = mktime( 0, 0, 0, $this_month - 2, 1, $this_year );
1126
	$timeranges[1]["start"] = mktime( 0, 0, 0, $this_month - 2, 1, $this_year );
1127
	$timeranges[1]["end"] = mktime( 0, 0, 0, $this_month - 1, 1, $this_year );
1128
	$timeranges[2]["start"] = mktime( 0, 0, 0, $this_month - 1, 1, $this_year );
1129
	$timeranges[2]["end"] = mktime( 0, 0, 0, $this_month, 1, $this_year );
1130
	$timeranges[3]["start"] = mktime( 0, 0, 0, $this_month, 1, $this_year );
1131
	$timeranges[3]["end"] = time(); // using mktime here can generate a php runtime warning
1132
1133
	$prod_data = array( );
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
1134
	foreach ( (array)$products as $product ) { //run through products and get each product income amounts and name
1135
		$sale_totals = array( );
0 ignored issues
show
introduced by
Empty array declaration must have no space between the parentheses
Loading history...
1136
		foreach ( $timeranges as $timerange ) { //run through time ranges of product, and get its income over each time range
1137
			$prodsql = "SELECT
1138
			SUM(`cart`.`price` * `cart`.`quantity`) AS sum
1139
			FROM `" . WPSC_TABLE_CART_CONTENTS . "` AS `cart`
1140
			INNER JOIN `" . WPSC_TABLE_PURCHASE_LOGS . "` AS `logs`
1141
				ON `cart`.`purchaseid` = `logs`.`id`
1142
			WHERE `logs`.`processed` >= 2
1143
				AND `logs`.`date` >= " . $timerange["start"] . "
1144
				AND `logs`.`date` < " . $timerange["end"] . "
1145
				AND `cart`.`prodid` = " . $product['prodid'] . "
1146
			GROUP BY `cart`.`prodid`"; //get the amount of income that current product has generaterd over current time range
1147
			$sale_totals[] = $wpdb->get_var( $prodsql ); //push amount to array
1148
		}
1149
		$prod_data[] = array(
1150
			'sale_totals' => $sale_totals,
1151
			'product_name' => $product['name'] ); //result: array of 2: $prod_data[0] = array(income)
1152
		$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...
1153
	}
1154
1155
	$tablerow = 1;
1156
	ob_start();
1157
	?>
1158
	<div style="padding-bottom:15px; "><?php esc_html_e( 'Last four months of sales on a per product basis:', 'wp-e-commerce' ); ?></div>
1159
    <table style="width:100%" border="0" cellspacing="0">
1160
    	<tr style="font-style:italic; color:#666;" height="20">
1161
    		<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>
1162
			<?php foreach ( $months as $mnth ): ?>
1163
			<td align="center" style=" font-family:\'Times New Roman\'; font-size:15px; border-bottom:solid 1px #000;"><?php echo date( "M", $mnth ); ?></td>
1164
			<?php endforeach; ?>
1165
		</tr>
1166
	<?php foreach ( (array)$prod_data as $sales_data ): ?>
1167
		<tr height="20">
1168
			<td width="20" style="font-weight:bold; color:#008080; border-bottom:solid 1px #000;"><?php echo $tablerow; ?></td>
1169
			<td style="border-bottom:solid 1px #000;width:60px"><?php echo $sales_data['product_name']; ?></td>
1170
			<?php foreach ( $sales_data['sale_totals'] as $amount ): ?>
1171
				<td align="center" style="border-bottom:solid 1px #000;"><?php echo wpsc_currency_display($amount); ?></td>
1172
			<?php endforeach; ?>
1173
		</tr>
1174
		<?php
1175
		$tablerow++;
1176
		endforeach; ?>
1177
	</table>
1178
	<?php
1179
	ob_end_flush();
1180
}
1181
1182
1183
//Modification to allow for multiple column layout
1184
1185
/**
1186
 * @todo docs
1187
 * @param $columns
1188
 * @param $screen
1189
 * @return mixed
1190
 */
1191
function wpec_two_columns( $columns, $screen ) {
1192
	if ( $screen == 'toplevel_page_wpsc-edit-products' )
1193
		$columns['toplevel_page_wpsc-edit-products'] = 2;
1194
1195
	return $columns;
1196
}
1197
add_filter( 'screen_layout_columns', 'wpec_two_columns', 10, 2 );
1198
1199
/**
1200
 * @todo docs
1201
 * @param $actions
1202
 * @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...
1203
 */
1204
function wpsc_fav_action( $actions ) {
1205
	$actions['post-new.php?post_type=wpsc-product'] = array( 'New Product', 'manage_options' );
1206
	return $actions;
1207
}
1208
add_filter( 'favorite_actions', 'wpsc_fav_action' );
1209
1210
/**
1211
 * Enqueue the admin scripts
1212
 *
1213
 * @uses wp_enqueue_script()      Enqueues scripts
1214
 * @uses home_url()               Returns the base url for the site
1215
 */
1216
function wpsc_print_admin_scripts() {
1217
	$version_identifier = WPSC_VERSION . '.' . WPSC_MINOR_VERSION;
1218
	wp_enqueue_script( 'wp-e-commerce-admin', WPSC_CORE_JS_URL . '/wp-e-commerce.js', array( 'jquery' ), $version_identifier );
1219
	wp_localize_script( 'wp-e-commerce-admin', 'wpsc_ajax', wpsc_javascript_localizations() );
1220
}
1221
1222
/**
1223
 * wpsc_ajax_ie_save save changes made using inline edit
1224
 *
1225
 * @since  3.8
1226
 * @access public
1227
 *
1228
 * @uses get_post_type_object()       Gets post object for given registered post type name
1229
 * @uses current_user_can()           Checks the capabilities of the current user
1230
 * @uses absint()                     Converts to a nonnegative integer
1231
 * @uses get_post()                   Gets the post object given post id
1232
 * @uses wp_get_object_terms()        Gets terms for given post object
1233
 * @uses wp_update_post()             Updates the post in the database
1234
 * @uses get_product_meta()           An alias for get_post_meta prefixes with the WPSC key
1235
 * @uses wpsc_convert_weight()        Converts to weight format specified by user
1236
 * @uses json_encode()                Encodes array for JS
1237
 * @uses esc_js()                     Escape single quotes, htmlspecialchar " < > &, and fix line endings.
1238
 *
1239
 * @returns nothing
1240
 */
1241
function wpsc_ajax_ie_save() {
1242
1243
	$product_post_type = get_post_type_object( 'wpsc-product' );
1244
1245
	if ( !current_user_can( $product_post_type->cap->edit_posts ) ) {
1246
		echo '({"error":"' . __( 'Error: you don\'t have required permissions to edit this product', 'wp-e-commerce' ) . '", "id": "'. esc_js( $_POST['id'] ) .'"})';
1247
		die();
1248
	}
1249
1250
	$id = absint( $_POST['id'] );
1251
	$post = get_post( $_POST['id'] );
0 ignored issues
show
introduced by
Overridding WordPress globals is prohibited
Loading history...
1252
	$parent = get_post( $post->post_parent );
1253
	$terms = wpsc_get_product_terms( $id, 'wpsc-variation', 'name' );
1254
1255
	$product = array(
1256
		'ID' => $_POST['id'],
1257
		'post_title' => $parent->post_title . ' (' . implode( ', ', $terms ) . ')',
1258
	);
1259
1260
	$id = wp_update_post( $product );
1261
	if ( $id > 0 ) {
1262
		//need parent meta to know which weight unit we are using
1263
		$parent_meta = get_product_meta($post->post_parent, 'product_metadata', true );
1264
		$product_meta = get_product_meta( $product['ID'], 'product_metadata', true );
1265
		if ( is_numeric( $_POST['weight'] ) || empty( $_POST['weight'] ) ){
1266
			$product_meta['weight'] = wpsc_convert_weight($_POST['weight'], $parent_meta['weight_unit'], 'pound', true);
1267
			$product_meta['weight_unit'] = $parent_meta['weight_unit'];
1268
		}
1269
1270
		update_product_meta( $product['ID'], 'product_metadata', $product_meta );
1271
		update_product_meta( $product['ID'], 'price', (float)$_POST['price'] );
1272
		update_product_meta( $product['ID'], 'special_price', (float)$_POST['special_price'] );
1273
		update_product_meta( $product['ID'], 'sku', sanitize_text_field( $_POST['sku'] ) );
1274
1275
		if ( !is_numeric($_POST['stock']) )
1276
			update_product_meta( $product['ID'], 'stock', '' );
1277
		else
1278
			update_product_meta( $product['ID'], 'stock', absint( $_POST['stock'] ) );
1279
1280
		$meta = get_product_meta( $id, 'product_metadata', true );
1281
		$price = get_product_meta( $id, 'price', true );
1282
		$special_price = get_product_meta( $id, 'special_price', true );
1283
		$sku = get_product_meta( $id, 'sku', true );
1284
		$sku = ( $sku )?$sku:__('N/A', 'wp-e-commerce');
1285
		$stock = get_product_meta( $id, 'stock', true );
1286
		$stock = ( $stock === '' )?__('N/A', 'wp-e-commerce'):$stock;
1287
		$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 );
1288
		echo '(' . json_encode( $results ) . ')';
1289
		die();
1290
	} else {
1291
		echo '({"error":"' . __( 'Error updating product', 'wp-e-commerce' ) . '", "id": "'. esc_js( $_POST['id'] ) .'"})';
1292
	}
1293
	die();
1294
}
1295
1296
/**
1297
 * @todo docs
1298
 *
1299
 * @uses add_meta_box  Allows addition of metaboxes to the wpsc_add_meta_boxes admin
1300
 */
1301
function wpsc_add_meta_boxes(){
1302
	add_meta_box( 'dashboard_right_now', __( 'Current Month', 'wp-e-commerce' ), 'wpsc_right_now', 'dashboard_page_wpsc-sales-logs', 'top' );
1303
}
1304
1305
/**
1306
 * Displays notice if user has Great Britain selected as their base country
1307
 * Since 3.8.9, we have deprecated Great Britain in favor of the UK
1308
 *
1309
 * @since 3.8.9
1310
 * @access private
1311
 * @link http://code.google.com/p/wp-e-commerce/issues/detail?id=1079
1312
 *
1313
 * @uses get_option()             Retrieves option from the WordPress database
1314
 * @uses get_outdate_isocodes()   Returns outdated isocodes
1315
 * @uses admin_url()              Returns admin_url of the site
1316
 *
1317
 * @return string  The admin notices for deprecated countries
1318
 */
1319
function _wpsc_action_admin_notices_deprecated_countries_notice() {
1320
	$base_country = get_option( 'base_country' );
1321
1322
	if ( ! in_array( $base_country, WPSC_Country::get_outdated_isocodes() ) )
1323
		return;
1324
1325
	switch ( $base_country ) {
1326
		case 'YU':
1327
			$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' );
1328
			break;
1329
		case 'UK':
1330
			$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' );
1331
			break;
1332
		case 'AN':
1333
			$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' );
1334
		case 'TP':
1335
			$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' );
1336
			break;
1337
	}
1338
1339
	$message = sprintf(
1340
		/* 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...
1341
		/* %1$s    */ 'http://en.wikipedia.org/wiki/ISO_3166-1',
1342
		/* %2$s    */ admin_url( 'options-general.php?page=wpsc-settings&tab=general' ),
1343
		/* %3$s    */ WPSC_VERSION
1344
	);
1345
	echo '<div id="wpsc-warning" class="error"><p>' . $message . '</p></div>';
1346
}
1347
1348
add_action( 'admin_notices'               , '_wpsc_action_admin_notices_deprecated_countries_notice' );
1349
add_action( 'wp_ajax_category_sort_order' , 'wpsc_ajax_set_category_order' );
1350
add_action( 'wp_ajax_variation_sort_order', 'wpsc_ajax_set_variation_order' );
1351
add_action( 'wp_ajax_wpsc_ie_save'        , 'wpsc_ajax_ie_save' );
1352
add_action( 'in_admin_header'             , 'wpsc_add_meta_boxes' );
1353
1354
/**
1355
 * Deletes file associated with a product.
1356
 *
1357
 * @access private
1358
 *
1359
 * @uses $wpdb              WordPress database object for queries
1360
 * @uses prepare()          Prepares a database query by escaping
1361
 * @uses wp_delete_post()   Removes a post attachment or page*
1362
 *
1363
 * @param int       $product_id     req        The id of the product
1364
 * @param string    $file_name      req        The string
1365
 *
1366
 * @return mixed
1367
 *
1368
 */
1369
function _wpsc_delete_file( $product_id, $file_name ) {
1370
	global $wpdb;
1371
1372
	$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 );
1373
	$product_id_to_delete = $wpdb->get_var( $sql );
1374
1375
	//Delete wpsc_download_status entry for this file
1376
	$wpdb->query( $wpdb->prepare( "DELETE FROM `".WPSC_TABLE_DOWNLOAD_STATUS."` WHERE `fileid`=%d AND `product_id` = %d", $product_id_to_delete, $product_id ) );
1377
1378
	return wp_delete_post( $product_id_to_delete, true );
1379
}
1380
1381
/**
1382
 * @todo docs
1383
 *
1384
 * @access private
1385
 *
1386
 * @uses add_query_arg()      Adds argument to the WordPress query
1387
 * @uses update_option()      Updates an option in the WordPress database given string and value
1388
 * @uses get_option()         Gets option from the database given string
1389
 */
1390
function _wpsc_admin_notices_3dot8dot9() {
1391
	$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>';
1392
	$message .= "\n<p>" . __( '<a href="%2$s">Hide this warning</a>', 'wp-e-commerce' ) . '</p>';
1393
	$message = sprintf(
1394
		$message,
1395
		'https://wpecommerce.org/wp-e-commerce-3-8-9-compatibility-issues/',
1396
		esc_url( add_query_arg( 'dismiss_389_upgrade_notice', 1 ) )
1397
	);
1398
1399
	echo '<div id="wpsc-3.8.9-notice" class="error">' . $message . '</div>';
1400
}
1401
1402
/**
1403
 * Checks to ensure that shipping is enabled, and one or both of the shipping/billing states are not displayed.
1404
 * If those condtions are met, and the user has not previously dismissed the notice, then we notify them
1405
 * that the shipping calculator now depend on those fields.
1406
 *
1407
 * @access private
1408
 *
1409
 * @uses add_query_arg()      Adds argument to the WordPress query
1410
 * @uses update_option()      Updates an option in the WordPress database given string and value
1411
 * @uses get_option()         Gets option from the database given string
1412
 */
1413
function _wpsc_admin_notices_3_8_14_1() {
1414
1415
	if ( get_option( 'do_not_use_shipping' ) ) {
1416
		return;
1417
	}
1418
1419
	global $wpdb;
1420
1421
	$state_visibility = $wpdb->get_var( "SELECT COUNT(active) FROM " . WPSC_TABLE_CHECKOUT_FORMS . " WHERE unique_name IN ( 'billingstate', 'shippingstate' ) AND active = '1'" );
1422
1423
	if ( '2' === $state_visibility ) {
1424
		return;
1425
	}
1426
1427
	$message = '<p>' . __( 'WP eCommerce has been updated, please confirm the checkout field display
1428
settings are correct for your store.<br><br><i>The visibility of the checkout billing and shipping
1429
drop downs that show states and provinces is now controlled by the "billingstate" and "shippingstate"
1430
options set in the <b>Store Settings</b> on the <b>Checkout</b> tab.  Prior versions used
1431
the "billingcountry" and "shippingcountry" settings to control the visibility of the drop downs.</i>' , 'wp-e-commerce' ) . '</p>';
1432
	$message .= "\n<p>" . __( '<a href="%s">Hide this warning</a>', 'wp-e-commerce' ) . '</p>';
1433
	$message = sprintf(
1434
		$message,
1435
		esc_url( add_query_arg( 'dismiss_3_8_14_1_upgrade_notice', 1 ) )
1436
	);
1437
1438
	echo '<div id="wpsc-3-8-14-1-notice" class="error">' . $message . '</div>';
1439
}
1440
1441
if ( ! get_option( 'wpsc_hide_3_8_14_1_notices' ) ) {
1442
	add_action( 'admin_notices', '_wpsc_admin_notices_3_8_14_1' );
1443
1444
  if ( isset( $_REQUEST['dismiss_3_8_14_1_upgrade_notice'] ) ) {
1445
    update_option( 'wpsc_hide_3_8_14_1_notices', true );
1446
  }
1447
}
1448
1449
/**
1450
 * @todo docs
1451
 * @access private
1452
 *
1453
 * @uses add_query_arg()      Adds argument to the WordPress query
1454
 * @uses update_option()      Updates an option in the WordPress database given string and value
1455
 * @uses get_option()         Gets option from the database given string
1456
 */
1457
function _wpsc_admin_notices_3dot8dot11() {
1458
	$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>';
1459
	$message .= "\n<p>" . __( '<a href="%4$s">Hide this warning</a>', 'wp-e-commerce' ) . '</p>';
1460
	$message  = sprintf(
1461
		$message,
1462
		WPSC_VERSION,
1463
		'https://github.com/wp-e-commerce/WP-e-Commerce/issues/359',
1464
		'http://docs.wpecommerce.org/documentation/3-8-11-user-logs',
1465
		esc_url( add_query_arg( 'dismiss_3811_upgrade_notice', 1 ) )
1466
	);
1467
1468
	echo '<div id="wpsc-3.8.11-notice" class="error">' . $message . '</div>';
1469
}
1470
1471
if ( isset( $_REQUEST['dismiss_3811_upgrade_notice'] ) )
1472
	update_option( '_wpsc_3811_user_log_notice', false );
1473
1474
if ( get_option( '_wpsc_3811_user_log_notice' ) )
1475
	add_action( 'admin_notices', '_wpsc_admin_notices_3dot8dot11' );
1476
1477
function _wpsc_notify_google_checkout_deprecation() {
1478
	$gateways = get_option( 'custom_gateway_options', array() );
1479
1480
	if ( false !== ( $key = array_search( 'google', $gateways ) ) ) {
1481
		unset( $gateways[ $key ] );
1482
	}
1483
1484
	if ( empty( $gateways ) ) {
1485
		$gateways[] = 'wpsc_merchant_testmode';
1486
	}
1487
1488
	update_option( 'custom_gateway_options', $gateways );
1489
1490
	$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>';
1491
1492
	echo '<div id="wpsc-3.8.11-notice" class="error">' . $message . '</div>';
1493
}
1494
1495
if ( in_array( 'google', get_option( 'custom_gateway_options', array() ) ) ) {
1496
	add_action( 'admin_notices', '_wpsc_notify_google_checkout_deprecation' );
1497
}
1498
1499
/**
1500
 * Adds links to premium support and documentation on WPeCommerce.org
1501
 *
1502
 * @since  3.9.0
1503
 *
1504
 * @param  array $links Original links
1505
 * @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...
1506
 */
1507
function wpsc_support_links( $links ) {
1508
	$links[] = sprintf( '<a href="%s">%s</a>', _x( 'https://wpecommerce.org/support/', 'Support URL', 'wp-e-commerce' ),  __( 'Support', 'wp-e-commerce' ) );
1509
	$links[] = sprintf( '<a href="%s">%s</a>', _x( 'http://docs.wpecommerce.org/', 'Documentation URL', 'wp-e-commerce' ),  __( 'Documentation', 'wp-e-commerce' ) );
1510
1511
	return $links;
1512
}
1513
1514
add_filter( 'plugin_action_links_' . WPSC_PLUGIN_BASENAME, 'wpsc_support_links' );
1515
1516
/**
1517
 * Adds removable query args, for compatibility with dismissable notices.
1518
 *
1519
 * @param  array $args Array of removable query args.
1520
 *
1521
 * @since  4.0
1522
 *
1523
 * @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...
1524
 */
1525
function wpsc_removable_query_args( $args ) {
1526
	$args[] = 'shipping_disabled';
1527
	return $args;
1528
}
1529
1530
add_filter( 'removable_query_args', 'wpsc_removable_query_args' );
1531
1532
/**
1533
 * Modify bulk post messages.
1534
 *
1535
 * @param  array $bulk_messages Array of bulk messages.
1536
 * @param  int   $bulk_counts   The amount of messages affected.
1537
 *
1538
 * @since  4.0
1539
 *
1540
 * @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...
1541
 */
1542
function wpsc_bulk_updated_messages( $bulk_messages, $bulk_counts ) {
1543
	$bulk_messages['wpsc-product'] = array(
1544
		'updated'   => _n( '%s product updated.', '%s products updated.', $bulk_counts['updated'], 'wp-e-commerce' ),
1545
		'locked'    => ( 1 == $bulk_counts['locked'] ) ? __( '1 product not updated, somebody is editing it.', 'wp-e-commerce' ) :
1546
		                   _n( '%s product not updated, somebody is editing it.', '%s products not updated, somebody is editing them.', $bulk_counts['locked'], 'wp-e-commerce' ),
1547
		'deleted'   => _n( '%s product permanently deleted.', '%s products permanently deleted.', $bulk_counts['deleted'], 'wp-e-commerce' ),
1548
		'trashed'   => _n( '%s product moved to the Trash.', '%s products moved to the Trash.', $bulk_counts['trashed'], 'wp-e-commerce' ),
1549
		'untrashed' => _n( '%s product restored from the Trash.', '%s products restored from the Trash.', $bulk_counts['untrashed'], 'wp-e-commerce' ),
1550
	);
1551
1552
	return $bulk_messages;
1553
}
1554
1555
add_filter( 'bulk_post_updated_messages', 'wpsc_bulk_updated_messages', 10, 2 );
1556