woocommerce-advanced-ordernumbers.php 31.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<?php
/**
 * Plugin Name: Advanced Ordernumbers
 * Plugin URI: http://open-tools.net/WooCommerce/Advanced-Ordernumbers.php
 * Description: Lets the user freely configure the order numbers in WooCommerce.
 * Version: 0.1.0
 * Author: Open Tools, Reinhold Kainhofer
 * Author URI: http://open-tools.net
 * Text Domain: woocommerce-advanced-ordernumbers
 * Domain Path: 
 * License: GPL2+
 WC requires at least: 2.2
WC tested up to: 2.3
*/

/**
17
 * The structure of this plugin originally followed the tutorial, although much of the plugin has been rewritten since then:
18
 * http://www.yaconiello.com/blog/how-to-write-wordpress-plugin/
19
 * A lot of coding ideas were also taken directly from the way things are implemented in WooCommerce itself.
20 21 22 23 24 25 26 27 28 29 30
 */
 
if ( ! defined( 'ABSPATH' ) ) { 
	exit; // Exit if accessed directly
}
/**
 * Check if WooCommerce is active
 **/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    // Put your plugin code here
    // Load the language files
31
	load_plugin_textdomain('opentools-ordernumbers', false, basename( dirname( __FILE__ ) ) . '/languages' );
