woocommerce-advanced-ordernumbers.php 38.2 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 this 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
 * The order number handling code itself comes straight from our general library, which is also used for VirtueMart and Magento.
21 22 23 24 25 26 27 28 29 30 31 32
 */
 
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' ) ) ) ) {

	if (!class_exists("OpenToolsOrdernumbers")) {
		class OpenToolsOrdernumbers {
33
			public $ordernumber_meta = "oton_number_";
34 35
			public $ordernumber_new_placeholder = "[New Order]";
			public $ordernumber_counter_prefix = 'ordernumber-counter-';
36
			
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
			
			/**
			 * STATIC HELPER FUNCTIONS, WooCommerce-specific
			 */
			public static function __($string) {
				return __($string, 'opentools-advanced-ordernumbers');
			}
			public static function rel_url($file) {
				return plugins_url($file, __FILE__);
			}
			public static function img_url($img) {
				return self::rel_url('assets/images/'.$img );
			}
			public static function css_url($css) {
				return self::rel_url('assets/css/'.$css );
			}
			public static function js_url($js) {
				return self::rel_url('assets/js/'.$js );
			}
			
			
			
			
60 61 62 63 64
			/**
			 * Construct the plugin object
			 */
			public function __construct()
			{
65
				$plugin = plugin_basename(__FILE__); 
66
				load_plugin_textdomain('opentools-ordernumbers', false, basename( dirname( __FILE__ ) ) . '/languages' );
67 68 69 70

				// Init settings
				$this->settings = array(
					array(
71 72
						'name' 		=> self::__( 'Advanced Order Numbers'),
						'desc'		=> self::__( 'Configure the format and the counters of the order numbers in WooCommerce.'),
73 74 75 76 77
						'type' 		=> 'title',
						'id' 		=> 'ordernumber_options'
					),

					array(
78 79
						'name' 		=> self::__( 'Customize Order Numbers'),
						'desc' 		=> self::__( 'Check to use custom order numbers rather than the default wordpress post ID.'),
80 81 82 83 84
						'id' 		=> 'customize_ordernumber',
						'type' 		=> 'checkbox',
						'default'	=> 'no'
					),
					array(
85
						'title'		=> self::__( 'Order number format'),
86
						'desc' 		=> self::__( '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. Advanced settings for the counter can be added as [#####:start/step], e.g. [#:100] to start new counters at 100, or [#/5] to increment the counter by 5. The number of # in the format determine how many digits are shown at least, e.g. [########] will always show at least 8 digits for the counter, e.g. 00000014.'),
87 88 89 90
						'desc_tip'	=> true,
						'id' 		=> 'ordernumber_format',
						'default'	=> '#',
						'type' 		=> 'text',
91
						'css'		=> 'width: 100%',
92 93
					),
					array(
94 95
						'title'		=> self::__( 'Use global counter'),
						'desc' 		=> self::__( '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).'),
96
						'desc_tip'	=> true,
97 98
						'id' 		=> 'ordernumber_global',
						'type' 		=> 'checkbox',
99
						'default'	=> 'no',
100 101 102 103
					),
					array( 'type' => 'sectionend', 'id' => 'ordernumber_options' ),
					
					// TODO: customize order password, and other numbers!
104 105

					array(
106 107
						'name' 		=> self::__( 'Custom Variables'),
						'desc'		=> self::__( 'Define your own (conditional) variables for use in the number formats'),
108 109 110 111 112 113 114 115 116 117
						'type' 		=> 'title',
						'id' 		=> 'ordernumber_variables'
					),
					array(
						'id' 		=> 'ordernumber_variables',
						'type' 		=> 'ordernumber_variables',
					),
					array( 'type' => 'sectionend', 'id' => 'ordernumber_variables' ),

					array(
118
						'name' 		=> self::__( 'Current Counters'),
119 120 121 122
						'type' 		=> 'title',
						'id' 		=> 'ordernumber_counters'
					),
					array(
123 124
						'name' 		=> self::__( 'All Ordernumber Counters'),
						'desc'		=> self::__( 'View and modify the current counter values. The counter value is the value used for the previous number. All changes are immediately applied!'),
125
						'desc_tip'	=> true,
126 127 128 129 130
						'id' 		=> 'ordernumber_counters',
						'type' 		=> 'ordernumber_counters',
					),
					array( 'type' => 'sectionend', 'id' => 'ordernumber_counters' ),

131 132 133
				);
				// Default options

134
				add_option ('customize_ordernumber', 'no');
135
				add_option ('ordernumber_format',    "#");
136
				add_option ('ordernumber_global',    'no');
137
				
138
 				add_option ('ordernumber_variables',  array());
139

140 141 142 143
				// register filters and actions
				
				// CONFIGURATION SCREENS
				add_filter( 'woocommerce_get_sections_checkout',                array($this, 'add_admin_section'));
144
				// The checkout settings page assumes all subpages are payment gateways, so we have to override this and manually pass our settings:
145 146 147
				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' ) );
148 149
				add_action( 'woocommerce_admin_field_ordernumber_variables',    array( $this, 'admin_field_variables' ) );
				add_action( 'pre_update_option_ordernumber_variables',          array( $this, 'update_option_variables'));
150 151 152
				
				add_action( 'woocommerce_order_actions',                        array( $this, 'add_order_action_new_number' ) );
				add_action( 'woocommerce_order_action_assign_new_ordernumber',  array( $this, 'order_action_assign_new_ordernumber' ) );
153 154 155 156 157 158 159 160 161

				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') );

162 163
				// Add the ordernumber post meta to the search in the backend
				add_filter( 'woocommerce_shop_order_search_fields', array($this, 'order_search_fields'));
164 165 166
				// 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 );

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

180 181 182 183
			/**
			 * 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
			 */
184
			function add_admin_section($sections) {
185 186 187 188
				$newsections = array();
				foreach ($sections as $sec => $name ) {
					$newsections[$sec] = $name;
					if ($sec == '') {
189
						$newsections['ordernumber'] = self::__('Order Numbers');
190 191 192
					}
				}
				return $newsections;
193 194
			}
			
195
			public function settings_output() {
196 197 198 199 200
				global $current_section;
				if ($current_section == 'ordernumber') {
					$settings = $this->settings;
					WC_Admin_Settings::output_fields( $settings );
				}
201 202
			}

203
			public function settings_save() {
204 205 206 207 208
				global $current_section;
				if ($current_section == 'ordernumber') {
					$settings = $this->settings;
					WC_Admin_Settings::save_fields( $settings );
				}
209
			}
210
			
211 212 213 214
			/** 
			 * 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 () {
215
				wp_register_style ( 'ordernumber-counter-style',  self::css_url('ordernumber-counter.css') );
216
				wp_enqueue_style('ordernumber-counter-style');
217

218
				wp_register_style ( 'ordernumber-variables-style',  self::css_url('ordernumber-variables.css') );
219
				wp_enqueue_style('ordernumber-variables-style');
220 221 222 223 224 225
			}
			/** 
			 * 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() {
			
226
				wp_register_script( 'ordernumber-counter-script', self::js_url( 'ordernumber-counter.js',  __FILE__), array('jquery') );
227 228 229 230 231
				wp_enqueue_script( 'ordernumber-counter-script');
				
				// Handle the translations:
				$localizations = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );
				
232 233 234 235 236
				$localizations['ORDERNUMBER_JS_JSONERROR'] = self::__("Error reading response from server:");
				$localizations['ORDERNUMBER_JS_NOT_AUTHORIZED'] = self::__("You are not authorized to modify order number counters.");
				$localizations['ORDERNUMBER_JS_NEWCOUNTER'] = self::__("Please enter the format/name of the new counter:");
				$localizations['ORDERNUMBER_JS_ADD_FAILED'] = self::__("Failed adding counter {0}");
				$localizations['ORDERNUMBER_JS_INVALID_COUNTERVALUE'] = self::__("You entered an invalid value for the counter.\n\n");
237
				
238 239 240 241
				$localizations['ORDERNUMBER_JS_EDITCOUNTER'] = self::__("{0}Please enter the new value for the counter '{1}' (current value: {2}):");
				$localizations['ORDERNUMBER_JS_MODIFY_FAILED'] = self::__("Failed modifying counter {0}");
				$localizations['ORDERNUMBER_JS_DELETECOUNTER'] = self::__("Really delete counter '{0}' with value '{1}'?");
				$localizations['ORDERNUMBER_JS_DELETE_FAILED'] = self::__("Failed deleting counter {0}");
242 243 244

				// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
				wp_localize_script( 'ordernumber-counter-script', 'ajax_ordernumber', $localizations );
245 246 247



248
				wp_register_script( 'ordernumber-variables-script', self::js_url( 'ordernumber-variables.js'), array('jquery') );
249
				wp_enqueue_script( 'ordernumber-variables-script');
250 251 252
				
				wp_register_script( 'ordernumber-admin', self::js_url( 'ordernumber-config.js'), array('jquery'));
				wp_enqueue_script( 'ordernumber-admin');
253
			}
254

255 256 257 258
			/**
			 * Render the Custom Variables configuration table
			 */
			public function admin_field_variables($settings) {
259 260 261
				$variables = get_option( $settings['id'], array() );
				if (!is_array($variables)) {
					$variables = array();
262
				} ?>
263 264
		<tr valign="top">
		    <td class="forminp forminp-<?php echo sanitize_title( $settings['type'] ) ?>" colspan="2">
265 266 267 268 269 270 271 272 273 274
				<?php
					print $this->customvar_admin_table($settings['id'], $variables);
				?>
			</td>
		</tr> 
		<?php
			}
			
			protected function customvar_admin_table($id, $variables) { ?>
			
275
				<table id="ordernumber_variables_template" style="display:none">
276
					<?php echo $this->create_replacements_row_html($id, array(), 'disabled'); ?>
277 278 279 280
				</table>

				<table id="ordernumber_variables" class="ordernumber_variables widefat wc_input_table sortable" cellspacing="0">
					<?php
281 282
						$columns = array(
							'variables_ifvar'    => self::__( 'If variable ...'),
283
							'variables_ifop'     => '',
284 285 286 287
							'variables_ifval'    => self::__( 'Value'),
							'variables_then'     => self::__( ''),
							'variables_thenvar'  => self::__( 'Set variable ...'),
							'variables_thenval'  => self::__( 'to value ...'),
288
							'sort'     => '',
289
							'variables_settings' => '',
290
						);
291 292 293 294 295 296 297 298 299 300 301
					?>
					<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">
302 303
								<em> <?php echo self::__('No custom variables have been defined.'); ?></em>
								<input type="hidden" name="<?php echo $id; ?>" value="" <?php echo (empty($variables))?'':'disabled'; ?>>
304 305 306 307 308 309 310 311 312 313 314 315 316 317
							</td>
						</tr>
					</thead>
					<colgroup>
						<?php 
							foreach ($columns as $key => $column) {
								echo '<col class="' . esc_attr($key) . '" />';
							}
						?>
					</colgroup>

					<tbody>
						<?php
						foreach ($variables as $var) {
318
							echo $this->create_replacements_row_html($id, $var);
319 320 321 322 323 324
						} ?>
					</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')">
325 326
									<div class='ordernumber-ajax-loading'><img src='<?php echo self::img_url( 'icon-16-new.png' ); ?>' class='ordernumber-counter-addbtn' /></div>
									<?php _e('Add new custom variable'); ?>
327 328 329 330 331
								</div>
							</td>
						</tr>
					</tfoot>
				</table>
332
				<?php
333 334 335
			}

			protected function create_replacements_row_html($name, $values = array(), $disabled = '') {
336
				$escname = esc_attr($name);
337 338 339
				$operator = (isset($values['conditionop'])?$values['conditionop']:'');
				$operators = array(
					'equals'       => '=', 
340
					'contains'     => self::__('contains'), 
341 342 343 344
					'smaller'      => '<',
					'smallerequal' => '<=',
					'larger'       => '>',
					'largerequal'  => '>=', 
345 346
					'startswith'   => self::__('starts with'),
					'endswith'     => self::__('ends with'),
347
				);
348
				// Wrap all output of the values with esc_html to prevent script injection attacks
349 350
				$html  = '
				<tr>
351 352
					<td class="variables_ifvar"><input name="' . $escname . '[conditionvar][]" value="' . (isset($values['conditionvar'])?esc_html($values['conditionvar']):'') . '" ' . esc_html($disabled) . '/></td>
					<td class="variables_ifop"      ><select name="' . $escname . '[conditionop][]" ' . $disabled . '>';
353 354 355
				foreach ($operators as $op => $opname) {
					$html .= '		<option value="' . esc_attr($op) . '" ' . (($op === $operator)?'selected':'') . '>' . esc_html($opname) . '</option>';
				}
356 357
				$html .= '</select></td>
					<td class="variables_ifval"   ><input name="' . $escname . '[conditionval][]" value="' . (isset($values['conditionval'])?esc_html($values['conditionval']):'') . '" ' . esc_html($disabled) . '/></td>
358
					<td class="variables_then">=></td>
359 360
					<td class="variables_thenvar"><input name="' . $escname . '[newvar][]"       value="' . (isset($values['newvar'])?esc_html($values['newvar']):'') .       '" ' . esc_html($disabled) . '/></td>
					<td class="variables_thenval"><input name="' . $escname . '[newval][]"       value="' . (isset($values['newval'])?esc_html($values['newval']):'') .       '" ' . esc_html($disabled) . '/></td>
361 362
					<td class="sort"></td>
					<td class="variables_settings"><img src="' . self::img_url( 'icon-16-delete.png' ) . '" class="ordernumber-replacement-deletebtn ordernumber-btn"></td>
363 364 365
				</tr>';
				return $html;
			}
366

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
			/** 
			 * 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;
385
			}
386

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

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
				// 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,
						);
					}
				} 
				?>
413

414 415
				
		<tr valign="top">
416 417 418 419 420
			<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'] ) ?>">
421
				<img src='<?php echo self::img_url( 'loading.gif' ); ?>' class='wc-ordernumber-loading' style="display: none; position: absolute; top: 2px; left: 0px; z-index: 9999;"/>
422 423 424
				<table class="wc_ordernumber_counters widefat" cellspacing="0">
					<?php
						$columns = apply_filters( 'woocommerce_ordernumber_counters_columns', array(
425 426 427
							'type'     => self::__( ''),
							'name'     => self::__( 'Counter name'),
							'value'    => self::__( 'Counter value'),
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
							'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
450 451 452 453
						foreach ($counters as $counter) {
							echo $this->create_admin_counter_row($counter['type'], $counter['name'], $counter['value']);
						} 
						?>
454 455 456 457 458
					</tbody>
					<tfoot>
						<tr class='addcounter_row'>
							<td class="counter_type"></td>
							<td colspan=3 class='counter_add'>
459
								<div class='ordernumber-counter-addbtn ordernumber-btn' onClick="ajaxAddCounter(this, 'ordernumber')">
460 461
									<div class='ordernumber-ajax-loading'><img src='<?php echo self::img_url( 'icon-16-new.png' ); ?>' class='ordernumber-counter-addbtn' /></div>
									<?php _e('Add new counter'); ?>
462 463 464 465 466 467 468 469 470 471
								</div>
							</td>
						</tr>
					</tfoot>
				</table>
			</td>
		</tr> 
		<?php
			}
			
472 473 474
			public function create_admin_counter_row ($type, $format, $value=0) {
				$html =	"
					<tr class='counter_row counter_type_" . $type . "'>
475 476
						<td class='counter_type'>" . self::__($type, 'wooocommerce-advanced-ordernumbers' ) . "</td>
						<td class='counter_format'>" . (empty($format)?("<i>".self::__("[Global]")."</i>"):esc_html($format)) . "</td>
477 478 479
						<td class='counter_value'>" . esc_html($value) . "</td>
						<td class='counter_buttons'>
							<div class='ordernumber-ajax-loading'>
480
							<img src='" . self::img_url( 'icon-16-edit.png' ) . "' 
481 482 483 484
										class='ordernumber-counter-editbtn ordernumber-btn' 
										onClick='ajaxEditCounter(this, " . json_encode($type) . ", " . json_encode($format) . ", " . json_encode($value) . ")' />
							</div>
							<div class='ordernumber-ajax-loading'>
485
								<img src='" . self::img_url( 'icon-16-delete.png' ) . "' 
486 487 488 489 490 491 492
										class='ordernumber-counter-deletebtn ordernumber-btn' 
										onClick='ajaxDeleteCounter(this, " . json_encode($type) . ", " . json_encode($format) . ", " . json_encode($value) . ")' />
							</div>
						</td>
					</tr>";
				return $html;
			}
493 494
			
			
495 496 497 498 499 500 501 502
			/** 
			 * 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;
			}
503 504 505 506 507 508 509 510 511 512 513
			
			/**
			 * 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);
			}
514
			
515 516 517 518 519
			/**
			 * Add the "create new order number" action to the edit order page in the Backend
			 */
			public function add_order_action_new_number($actions) {
				$actions['assign_new_ordernumber'] = self::__('Assign a new order number');
520
				return $actions;
521 522 523 524 525
			}
			/**
			 * Handle the "Assign a new order number" action from the edit order page in the backend
			 */
			public function order_action_assign_new_ordernumber( $order ) {
526
				$number = $this->assignNumber($order->id, $order, 'ordernumber');
527 528 529
			}
			
			
530 531 532 533 534
			/** 
			 * 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.
			 */
535
			public function check_assignNumber($post_id, $post, $update) {
536 537 538 539 540 541 542 543 544 545
				// 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);
				}
			}
546

547
			/**
548
			 * Counter handling (simple loading/storing counters), storing them as options
549
			 */
550
			function _getCounter($type, $format, $start=0) {
551
				$count = get_option ($this->ordernumber_counter_prefix.$type.'-'.$format, $start);
552 553 554 555
				return $count;
			}
			// Insert new counter value into the db or update existing one
			function _setCounter($type, $format, $value) {
556
				return update_option($this->ordernumber_counter_prefix.$type.'-'.$format, $value);
557
			}
558 559 560
			function _deleteCounter($type, $format) {
				return delete_option($this->ordernumber_counter_prefix.$type.'-'.$format);
			}
561
			
562 563 564 565 566 567 568 569 570
			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'];
571
				$value = isset($_POST['value'])?$_POST['value']:"0";
572 573 574
				$json = array('action' => 'add_counter', 'success' => 0);
				if ($this->_getCounter($type, $format, -1) != -1) {
					// Counter already exists => error message
575
					$json['error'] = sprintf(self::__('Counter "%s" already exists, cannot create again.'), $format);
576 577 578 579 580 581 582 583 584 585 586 587
				} 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);
			}
588
			
589 590 591 592 593 594 595
			
			
			/** ***********************************************************
			 * 
			 *  REPLACEMENT FUNCTIONS
			 *
			 **************************************************************/
596 597 598 599 600 601 602 603 604
			
			/* 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;
605 606
			}

607 608 609 610 611 612 613 614 615 616 617 618 619
			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;
620
				}
621 622
				return self::randomString ($alphabet, $len);
			}
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
	
			protected function setupDateTimeReplacements (&$reps, $order, $nrtype) {
				$utime = microtime(true);
				$reps["[year]"] = date ("Y", $utime);
				$reps["[year2]"] = date ("y", $utime);
				$reps["[month]"] = date("m", $utime);
				$reps["[day]"] = date("d", $utime);
				$reps["[hour]"] = date("H", $utime);
				$reps["[hour12]"] = date("h", $utime);
				$reps["[ampm]"] = date("a", $utime);
				$reps["[minute]"] = date("i", $utime);
				$reps["[second]"] = date("s", $utime);
				$milliseconds = (int)(1000*($utime - (int)$utime));
				$millisecondsstring = sprintf('%03d', $milliseconds);
				$reps["[decisecond]"] = $millisecondsstring[0];
				$reps["[centisecond]"] = substr($millisecondsstring, 0, 2);
				$reps["[millisecond]"] = $millisecondsstring;
			}
641

642 643 644 645
			protected function setupAddressReplacements(&$reps, $prefix, $address, $nrtype) {
				$reps["[email]"]     = $address->billing_email;
				$reps["[firstname]"] = $address->billing_first_name;
				$reps["[lastname]"]  = $address->billing_last_name;
646

647 648 649 650
				$reps["[company]"]   = $address->billing_company;
				$reps["[zip]"]       = $address->billing_postcode;
				$reps["[postcode]"]  = $address->billing_postcode;
				$reps["[city]"]      = $address->billing_city;
651
        
652 653
				$country = $address->billing_country;
				$state = $address->billing_state;
654 655
				$allcountries = WC()->countries->get_countries();
				$states = WC()->countries->get_states($country);
656
				$reps["[country]"]     = $country;
657 658
				$reps["[countryname]"] = ( isset( $allcountries[ $country ] ) ) ? $allcountries[ $country ] : $country;

659 660
				$reps["[state]"]       = $state;
				$reps["[statename]"]   = ( $country && $state && isset( $states[ $country ][ $state ] ) ) ? $states[ $country ][ $state ] : $state;
661 662 663 664 665 666 667
			}
			
			protected function setupStoreReplacements (&$reps, $order, $nrtype) {
			}
    
			protected function setupOrderReplacements (&$reps, $order, $nrtype) {
				$reps["[orderid]"] = $order->id;
668
				
669 670 671 672
				if ($nrtype != 'ordernumber') {
					$reps["[ordernumber]"] = $order->get_order_number();
				}
				$reps["[orderstatus]"] = $order->get_status();
673
				$reps["[currency]"]    = $order->get_order_currency();
674 675 676 677

				$this->setupAddressReplacements($reps, "", $order, $nrtype);
	
				$reps["[articles]"]    = $order->get_item_count();
678 679
// 				$reps["[downloadpermitted]"] = $order->is_download_permitted();
// 				$reps["[hasdownloads]"] = $order->has_downloadable_item();
680
// 				$reps["[coupons]"] = $order->get_used_coupons();
681 682 683 684 685
				$reps["[ordertotal]"]      = $order->get_total();
				$reps["[amount]"]      = $order->get_total();
				$reps["[ordersubtotal]"]      = $order->get_subtotal();
				$reps["[totaltax]"]      = $order->get_total_tax();
				$reps["[totalshipping]"]      = $order->get_total_shipping();
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
				
				// List-valued properties for custom variable checks:
				// TODO: Also implement variable for:
				//  - Shipping needed
				//  - Downloads available
				$lineitems = $order->get_items();
				$skus = array();
				$categories = array();
				$tags = array();
				$shippingclasses = array();
				foreach ($lineitems as $l) {
					$p = $order->get_product_from_item($l);
					$skus[$p->get_sku()] = 1;
					foreach (wc_get_product_terms( $p->id, 'product_cat') as $c) {
						$categories[$c->slug] = 1;
					}
					foreach (wc_get_product_terms( $p->id, 'product_tag') as $c) {
						$tags[$c->slug] = 1;
					}
					$shippingclasses[$p->get_shipping_class()] = 1;
				}
				$reps["[skus]"] = array_keys($skus);
				$reps["[categories]"] = array_keys($categories);
				$reps["[tags]"] = array_keys($tags);
				$reps["[shippingclasses]"] = array_keys($shippingclasses);
711
			}
712 713 714 715 716 717

			protected function setupUserReplacements (&$reps, $details, $nrtype) {
				$reps["[ipaddress]"]   = $details->customer_ip_address;
				$reps["[userid]"]      = $details->get_user_id();
			}

718 719 720 721 722 723 724 725
			protected function setupShippingReplacements(&$reps, $order, $nrtype) {
// 				$reps["[shippingmethod]"] = $order->getShippingMethod();
			}
			
			/*protected function setupInvoiceReplacements (&$reps, $invoice, $order, $nrtype) {
				$reps["[invoiceid]"] = $invoice->getId();
			}*/