32 33 34

	if (!class_exists("OpenToolsOrdernumbers")) {
		class OpenToolsOrdernumbers {
35
			public $ordernumber_meta = "_order_number";
36 37
			public $ordernumber_new_placeholder = "[New Order]";
			public $ordernumber_counter_prefix = 'ordernumber-counter-';
38
			
39 40 41 42 43
			/**
			 * Construct the plugin object
			 */
			public function __construct()
			{
44
				$plugin = plugin_basename(__FILE__); 
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71


				// Init settings
				$this->settings = array(
					array(
						'name' 		=> __( 'Advanced Order Numbers', 'woocommerce-advanced-ordernumbers' ),
						'desc'		=> __( 'Configure the format and the counters of the order numbers in WooCommerce.', 'woocommerce-advanced-ordernumbers' ),
						'type' 		=> 'title',
						'id' 		=> 'ordernumber_options'
					),

					array(
						'name' 		=> __( 'Customize Order Numbers', 'woocommerce-advanced-ordernumbers' ),
						'desc' 		=> __( 'Check to use custom order numbers rather than the default wordpress post ID.', 'woocommerce-advanced-ordernumbers' ),
						'id' 		=> 'customize_ordernumber',
						'type' 		=> 'checkbox',
						'default'	=> 'no'
					),
					array(
						'title'		=> __( 'Order number format', 'woocommerce-advanced-ordernumbers' ),
						'desc' 		=> __( 'The format for the order numbers (variables can be entered as [...], the counter is indicated by the #). To use a different counter name than displayed, put the custom counter name after a |, e.g. "[year]-[month]/#|[year]" to use the month in the order number, but reset the counter only yearly.', 'woocommerce-advanced-ordernumbers' ),
						'desc_tip'	=> true,
						'id' 		=> 'ordernumber_format',
						'default'	=> '#',
						'type' 		=> 'text',
					),
					array(
72 73 74
						'title'		=> __( 'Use global counter', 'woocommerce-advanced-ordernumbers' ),
						'desc' 		=> __( 'A global counter is independent of the number format and will never reset. A non-global counter runs within the number format and will start from the inital value whenever any of the variables used in the format changes (to be precise: a new counter will be used, so it is possible to have multiple counters running in parallel).', 'woocommerce-advanced-ordernumbers' ),
						'desc_tip'	=> true,
75 76 77 78 79
						'id' 		=> 'ordernumber_global',
						'type' 		=> 'checkbox',
						'default'	=> 'no'
					),
					array(
80
						'title' 	=> __( 'Counter Digits', 'woocommerce-advanced-ordernumbers' ),
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
						'desc' 		=> __( 'Minimum number of digits for the number', 'woocommerce-advanced-ordernumbers' ),
						'desc_tip'	=> true,
						'id' 		=> 'ordernumber_padding',
						'type' 		=> 'number',
						'default'	=> '0'
					),
					array(
						'title' 	=> __( 'Counter Start', 'woocommerce-advanced-ordernumbers' ),
						'desc' 		=> __( 'Start value for each new counter', 'woocommerce-advanced-ordernumbers' ),
						'desc_tip'	=> true,
						'id' 		=> 'ordernumber_start',
						'type' 		=> 'number',
						'default'	=> '1'
					),
					array(
						'title'	=> __( 'Counter step', 'woocommerce-advanced-ordernumbers' ),
						'desc' 		=> __( 'By how much the counter will be increased after each order. Typically 1.', 'woocommerce-advanced-ordernumbers' ),
						'desc_tip'	=> true,
						'id' 		=> 'ordernumber_step',
						'type' 		=> 'number',
						'default'	=> '1'
					),
					array( 'type' => 'sectionend', 'id' => 'ordernumber_options' ),
					
					// TODO: customize order password, and other numbers!
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

					array(
						'name' 		=> __( 'Custom Variables', 'woocommerce-advanced-ordernumbers' ),
						'desc'		=> __( 'Define your own (conditional) variables for use in the number formats', 'woocommerce-advanced-ordernumbers' ),
						'type' 		=> 'title',
						'id' 		=> 'ordernumber_variables'
					),
					array(
// 						'title'		=> __( 'Custom ', 'woocommerce-advanced-ordernumbers' ),
// 						'desc' 		=> __( 'The format for the order numbers (variables can be entered as [...], the counter is indicated by the #). To use a different counter name than displayed, put the custom counter name after a |, e.g. "[year]-[month]/#|[year]" to use the month in the order number, but reset the counter only yearly.', 'woocommerce-advanced-ordernumbers' ),
						'id' 		=> 'ordernumber_variables',
						'type' 		=> 'ordernumber_variables',
					),
					array( 'type' => 'sectionend', 'id' => 'ordernumber_variables' ),

					array(
						'name' 		=> __( 'Current Counters', 'woocommerce-advanced-ordernumbers' ),
						'type' 		=> 'title',
						'id' 		=> 'ordernumber_counters'
					),
					array(
127 128 129
						'name' 		=> __( 'All Ordernumber Counters', 'woocommerce-advanced-ordernumbers' ),
						'desc'		=> __( 'View and modify the current counter values. The counter value is the value used for the previous number. All changes are immediately applied!', 'woocommerce-advanced-ordernumbers' ),
						'desc_tip'	=> true,
130 131 132 133 134
						'id' 		=> 'ordernumber_counters',
						'type' 		=> 'ordernumber_counters',
					),
					array( 'type' => 'sectionend', 'id' => 'ordernumber_counters' ),

135 136 137 138 139 140 141 142 143
				);
				// Default options

				add_option ('customize_ordernumber', '0');
				add_option ('ordernumber_format',    "#");
				add_option ('ordernumber_global',    '0');
				add_option ('ordernumber_padding',   '1');
				add_option ('ordernumber_start',     '1');
				add_option ('ordernumber_step',      '1');
144
				
145
 				add_option ('ordernumber_variables',  array());
146

147 148 149 150
				// register filters and actions
				
				// CONFIGURATION SCREENS
				add_filter( 'woocommerce_get_sections_checkout',                array($this, 'add_admin_section'));
151
				// The checkout settings page assumes all subpages are payment gateways, so we have to override this and manually pass our settings:
152 153 154
				add_action( 'woocommerce_settings_checkout',                    array( $this, 'settings_output' ) );
				add_action( 'woocommerce_settings_save_checkout',               array( $this, 'settings_save' ) );
				add_action( 'woocommerce_admin_field_ordernumber_counters',     array( $this, 'admin_field_counters' ) );
155 156
				add_action( 'woocommerce_admin_field_ordernumber_variables',    array( $this, 'admin_field_variables' ) );
				add_action( 'pre_update_option_ordernumber_variables',          array( $this, 'update_option_variables'));
157 158 159 160 161 162 163 164 165

				add_action( 'admin_print_styles-woocommerce_page_wc-settings',  array($this, 'print_admin_styles'));
				add_action( 'admin_print_scripts-woocommerce_page_wc-settings', array($this, 'print_admin_scripts'));
				
				// AJAX counter modifications
				add_action( 'wp_ajax_set_counter',    array($this, 'counter_set_callback') );
				add_action( 'wp_ajax_add_counter',    array($this, 'counter_add_callback') );
				add_action( 'wp_ajax_delete_counter', array($this, 'counter_delete_callback') );

166 167
				// Add the ordernumber post meta to the search in the backend
				add_filter( 'woocommerce_shop_order_search_fields', array($this, 'order_search_fields'));
168 169 170
				// Sort the order list in the backend by order number rather than ID, make sure this is called LAST so we modify the defaults passed as arguments
				add_filter( 'manage_edit-shop_order_sortable_columns', array( $this, 'modify_order_column_sortkey' ), 9999 );

171 172 173 174
				// When a new order is created, we immediately assign the order number:
				add_action( 'wp_insert_post', array(&$this, 'check_create_ordernumber'), 10, 3);
				add_action( 'save_post', array(&$this, 'check_create_ordernumber'), 10, 3);
				// The filter to actually return the order number for the given order
175
				add_filter ('woocommerce_order_number', array(&$this, 'get_ordernumber'), 10, 2/*<= Also get the order object! */);
176 177
			}
    
178 179
			// Activate the plugin
			public static function activate() {}
180
    
181 182 183
			// Deactivate the plugin
			public static function deactivate() {}

184 185 186 187
			/**
			 * Insert our own section in the checkout setting page. Rearrange the sections array to make sure our settings
			 * come second place, directly after the default page with the '' key and before all the payment gateways
			 */
188
			function add_admin_section($sections) {
189 190 191 192 193 194 195 196
				$newsections = array();
				foreach ($sections as $sec => $name ) {
					$newsections[$sec] = $name;
					if ($sec == '') {
						$newsections['ordernumber'] = __( 'Order Numbers', 'woocommerce-advanced-ordernumbers');
					}
				}
				return $newsections;
197 198
			}
			
199
			public function settings_output() {
200 201 202 203 204
				global $current_section;
				if ($current_section == 'ordernumber') {
					$settings = $this->settings;
					WC_Admin_Settings::output_fields( $settings );
				}
205 206
			}

207
			public function settings_save() {
208 209 210 211 212
				global $current_section;
				if ($current_section == 'ordernumber') {
					$settings = $this->settings;
					WC_Admin_Settings::save_fields( $settings );
				}
213
			}
214
			
215 216 217 218 219 220
			/** 
			 * Print the CSS for the counter values and counter variables tables to the page header in the WC backend admin setting page
			 */
			public function print_admin_styles () {
				wp_register_style ( 'ordernumber-counter-style',  plugins_url('assets/css/ordernumber-counter.css', __FILE__) );
				wp_enqueue_style('ordernumber-counter-style');
221 222 223

				wp_register_style ( 'ordernumber-variables-style',  plugins_url('assets/css/ordernumber-variables.css', __FILE__) );
				wp_enqueue_style('ordernumber-variables-style');
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
			}
			/** 
			 * Print the JS for the counter values and counter variables tables to the page header in the WC backend admin setting page
			 */
			public function print_admin_scripts() {
			
				wp_register_script( 'ordernumber-counter-script', plugins_url( 'assets/js/ordernumber-counter.js',  __FILE__), array('jquery') );
				wp_enqueue_script( 'ordernumber-counter-script');
				
				// Handle the translations:
				$localizations = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );
				
				$localizations['ORDERNUMBER_JS_JSONERROR'] = __("Error reading response from server:");
				$localizations['ORDERNUMBER_JS_NOT_AUTHORIZED'] = __("You are not authorized to modify order number counters.");
				$localizations['ORDERNUMBER_JS_NEWCOUNTER'] = __("Please enter the format/name of the new counter:");
				$localizations['ORDERNUMBER_JS_ADD_FAILED'] = __("Failed adding counter {0}");
				$localizations['ORDERNUMBER_JS_INVALID_COUNTERVALUE'] = __("You entered an invalid value for the counter.\n\n");
				
				$localizations['ORDERNUMBER_JS_EDITCOUNTER'] = __("{0}Please enter the new value for the counter '{1}' (current value: {2}):");
				$localizations['ORDERNUMBER_JS_MODIFY_FAILED'] = __("Failed modifying counter {0}");
				$localizations['ORDERNUMBER_JS_DELETECOUNTER'] = __("Really delete counter '{0}' with value '{1}'?");
				$localizations['ORDERNUMBER_JS_DELETE_FAILED'] = __("Failed deleting counter {0}");

				// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
				wp_localize_script( 'ordernumber-counter-script', 'ajax_ordernumber', $localizations );
249 250 251 252 253



				wp_register_script( 'ordernumber-variables-script', plugins_url( 'assets/js/ordernumber-variables.js',  __FILE__), array('jquery') );
				wp_enqueue_script( 'ordernumber-variables-script');
254
			}
255

256 257 258 259
			/**
			 * Render the Custom Variables configuration table
			 */
			public function admin_field_variables($settings) {
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
				$variables = get_option( $settings['id'], array() );
				if (!is_array($variables)) {
					$variables = array();
				}
// echo "<pre>Admin field " . print_r($settings['id'],1) . " has value: " . print_r($variables, 1) . "</pre>";

				// Description handling
				$field_description = WC_Admin_Settings::get_field_description( $settings );
				extract( $field_description );
				?>

		<tr valign="top">
		    <td class="forminp forminp-<?php echo sanitize_title( $settings['type'] ) ?>" colspan="2">
				<table id="ordernumber_variables_template" style="display:none">
					<?php echo $this->create_replacements_row_html($settings['id'], array(), 'disabled'); ?>
				</table>

				<table id="ordernumber_variables" class="ordernumber_variables widefat wc_input_table sortable" cellspacing="0">
					<?php
						$columns = apply_filters( 'woocommerce_ordernumber_variables_columns', array(
							'variables_ifvar'    => __( 'If variable ...', 'woocommerce-advanced-ordernumbers' ),
							'variables_ifop'     => '',
							'variables_ifval'    => __( 'Value', 'woocommerce-advanced-ordernumbers' ),
							'variables_then'     => __( '', 'woocommerce-advanced-ordernumbers' ),
							'variables_thenvar'  => __( 'Set variable ...', 'woocommerce-advanced-ordernumbers' ),
							'variables_thenval'  => __( 'to value ...', 'woocommerce-advanced-ordernumbers' ),
							'sort'     => '&nbsp;',
							'variables_settings' => '',
						) );
					?>
					<thead>
						<tr>
							<?php
								foreach ( $columns as $key => $column ) {
									echo '<th class="' . esc_attr( $key ) . '">' . esc_html( $column ) . '</th>';
								}
							?>
						</tr>
						<tr id = "ordernumber-replacements-empty-row" class="oton-empty-row-notice <?php echo (empty($variables))?'':'rowhidden'; ?>">
							<td class="oton-empty-row-notice" colspan="8">
								<em> <?php echo __('No custom variables have been defined.', 'woocommerce-advanced-ordernumbers'); ?></em>
								<input type="hidden" name="<?php echo $settings['id']; ?>" value="" <?php echo (empty($variables))?'':'disabled'; ?>>
							</td>
						</tr>
					</thead>
					<colgroup>
						<?php 
							foreach ($columns as $key => $column) {
								echo '<col class="' . esc_attr($key) . '" />';
							}
						?>
					</colgroup>

					<tbody>
						<?php
						foreach ($variables as $var) {
							echo $this->create_replacements_row_html($settings['id'], $var);
						} ?>
					</tbody>
					<tfoot>
						<tr class='addreplacement_row'>
							<td colspan=8 class='variable_add'>
								<div class='ordernumber-variables-addbtn ordernumber-btn' onClick="ordernumberVariablesAddRow('ordernumber_variables_template', 'ordernumber_variables')">
									<div class='ordernumber-ajax-loading'><img src='<?php echo plugins_url( 'assets/images/icon-16-new.png', __FILE__ ); ?>' class='ordernumber-counter-addbtn' /></div>
									<?php _e('Add new custom variable', 'woocommerce-advanced-ordernumbers'); ?>
								</div>
							</td>
						</tr>
					</tfoot>
				</table>
			</td>
		</tr> 
		<?php
			}

			protected function create_replacements_row_html($name, $values = array(), $disabled = '') {
				$operator = (isset($values['conditionop'])?$values['conditionop']:'');
				$operators = array(
					'equals'       => '=', 
					'contains'     => __('contains', 'woocommerce-advanced-ordernumbers'), 
					'smaller'      => '<',
					'smallerequal' => '<=',
					'larger'       => '>',
					'largerequal'  => '>=', 
					'startswith'   => __('starts with', 'woocommerce-advanced-ordernumbers'),
					'endswith'     => __('ends with', 'woocommerce-advanced-ordernumbers'),
				);
				$html  = '
				<tr>
					<td class="oton-replacement-variable"><input name="' . $name . '[conditionvar][]" value="' . (isset($values['conditionvar'])?$values['conditionvar']:'') . '" ' . $disabled . '/></td>
					<td class="oton-replacement-op"      ><select name="' . $name . '[conditionop][]" ' . $disabled . '>';
				foreach ($operators as $op => $opname) {
					$html .= '		<option value="' . esc_attr($op) . '" ' . (($op === $operator)?'selected':'') . '>' . esc_html($opname) . '</option>';
				}
				$html .= '</td>
					<td class="oton-replacement-value"   ><input name="' . $name . '[conditionval][]" value="' . (isset($values['conditionval'])?$values['conditionval']:'') . '" ' . $disabled . '/></td>
					<td>=></td>
					<td class="oton-replacement-variable"><input name="' . $name . '[newvar][]"       value="' . (isset($values['newvar'])?$values['newvar']:'') .       '" ' . $disabled . '/></td>
					<td class="oton-replacement-newvalue"><input name="' . $name . '[newval][]"       value="' . (isset($values['newval'])?$values['newval']:'') .       '" ' . $disabled . '/></td>
					<td class="sort">&nbsp;</td>
					<td><img src="' . plugins_url( 'assets/images/icon-16-delete.png', __FILE__ ) . '" class="ordernumber-replacement-deletebtn ordernumber-btn"></td>
				</tr>';
				return $html;
			}
364
			
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
			/** 
			 * Store the variable replacements array into the options. Need to transpose the array before we can store it into the options...
			 * This filter is called directly before the option is saved.
			 */
			public function update_option_variables ($value) {
				if (!is_array($value)) 
					return array();
				$keys = array_keys($value);
				$vallist = array();
				
				foreach (array_keys($value[$keys[0]]) as $i) {
					$entry = array();
					foreach ($keys as $k) {
						$entry[$k] = $value[$k][$i];
					}
					$vallist[] = $entry;
				}
				return $vallist;
383
			}
384

385 386 387 388 389
			
			/**
			 * Render the Counter Values modification table
			 */
			public function admin_field_counters ($settings) {
390 391 392 393
				// Description handling
				$field_description = WC_Admin_Settings::get_field_description( $settings );
				extract( $field_description );

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
				// First, get all counter names:
				$counters = array();
				$pfxlen = strlen($this->ordernumber_counter_prefix );
				foreach (wp_load_alloptions() as $name => $value) {
					if (substr($name, 0, $pfxlen) == $this->ordernumber_counter_prefix) {
						$parts = explode('-', substr($name, $pfxlen), 2);
						if (sizeof($parts)==1) {
							array_unshift($parts, 'ordernumber');
						}
						$counters[] = array(
							'type' => $parts[0],
							'name' => $parts[1],
							'value' => $value,
						);
					}
				} 
				?>
411

412 413
				
		<tr valign="top">
414 415 416 417 418
			<th scope="row" class="titledesc">
				<label for="<?php echo esc_attr( $settings['id'] ); ?>"><?php echo esc_html( $settings['title'] ); ?></label>
				<?php echo $tooltip_html; ?>
			</th>
		    <td class="forminp forminp-<?php echo sanitize_title( $settings['type'] ) ?>">
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
				<img src='<?php echo plugins_url( 'assets/images/loading.gif', __FILE__ ); ?>' class='wc-ordernumber-loading' style="display: none; position: absolute; top: 2px; left: 0px; z-index: 9999;"/>
				<table class="wc_ordernumber_counters widefat" cellspacing="0">
					<?php
						$columns = apply_filters( 'woocommerce_ordernumber_counters_columns', array(
							'type'     => __( '', 'woocommerce-advanced-ordernumbers' ),
							'name'     => __( 'Counter name', 'woocommerce-advanced-ordernumbers' ),
							'value'    => __( 'Counter value', 'woocommerce-advanced-ordernumbers' ),
							'settings' => ''
						) );
					?>
					<thead>
						<tr>
							<?php
								foreach ( $columns as $key => $column ) {
									echo '<th class="counter_' . esc_attr( $key ) . '">' . esc_html( $column ) . '</th>';
								}
							?>
						</tr>
					</thead>
					<colgroup>
						<?php 
							foreach ($columns as $key => $column) {
								echo '<col class="counter_' . esc_attr($key) . '" />';
							}
						?>
					</colgroup>

					<tbody>
						<?php
448 449 450 451
						foreach ($counters as $counter) {
							echo $this->create_admin_counter_row($counter['type'], $counter['name'], $counter['value']);
						} 
						?>
452 453 454 455 456
					</tbody>
					<tfoot>
						<tr class='addcounter_row'>
							<td class="counter_type"></td>
							<td colspan=3 class='counter_add'>
457
								<div class='ordernumber-counter-addbtn ordernumber-btn' onClick="ajaxAddCounter(this, 'ordernumber')">
458 459 460 461 462 463 464 465 466 467 468 469
									<div class='ordernumber-ajax-loading'><img src='<?php echo plugins_url( 'assets/images/icon-16-new.png', __FILE__ ); ?>' class='ordernumber-counter-addbtn' /></div>
									<?php _e('Add new counter', 'woocommerce-advanced-ordernumbers'); ?>
								</div>
							</td>
						</tr>
					</tfoot>
				</table>
			</td>
		</tr> 
		<?php
			}
			
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
			public function create_admin_counter_row ($type, $format, $value=0) {
				$html =	"
					<tr class='counter_row counter_type_" . $type . "'>
						<td class='counter_type'>" . __($type, 'wooocommerce-advanced-ordernumbers' ) . "</td>
						<td class='counter_format'>" . (empty($format)?("<i>".__("[Global]", 'woocommerce-advanced-ordernumbers')."</i>"):esc_html($format)) . "</td>
						<td class='counter_value'>" . esc_html($value) . "</td>
						<td class='counter_buttons'>
							<div class='ordernumber-ajax-loading'>
							<img src='" . plugins_url( 'assets/images/icon-16-edit.png', __FILE__ ) . "' 
										class='ordernumber-counter-editbtn ordernumber-btn' 
										onClick='ajaxEditCounter(this, " . json_encode($type) . ", " . json_encode($format) . ", " . json_encode($value) . ")' />
							</div>
							<div class='ordernumber-ajax-loading'>
								<img src='" . plugins_url( 'assets/images/icon-16-delete.png', __FILE__ ) . "' 
										class='ordernumber-counter-deletebtn ordernumber-btn' 
										onClick='ajaxDeleteCounter(this, " . json_encode($type) . ", " . json_encode($format) . ", " . json_encode($value) . ")' />
							</div>
						</td>
					</tr>";
				return $html;
			}
491 492
			
			
493 494 495 496 497 498 499 500
			/** 
			 * Hook to add the order numer post meta field to the searchable field 
			 * (so the admin can search for the order number in the backend)
			 */
			public function order_search_fields($fields) {
				$fields[] = $this->ordernumber_meta;
				return $fields;
			}
501 502 503 504 505 506 507 508 509 510 511
			
			/**
			 * Sort the order list's "Order" column by our post meta rather than by ID
			 */
			public function modify_order_column_sortkey($columns) {
				$custom = array(
					'order_title' => $this->ordernumber_meta,
				);
				// Use the passed columns as "default", so effectively, only the order_title will be changed:
				return wp_parse_args ($custom, $columns);
			}
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
			
			/** 
			 * Handle new posts created in the frontend. This action will be called for all posts, 
			 * not only for orders, so we need to check explicitly. Also, this function will be called
			 * for order updates, so we need to check the update argument, too.
			 */
			public function check_create_ordernumber($post_id, $post, $update) {
				// Is the post really an order?
				// Order numbers are only assigned to orders on creation, not when updating!
				if ($post->post_type != 'shop_order') {
					return;
				} else {
					// Handle new admin-created orders, where the address is entered later on!
					// Assign an order number:
					$number = $this->assign_new_ordernumber($post_id, $post, $update);
				}
				
			}
530

531
			/**
532
			 * Counter handling (simple loading/storing counters), storing them as options
533
			 */
534
			function _getCounter($type, $format, $start=0) {
535
				$count = get_option ($this->ordernumber_counter_prefix.$type.'-'.$format, $start);
536 537 538 539
				return $count;
			}
			// Insert new counter value into the db or update existing one
			function _setCounter($type, $format, $value) {
540
				return update_option($this->ordernumber_counter_prefix.$type.'-'.$format, $value);
541
			}
542 543 544
			function _deleteCounter($type, $format) {
				return delete_option($this->ordernumber_counter_prefix.$type.'-'.$format);
			}
545
			
546 547 548 549 550 551 552 553 554
			public function counter_delete_callback() {
				$json = array('action' => 'delete_counter', 'success' => 0);
				$json['success'] = $this->_deleteCounter($_POST['nrtype'], $_POST['counter']);
				wp_send_json($json);
			}

			public function counter_add_callback () {
				$type = $_POST['nrtype'];
				$format = $_POST['counter'];
555
				$value = isset($_POST['value'])?$_POST['value']:"0";
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
				$json = array('action' => 'add_counter', 'success' => 0);
				if ($this->_getCounter($type, $format, -1) != -1) {
					// Counter already exists => error message
					$json['error'] = sprintf(__('Counter "%s" already exists, cannot create again.'), $format);
				} else {
					$json['success'] = $this->_setCounter($type, $format, $value);
					$json['newrow']  = $this->create_admin_counter_row($type, $format, $value);
				}
				wp_send_json($json);
			}
			
			public function counter_set_callback () {
				$json = array('action' => 'set_counter', 'success' => 0);
				$json['success'] = $this->_setCounter($_POST['nrtype'], $_POST['counter'], $_POST['value']);
				wp_send_json($json);
			}
572
			
573
			/**
574 575 576 577 578 579 580 581 582 583 584 585 586 587
			 * Variable replacements:
			 *   - Random strings/digits
			 *   - Order properties
			 *   - User properties
			 */
			
			/* Return a random "string" of the given length taken from the given alphabet */
			static function randomString($alphabet, $len) {
				$alen = strlen($alphabet);
				$r = "";
				for ($n=0; $n<$len; $n++) {
					$r .= $alphabet[mt_rand(0, $alen-1)];
				}
				return $r;
588 589
			}

590 591 592 593 594 595 596 597 598 599 600 601 602
			function replaceRandom ($match) {
				/* the regexp matches (random)(Type)(Len) as match, Type and Len is optional */
				$len = ($match[3]?$match[3]:1);
				// Fallback: If no Type is given, use Digit
				$alphabet = "0123456789";
				// Select the correct alphabet depending on Type
				switch (strtolower($match[2])) {
					case "digit": $alphabet = "0123456789"; break;
					case "hex": $alphabet = "0123456789abcdef"; break;
					case "letter": $alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; break;
					case "uletter": $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; break;
					case "lletter": $alphabet = "abcdefghijklmnopqrstuvwxyz"; break;
					case "alphanum": $alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; break;
603
				}
604 605 606
				return self::randomString ($alphabet, $len);
			}
    
607

608
			/* replace the variables in the given format. $type indicates the type of number, currently only 'ordernumber', because WooCommerce does not support invoices or customer numbers. We might allow the shop owner to customize the order password, though. */
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
			function replace_fields ($fmt, $type, $order) {
				// First, replace all randomXXX[n] fields. This needs to be done with a regexp and a callback:
				$fmt = preg_replace_callback ('/\[(random)(.*?)([0-9]*?)\]/', array($this, 'replaceRandom'), $fmt);
        
				$reps = array (
					"[year]" => date ("Y"),
					"[year2]" => date ("y"),
					"[month]" => date("m"),
					"[day]" => date("d"),
					"[hour]" => date("H"),
					"[hour12]" => date("h"),
					"[ampm]" => date("a"),
					"[minute]" => date("i"),
					"[second]" => date("s"),
					"[orderid]" => $order->id,
				);
625

626
				$reps["[userid]"]      = $order->get_user_id();
627 628 629 630 631 632
				$reps["[ipaddress]"]   = $order->customer_ip_address;
				$reps["[orderstatus]"] = $order->get_status();
				$reps["[email]"]       = $order->billing_email;
        
				
				$reps["[firstname]"] = $order->billing_first_name;
633
				$reps["[lastname]"]  = $order->billing_last_name;
634

635 636 637 638
				$reps["[company]"]   = $order->billing_company;
				$reps["[zip]"]       = $order->billing_postcode;
				$reps["[postcode]"]  = $order->billing_postcode;
				$reps["[city]"]      = $order->billing_city;
639 640 641 642 643
        
				$country = $order->billing_country;
				$state = $order->billing_state;
				$allcountries = WC()->countries->get_countries();
				$states = WC()->countries->get_states($country);
644
				$reps["[country]"]     = $country;
645 646
				$reps["[countryname]"] = ( isset( $allcountries[ $country ] ) ) ? $allcountries[ $country ] : $country;

647 648
				$reps["[state]"]       = $state;
				$reps["[statename]"]   = ( $country && $state && isset( $states[ $country ][ $state ] ) ) ? $states[ $country ][ $state ] : $state;
649
				
650 651 652 653
				$reps["[articles]"]    = $order->get_item_count();
				$reps["[currency]"]    = $order->get_order_currency();
// 				$reps["[downloadpermitted]"] = $order->is_download_permitted();
// 				$reps["[hasdownloads]"] = $order->has_downloadable_item();
654 655 656 657 658 659 660 661 662 663 664
// 				$reps["[coupons]"] = $order->get_used_coupons();
				
				if ($type != 'ordernumber') {
					$reps["[ordernumber]"] = $order->get_order_number();
				}
				$user = $order->get_user();
				if ($user) {
//					TODO: Shall we supply a variable for the user's login / display name?
// 					$reps["[user]"] = print_r($user,1);
// 					if (isset($order->username)) $reps["[username]"] = $order->username;
				}
665

666 667 668
				// Allow customization via plugins: filter function($reps, $order, $type, $fmt)
				$reps = apply_filters( 'opentools_ordernumber_replacements', $reps, $order, $type, $fmt);
				return str_ireplace (array_keys($reps), array_values($reps), $fmt);
669
			}
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

			function create_ordernumber($orderid, $order, $type='ordernumber') {
				if (get_option('customize_'.$type, 'false')) {
					$fmt     = get_option ($type.'_format',  "#");
					$global  = get_option ($type.'_global',  1);
					$padding = get_option ($type.'_padding', 1);
					$step    = get_option ($type.'_step',    1);
					$start   = get_option ($type.'_start',   1)-$step; // The counter contains the PREVIOUS number!

					$nr = $this->replace_fields ($fmt, $type, $order);

					// Split at a | to get the number format and a possibly different counter increment format
					// If a separate counter format is given after the |, use it, otherwise reuse the number format itself as counter format
					$parts = explode ("|", $nr);
					$format = $parts[0];
        
					$counterfmt = ($global==1)?"":$parts[(count($parts)>1)?1:0];
        
					// Look up the current counter
					$count = $this->_getCounter($type, $counterfmt, $start) + $step;
					$this->_setCounter($type, $counterfmt, $count);
					// return the format with the counter inserted
					$number = str_replace ("#", sprintf('%0' . $padding . 's', $count), $format);
693
					update_post_meta( $orderid, $this->ordernumber_meta, $number );
694 695 696 697 698
					return $number;
				} else {
					return $orderid;
				}
			}
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
			
			/** 
			 * The hook to assign a customized order number (unless the order already has one assigned)
			 */
			function assign_new_ordernumber($orderid, $order, $update=true) {
				if ((!$update) && ($order->post_status == 'auto-draft')) {
					// New order => assign placeholder, which will later be overwritten the real order number
					update_post_meta( $orderid, $this->ordernumber_meta, $this->ordernumber_new_placeholder );
				}
				// If we do not have an order (yet), we cannot proceed. But we probably have created the 
				// ordernumber placeholder for that post, so this function has done its job and we can return
				if (!$order instanceof WC_Order) {
					return;
				}
				$number = get_post_meta( $orderid, $this->ordernumber_meta, 'true');
				if ($number == $this->ordernumber_new_placeholder && $order->post_status != 'auto-draft') {
					$number = $this->create_ordernumber($orderid, $order, 'ordernumber');
					// Assign a new number
				}
				return $number;
			}

721 722 723 724
			/** 
			 * The hook to customize order numbers (requests the order number from the database; creates a new ordernumber if no entry exists in the database)
			 */
			function get_ordernumber($orderid, $order) {
725
				$stored_number = get_post_meta( $orderid, $this->ordernumber_meta, 'true');
726 727 728 729 730
				if ($stored_number == $this->ordernumber_new_placeholder) {
					// Check whether the order was now really created => create order number now
					return $this->assign_new_ordernumber($orderid, $order);
				} elseif (!empty($stored_number)) {
					// Order number already exists => simply return it
731
					return $stored_number;
732
				} else {
733
					// No order number was created for this order, so simply use the orderid as default.
734
					return $orderid;
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
				}
			}

		}
	}

	if (class_exists("OpenToolsOrdernumbers")) {
		// Installation and uninstallation hooks
		register_activation_hook(__FILE__, array('OpenToolsOrdernumbers', 'activate'));
		register_deactivation_hook(__FILE__, array('OpenToolsOrdernumbers', 'deactivate'));

		// instantiate the plugin class
		$ordernumber_plugin = new OpenToolsOrdernumbers();
	}
 
}