726 727 728 729 730
			protected function setupThirdPartyReplacements (&$reps, $details, $nrtype) {
				$reps = apply_filters( 'opentools_ordernumber_replacements', $reps, $details, $nrtype);
			}
			
			protected function setupReplacements($nrtype, $details) {
731
				$reps = array();
732 733 734 735 736 737
				$this->setupDateTimeReplacements($reps, $details, $nrtype);
				$this->setupStoreReplacements($reps, $details, $nrtype);
				$this->setupOrderReplacements($reps, $details, $nrtype);
				$this->setupUserReplacements($reps, $details, $nrtype);
				$this->setupShippingReplacements($reps, $details, $nrtype);
				$this->setupThirdPartyReplacements($reps, $details, $nrtype);
738 739 740 741
				return $reps;
			}

			
742
			protected function setupCustomVariables ($nrtype, $order, $reps, $customvars) {
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
				foreach ($customvars as $c) {
					$conditionvar = strtolower($c['conditionvar']);
					$op = $c['conditionop'];

					$found = false;
					$match = false;
					$compareval = null;

					if (isset($reps[$conditionvar])) {
						$found = true;
						$compareval = $reps[$conditionvar];
					} elseif (isset($reps['['.$conditionvar.']'])) {
						$found = true;
						$compareval = $reps['['.$conditionvar.']'];
					}/* elseif ($order && $compareval = $order->getData($conditionvar)) {
						// TODO: Handle order property
						$found = true;
					}*/ else {
						// TODO: Handly other possible properties!
						// TODO: Print out warning that variable could not be found.
					}
					if ($found) {
						$condval = $c['conditionval'];
						switch ($op) {
767 768
							case 'nocondition':
									$match = true; break;
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
							case 'equals': 
									$match = ($compareval == $condval); break;
							case 'contains':
									if (is_array($compareval)) {
										$match = in_array($condval, $compareval);
									} else {
										$match = strpos ($compareval, $condval);
									}
									break;
							case 'smaller':
									$match = ($compareval<$condval); break;
							case 'smallerequal':
									$match = ($compareval<=$condval); break;
							case 'larger':
									$match = ($compareval>$condval); break;
							case 'largerequal':
									$match = ($compareval>=$condval); break;
							case 'startswith':
									$match = (substr("$compareval", 0, strlen("$condval")) === "$condval"); break;
							case 'endswith':
									$match = (substr("$compareval", -strlen("$condval")) === "$condval"); break;
						}
					} elseif (empty($conditionvar)) {
						$match = true;
					}
					if ($match) {
						$varname = '['.strtolower($c['newvar']).']';
						$reps[$varname] = $c['newval'];
					}
798
				}
799 800
				return $reps;
			}
801

802
			// Allow the user to override the format like any other custom variable:
803
			protected function setupNumberFormatString($fmt, $type, $order, $reps) {
804 805 806 807 808 809 810
				if (isset($reps['['.$type.'_format]'])) {
					return $reps['['.$type.'_format]'];
				} else {
					return $fmt;
				}
			}
			
811 812 813
			protected function doReplacements ($fmt, $reps) {
				// First, replace all random...[n] fields. This needs to be done with a regexp and a callback:
				$fmt = preg_replace_callback ('/\[(random)(.*?)([0-9]*?)\]/', array($this, 'replaceRandom'), $fmt);
814 815
				// Only use string-valued variables for replacement (array-valued variables can be used in custom variable definitions!)
				$reps = array_filter($reps, function($v) { return !is_array($v);} );
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
				return str_ireplace (array_keys($reps), array_values($reps), $fmt);
			}
			
			protected function extractCounterSettings ($fmt, $type, $ctrsettings) {
				// First, extract all counter settings, i.e. all strings of the form [#####:startval/increment] or [####/increment:startval]
				$regexp = '%\[(#+)(/([0-9]+))?(:([0-9]+))?(/([0-9]+))?\]%';
// 				$counters = array();
				
				if (preg_match($regexp, $fmt, $counters)) {
					// $counters is an array of the form:
					// Array (
					// 		[0] => [#####:100/3]
					// 		[1] => #####
					// 		[2] => 
					// 		[3] => 
					// 		[4] => :100
					// 		[5] => 100
					// 		[6] => /3
					// 		[7] => 3
					// )
					$ctrsettings["${type}_padding"] = strlen($counters[1]);
					if (!empty($counters[2])) {
						// $counters[2] contains the whole "/n" part, while $counters[3] contains just the step itself
						$ctrsettings["${type}_step"] = $counters[3]; 
					}
					if (!empty($counters[4])) {
						// $counters[4] contains the whole ":n" part, while $counters[5] contains just the start value itself
						$ctrsettings["${type}_start"] = $counters[5]; 
					}
					
					if (!empty($counters[6])) {
						// $counters[6] contains the whole ":n" part, while $counters[7] contains just the start value itself
						$ctrsettings["${type}_step"] = $counters[7]; 
					}
					
// print("<pre>Counters regexp matches: ".print_r($counters,1)."</pre>");
					$fmt = preg_replace($regexp, "#", $fmt);
				}
				// 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 ("|", $fmt);
				$ctrsettings["${type}_format"] = $parts[0];
				$ctrsettings["${type}_counter"] = ($ctrsettings["${type}_global"]=='yes')?"":$parts[(count($parts)>1)?1:0];
				
// print("<pre>Counter settings are: ".print_r($ctrsettings,1)."</pre>");
				return $ctrsettings;
			}
863 864

			/* 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. */
865 866 867 868 869 870
			function createNumber ($fmt, $type, $order, $customvars, $ctrsettings) {
				$reps   = $this->setupReplacements ($type, $order);
				$reps   = $this->setupCustomVariables ($type, $order, $reps, $customvars);
				$format = $this->setupNumberFormatString($fmt, $type, $order, $reps);
				$format = $this->doReplacements($format, $reps);
				$ctrsettings = $this->extractCounterSettings ($format, $type, $ctrsettings);
871

872 873 874 875 876 877 878
				$countername = $ctrsettings["${type}_counter"];
				// Look up the current counter
				$count = $this->_getCounter($type, $countername, $ctrsettings["${type}_start"] - $ctrsettings["${type}_step"]) + $ctrsettings["${type}_step"];
				$this->_setCounter($type, $countername, $count);
				// return the format with the counter inserted
				$number = str_replace ("#", sprintf('%0' . $ctrsettings["${type}_padding"] . 's', $count), $ctrsettings["${type}_format"]);
				return $number;
879 880
			}
			
881 882
			function assignNumber($orderid, $order, $type='ordernumber') {
				if (get_option('customize_'.$type, 'no')!='no') {
883
					$fmt     = get_option ($type.'_format',  "#");
884 885 886 887 888 889 890 891
					$ctrsettings = array(
						"${type}_format"  => '',
						"${type}_counter" => '',
						"${type}_global"  => get_option ($type.'_global',  'no'),
						"${type}_padding" => 1,
						"${type}_step"    => 1,
						"${type}_start"   => 1,
					);
892
					$customvars = get_option ('ordernumber_variables',   array());
893

894
					$number = $this->createNumber ($fmt, $type, $order, $customvars, $ctrsettings);
895
					update_post_meta( $orderid, $this->ordernumber_meta.$type, $number );
896 897 898 899 900
					return $number;
				} else {
					return $orderid;
				}
			}
901 902 903 904 905
			
			/** 
			 * The hook to assign a customized order number (unless the order already has one assigned)
			 */
			function assign_new_ordernumber($orderid, $order, $update=true) {
906
				if ((!$update) /*&& ($order->post_status == 'auto-draft')*/) {
907
					// New order => assign placeholder, which will later be overwritten the real order number
908
					update_post_meta( $orderid, $this->ordernumber_meta.'ordernumber', $this->ordernumber_new_placeholder );
909 910 911 912 913 914
				}
				// 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;
				}
915
				$number = get_post_meta( $orderid, $this->ordernumber_meta.'ordernumber', 'true');
916
				if ($number == $this->ordernumber_new_placeholder && $order->post_status != 'auto-draft') {
917
					$number = $this->assignNumber($orderid, $order, 'ordernumber');
918 919 920 921 922
					// Assign a new number
				}
				return $number;
			}

923
			/** 
924
			 * The generic function to retrieve a particular number
925
			 */
926 927
			function get_number($orderid, $order, $type = 'ordernumber') {
				$stored_number = get_post_meta( $orderid, $this->ordernumber_meta.$type, 'true');
928 929
				if ($stored_number == $this->ordernumber_new_placeholder) {
					// Check whether the order was now really created => create order number now
930
					return $this->assign_new_ordernumber($orderid, $order, $type);
931 932
				} elseif (!empty($stored_number)) {
					// Order number already exists => simply return it
933
					return $stored_number;
934
				} else {
935
					// No order number was created for this order, so simply use the orderid as default.
936
					return $orderid;
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
				}
			}

		}
	}

	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();
	}
 
}