PluginProbe
MBE eShip / 2.6.1
MBE eShip v2.6.1
2.8.1 trunk 1.0.0 1.1.0 1.1.3 1.2.1 1.2.2 1.3.0 1.4.0 1.4.1 1.5.0 1.5.1 1.5.2 1.6.0 1.7.0 1.7.1 2.0.0 2.0.1 2.0.2 2.0.3 2.0.4 2.1.0 2.1.1 2.1.2 2.2.1 All 37 releases
mail-boxes-etc / mail-boxes-etc.php

mail-boxes-etc.php in MBE eShip 2.6.1, at mail-boxes-etc.php

3,020 lines 133.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*
3 Plugin Name: MBE eShip
4 Description: Mail Boxes Etc. Online MBE Plugin integration for main Ecommerce platforms.
5 Version: 2.6.1
6 Author: MBE Worldwide S.p.A.
7 Author URI: https://www.mbeglobal.com/
8 Text Domain: mail-boxes-etc
9 WC requires at least: 6.2
10 WC tested up to: 9.2
11 Domain Path: /languages
12 */
13
14 use MbeExceptions\ApiRequestException;
15 use MbeExceptions\DbException;
16
17 if ( ! defined( 'MBE_ESHIP_ID' ) ) {
18 define( "MBE_ESHIP_ID", "mbe_eship" );
19 }
20
21 if ( ! defined( 'MBE_ESHIP_PLUGIN_DIR' ) ) {
22 define( "MBE_ESHIP_PLUGIN_DIR", plugin_dir_path( __FILE__ ) );
23 }
24
25 if ( ! defined( 'MBE_ESHIP_PLUGIN_URL' ) ) {
26 define( "MBE_ESHIP_PLUGIN_URL", plugin_dir_url( __FILE__ ) );
27 }
28
29 if ( ! defined( 'MBE_ESHIP_PLUGIN_OLD_LOG_DIR' ) ) {
30 define( "MBE_ESHIP_PLUGIN_OLD_LOG_DIR", MBE_ESHIP_PLUGIN_DIR . 'log' );
31 }
32
33 if ( ! function_exists( 'get_plugin_data' ) ) {
34 defined( 'ABSPATH' ) || exit;
35 require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
36 }
37 $plugin_data = get_plugin_data( __FILE__, false, false );
38
39 /** Plugin version */
40 if ( ! defined( 'MBE_ESHIP_PLUGIN_VERSION' ) ) {
41 define( "MBE_ESHIP_PLUGIN_VERSION", $plugin_data['Version'] );
42 }
43
44 /** Plugin Name */
45 if ( ! defined( 'MBE_ESHIP_PLUGIN_NAME' ) ) {
46 define( "MBE_ESHIP_PLUGIN_NAME", $plugin_data['Name'] );
47 }
48
49 /** MBE Elink Database version */
50 if ( ! defined( 'MBE_ESHIP_DATABASE_VERSION_OPTION' ) ) {
51 define( 'MBE_ESHIP_DATABASE_VERSION_OPTION', 'mbe_eship_db_version' );
52 }
53 if ( ! defined( 'MBE_ESHIP_DATABASE_VERSION' ) ) {
54 define( 'MBE_ESHIP_DATABASE_VERSION', '1.2.0' );
55 }
56
57 if ( ! defined( 'MBE_E_LINK_DEBUG_LOG' ) ) {
58 define( 'MBE_E_LINK_DEBUG_LOG', true );
59 }
60
61 /** MBE GEL Proximity **/
62 if ( ! defined( 'MBE_ESTIMATE_DELIVERY_POINT_LABELING_SERVICES' ) ) {
63 define( 'MBE_ESTIMATE_DELIVERY_POINT_LABELING_SERVICES', [ 'NMDP' ] );
64 }
65
66 if ( ! defined( 'MBE_ESTIMATE_DELIVERY_POINT_PRENEGOTIATED_SERVICES' ) ) {
67 define( 'MBE_ESTIMATE_DELIVERY_POINT_PRENEGOTIATED_SERVICES', [ 'GPP' ] );
68 }
69
70 if ( ! defined( 'MBE_ESTIMATE_DELIVERY_POINT_SERVICES' ) ) {
71 define( 'MBE_ESTIMATE_DELIVERY_POINT_SERVICES', array_merge( MBE_ESTIMATE_DELIVERY_POINT_LABELING_SERVICES, MBE_ESTIMATE_DELIVERY_POINT_PRENEGOTIATED_SERVICES ) );
72 }
73
74 if ( ! defined( 'MBE_ESTIMATE_DELIVERY_POINT_SERVICES_REGEXP' ) ) {
75 define( 'MBE_ESTIMATE_DELIVERY_POINT_SERVICES_REGEXP', '/' . ( implode( '|', MBE_ESTIMATE_DELIVERY_POINT_SERVICES ) ) . '/' );
76 }
77
78 if ( ! defined( 'MBE_DELIVERY_POINT_SERVICE' ) ) {
79 define( 'MBE_DELIVERY_POINT_SERVICE', 'MDPS' );
80 }
81 if ( ! defined( 'MBE_DELIVERY_POINT_SERVICE_METHOD' ) ) {
82 define( 'MBE_DELIVERY_POINT_SERVICE_METHOD', MBE_ESHIP_ID . ':' . MBE_DELIVERY_POINT_SERVICE );
83 }
84 if ( ! defined( 'MBE_DELIVERY_POINT_DESCRIPTION' ) ) {
85 define( 'MBE_DELIVERY_POINT_DESCRIPTION', 'Delivery Point' );
86 }
87 if ( ! defined( 'MBE_DELIVERY_POINT_WEIGHT_LIMIT' ) ) {
88 define( 'MBE_DELIVERY_POINT_WEIGHT_LIMIT', 35 );
89 }
90
91 if ( ! defined( 'MBE_SCHEMA_FLAG_OPTION' ) ) {
92 define( 'MBE_SCHEMA_FLAG_OPTION', MBE_ESHIP_ID . '_' . 'need_default_values' );
93 }
94
95 if ( ! defined( 'WOOCOMMERCE_MBE_TABS_PAGE' ) ) {
96 define( 'WOOCOMMERCE_MBE_TABS_PAGE', 'woocommerce_mbe_tabs' );
97 }
98
99 if ( ! defined( 'WOOCOMMERCE_MBE_TABS_PICKUP_PAGE' ) ) {
100 define( 'WOOCOMMERCE_MBE_TABS_PICKUP_PAGE', 'pickup_batches_tabs' );
101 }
102
103 if ( ! defined( 'WOOCOMMERCE_MBE_TABS_PICKUP_PAGE' ) ) {
104 define( 'WOOCOMMERCE_MBE_TABS_PICKUP_PAGE', 'pickup_batches_tabs' );
105 }
106
107 // REST API ENDPOINT CONSTANT
108 if ( ! defined( 'MBE_WC_REST_API_NAMESPACE' ) ) {
109 define( 'MBE_WC_REST_API_NAMESPACE', 'wc/v3' );
110 }
111 if ( ! defined( 'MBE_REST_API_ENDPOINT_SET_SHIPPING_STATUS' ) ) {
112 define( 'MBE_REST_API_ENDPOINT_SET_SHIPPING_STATUS', '/mbe/order/set-shipping-status' );
113 }
114 if ( ! defined( 'MBE_WC_REST_API_USERNAME' ) ) {
115 define( 'MBE_WC_REST_API_USERNAME', MBE_ESHIP_ID . '_api_user' );
116 }
117 if ( ! defined( 'MBE_WC_REST_API_USER_EMAIL' ) ) {
118 define( 'MBE_WC_REST_API_USER_EMAIL', 'mbeapiuser@mbeglobal.com' );
119 }
120 if ( ! defined( 'MBE_WC_REST_API_USER_ROLE' ) ) {
121 define( 'MBE_WC_REST_API_USER_ROLE', MBE_ESHIP_ID . '_rest_api_user' );
122 }
123 if ( ! defined( 'MBE_WC_REST_API_ORDER_STATUS_DELIVERED' ) ) {
124 define( 'MBE_WC_REST_API_ORDER_STATUS_DELIVERED', 'wc-mbe-api-delivered' );
125 }
126 if ( ! defined( 'MBE_WC_REST_API_ORDER_STATUS_DELIVERED_DESCRIPTION' ) ) {
127 define( 'MBE_WC_REST_API_ORDER_STATUS_DELIVERED_DESCRIPTION', 'Delivered MBE' );
128 }
129
130 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Helper/Data.php' );
131 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Helper/Logger.php' );
132 //require_once(MBE_E_LINK_PLUGIN_DIR . '/lib/Helper/Tracking.php');
133 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Helper/Csv.php' );
134 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Helper/Rates.php' );
135 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Traits/Mbe_Entity_Model_Trait.php' );
136 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Traits/ShipmentActions.php' );
137 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Interfaces/EntityModelInterface.php' );
138 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Factories/CsvEntityFactory.php' );
139 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Factories/CsvEditorEntityFactory.php' );
140 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Model/CsvShipping.php' );
141 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Model/CsvPackage.php' );
142 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Model/CsvPackageProduct.php' );
143 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Model/CsvPickupAddress.php' );
144 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Model/PickupCustomData.php' );
145
146 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Metaboxes/DepartmentAddressData.php' );
147 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Metaboxes/AdvancedReturnAddressData.php' );
148 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Mbe/MbeWs.php' );
149 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Mbe/MbeSoapClient.php' );
150 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Model/Ws.php' );
151 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Model/Carrier.php' );
152 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/Exceptions/MbeExceptions.php' );
153 require_once( MBE_ESHIP_PLUGIN_DIR . 'backward_compatibility/array_column.php' );
154
155 //if ( ! class_exists( '\Dompdf\Dompdf' ) ) {
156 // require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/dompdf/autoload.inc.php' );
157 //}
158
159 require_once( MBE_ESHIP_PLUGIN_DIR . 'lib/vendor/autoload.php' );
160
161 function mbe_eship_is_old_elink_plugin_active() {
162 $activePlugins = array_keys( get_plugins() );
163 $oldPlugin = array_filter( $activePlugins, function ( $item ) {
164 return preg_match( '/mail-boxes-etc.php/', $item );
165 } );
166
167 return is_plugin_active( array_values( $oldPlugin )[0] );
168 }
169
170 /**
171 * Plugin activation check
172 */
173 function mbe_eship_activation_check() {
174 if ( ! class_exists( 'SoapClient' ) ) {
175 deactivate_plugins( basename( __FILE__ ) );
176 wp_die( 'Sorry, but you cannot run this plugin, it requires the <a href="http://php.net/manual/en/class.soapclient.php">SOAP</a> support on your server/hosting to function.' );
177 }
178 }
179
180 /**
181 * Transfer the settings from the old plugin to the new ones
182 * @return void
183 */
184 function mbe_eship_update_new_settings_check() {
185 global $wpdb;
186 $logger = new Mbe_Shipping_Helper_Logger();
187
188 $schemaFlagOption = MBE_ESHIP_ID . '_' . 'need_new_settings';
189 $oldOption = get_option( Mbe_Shipping_Helper_Data::MBE_ELINK_SETTINGS );
190 $mbeNeedUpdate = ! ( get_option( $schemaFlagOption ) === 'no' ) && ! empty( $oldOption );
191 // To check if plugin was already configured but options weren't migrated yet
192 $notConfigured = empty( get_option( MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_ALLOWED_SHIPMENT_SERVICES ) );
193 $csv_rates_model = new Mbe_Shipping_Model_Csv_Shipping();
194 $csv_package_model = new Mbe_Shipping_Model_Csv_Package();
195 $csv_package_product_model = new Mbe_Shipping_Model_Csv_Package_Product();
196
197 // TODO: Check if the impact can be mitigated moving this line inside the if
198 $tableExist = $csv_rates_model->tableExists() && $csv_package_model->tableExists() && $csv_package_product_model->tableExists();
199
200 if ( $mbeNeedUpdate && $tableExist && $notConfigured ) {
201
202 $logger->log( 'Migrating from MBE e-Link --- Starting', true );
203 // try {
204
205 $logger->log( 'Migrating from MBE e-Link --- Options', true );
206 foreach ( $oldOption as $key => $value ) {
207 update_option( MBE_ESHIP_ID . '_' . $key, $value );
208 }
209
210 $logger->log( 'Migrating from MBE e-Link --- Login', true );
211 $wsUser = $oldOption[ Mbe_Shipping_Helper_Data::XML_PATH_WS_USERNAME ];
212 $wsPwd = $oldOption[ Mbe_Shipping_Helper_Data::XML_PATH_WS_PASSWORD ];
213
214 // Set advanced login mode
215 if ( ! empty( $wsUser ) && ! empty( $wsPwd ) ) {
216 update_option( MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_LOGIN_MODE, Mbe_Shipping_Helper_Data::MBE_LOGIN_MODE_ADVANCED );
217 update_option( MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_LOGIN_LINK_ADV, true );
218 }
219
220 $logger->log( 'Migrating from MBE e-Link --- Configuration mode', true );
221 $csvMode = $oldOption[ Mbe_Shipping_Helper_Data::XML_PATH_SHIPMENTS_CSV_MODE ];
222 if ( $csvMode <> Mbe_Shipping_Helper_Data::MBE_CSV_MODE_DISABLED ) {
223 update_option( MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_COURIER_CONFIG_MODE, Mbe_Shipping_Helper_Data::MBE_COURIER_MODE_CSV );
224 } else if ( $oldOption['mbe_enable_custom_mapping'] === 'yes' ) {
225 update_option( MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_COURIER_CONFIG_MODE, Mbe_Shipping_Helper_Data::MBE_COURIER_MODE_MAPPING );
226 } else {
227 update_option( MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_COURIER_CONFIG_MODE, Mbe_Shipping_Helper_Data::MBE_COURIER_MODE_SERVICES );
228 }
229
230 // Migrate CSV tables
231 $logger->log( 'Migrating from MBE e-Link --- Csv Tables', true );
232 // TODO: move tablexists here ?
233 $csvTables = [
234 $csv_rates_model->getTableName() => 'mbeshippingrate',
235 $csv_package_model->getTableName() => 'mbe_shipping_standard_packages',
236 $csv_package_product_model->getTableName() => 'mbe_shipping_standard_package_product',
237 ];
238
239 foreach ( $csvTables as $key => $value ) {
240 // Check if old table exists
241 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
242 if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->prefix . $value ) ) == $wpdb->prefix . $value ) {
243 $wpdb->query( $wpdb->prepare( "INSERT INTO %i SELECT * FROM %i", $key, $wpdb->prefix . $value ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
244 }
245 }
246
247 update_option( $schemaFlagOption, 'no' );
248
249 $logger->log( 'Migrating from MBE e-Link --- Complete', true );
250 // } catch ( Exception $e ) {
251 //
252 // }
253 } else if ( ! ( get_option( $schemaFlagOption ) === 'no' ) && empty( $oldOption ) ) {
254 $logger->log( 'Migrating from MBE e-Link --- Old options are missing ' );
255 } else if ( $mbeNeedUpdate && ! $notConfigured ) {
256 $logger->log( 'Migrating from MBE e-Link --- No migration, Plugin already configured ' );
257 }
258 }
259
260 function mbe_eship_check_log_folder_htaccess() {
261 $helper = new Mbe_Shipping_Helper_Data();
262 $dirPath = trailingslashit( $helper->getMbeLogDir() );
263 $filePath = $dirPath . '.htaccess';
264 if ( ! file_exists( $filePath ) ) {
265 $helper->createHtaccessDenyAll( $dirPath );
266 }
267 }
268
269 function mbe_eship_rest_api_key_check() {
270 if ( is_admin() ) {
271 $logger = new Mbe_Shipping_Helper_Logger();
272 $user_id = username_exists( MBE_WC_REST_API_USERNAME );
273
274 if ( $user_id && email_exists( MBE_WC_REST_API_USER_EMAIL ) ) {
275 $helper = new Mbe_Shipping_Helper_Data();
276
277 if ( ! $helper->hasApiKey( $user_id ) ) {
278 try {
279 mbe_eship_generate_and_send_api_key( $user_id );
280 } catch ( DbException $e ) {
281 $logger->log( 'REST API Check - Generate and Send Api Key EXCEPTION: ' . $e->getMessage() );
282 }
283 }
284 } else {
285 $logger->log( 'REST API Check - Generate and Send Api Key - User/Email missing' );
286 }
287 }
288 }
289
290 function mbe_eship_uninstall_db_options() {
291 global $wpdb;
292 $csv_rates_model = new Mbe_Shipping_Model_Csv_Shipping();
293 $csv_package_model = new Mbe_Shipping_Model_Csv_Package();
294 $csv_package_product_model = new Mbe_Shipping_Model_Csv_Package_Product();
295 $pickup_custom_data_model = new Mbe_Shipping_Model_Pickup_Custom_Data();
296
297 // Delete all the tables
298 $tables = [
299 $csv_rates_model->getTableName(),
300 $csv_package_model->getTableName(),
301 $csv_package_product_model->getTableName(),
302 $pickup_custom_data_model->getTableName(),
303 ];
304
305 // Remove "old plugin" tables too if any
306 array_push( $tables,
307 $wpdb->prefix . 'mbe_shipping_standard_package_product',
308 $wpdb->prefix . 'mbe_shipping_standard_packages',
309 $wpdb->prefix . 'mbeshippingrate' );
310
311 foreach ( $tables as $table ) {
312 $wpdb->query( $wpdb->prepare( "DROP TABLE IF EXISTS %i", $table ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
313 }
314
315 // Delete the REST API User, Role and Keys if any
316 $userLogin = MBE_WC_REST_API_USERNAME;
317 $mbeApiRole = MBE_WC_REST_API_USER_ROLE;
318
319 if ( username_exists( $userLogin ) ) {
320 $user = get_user_by( 'login', $userLogin );
321 if ( ! wp_delete_user( $user->ID ) ) {
322 error_log( MBE_ESHIP_PLUGIN_NAME . ': REST API User Deletion - User not deleted' );
323 }
324 remove_role( $mbeApiRole );
325 } else {
326 error_log( MBE_ESHIP_PLUGIN_NAME . ': REST API User Deletion - User not found' );
327 }
328 error_log( MBE_ESHIP_PLUGIN_NAME . ': REST API User Deletion - User, Role and Keys deleted successfully' );
329
330 // Delete all the options
331 $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE '" . MBE_ESHIP_ID . "\_%'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
332
333 // Delete the "old plugin" db version option, since we are removing the tables
334 delete_option( 'mbe_elink_db_version' );
335
336 // Remove all pickup meta items from the orders
337 $queryMeta = $wpdb->prepare( "DELETE FROM $wpdb->order_itemmeta where meta_key in (%s, %s, %s)", Mbe_Shipping_Helper_Data::META_FIELD_IS_PICKUP_SHIPPING, Mbe_Shipping_Helper_Data::META_FIELD_PICKUP_BATCH_ID, Mbe_Shipping_Helper_Data::META_FIELD_PICKUP_CUSTOM_DATA_ID );
338 $wpdb->query( $queryMeta ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
339
340 }
341
342 function mbe_eship_install_db() {
343
344 $helper = new Mbe_Shipping_Helper_Data();
345 $currentVersion = get_option( MBE_ESHIP_DATABASE_VERSION_OPTION ) ?: '0';
346
347 if ( version_compare( $currentVersion, MBE_ESHIP_DATABASE_VERSION, '<' ) ) {
348 require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
349 $dbDelta = dbDelta( get_mbe_elink_db_schema() );
350
351 // ADD conditions to verify if the database has been correctly updated accordingly to the last schema changes
352 // If only a new table is added , $updateCondition can be kept as "true" but mbe_elink_db_tables_exist() must be updated
353 $updateCondition = true;
354
355 if ( mbe_elink_db_tables_exist() && $updateCondition ) {
356 update_option( MBE_ESHIP_DATABASE_VERSION_OPTION, MBE_ESHIP_DATABASE_VERSION );
357 }
358 }
359 }
360
361 function mbe_elink_db_tables_exist() {
362 $csv_rates_model = new Mbe_Shipping_Model_Csv_Shipping();
363 $csv_package_model = new Mbe_Shipping_Model_Csv_Package();
364 $csv_package_product_model = new Mbe_Shipping_Model_Csv_Package_Product();
365 $pickup_custom_data_model = new Mbe_Shipping_Model_Pickup_Custom_Data();
366
367 return $csv_rates_model->tableExists()
368 && $csv_package_model->tableExists()
369 && $csv_package_product_model->tableExists()
370 && $pickup_custom_data_model->tableExists();
371 }
372
373 function get_mbe_elink_db_schema() {
374 $csv_rates_model = new Mbe_Shipping_Model_Csv_Shipping();
375 $csv_package_model = new Mbe_Shipping_Model_Csv_Package();
376 $csv_package_product_model = new Mbe_Shipping_Model_Csv_Package_Product();
377 $pickup_custom_data_model = new Mbe_Shipping_Model_Pickup_Custom_Data();
378
379 return $csv_rates_model->getSqlCreate()
380 . $csv_package_model->getSqlCreate()
381 . $csv_package_product_model->getSqlCreate()
382 . $pickup_custom_data_model->getSqlCreate();
383 }
384
385 function mbe_eship_update_db_check() {
386 $action = sanitize_text_field( $_REQUEST['action'] ?? '' );
387 if ( ! empty( $action ) && $action !== 'deactivate' ) {
388 mbe_eship_install_db();
389 }
390 }
391
392 function declare_compatibility() {
393 // HPOS
394 if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
395 \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
396 }
397 // BLOCK CHECKOUT
398 if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
399 \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, false );
400 }
401 }
402
403
404 // ** REST API Management ** //
405 // ** User, role, apikey creation and deletion ** //
406
407 function mbe_rest_api_user_creation_and_sync_to_mol() {
408 $logger = new Mbe_Shipping_Helper_Logger();
409
410 if ( ! class_exists( 'woocommerce' ) ) {
411 $logger->log( 'REST API User Creation - Woocommerce is not active' );
412
413 return false;
414 }
415
416 // Create the MBE REST API user role if not exists
417 add_role( MBE_WC_REST_API_USER_ROLE, strtoupper( str_replace( '_', ' ', MBE_ESHIP_ID ) ) . ' REST API User'
418 // ,array(
419 // 'read' => true,
420 // 'edit_posts' => false,
421 // 'delete_posts' => false,
422 // add capabilities
423 // )
424 );
425
426 // Create the MBE REST API user with a random password (no backend login is required for api access)
427 $password = wc_rand_hash();
428
429 if ( ! username_exists( MBE_WC_REST_API_USERNAME ) && ! email_exists( MBE_WC_REST_API_USER_EMAIL ) ) {
430 $user_id = wp_create_user( MBE_WC_REST_API_USERNAME, $password, MBE_WC_REST_API_USER_EMAIL );
431 if ( ! is_wp_error( $user_id ) ) {
432 // Assign the custom role to the user
433 $user = new WP_User( $user_id );
434 $user->set_role( MBE_WC_REST_API_USER_ROLE );
435 try {
436 mbe_eship_generate_and_send_api_key( $user_id );
437 } catch ( DbException $e ) {
438 $logger->log( 'REST API User Creation - Generate Api Key EXCEPTION: ' . $e->getMessage() );
439 }
440 } else {
441 /** @var WP_Error $user_id */
442 $logger->log( 'REST API User Creation - EXCEPTION: ' . $user_id->get_error_message() );
443 }
444 } else {
445 $logger->log( 'REST API User Creation - User already exists' );
446 }
447 }
448
449 /**
450 * @param Mbe_Shipping_Helper_Data $helper
451 * @param $user_id
452 * @param Mbe_Shipping_Helper_Logger $logger
453 * @param Mbe_Shipping_Model_Ws $ws
454 *
455 * @return void
456 * @throws DbException
457 */
458 function mbe_eship_generate_and_send_api_key( $user_id ): void {
459 $helper = new Mbe_Shipping_Helper_Data();
460 $ws = new Mbe_Shipping_Model_Ws();
461 $logger = new Mbe_Shipping_Helper_Logger();
462
463 try {
464 $stepMessage = 'generateMbeRestApiKey';
465 $apiKeys = $helper->generateMbeRestApiKey( $user_id );
466
467 $logger->log( 'REST API Creation - New WooCommerce API Key created' );
468
469 $stepMessage = 'sendRestApiCredentials';
470 $result = $ws->sendRestApiCredentials( base64_encode( $apiKeys['key'] . ':' . $apiKeys['secret'] ) );
471
472 } catch ( ApiRequestException $e ) {
473 $logger->log( 'REST API Creation - Send Api Key EXCEPTION: ' . $stepMessage . ' - ' . $e->getMessage() );
474 // delete the api key so it will be regenerated by the control hooked on plugin save
475 $helper->removeMbeRestApiKey( $user_id );
476 } catch ( \Exception $e ) {
477 $logger->log( 'REST API Creation - EXCEPTION: ' . $stepMessage . ' - ' . $e->getMessage() );
478 $helper->removeMbeRestApiKey( $user_id );
479 }
480 }
481
482 register_uninstall_hook( __FILE__, 'mbe_eship_uninstall_db_options' ); // ONLY ONE Uninstall Hook is registrable
483 register_activation_hook( __FILE__, 'mbe_eship_activation_check' );
484 register_activation_hook( __FILE__, 'mbe_eship_install_db' );
485
486
487 // ** REST API Management ** //
488 // ** User, role, apikey creation and deletion ** //
489 register_initial_settings();
490 register_activation_hook( __FILE__, 'mbe_rest_api_user_creation_and_sync_to_mol' );
491 // ** //
492
493 //register_activation_hook( __FILE__, 'mbe_eship_create_options_default' );
494 //add_action( 'plugins_loaded','mbe_eship_create_options_default' );
495 //add_action( 'plugins_loaded','mbe_eship_check_pickup_request_mode' );
496
497 add_action( 'plugins_loaded', 'mbe_eship_update_db_check', 9 );
498 add_action( 'plugins_loaded', 'mbe_eship_update_new_settings_check', 10 );
499 add_action( 'plugins_loaded', 'mbe_eship_check_log_folder_htaccess', 10 );
500 add_action( 'before_woocommerce_init', 'declare_compatibility' );
501
502
503 /**
504 * Check if WooCommerce is active
505 */
506 if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
507 if ( ! function_exists( 'mbe_e_link_get_settings_url' ) ) {
508 function mbe_e_link_get_settings_url() {
509 return version_compare( WC()->version, '2.1', '>=' ) ? "wc-settings" : "woocommerce_settings";
510 }
511 }
512
513 if ( ! function_exists( 'mbe_e_link_plugin_override' ) ) {
514 add_action( 'plugins_loaded', 'mbe_e_link_plugin_override' );
515 function mbe_e_link_plugin_override() {
516 if ( ! function_exists( 'WC' ) ) {
517 function WC() {
518 return $GLOBALS['woocommerce'];
519 }
520 }
521 }
522 }
523
524 if ( ! class_exists( 'mbe_e_link_wooCommerce_shipping_setup' ) ) {
525 class mbe_e_link_wooCommerce_shipping_setup {
526 use \Traits\ShipmentActions;
527
528 protected $helper;
529
530 public function __construct() {
531 add_filter( 'woocommerce_get_settings_pages', array( $this, 'load_custom_settings_tab' ) );
532
533 // Check if Pickup request activation flag is set and in case force the default value setter to run
534 add_action( 'mbe_eship_custom_settings_loaded', array(
535 $this,
536 'mbe_eship_check_pickup_default_options'
537 ) );
538
539 // Check if Tax and Duties request activation flag is set and in case force the default value setter to run
540 add_action( 'mbe_eship_custom_settings_loaded', array(
541 $this,
542 'mbe_eship_check_tax_and_duties_default_options'
543 ) );
544
545 // Check default values for settings
546 add_action( 'mbe_eship_custom_settings_loaded', array(
547 $this,
548 'mbe_eship_create_options_default'
549 ), 20 );
550
551 // Add settings link in the plugin list
552 add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array(
553 $this,
554 'plugin_action_links'
555 ) );
556 // Add MBE shipping method to WooCommerce but remove the tab from WooCommerce => Settings => Shipping
557 add_filter( 'woocommerce_shipping_methods', array( $this, 'wf_mbe_wooCommerce_shipping_methods' ) );
558 add_action( 'woocommerce_shipping_init', array( $this, 'wf_mbe_wooCommerce_shipping_init' ) );
559
560 // Action for downloading log files
561 add_action( 'admin_post_mbe_download_log_files', array( $this, 'mbe_download_log_files' ) );
562 add_action( 'admin_post_mbe_download_standard_package_file', array(
563 $this,
564 'mbe_download_standard_package_file'
565 ), 10, 0 );
566 add_action( 'admin_post_mbe_download_shipping_file', array(
567 $this,
568 'mbe_download_shipping_file'
569 ), 10, 0 );
570 add_filter( 'query_vars', array( $this, 'mbe_add_query_vars' ) );
571
572 // Action for deleting log files
573 add_action( 'admin_post_mbe_delete_log_files', array( $this, 'mbe_delete_log_files' ) );
574
575 // Action for generating API KEY
576 // add_action( 'admin_post_mbe_generate_api_key', array( $this, 'mbe_generate_api_key' ) );
577
578 //Action for new settings
579 add_action( 'admin_post_mbe_sign_in', array( $this, 'mbe_sign_in' ) );
580 add_action( 'admin_post_mbe_goto_advanced_login', array( $this, 'mbe_goto_advanced_login' ) );
581 add_action( 'admin_post_mbe_reset_login', array( $this, 'mbe_reset_login' ) );
582
583 // Action to download single order pickup manifest
584 add_action( 'admin_post_mbe_download_pickup_manifest', array( $this, 'mbe_download_pickup_manifest' ) );
585
586 // Action to download multiple waybill showing partial errors (called by add_order_list via JS when "reload-download" parameter is set)
587 add_action( 'admin_post_mbe_download_multiple_waybill', array(
588 $this,
589 'mbe_download_multiple_waybill'
590 ) );
591
592 // Action to download delivery point single order waybill
593 add_action( 'admin_post_mbe_download_delivery_point_waybill', array(
594 $this,
595 'mbe_download_delivery_point_waybill'
596 ) );
597
598 // Add menu
599 add_action( 'admin_menu', array( $this, 'add_mbe_tab' ) );
600
601 // Load translations
602 add_action( 'plugins_loaded', array( $this, 'wan_load_wf_shipping_mbe' ) );
603
604 // Add Delivery Point Field to Admin Order details view
605 add_action( 'woocommerce_admin_order_data_after_billing_address', array(
606 $this,
607 'wf_mbe_delivery_point_show_meta_field'
608 ), 10, 1 );
609
610 // Add box in the order detail
611 add_action( 'wp_loaded', array( $this, 'wf_mbe_wooCommerce_shipping_init_box' ) );
612
613 // Get default data for pickup from MOL when loading pickup settings page or before creating a new pickup shipment
614 // add_action('woocommerce_before_settings_'. MBE_ESHIP_ID , array($this, 'mbe_woocommerce_get_pickup_default_data'));
615 add_action( MBE_ESHIP_ID . '_before_output_section_mbe_pickup', array(
616 $this,
617 'mbe_woocommerce_get_pickup_default_data'
618 ), 5 );
619 add_action( MBE_ESHIP_ID . '_before_create_pickup', array(
620 $this,
621 'mbe_woocommerce_get_pickup_default_data'
622 ), 5 );
623
624 // Send default data for pickup to MOL
625 add_action( 'woocommerce_update_options_' . MBE_ESHIP_ID . '_mbe_pickup', array(
626 $this,
627 'mbe_woocommerce_set_pickup_default_data'
628 ) );
629
630 // Action to create a return shipment
631 add_action( 'admin_post_mbe_create_return_shipment', array( $this, 'mbe_create_return_shipment' ) );
632 add_action( MBE_ESHIP_ID . '_before_create_advanced_return', array(
633 $this,
634 'mbe_woocommerce_get_advanced_return_address_data'
635 ), 5 );
636
637 // //Action to edit a pickup batch
638 // add_action('admin_post_mbe_edit_pickup', array($this, 'pickup_data_form_page_handler'));
639
640 // Action to ship a pickup batch
641 add_action( 'admin_post_mbe_send_pickup', array( $this, 'mbe_send_pickup' ) );
642
643 // Action to delete a pickup batch
644 add_action( 'admin_post_mbe_delete_pickup_custom_data', array(
645 $this,
646 'mbe_delete_pickup_custom_data'
647 ) );
648
649 // Action to detach an order from a pickup batch
650 add_action( 'admin_post_mbe_detach_order_from_batch', array( $this, 'mbe_detach_order_from_batch' ) );
651
652 // Action to check batch items after detach
653 add_action( MBE_ESHIP_ID . '_after_detach', array( $this, 'mbe_after_detach_check_pickup_items' ) );
654
655 // Action to check pickup status after deleting the pickup addresses
656 add_action( MBE_ESHIP_ID . '_csv_editor_deleted', array(
657 $this,
658 'mbe_after_delete_pickup_address_disable_pickup_if_no_default_address'
659 ), 10, 2 );
660
661 // Script to manage custom mbebuttons actions
662 add_action( 'admin_enqueue_scripts', array( $this, 'mbe_helper_scripts' ) );
663
664 $this->helper = new Mbe_Shipping_Helper_Data();
665 if ( $this->helper->isEnabled() ) {
666 add_action( 'wp_enqueue_scripts', array( $this, 'mbe_gel_proximity_scripts' ) );
667
668 add_action( 'closure_event', array( $this, 'automatic_closure' ) );
669 add_action( 'woocommerce_settings_saved', array( $this, 'add_cron_job' ) );
670 add_action( 'woocommerce_admin_updated', array( $this, 'mbe_error_notice' ) );
671
672 //Add admin notice
673 add_action( 'admin_notices', array( $this, 'mbe_shipping_admin_notices' ) );
674
675 // Add label "Free" to Frontend if the price is 0
676 add_filter( 'woocommerce_cart_shipping_method_full_label', array(
677 $this,
678 'wf_mbe_wooCommerce_set_free_label'
679 ), 10, 2 );
680
681 // Create shipping automatically on status processing
682 add_action( 'woocommerce_order_status_processing', array( $this, 'mbe_update_tracking' ), 10, 2 );
683
684 // Create shipping manually
685 add_filter( 'woocommerce_order_actions', array( $this, 'add_order_meta_box_actions' ), 10, 2 );
686 add_action( 'woocommerce_order_action_mbe_shipping_creation', array(
687 $this,
688 'process_order_meta_box_actions'
689 ) );
690
691 // Add frontend tracking
692 add_action( 'woocommerce_order_details_after_order_table', array(
693 $this,
694 'woocommerce_order_details_tracking'
695 ) );
696
697 // Add frontend GEL proximity delivery points map
698 add_action( 'woocommerce_after_shipping_rate', array(
699 $this,
700 'wf_mbe_wooCommerce_shipping_gel_delivery_point_map'
701 ), 10, 2 );
702
703 // Add filter to hide custom order item metakeys
704 add_filter( 'woocommerce_order_item_get_formatted_meta_data', array(
705 $this,
706 'wf_mbe_wooCommerce_shipping_hide_custom_order_meta_keys'
707 ), 10, 2 );
708
709 // Add Delivery point dataset to the checkout fields list
710 // add_filter( 'woocommerce_checkout_fields', array(
711 // $this,
712 // 'wf_mbe_delivery_point_add_selected_location_field'
713 // ) );
714
715 // Add Delivery point address form field validation
716 add_action( 'woocommerce_after_checkout_validation', array(
717 $this,
718 'wf_mbe_delivery_point_validation'
719 ), 10, 2 );
720
721 // Set Delivery Point address as order's shipping address
722 add_filter( 'woocommerce_checkout_posted_data', array(
723 $this,
724 'wf_mbe_delivery_point_set_shipping_address'
725 ) );
726
727 // Set Delivery Point shipment metafield value for the "old" shortcode checkout
728 add_action( 'woocommerce_checkout_update_order_meta', array(
729 $this,
730 'wf_mbe_delivery_point_set_meta_field'
731 ), 10, 2 );
732
733
734 add_action( 'woocommerce_checkout_update_order_review', array(
735 $this,
736 'wf_mbe_delivery_point_set_meta_field_review'
737 ) );
738
739 // Update package payload for dynamic shipping cost base on selected delivery point
740 add_filter( 'woocommerce_cart_shipping_packages', array(
741 $this,
742 'wf_mbe_delivery_point_update_package_for_cost_recalculation'
743 ) );
744
745 // Remove the delivery point session variable
746 add_action( 'woocommerce_checkout_order_created', array(
747 $this,
748 'wf_mbe_remove_delivery_point_session_variable'
749 ) );
750 add_action( 'woocommerce_cart_emptied', array(
751 $this,
752 'wf_mbe_remove_delivery_point_session_variable'
753 ) );
754 add_action( 'woocommerce_cart_is_empty', array(
755 $this,
756 'wf_mbe_remove_delivery_point_session_variable'
757 ) );
758
759 // Set Custom Mapping metafield value for the "old" shortcode checkout
760 add_action( 'woocommerce_checkout_update_order_meta', array(
761 $this,
762 'wf_mbe_wooCommerce_shipping_custom_mapping_meta_field'
763 ) );
764
765 // Set Custom Mapping metafield value for the "new" blocks checkout
766 add_action( 'woocommerce_store_api_checkout_update_order_meta', array(
767 $this,
768 'wf_mbe_wooCommerce_shipping_custom_mapping_meta_field_checkout_block'
769 ) );
770
771 // Add track ID to transational emails
772 add_action( 'woocommerce_email_order_details', array(
773 $this,
774 'mbe_woocommerce_email_track_id'
775 ), 20, 4 );
776
777 // Check the pickup request mode <=> shipping mode
778 add_action( 'woocommerce_settings_page_init', array(
779 $this,
780 'mbe_eship_check_pickup_request_mode'
781 ) );
782
783 // Check if the tax and duties must be disabled
784 add_action( 'woocommerce_settings_page_init', array( $this, 'mbe_eship_check_tax_and_duties' ) );
785
786 // Set or update pickup data on shipment creation
787 add_action( MBE_ESHIP_ID . '_before_create_pickup', array( $this, 'mbe_edit_pickup_data' ) );
788
789 // Set or update department address data in shipment list
790 add_action( MBE_ESHIP_ID . '_add_department_data', array(
791 $this,
792 'mbe_edit_department_address_data'
793 ) );
794
795 // Action to select a department address for the pickup order
796 add_action( 'admin_post_mbe_select_department_address_pickup', array(
797 $this,
798 'mbe_select_department_address_pickup'
799 ) );
800
801 // Show Tax and Duties in Checkout shortcodes
802 add_action( 'woocommerce_review_order_before_submit', array(
803 $this,
804 'mbe_show_tax_and_duties_checkout_message'
805 ) );
806
807 if($this->helper->isEnabledTaxAndDuties()) {
808 add_action( 'woocommerce_cart_calculate_fees', array(
809 $this,
810 'mbe_eship_add_tax_and_duties_fee'
811 ) );
812 }
813
814 // Check insurance services selected when saving settings
815 add_action( 'woocommerce_settings_save_' . MBE_ESHIP_ID, array(
816 $this,
817 'mbe_check_insurance_mode_selected'
818 ) );
819
820 // Add REST API endpoint for Tracking
821 add_action( 'rest_api_init', array(
822 $this,
823 'register_woocommerce_mbe_order_shipping_status_route'
824 ) );
825 // Add REST API Status for Orders
826 add_filter( 'wc_order_statuses', array( $this, 'mbe_eship_add_order_delivered_status' ) );
827
828 add_action( 'init', array( $this, 'mbe_eship_register_post_status' ), 9 );
829 add_action( 'admin_head', array( $this, 'mbe_eship_style_delivered_status' ) );
830
831
832 // Check REST API User/Key is enabled. Run only after MBE settings are saved, doesn't run for other WC settings
833 add_action( 'woocommerce_settings_save_' . MBE_ESHIP_ID, function () {
834 if ( ! has_action( 'woocommerce_settings_saved', 'mbe_eship_rest_api_key_check' ) ) {
835 add_action( 'woocommerce_settings_saved', 'mbe_eship_rest_api_key_check', 5 );
836 }
837 } );
838 // Remove the Check REST API once executed (using priority)
839 add_action( 'woocommerce_settings_saved', function () {
840 if ( has_action( 'woocommerce_settings_saved', 'mbe_eship_rest_api_key_check' ) ) {
841 remove_action( 'woocommerce_settings_saved', 'mbe_eship_rest_api_key_check' );
842 }
843 }, 10 );
844
845 }
846 }
847
848 function mbe_eship_style_delivered_status() {
849 if ( ! ( is_admin() &&
850 ( get_current_screen()->id === 'woocommerce_page_wc-orders' || get_current_screen()->id === 'edit-shop_order' )
851 ) ) {
852 return;
853 } // Exit
854
855 $deliveredStatus = substr( MBE_WC_REST_API_ORDER_STATUS_DELIVERED, 3 );
856
857 ?>
858 <style>
859 .order-status.status-<?php echo sanitize_title( $deliveredStatus ); ?> {
860 background: #c6e1c6;
861 color: #5b841b;
862 }
863 </style>
864 <?php
865 }
866
867 public function mbe_eship_add_order_delivered_status( array $statuses ) {
868 $statuses[ MBE_WC_REST_API_ORDER_STATUS_DELIVERED ] = __( MBE_WC_REST_API_ORDER_STATUS_DELIVERED_DESCRIPTION, 'mail-boxes-etc' );
869
870 return $statuses;
871 }
872
873 public function mbe_eship_register_draft_order_post_status( array $statuses ) {
874 $statuses[ MBE_WC_REST_API_ORDER_STATUS_DELIVERED ] = $this->mbe_eship_get_post_status_properties();
875
876 return $statuses;
877 }
878
879 function mbe_eship_register_post_status() {
880 $is_registered = get_post_stati( [ 'name' => MBE_WC_REST_API_ORDER_STATUS_DELIVERED ] );
881 if ( empty( $is_registered ) ) {
882 register_post_status(
883 MBE_WC_REST_API_ORDER_STATUS_DELIVERED,
884 $this->mbe_eship_get_post_status_properties()
885 );
886 }
887 }
888
889 function mbe_eship_get_post_status_properties() {
890 return [
891 'label' => __( MBE_WC_REST_API_ORDER_STATUS_DELIVERED_DESCRIPTION, 'mail-boxes-etc' ),
892 'public' => true,
893 'exclude_from_search' => false,
894 'show_in_admin_all_list' => true,
895 'show_in_admin_status_list' => true,
896 /* %s: number of orders */
897 'label_count' => _n_noop( __( MBE_WC_REST_API_ORDER_STATUS_DELIVERED_DESCRIPTION ) . ' <span class="count">(%s)</span>', __( MBE_WC_REST_API_ORDER_STATUS_DELIVERED_DESCRIPTION ) . ' <span class="count">(%s)</span>', 'mail-boxes-etc' ),
898 ];
899 }
900
901 function register_woocommerce_mbe_order_shipping_status_route() {
902 register_rest_route( MBE_WC_REST_API_NAMESPACE, MBE_REST_API_ENDPOINT_SET_SHIPPING_STATUS, array(
903
904 'methods' => WP_REST_Server::EDITABLE,
905 'callback' => array( $this, 'rest_api_handle_mbe_order_shipping_status_endpoint' ),
906 'permission_callback' => array( $this, 'rest_api_mbe_api_key_permission_check' )
907 ) );
908 }
909
910 // Authentication callback function
911 function rest_api_mbe_api_key_permission_check( $request ) {
912 $logger = new Mbe_Shipping_Helper_Logger();
913 $logger->log( 'REST API Endpoint - Permission check' );
914
915 // Get the custom MOL request header
916 $MolApiKeyHeader = $request->get_header( 'authorization-api-key' ) ?? '';
917
918 if ( empty( $MolApiKeyHeader ) ) {
919 return new WP_Error( 'rest_forbidden', 'You do not have permission to access this endpoint.', array( 'status' => 403 ) );
920 }
921
922 $apiKey = explode( ':', base64_decode( $MolApiKeyHeader ) );
923
924 // Set the keys to be used in WC_REST_Authentication
925 $_GET['consumer_key'] = $apiKey[0] ?? '';
926 $_GET['consumer_secret'] = $apiKey[1] ?? '';
927
928 $auth = new WC_REST_Authentication();
929 $userId = $auth->authenticate( false );
930
931 if ( ! empty( $userId ) ) {
932 $logger->log( 'REST API Endpoint - Permission check - OK' );
933
934 return true;
935 }
936 $logger->logVar( $request, 'REST API Endpoint - Permission check - Failed' );
937
938 return new WP_Error( 'rest_forbidden', 'You do not have permission to access this endpoint.', array( 'status' => 403 ) );
939 }
940
941 function rest_api_handle_mbe_order_shipping_status_endpoint( $request ) {
942 // Handle the request and return a response
943 $logger = new Mbe_Shipping_Helper_Logger();
944 $requestParameters = $request->get_params();
945 $logger->log( 'REST API Endpoint - Incoming request' );
946
947 $isAdvancedReturn = false;
948
949 if ( ! empty( $requestParameters ) ) {
950 $trackingNumber = trim( sanitize_text_field( $requestParameters[0]['mbeTrackingNumber'] ?? '' ) );
951 $mbeStatus = $requestParameters[0]['mbeStatus'];
952
953 $trackingNumber = preg_replace( '/-\d(1,2)$/', '', $trackingNumber );
954 $logger->log( 'REST API Endpoint - Tracking Number: ' . $trackingNumber . ' - Status code: ' . $mbeStatus );
955
956 $orders = [];
957 if ( ! empty( $trackingNumber ) ) {
958 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
959 $orders = wc_get_orders( [
960 'meta_key' => Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_NUMBER,
961 'meta_value' => $trackingNumber
962 ] );
963 if ( empty( $orders ) ) { // Check if it matches a return shipment
964 $orders = wc_get_orders( [
965 'meta_key' => Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_RETURN_TRACKING_NUMBER,
966 'meta_value' => $trackingNumber
967 ] );
968 $isAdvancedReturn = true;
969 }
970
971 } else {
972 $trackingFilter = array(
973 'post_type' => 'shop_order',
974 'post_status' => 'wc-%',
975 'nopaging' => 'true',
976 'fields' => 'ids',
977 'meta_key' => Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_NUMBER,
978 'meta_value' => $trackingNumber,
979 );
980 $query = new WP_Query( $trackingFilter );
981 $orderIds = $query->get_posts();
982 if ( empty( $orderIds ) ) {
983 $trackingFilter = array(
984 'post_type' => 'shop_order',
985 'post_status' => 'wc-%',
986 'nopaging' => 'true',
987 'fields' => 'ids',
988 'meta_key' => Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_RETURN_TRACKING_NUMBER,
989 'meta_value' => $trackingNumber,
990 );
991 $query = new WP_Query( $trackingFilter );
992 $orderIds = $query->get_posts();
993 $isAdvancedReturn = true;
994 }
995
996 $orders[] = wc_get_order( $orderIds[0] );
997
998 }
999 }
1000
1001 // there should be only one order for each master tracking number, so we get the first one
1002 $order = $orders[0] ?? null;
1003 if ( ! empty( $order ) ) {
1004 try {
1005
1006 if ( $isAdvancedReturn ) {
1007 $this->helper->setOrderMbeAdvancedReturnTrackingStatus( $order, serialize( $requestParameters[0] ) );
1008 }
1009
1010 // Update the the order status only for shop shipments and not for return shipments
1011 if ( ! $isAdvancedReturn && $this->helper->setOrderMbeTrackingStatus( $order, serialize( $requestParameters[0] ) ) !== false ) {
1012 $deliveredStatus = substr( MBE_WC_REST_API_ORDER_STATUS_DELIVERED, 3 );
1013
1014 // Update order status if the shipment has been delivered and the status wasn't yet updated
1015 if ( 1 == $mbeStatus && $order->get_status() !== $deliveredStatus ) {
1016 $order->set_status( $deliveredStatus );
1017 $order->save();
1018 $logger->log( 'Order delivered status updated successfully' );
1019 }
1020
1021 $message = 'Shipment status updated successfully.';
1022 $logger->log( $message );
1023
1024 $data = array(
1025 'message' => $message,
1026 'status' => 'success',
1027 'request-param' => $request->get_params()
1028 );
1029 }
1030
1031 return new WP_REST_Response( $data, 200 );
1032
1033 } catch ( Exception $e ) {
1034 $message = 'An error occured : ' . $e->getMessage();
1035 $logger->log( $message );
1036
1037 $data = array(
1038 'message' => $message,
1039 'status' => 'Error',
1040 'request-parameters' => $requestParameters
1041 );
1042
1043 return new WP_REST_Response( $data, 500 );
1044 }
1045 } else {
1046 $message = 'Order not found';
1047 $logger->log( $message );
1048
1049 $data = array(
1050 'message' => $message,
1051 'status' => 'Error',
1052 'request-parameters' => $requestParameters
1053 );
1054
1055 return new WP_REST_Response( $data, 404 );
1056 }
1057 }
1058
1059 $message = 'Empty payload';
1060 $logger->log( $message );
1061 $data = array(
1062 'message' => $message,
1063 'status' => 'Error',
1064 'request-parameters' => $requestParameters
1065 );
1066
1067 return new WP_REST_Response( $data, 400 );
1068 }
1069
1070 function mbe_gel_proximity_scripts() {
1071 $logger = new Mbe_Shipping_Helper_Logger();
1072
1073 if ( ! empty( $this->helper->getGelProximityMerchantCode() ) ) {
1074 wp_enqueue_script( MBE_ESHIP_ID . '-gel-proxmity-map-js', Mbe_Shipping_Helper_Data::GEL_PROXIMITY_URL . '/sdk/latest.js', '', rand() );
1075 wp_enqueue_script( MBE_ESHIP_ID . '-gel-proxmity-map-initialization', MBE_ESHIP_PLUGIN_URL . 'lib/js/gel-proximity-map-initilization.js', '', rand() );
1076 wp_add_inline_script( MBE_ESHIP_ID . '-gel-proxmity-map-initialization', 'const ' . 'mbe_gel_proxmity_data = ' . json_encode( array(
1077 'urlEndUser' => $this->helper->getGelProxymityUrlEndUser(),
1078 'merchantCode' => $this->helper->getGelProximityMerchantCode(),
1079 'apiKey' => $this->helper->getGelProxymityApiKey(),
1080 'locale' => get_user_locale(),
1081 'debug' => $this->helper->debug()
1082 ) ), 'before' );
1083 } else {
1084 $logger->log( 'GEL scripts not initialized, missing Merchant Code' );
1085 }
1086 }
1087
1088 function mbe_helper_scripts() {
1089 wp_enqueue_script( MBE_ESHIP_ID . '-helper-scripts-js', MBE_ESHIP_PLUGIN_URL . 'lib/js/mbe-helper-scripts.js', '', rand() );
1090 }
1091
1092 function load_custom_settings_tab( $settings ) {
1093 // if( ! class_exists(Mbe_Settings::class)) {
1094 // $settings[] = include __DIR__ . '/includes/class-mbe-settings-page.php';
1095 // } else {
1096 // $settings = Mbe_Settings();
1097 // }
1098
1099 $mbeSettings = include __DIR__ . '/includes/class-mbe-settings-page.php';
1100 $settings[] = $mbeSettings;
1101
1102 do_action( 'mbe_eship_custom_settings_loaded', $mbeSettings );
1103
1104 return $settings;
1105
1106 }
1107
1108 function mbe_eship_create_options_default( $mbeSettingsPage ) {
1109 // Check if it's needed and not already running
1110 if ( ! ( get_option( MBE_SCHEMA_FLAG_OPTION ) === 'no' ) && ! get_transient( MBE_ESHIP_ID . '_set_options_default' ) ) {
1111 $logger = new Mbe_Shipping_Helper_Logger();
1112 $logger->log( 'Saving settings default value - Starting', true );
1113 // set transient to flag it's running.
1114 set_transient( MBE_ESHIP_ID . '_set_options_default', 'yes', MINUTE_IN_SECONDS * 5 );
1115
1116 // Include settings so that we can run through defaults.
1117 if ( ! class_exists( WC_Settings_Page::class ) ) {
1118 require_once( WP_PLUGIN_DIR . '/woocommerce/includes/admin/settings/class-wc-settings-page.php' );
1119 }
1120
1121 // $mbeSettingsPage = include_once __DIR__ . '/includes/class-mbe-settings-page.php';
1122 $sections = $mbeSettingsPage->get_sections();
1123 // Remove the Welcome page from the list
1124 unset( $sections[''] );
1125
1126 $subsections = array_unique( array_keys( $sections ) );
1127
1128 foreach ( $subsections as $subsection ) {
1129 foreach ( $mbeSettingsPage->get_settings_for_section( $subsection ) as $value ) {
1130 if ( isset( $value['default'] ) && isset( $value['id'] ) ) {
1131 add_option( $value['id'], $value['default'] );
1132 }
1133 }
1134 }
1135
1136 update_option( MBE_SCHEMA_FLAG_OPTION, 'no' );
1137 delete_transient( MBE_ESHIP_ID . '_set_options_default' );
1138 $logger->log( 'Saving settings default value - Done', true );
1139 }
1140 }
1141
1142 function mbe_eship_check_pickup_default_options() {
1143 $helper = new Mbe_Shipping_Helper_Data();
1144 $logger = new Mbe_Shipping_Helper_Logger();
1145 // Check if Activation flag exists and if not run the default value setter
1146 if ( ! $helper->hasOption( Mbe_Shipping_Helper_Data::XML_PATH_PICKUP_REQUEST_ENABLED ) && $helper->isEnabledThirdPartyPickups() ) {
1147 update_option( MBE_SCHEMA_FLAG_OPTION, 'yes' );
1148 $logger->log( 'Updating schema flag to run default value setter for Pickup request' );
1149 }
1150 }
1151
1152 function mbe_eship_check_pickup_request_mode() {
1153 $logger = new Mbe_Shipping_Helper_Logger();
1154
1155 // Disable pickup if Shipping mode is not coherent
1156 // $disablePickup = !$this->helper->isEnabledThirdPartyPickups() || (
1157 // $this->helper->getShipmentsCreationMode() === Mbe_Shipping_Helper_Data::MBE_CREATION_MODE_AUTOMATICALLY
1158 // && $this->helper->getPickupRequestMode() === Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_MANUAL
1159 // );
1160
1161 // Disable pickup if the user doesn't have the rights set in MOL
1162 $disablePickup = ! $this->helper->isEnabledThirdPartyPickups();
1163
1164 if ( $disablePickup && $this->helper->getPickupRequestEnabled() ) {
1165 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_PICKUP_REQUEST_ENABLED, 0 );
1166 // WC_Admin_Settings::add_error(
1167 // __( 'Pickup request cannot be enabled, please check the settings', 'mail-boxes-etc' )
1168 // . ':' . __( 'Shipments creation in MBE Online - Mode', 'mail-boxes-etc' )
1169 // . ' or '
1170 // . __( 'Pickup Request - Mode', 'mail-boxes-etc' )
1171 // . ' ' . __( 'or the MBE Online options for third party pickup', 'mail-boxes-etc' )
1172 // );
1173 // $logger->log( 'Pickup mode and Shipping mode are not set correctly, disabling pickup' );
1174 WC_Admin_Settings::add_error(
1175 __( 'Pickup request cannot be enabled, please check the settings', 'mail-boxes-etc' )
1176 . ' ' . __( 'for third party pickup in MBE Online', 'mail-boxes-etc' )
1177 );
1178 $logger->log( 'Pickup is disabled in MOL, disabling pickup' );
1179 }
1180
1181 // Disable pickup if the pickup mode is auto and a default address is not set
1182 if ( $this->helper->getPickupRequestEnabled()
1183 && ! $this->helper->hasDefaultPickupAddress()
1184 && $this->helper->getPickupRequestMode() === Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_AUTOMATIC
1185 ) {
1186 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_PICKUP_REQUEST_ENABLED, 0 );
1187 WC_Admin_Settings::add_error( __( 'Pickup request cannot be enabled, please set a default pickup address', 'mail-boxes-etc' ) );
1188 $logger->log( 'Default pickup address missing, disabling pickup' );
1189 }
1190
1191 // If Pickup is still enabled and shipping mode is automatic but pickup mode is still manual, set pickup mode to automatic too
1192 if ( $this->helper->getPickupRequestEnabled()
1193 && $this->helper->getShipmentsCreationMode() === Mbe_Shipping_Helper_Data::MBE_CREATION_MODE_AUTOMATICALLY
1194 && $this->helper->getPickupRequestMode() === Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_MANUAL
1195 ) {
1196 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_PICKUP_REQUEST_MODE, Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_AUTOMATIC );
1197 }
1198 }
1199
1200 function mbe_check_insurance_mode_selected() {
1201 $helper = new Mbe_Shipping_Helper_Data();
1202 $requestSelectedServices = wc_clean( $_REQUEST[ MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_ALLOWED_SHIPMENT_SERVICES ] ?? [] );
1203 $lastInsuranceServicesSelected = '';
1204
1205 foreach ( $requestSelectedServices as $request_selected_service ) {
1206 $insuranceService = $helper->isShippingWithInsurance( $request_selected_service );
1207 if ( ! empty( $insuranceService ) && ( $insuranceService !== $lastInsuranceServicesSelected && ! empty( $lastInsuranceServicesSelected ) ) ) {
1208 $helper->logErrorAndSetWCAdminMessage( __( 'Only one between MBE SafaValue, MBE SafeValue4Business and Courier Insurance can be activated at the same time' ) );
1209 $helper->setPostOption( MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_ALLOWED_SHIPMENT_SERVICES, $helper->getAllowedShipmentServicesArray() );
1210
1211 return false;
1212 } else {
1213 $lastInsuranceServicesSelected = $insuranceService ?: $lastInsuranceServicesSelected;
1214 }
1215 }
1216 }
1217
1218 function mbe_error_notice() {
1219 require_once( ABSPATH . 'wp-admin/includes/screen.php' );
1220 if ( is_admin() ) {
1221 if ( ! isset( get_current_screen()->id ) || get_current_screen()->id !== 'woocommerce_page_wc-settings' ) {
1222 return;
1223 } //only show on 'order' pages
1224 echo '<div class="notice notice-error"><p>Warning - If you modify template files this could cause problems with your website.</p></div>';
1225 }
1226 }
1227
1228 /**
1229 * Plugin cron job
1230 */
1231 function automatic_closure() {
1232 $logger = new Mbe_Shipping_Helper_Logger();
1233 $logger->log( 'Cron automatic_closure' );
1234 include_once 'includes/cron.php';
1235 }
1236
1237 function remove_cron_job() {
1238 wp_clear_scheduled_hook( 'closure_event' );
1239 }
1240
1241 public function add_cron_job() {
1242 $logger = new Mbe_Shipping_Helper_Logger();
1243 $time = $this->helper->getShipmentsClosureTime();
1244 if ( $this->helper->isEnabled() && $this->helper->isClosureAutomatically() ) {
1245 $closureTime = strtotime( "today $time " . wp_timezone_string() );
1246 $cron_jobs = get_option( 'cron' );
1247 $array = array_column( $cron_jobs, 'closure_event' );
1248 if ( ! empty( $array ) ) {
1249 $index = array_search( array( 'closure_event' => $array[0] ), $cron_jobs );
1250 $scheduledTime = date( 'H:i:s', $index );
1251 if ( $scheduledTime != $time ) {
1252 wp_clear_scheduled_hook( 'closure_event' );
1253 wp_schedule_event( $closureTime, 'daily', 'closure_event' );
1254 $logger->log( "Cron automatic closure set at: $time " . wp_timezone_string() );
1255 }
1256 } else {
1257 wp_schedule_event( $closureTime, 'daily', 'closure_event' );
1258 $logger->log( "Cron automatic closure set at: $time " . wp_timezone_string() );
1259 }
1260 } else {
1261 wp_clear_scheduled_hook( 'closure_event' );
1262 }
1263 }
1264
1265 /**
1266 * Add settings link in the plugin list
1267 */
1268
1269 public function plugin_action_links( $links ) {
1270 $plugin_links = array(
1271 '<a href="' . admin_url( 'admin.php?page=' . mbe_e_link_get_settings_url() . '&tab=' . MBE_ESHIP_ID ) . '">' . __( 'Settings', 'mail-boxes-etc' ) . '</a>',
1272 );
1273
1274 return array_merge( $plugin_links, $links );
1275 }
1276
1277 /**
1278 * Add shipping method to WooCommerce
1279 */
1280
1281 public function wf_mbe_wooCommerce_shipping_methods( $methods ) {
1282 $methods[] = 'mbe_shipping_method';
1283
1284 return $methods;
1285 }
1286
1287 public function wf_mbe_wooCommerce_shipping_init() {
1288 include_once( 'includes/class-mbe-shipping.php' );
1289 }
1290
1291 /**
1292 * Add box in the order detail
1293 */
1294
1295 public function wf_mbe_wooCommerce_shipping_init_box() {
1296 include_once( 'includes/class-mbe-tracking-admin.php' );
1297 }
1298
1299 /**
1300 * Add menu tab in WooCommerce
1301 */
1302
1303 function add_mbe_tab() {
1304 add_submenu_page( 'woocommerce', __( 'MBE Shipments List', 'mail-boxes-etc' ), __( 'MBE Shipments List', 'mail-boxes-etc' ), 'manage_woocommerce', WOOCOMMERCE_MBE_TABS_PAGE, array(
1305 $this,
1306 'add_order_list'
1307 ) );
1308
1309 add_submenu_page( null, __( 'MBE CSV Editor', 'mail-boxes-etc' ), __( 'MBE CSV Editor', 'mail-boxes-etc' ), 'manage_woocommerce', 'woocommerce_mbe_csv_tabs', array(
1310 $this,
1311 'add_csv_list'
1312 ) );
1313
1314 add_submenu_page( null, __( 'Add new', 'mail-boxes-etc' ), __( 'Add new', 'mail-boxes-etc' ), 'activate_plugins', MBE_ESHIP_ID . '_csv_edit_form', array(
1315 $this,
1316 'csv_form_page_handler'
1317 ) );
1318
1319 // PICKUP Pages
1320 if ( $this->helper->isEnabledThirdPartyPickups() ) {
1321 add_submenu_page( null, __( 'MBE Pickup Batches List', 'mail-boxes-etc' ), __( 'Pickup', 'mail-boxes-etc' ), 'manage_woocommerce', MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE, array(
1322 $this,
1323 'add_pickup_batches_list'
1324 ) );
1325
1326
1327 add_submenu_page( null, __( 'MBE Pickup Data Editor', 'mail-boxes-etc' ), __( 'MBE Pickup Data Editor', 'mail-boxes-etc' ), 'manage_woocommerce', MBE_ESHIP_ID . '_pickup_data_tabs', array(
1328 $this,
1329 'pickup_data_form_page_handler'
1330 ) );
1331 }
1332
1333 //DEPARTMENT Address Selection Page
1334 if ( ! $this->helper->isCreationAutomatically() ) {
1335 add_submenu_page( null, __( 'MBE Department Data Selection', 'mail-boxes-etc' ), __( 'MBE Department Data Selection', 'mail-boxes-etc' ), 'manage_woocommerce', MBE_ESHIP_ID . '_department_address_data_tabs', array(
1336 $this,
1337 'department_address_data_form_page_handler'
1338 ) );
1339 }
1340
1341 // ADVANCED RETURN Address Data Page
1342 if ( $this->helper->canAdvancedReturn() ) {
1343 add_submenu_page( null, __( 'MBE Advanced Return Address Data', 'mail-boxes-etc' ), __( 'MBE Advanced Return Address Data', 'mail-boxes-etc' ), 'manage_woocommerce', MBE_ESHIP_ID . '_advanced_return_address_data_tabs', array(
1344 $this,
1345 'advanced_return_address_data_form_page_handler'
1346 ) );
1347 }
1348 }
1349
1350 /**
1351 * Add order list in MBE tab
1352 */
1353
1354 function add_order_list() {
1355 require_once 'includes/class-mbe-order.php';
1356 $orders = new Mbe_E_Link_Order_List_Table();
1357 $orders->prepare_items();
1358 ?>
1359
1360 <nav class="nav-tab-wrapper woo-nav-tab-wrapper">
1361 <a href="#" class="nav-tab nav-tab-active">
1362 <h2><?php esc_html_e( 'MBE Shipments List', 'mail-boxes-etc' ) ?></h2>
1363 </a>
1364 <?php if ( $this->helper->isEnabledThirdPartyPickups() ) { ?>
1365 <a href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?page=' . MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE ) ) ?>"
1366 class="nav-tab ">
1367 <h2><?php esc_html_e( 'MBE Manual Pickup', 'mail-boxes-etc' ) ?></h2>
1368 </a>
1369 <?php } ?>
1370 </nav>
1371 <div class="wrap">
1372 <?php $this->mbe_eship_wp_notification() ?>
1373
1374 <form id="certificates-filter" method="get">
1375 <input type="hidden" name="page"
1376 value="<?php echo ( ! empty( $_REQUEST['page'] ) ) ? esc_attr( wp_unslash( $_REQUEST['page'] ) ) : ''; ?>"
1377 />
1378
1379 <?php
1380 $orders->display();
1381 ?>
1382 </form>
1383 </div>
1384
1385 <?php
1386 $downloadFile = sanitize_url( $_GET['reload-download'] ?? null );
1387 if ( ! empty( $downloadFile ) && isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], WOOCOMMERCE_MBE_TABS_PAGE ) ) {
1388 $actionUrl = sprintf( "%sadmin-post.php?action=mbe_download_multiple_waybill&downloadFile=%s&nonce=%s", get_admin_url(), urlencode( $downloadFile ), wp_create_nonce( 'mbe_download_multiple_waybill' ) );
1389 echo "<script>jQuery(document).ready(mbeButtonAction(this, " . json_encode( $actionUrl ) . ",'_blank', 'false'))</script>";
1390 }
1391 }
1392
1393 function mbe_download_multiple_waybill() {
1394 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_multiple_waybill' ) ) {
1395 // Unset the session variable
1396 $downloadFile = sanitize_url( $_REQUEST['downloadFile'] );
1397 $this->helper->mbe_download_file( $downloadFile, "mbe-labels.pdf", 'application/pdf', true );
1398 }
1399 }
1400
1401 function add_pickup_batches_list() {
1402 require_once 'includes/class-mbe-pickup-batches.php';
1403 $ordersPickupBatches = new Mbe_E_Link_Pickup_Batches_List_Table();
1404 $ordersPickupBatches->prepare_items();
1405 ?>
1406
1407 <nav class="nav-tab-wrapper woo-nav-tab-wrapper">
1408 <a href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?page=' . WOOCOMMERCE_MBE_TABS_PAGE ) ) ?>"
1409 class="nav-tab ">
1410 <h2><?php esc_html_e( 'MBE Shipments List', 'mail-boxes-etc' ) ?></h2>
1411 </a>
1412 <?php if ( $this->helper->isEnabledThirdPartyPickups() ) { ?>
1413 <a href="#" class="nav-tab nav-tab-active">
1414 <h2><?php esc_html_e( 'MBE Manual Pickup', 'mail-boxes-etc' ) ?></h2>
1415 </a>
1416 <?php } ?>
1417 </nav>
1418 <div class="wrap">
1419 <?php $this->mbe_eship_wp_notification() ?>
1420
1421 <!-- <form id="certificates-filter" method="get">
1422 <input type="hidden" name="page"
1423 value="<?php /*echo ( ! empty( $_REQUEST['page'] ) ) ? esc_attr( wp_unslash( $_REQUEST['page'] ) ) : ''; */ ?>"
1424 />
1425 -->
1426 <?php $a = $ordersPickupBatches->display() ?>
1427 <!-- </form>-->
1428 </div>
1429
1430 <?php
1431 }
1432
1433 function add_csv_list() {
1434 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'woocommerce_mbe_csv_tabs' ) ) {
1435 $csvType = sanitize_text_field( $_REQUEST['csv'] ?? '' );
1436 $csvFactory = new Mbe_Csv_Editor_Model_Factory();
1437 $csv = $csvFactory->create( $csvType );
1438 $message = sanitize_text_field( $_REQUEST['message'] ?? '' );
1439 if ( ! empty( $csv ) ) {
1440 $title = $csv->get_title( false );
1441 $csv->prepare_items();
1442 if ( 'delete' === $csv->current_action() ) {
1443 $message = sprintf( __( 'Items deleted: %d', 'mail-boxes-etc' ), count( (array) wc_clean( $_REQUEST['id'] ) ) );
1444 }
1445 ?>
1446
1447 <div class="wrap">
1448 <h2><?php esc_html_e( 'MBE ' . $title . ' ' . __( 'Editor' ) ) ?>
1449 <a class="add-new-h2"
1450 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?page=' . mbe_e_link_get_settings_url() . '&tab=' . MBE_ESHIP_ID . '&section=' . $csv->get_backlink() ) ); ?>">
1451 <?php esc_html_e( 'Back to settings', 'mail-boxes-etc' ) ?>
1452 </a>
1453 </h2>
1454
1455 <?php $this->mbe_eship_wp_notification() ?>
1456 <?php if ( ! empty( $notice ) ): ?>
1457 <div id="notice" class="notice notice-error is-dismissible">
1458 <p><?php echo wp_kses_post( $notice ) ?></p></div>
1459 <?php endif; ?>
1460 <?php if ( ! empty( $message ) ): ?>
1461 <div id="message" class="notice notice-success is-dismissible">
1462 <p><?php echo wp_kses_post( $message ) ?></p></div>
1463 <?php endif; ?>
1464
1465 <form id="certificates-filter" method="get">
1466 <?php //Fields to be sent with request and bulk actions ?>
1467 <input type="hidden" name="page"
1468 value="<?php echo ( ! empty( $_REQUEST['page'] ) ) ? esc_attr( wp_unslash( $_REQUEST['page'] ) ) : ''; ?>"
1469 />
1470 <input type="hidden" name="csv"
1471 value="<?php esc_attr_e( $csvType ) ?>"
1472 />
1473 <?php $csv->display() ?>
1474 </form>
1475 </div>
1476 <?php
1477 } else {
1478 ?>
1479 <div class="wrap">
1480 <h2><?php esc_html_e( 'Missing or wrong csv type', 'mail-boxes-etc' ) ?>
1481 <a class="add-new-h2"
1482 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?page=' . mbe_e_link_get_settings_url() . '&tab=' . MBE_ESHIP_ID . '&section=mbe_general' ) ); ?>">
1483 <?php esc_html_e( 'Back to settings', 'mail-boxes-etc' ) ?>
1484 </a>
1485 </h2>
1486 </div>
1487 <?php
1488 }
1489 } else {
1490 wp_redirect( wp_get_referer() );
1491 }
1492 }
1493
1494 /**
1495 * Creation shipping manually action
1496 */
1497
1498 function add_order_meta_box_actions( $actions, $order ) {
1499 if ( is_array( $actions ) ) {
1500 // $this->>helper = new Mbe_Shipping_Helper_Data();
1501 if ( $order ) {
1502 if ( $this->helper->isMbeShipping( $order ) ) {
1503 if ( ! $this->helper->isCreationAutomatically() && ! $this->helper->hasTracking( $order->get_id() ) ) {
1504 $actions['mbe_shipping_creation'] = __( 'Create MBE shipping', 'mail-boxes-etc' );
1505 }
1506 }
1507 }
1508 }
1509
1510 return $actions;
1511 }
1512
1513 function process_order_meta_box_actions( $order ) {
1514 if ( $this->helper->isMbeShipping( $order ) ) {
1515 include_once 'includes/class-mbe-tracking-factory.php';
1516 $orderId = $this->helper->getOrderId( $order );
1517 mbe_tracking_factory::create( $orderId );
1518 }
1519 }
1520
1521
1522 public function mbe_update_tracking( $order_id ) {
1523 $order = wc_get_order( $order_id );
1524 if ( $this->helper->isEnabled() && $this->helper->isMbeShipping( $order ) && $this->helper->isCreationAutomatically() && empty( $this->helper->getTrackings( $order_id ) ) ) {
1525 // include_once 'includes/class-mbe-tracking-factory.php';
1526 // mbe_tracking_factory::create( $order_id );
1527 $pickupInfo = [];
1528 if ( $this->helper->getPickupRequestEnabled()
1529 && Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_AUTOMATIC === $this->helper->getPickupRequestMode()
1530 ) {
1531 $pickupInfo = [
1532 'is-pickup' => true,
1533 'is-batch' => false,
1534 'custom-data-id' => null,
1535 ];
1536 }
1537 $post_ids = array_map( 'absint', (array) $order_id );
1538 $this->processShipmentCreation( $post_ids, $pickupInfo );
1539 }
1540 }
1541
1542 /**
1543 * Set Free Label to Carriers
1544 */
1545
1546 public function wf_mbe_wooCommerce_set_free_label( $full_label, $method ) {
1547 if ( (float) $method->cost == 0.0 ) {
1548 return $full_label . ': ' . __( "Free", 'mail-boxes-etc' );
1549 } else {
1550 return $full_label;
1551 }
1552 }
1553
1554 public function wan_load_wf_shipping_mbe() {
1555 load_plugin_textdomain( 'mail-boxes-etc', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
1556 }
1557
1558 /*
1559 * Add front tracking
1560 */
1561
1562 public function woocommerce_order_details_tracking( $order ) {
1563 // $this->>helper = new Mbe_Shipping_Helper_Data();
1564 $orderId = $this->helper->getOrderId( $order );
1565 $trackings = $this->helper->getTrackings( $orderId );
1566 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
1567 $tracking_url = $order === false? '' : $order->get_meta( Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_URL );
1568 $trackingName = $order === false? '' : $order->get_meta( 'woocommerce_mbe_tracking_name' );
1569 } else {
1570 $tracking_url = get_post_meta( $orderId, Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_URL, true );
1571 $trackingName = get_post_meta( $orderId, 'woocommerce_mbe_tracking_name', true );
1572 }
1573
1574 if ( $this->helper->isMbeShipping( $order ) && ! empty( $trackings ) ) {
1575 echo "<h2>" . esc_html__( 'Mail Boxes ETC Tracking', 'mail-boxes-etc' ) . "</h2>";
1576 echo '
1577 <table class="shop_table tracking_details">
1578 <thead>
1579 <tr>
1580 <th class="service-name">' . esc_html__( 'Service', 'mail-boxes-etc' ) . '</th>
1581 <th class="tracking-link">' . esc_html__( 'Tracking', 'mail-boxes-etc' ) . '</th>
1582 </tr>
1583 </thead>
1584 <tbody>';
1585 foreach ( $trackings as $track ) {
1586 echo '<tr class="order_item">
1587 <td class="tracking-name">' . esc_html( $trackingName ) . '</td>
1588 <td class="product-total"><a target="_blank" href="' . esc_attr( $tracking_url . $track ) . '">' . esc_html( $track ) . '</a></td>
1589 </tr>';
1590 }
1591 echo '</tbody></table>';
1592 }
1593 }
1594
1595 /**
1596 * Adds GEL delivery point map to the WooCommerce shipping method
1597 *
1598 * @param object $method The WooCommerce shipping method object
1599 */
1600 public function wf_mbe_wooCommerce_shipping_gel_delivery_point_map( $method ) {
1601 $mbeServiceSelected = (
1602 $this->isDeliveryPointServiceMethod( WC()->session->get( 'chosen_shipping_methods' ) )
1603 && $method->id === WC()->session->get( 'chosen_shipping_methods' )[0]
1604 );
1605
1606 if ( $mbeServiceSelected && is_checkout() ) {
1607 // Generate the delivery point GEL services list (NET_xxx codes) for GEL map initialization
1608 // $gelServices = '';
1609 // foreach ( $method->meta_data['delivery_point_services']['courier'] as $gel_service ) {
1610 // $gelServices .= "'" . $gel_service ."'" . ',';
1611 // }
1612
1613 // Generate the prices parameter for GEL map initialization
1614 $prenegotiatedFound = false;
1615 $labelingFound = false;
1616 $deliveryPointPrices = [ 'currencyCode' => get_woocommerce_currency() ];
1617 foreach ( array_combine( $method->get_meta_data()['delivery_point_services']['mol'], $method->get_meta_data()['delivery_point_services']['prices'] ) as $key => $value ) {
1618 if ( ! $prenegotiatedFound && in_array( $key, MBE_ESTIMATE_DELIVERY_POINT_PRENEGOTIATED_SERVICES ) ) {
1619 $deliveryPointPrices ['prenegotiated'] = (float) $value;
1620 $prenegotiatedFound = true;
1621 if ( $labelingFound ) {
1622 break;
1623 }
1624 }
1625
1626 if ( ! $labelingFound && in_array( $key, MBE_ESTIMATE_DELIVERY_POINT_LABELING_SERVICES ) ) {
1627 $deliveryPointPrices ['labeling'] = (float) $value;
1628 $labelingFound = true;
1629 if ( $prenegotiatedFound ) {
1630 break;
1631 }
1632 }
1633 }
1634
1635 if ( wc_tax_enabled() && WC()->cart->display_prices_including_tax() ) {
1636 $taxPercentage = $this->getShippingTaxPercentageFromCart();
1637
1638 if ( $taxPercentage > 0 ) {
1639 foreach (
1640 array_intersect_key( $deliveryPointPrices, [
1641 'prenegotiated' => '',
1642 'labeling' => ''
1643 ] ) as $key => $price
1644 ) {
1645 $deliveryPointPrices[ $key ] += $this->helper->round( $price * $taxPercentage / 100 );
1646 }
1647 }
1648 }
1649
1650 // Add the form field to the section and set value in case of delivery point selection price refresh
1651 echo '<div style="margin-bottom: 0.5em; padding-left: 20px;">';
1652 $sessionDeliveryPoint = WC()->session->get( 'mbe_delivery_point' ) ?? null;
1653 $gelProximitySelectionLabel = null;
1654 $gelProximitySelection = null;
1655
1656 if ( ! empty( $sessionDeliveryPoint ) ) {
1657 $gelProximitySelection = json_encode( (array) $sessionDeliveryPoint );
1658 $gelProximitySelectionLabel = $sessionDeliveryPoint->networkName . ', ' . $sessionDeliveryPoint->address . ', ' . $sessionDeliveryPoint->zipCode . ', ' . $sessionDeliveryPoint->city;
1659 }
1660
1661 woocommerce_form_field( 'gel-proximity-selection-label', array(
1662 'id' => 'gel-proximity-selection-label',
1663 'class' => 'woocommerce-validated',
1664 'type' => 'text',
1665 'required' => true,
1666 'custom_attributes' => array(
1667 'style' => 'font-size: 0.8em;',
1668 'readonly' => 'readonly',
1669 'onclick' => 'openGELProximityModal()'
1670 ),
1671 'placeholder' => __( 'Click to select a delivery point', 'mail-boxes-etc' ),
1672 ), $gelProximitySelectionLabel
1673 );
1674
1675 woocommerce_form_field( 'gel-proximity-selection', array(
1676 'type' => 'hidden',
1677 'id' => 'gel-proximity-selection',
1678 ), $gelProximitySelection
1679 );
1680
1681 woocommerce_form_field( 'gel-proximity-selection-update', array(
1682 'type' => 'hidden',
1683 'id' => 'gel-proximity-selection-update',
1684 ), false // alway set the field to false, tha value must be true only when posting from gel-proximity-map-initilization.js
1685 );
1686
1687 echo '<script type="text/javascript">
1688 mbeGelSDK.options.networks = ' . json_encode( $method->get_meta_data()['delivery_point_services']['courier'] ) . '
1689 mbeGelSDK.options.prices = ' . json_encode( $deliveryPointPrices ) . '
1690 </script>';
1691
1692 echo '</div>';
1693 }
1694
1695 }
1696
1697 function wf_mbe_delivery_point_validation( $data, $errors ) {
1698 if ( isset( $_POST['gel-proximity-selection'] ) && empty( $data['mbe_delivery_point_data'] ) ) {
1699 $errors->add( 'validation', __( 'Select a delivery point to proceed', 'mail-boxes-etc' ) );
1700 }
1701 }
1702
1703 function wf_mbe_delivery_point_show_meta_field( $order ) {
1704 $order_meta_delvery_point = $this->helper->getOrderDeliveryPointShipment( $order->get_id() );
1705 if ( ! empty( $order_meta_delvery_point ) ) {
1706 echo '<p><strong>' . esc_html__( 'Delivery Point' ) . ':</strong> ' . esc_html__( $order_meta_delvery_point, 'mail-boxes-etc' ) . '</p>';
1707 }
1708 }
1709
1710 function wf_mbe_delivery_point_set_meta_field( $order_id, $data ) {
1711 $logger = new Mbe_Shipping_Helper_Logger();
1712 $order = wc_get_order( $order_id );
1713 if ( $this->helper->isMbeShipping( $order ) ) {
1714 if ( ! empty( $data['mbe_delivery_point_data'] ) ) {
1715 $this->helper->setOrderDeliveryPointShipment( $order_id, 'Yes' );
1716 $this->helper->setOrderDeliveryPointCustomData( $order_id, $data['mbe_delivery_point_data'] );
1717 } else {
1718 $logger->log( __( 'Missing Access Point ID in $_POST' ) );
1719 $this->helper->setOrderDeliveryPointShipment( $order_id, 'No' );
1720 }
1721 $order->save();
1722 }
1723 }
1724
1725 function wf_mbe_delivery_point_update_package_for_cost_recalculation( $packages ) {
1726
1727 $deliveryPoint = WC()->session->get( 'mbe_delivery_point' ) ?? null;
1728 if ( ! empty( $deliveryPoint ) ) {
1729 if ( wc_tax_enabled() && WC()->cart->display_prices_including_tax() && ! empty( WC()->cart->get_shipping_taxes() ) && ( WC()->session->get( 'mbe_delivery_point_update' ) ?? false ) ) {
1730 $logger = new Mbe_Shipping_Helper_Logger();
1731 $logger->logVar( $deliveryPoint, 'Delivery Point recalculation - removing taxes from map cost' );
1732 $deliveryPoint->cost = $this->helper->round( $this->helper->calculateNetPriceFromGross( $deliveryPoint->cost, $this->getShippingTaxPercentageFromCart() ) );
1733 $logger->logVar( $deliveryPoint, 'Delivery Point recalculation - taxes removed from map cost' );
1734 WC()->session->set( 'mbe_delivery_point', $deliveryPoint );
1735 WC()->session->set( 'mbe_delivery_point_update', null );
1736 WC()->session->set( 'mbe_delivery_point_markup', $this->helper->getHandlingFee() );
1737 }
1738
1739 // Always check if markup/handling fee has been changed (valid only in the same session) and update the delivery point cost and the session option
1740 if ( $this->helper->getHandlingFee() !== WC()->session->get( 'mbe_delivery_point_markup' ) ) {
1741 $deliveryPoint->cost = $deliveryPoint->cost - WC()->session->get( 'mbe_delivery_point_markup' ) + $this->helper->getHandlingFee();
1742 WC()->session->set( 'mbe_delivery_point', $deliveryPoint );
1743 WC()->session->set( 'mbe_delivery_point_markup', $this->helper->getHandlingFee() );
1744 }
1745 foreach ( $packages as $packageKey => $packageValue ) {
1746 $packages[ $packageKey ]['delivery_point'] = $deliveryPoint;
1747 }
1748 }
1749
1750 return $packages;
1751 }
1752
1753 function wf_mbe_delivery_point_set_meta_field_review( $data ) {
1754 $logger = new Mbe_Shipping_Helper_Logger();
1755 WC()->session->set( 'mbe_delivery_point', null );
1756 $postData = array();
1757 parse_str( $data, $postData );
1758 $deliveryPoint = json_decode( $postData['gel-proximity-selection'] ?? '' );
1759 $deliveryPointUpdate = json_decode( $postData['gel-proximity-selection-update'] ?? false );
1760
1761 if ( ! empty( $deliveryPoint ) && $this->isDeliveryPointServiceMethod( $postData['shipping_method'] ) ) {
1762 $logger->logVar( $deliveryPoint, 'Delivery point selection, refresh rates' );
1763 WC()->session->set( 'mbe_delivery_point', $deliveryPoint );
1764 WC()->session->set( 'mbe_delivery_point_update', $deliveryPointUpdate );
1765 }
1766
1767 // Check if the session variable is empty due to a json_decode() error and log an error
1768 if ( ! empty( $postData['gel-proximity-selection'] ) && empty( $deliveryPoint ) ) {
1769 $message = __( 'Possible issue with delivery point content/escaping. This delivery point cannot be correctly selected' );
1770 $logger->logVar( $postData['gel-proximity-selection'], $message );
1771 WC()->session->set( 'mbe_delivery_point', null ); // remove the delivery point to be sure it's not retaining an old value
1772 wc_add_notice( $message, 'error' );
1773 }
1774 }
1775
1776 function wf_mbe_delivery_point_set_shipping_address( $data ) {
1777 $logger = new Mbe_Shipping_Helper_Logger();
1778 // convert $data['shipping_method'] to array to avoid issues with empty (virtual products) or string values
1779 $shippingMethod = is_array( $data['shipping_method'] ) ? $data['shipping_method'] : [ $data['shipping_method'] ];
1780 $serviceOK = $this->isDeliveryPointServiceMethod( $shippingMethod );
1781 $logger->logVar( $shippingMethod, 'wf_mbe_wooCommerce_shipping_uap_address - Shipping Method' );
1782 if ( ! empty( $_POST['gel-proximity-selection'] ) && $serviceOK ) {
1783 $deliveryPointAddress = json_decode( stripslashes( $_POST['gel-proximity-selection'] ) );
1784 $logger->logVar( $deliveryPointAddress->code, 'wf_mbe_gel_delivery_point_set_shipping_address - GEL PUDO' );
1785 // Set the Delivery Point address as shipping address
1786 // $_POST['mbe_delivery_point_data'] = sanitize_text_field( $deliveryPointAddress->pickupPointId );
1787 $mbeDeliveryPointData = wp_json_encode( $deliveryPointAddress );
1788 $data['mbe_delivery_point_data'] = $mbeDeliveryPointData !== false ? $mbeDeliveryPointData : ''; // encode to json again to run some sanitization
1789 $data['shipping_company'] = sanitize_text_field( $deliveryPointAddress->description );
1790 $data['shipping_address_1'] = sanitize_text_field( $deliveryPointAddress->address );
1791 $data['shipping_postcode'] = sanitize_text_field( $deliveryPointAddress->zipCode );
1792 $data['shipping_city'] = sanitize_text_field( $deliveryPointAddress->city );
1793 $data['shipping_country'] = sanitize_text_field( $deliveryPointAddress->country );
1794 $data['shipping_state'] = array_search( ucfirst( strtolower( sanitize_text_field( $deliveryPointAddress->city ) ) ), WC()->countries->get_states( sanitize_text_field( $deliveryPointAddress->country ) ) );
1795 }
1796
1797 return $data;
1798 }
1799
1800 /**
1801 * Remove the delivery point session variable
1802 *
1803 * This method removes the custom WC_Session variable 'mbe_delivery_point' that is used to store
1804 * the selected delivery point during checkout process.
1805 *
1806 * @return void
1807 */
1808 function wf_mbe_remove_delivery_point_session_variable() {
1809 // Remove the custom WC_Session variable
1810 WC()->session->set( 'mbe_delivery_point', null );
1811 }
1812
1813 function wf_mbe_wooCommerce_shipping_custom_mapping_meta_field( $order_id ) {
1814 if ( $this->helper->isMbeShippingCustomMapping( $this->helper->getShippingMethod( wc_get_order( $order_id ) ) ) ) {
1815 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
1816 $order = wc_get_order( $order_id );
1817 $order->update_meta_data( Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_CUSTOM_MAPPING, 'yes' );
1818 $order->save();
1819 } else {
1820 update_post_meta( $order_id, Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_CUSTOM_MAPPING, 'yes' );
1821 }
1822 }
1823 }
1824
1825 function wf_mbe_wooCommerce_shipping_custom_mapping_meta_field_checkout_block( WC_Order $order ) {
1826 if ( $this->helper->isMbeShippingCustomMapping( $this->helper->getShippingMethod( $order ) ) ) {
1827 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
1828 $order->update_meta_data( Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_CUSTOM_MAPPING, 'yes' );
1829 $order->save();
1830 } else {
1831 update_post_meta( $order->get_id(), Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_CUSTOM_MAPPING, 'yes' );
1832 }
1833 }
1834 }
1835
1836
1837 function mbe_woocommerce_email_track_id( $order, $sent_to_admin, $plain_text, $email ) {
1838 $mailArray = [ 'customer_invoice', 'customer_completed_order' ];
1839 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
1840 $trackingUrl = $order === false? '' : $order->get_meta( Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_URL );
1841 } else {
1842 $trackingUrl = get_post_meta( $order->get_id(), Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_URL, true );
1843 }
1844
1845 $trackId = $this->helper->getTrackingsString( $order->get_id() );
1846 if ( ! empty( $trackId ) && in_array( $email->id, $mailArray ) && $this->helper->getTrackingSetting() ) {
1847 echo '<table id="track_id" style="width: 100%; vertical-align: top; margin-bottom: 40px; padding: 0px; border:0px; border-spacing: 0; border-collapse: collapse;">
1848 <tbody>
1849 <tr>
1850 <td style="vertical-align: top; width: 40%; text-align: left; font-family: \'Helvetica Neue\', Helvetica, Roboto, Arial, sans-serif; border: 0; padding: 0;">
1851 <h2 style="color: #96588a; display: block; font-family: &quot;Helvetica Neue&quot;, Helvetica, Roboto, Arial, sans-serif; font-size: 18px; font-weight: bold; line-height: 130%; margin: 0 0 18px; text-align: left;"> ' . esc_html__( woocommerce_mbe_tracking_admin::TRACKING_TITLE_DISPLAY, 'mail-boxes-etc' ) . ' </h2>
1852 </td>
1853 </tr>
1854 <tr>
1855 <td style="vertical-align: top; width: 40%; text-align: left; font-family: \'Helvetica Neue\', Helvetica, Roboto, Arial, sans-serif; border: 0; padding: 0;">
1856 <strong>' . esc_html__( 'Tracking id: ', 'mail-boxes-etc' ) . '</strong>
1857 </td>
1858 <td style="vertical-align: top; width: 40%; text-align: left; font-family: \'Helvetica Neue\', Helvetica, Roboto, Arial, sans-serif; border: 0; padding: 0;">
1859 <a href="' . esc_url_raw( $trackingUrl . $trackId ) . '">
1860 ' . esc_html( $trackId ) . '
1861 </a>
1862 </td>
1863 </tr>
1864 </tbody>
1865 </table>';
1866 }
1867 }
1868
1869 function mbe_add_query_vars( $vars ) {
1870 $vars[] = "mbe_filetype";
1871
1872 return $vars;
1873 }
1874
1875 public function mbe_download_standard_package_file() {
1876 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_standard_package_file' ) ) {
1877 $fileType = sanitize_text_field( $_GET['mbe_filetype'] );
1878
1879 switch ( $fileType ) {
1880 case 'package':
1881 $this->helper->mbe_download_file( $this->helper->getCurrentCsvPackagesDir() );
1882 break;
1883 case 'package-template':
1884 $this->helper->mbe_download_file( $this->helper->getCsvTemplatePackagesDir() );
1885 break;
1886 case 'package-product':
1887 $this->helper->mbe_download_file( $this->helper->getCurrentCsvPackagesProductDir() );
1888 break;
1889 case 'package-product-template':
1890 $this->helper->mbe_download_file( $this->helper->getCsvTemplatePackagesProductDir() );
1891 break;
1892 default:
1893 break;
1894 }
1895 }
1896 }
1897
1898 public function mbe_download_shipping_file() {
1899 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_shipping_file' ) ) {
1900 $fileType = sanitize_text_field( $_GET['mbe_filetype'] );
1901
1902 switch ( $fileType ) {
1903 case 'shipping':
1904 $this->helper->mbe_download_file( $this->helper->getShipmentsCsvFileDir() );
1905 break;
1906 case 'shipping-template':
1907 $this->helper->mbe_download_file( $this->helper->getShipmentsCsvTemplateFileDir() );
1908 break;
1909 default:
1910 break;
1911 }
1912 }
1913 }
1914
1915 public function mbe_download_log_files() {
1916 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_log_files' ) ) {
1917 $zipfilepath = trailingslashit( $this->helper->getMbeLogDir() ) . 'log.zip';
1918 $wslogfilepath = $this->helper->getLogWsPath();
1919 $pluginfilepath = $this->helper->getLogPluginPath();
1920 $logZip = new \ZipArchive();
1921 if ( $logZip->open( $zipfilepath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE ) === true ) {
1922 $logZip->addFile( $wslogfilepath, substr( $wslogfilepath, strrpos( $wslogfilepath, '/' ) + 1 ) );
1923 $logZip->addFile( $pluginfilepath, substr( $pluginfilepath, strrpos( $pluginfilepath, '/' ) + 1 ) );
1924 if ( $logZip->count() > 0 && $logZip->close() ) {
1925 $this->helper->mbe_download_file( $zipfilepath, 'mbe_log.zip', 'application/zip', true );
1926 }
1927 }
1928 $logZip = null;
1929 error_log( __( 'MBE Download log - files not found' ) );
1930 }
1931 exit;
1932 }
1933
1934
1935 public function mbe_delete_log_files() {
1936 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_delete_log_files' ) ) {
1937 try {
1938 $wslogfilepath = $this->helper->getLogWsPath();
1939 $pluginfilepath = $this->helper->getLogPluginPath();
1940 if ( file_exists( $wslogfilepath ) ) {
1941 wp_delete_file( $wslogfilepath );
1942 }
1943 if ( file_exists( $pluginfilepath ) ) {
1944 wp_delete_file( $pluginfilepath );
1945 }
1946 } catch ( \Exception $e ) {
1947 error_log( __( 'MBE Delete log - Unexpected error' ) . ' - ' . $e->getMessage() );
1948 }
1949 }
1950 wp_redirect( wp_get_referer() );
1951 }
1952
1953
1954 public function mbe_goto_advanced_login() {
1955 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_goto_advanced_login' ) ) {
1956 $this->helper->setLoginMode( false );
1957 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_LOGIN_LINK_ADV, true );
1958 }
1959 wp_redirect( wp_get_referer() );
1960 }
1961
1962 public function mbe_sign_in() {
1963 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_sign_in' ) ) {
1964 $mbeUser = $_GET[ MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_MBE_USERNAME ];
1965 $mbePwd = $_GET[ MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_MBE_PASSWORD ];
1966 $mbeCountry = $_GET[ MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_COUNTRY ];
1967 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_LOGIN_LINK_ADV, false );
1968
1969 if ( ! empty( $mbePwd ) && ! empty( $mbeUser ) ) {
1970 // Set the option in case it wasn't saved before
1971 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_MBE_USERNAME, $mbeUser );
1972 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_MBE_PASSWORD, $mbePwd );
1973 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_COUNTRY, $mbeCountry );
1974 $this->helper->setWsUrl( $mbeCountry );
1975
1976 if ( $this->mbe_generate_api_key() ) {
1977 // set advanced
1978 $this->helper->setLoginMode( false );
1979 update_option( 'mbe_shipping_admin_messages', [
1980 'message' => urlencode( __( 'Logged in', 'mail-boxes-etc' ) ),
1981 'status' => urlencode( 'success' )
1982 ] );
1983 } else {
1984 update_option( 'mbe_shipping_admin_messages', [
1985 'message' => urlencode( __( 'Error Logging in. Please enable debug and check the log files for more details', 'mail-boxes-etc' ) ),
1986 'status' => urlencode( 'error' )
1987 ] );
1988 }
1989 } else {
1990 update_option( 'mbe_shipping_admin_messages', [
1991 'message' => urlencode( __( 'Missing MBE Online Login Information', 'mail-boxes-etc' ) ),
1992 'status' => urlencode( 'error' )
1993 ] );
1994 }
1995 }
1996
1997 wp_redirect( wp_get_referer() );
1998 }
1999
2000 public function mbe_reset_login() {
2001 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_reset_login' ) ) {
2002 $logger = new Mbe_Shipping_Helper_Logger();
2003
2004 $this->helper->setLoginMode();
2005 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_WS_USERNAME, '' );
2006 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_WS_PASSWORD, '' );
2007 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_WS_URL, '' );
2008
2009 // delete the api key so it will be regenerated by the control hooked on plugin save
2010 $user_id = username_exists( MBE_WC_REST_API_USERNAME );
2011 if ( $user_id && email_exists( MBE_WC_REST_API_USER_EMAIL ) ) {
2012 $logger->log( 'Reset login - Delete Api Key' );
2013 $this->helper->removeMbeRestApiKey( $user_id );
2014 }
2015 }
2016 wp_redirect( wp_get_referer() );
2017 }
2018
2019 public function mbe_generate_api_key() {
2020 $logger = new Mbe_Shipping_Helper_Logger();
2021 $logger->log( 'MBE Generate API KEY - Start' );
2022 $status = 'success';
2023 try {
2024 $ws = new MbeWs( true );
2025 $response = $ws->generateApiKey( $this->helper->getMbeUsername(), $this->helper->getMbePassword() );
2026 if ( ! empty( $response ) ) {
2027 $this->helper->setWsUsername( $response->apiKey );
2028 $this->helper->setWsPassword( $response->apiSecret );
2029 $logger->log( 'MBE Generate API KEY - Done' );
2030 $message = __( 'eShip credentials generated correctly', 'mail-boxes-etc' );
2031 } else {
2032 $logger->log( 'MBE Generate API KEY - Empty response' );
2033 $message = __( 'eShip credentials not generated - Empty response', 'mail-boxes-etc' );
2034 $status = 'error';
2035 }
2036
2037 } catch ( \Exception $e ) {
2038 $logger->log( __( 'MBE Generate API KEY' ) . ' - ' . $e->getMessage() );
2039 $message = __( 'eShip credentials not generated. Check the log files for more details', 'mail-boxes-etc' );
2040 $status = 'error';
2041 }
2042 update_option( 'mbe_shipping_admin_messages', [
2043 'message' => urlencode( $message ),
2044 'status' => urlencode( $status )
2045 ] );
2046
2047 if ( $status === 'success' ) {
2048 return true;
2049 } else {
2050 return false;
2051 }
2052 // wp_redirect(wp_get_referer());
2053
2054 }
2055
2056 public function mbe_shipping_admin_notices() {
2057 // Manage WC environment notification
2058 $apiKeyMessage = maybe_unserialize( get_option( 'mbe_shipping_admin_messages' ) );
2059 if ( ! empty( $apiKeyMessage ) ) {
2060 $messageStatus = urldecode( $apiKeyMessage['status'] );
2061 $messageText = urldecode( $apiKeyMessage['message'] );
2062 if ( $messageStatus === 'error' ) {
2063 WC_Admin_Settings::add_error( $messageText );
2064 } else {
2065 WC_Admin_Settings::add_message( $messageText );
2066 }
2067 }
2068 delete_option( 'mbe_shipping_admin_messages' );
2069 }
2070
2071 // Set the local pickup default data
2072 public function mbe_woocommerce_get_pickup_default_data() {
2073 $ws = new Mbe_Shipping_Model_Ws();
2074 // get MOL default data
2075 $pickupData = $ws->getPickupDefaultData();
2076 // set local default data
2077 $this->helper->setLocalPickupDefaultData( $pickupData );
2078 }
2079
2080 // Send the local pickup default data to MOL
2081 public function mbe_woocommerce_set_pickup_default_data() {
2082 $ws = new Mbe_Shipping_Model_Ws();
2083 $ws->setPickupDefaultData( $this->helper->getLocalPickupDefaultData() );
2084 }
2085
2086 public function mbe_download_pickup_manifest() {
2087 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_pickup_manifest' ) ) {
2088 $ws = new Mbe_Shipping_Model_Ws();
2089 $logger = new Mbe_Shipping_Helper_Logger();
2090 try {
2091 $postId = sanitize_text_field( $_REQUEST['mbe_pickup_postid'] );
2092
2093 if ( ! $this->helper->isPickupShipped( $postId ) ) {
2094 throw new \MbeExceptions\ValidationException( __( 'Please select only pickup batches', 'mail-boxes-etc' ) );
2095 }
2096
2097 if ( ! $this->helper->hasTracking( $postId ) ) {
2098 throw new \MbeExceptions\ValidationException( sprintf( __( 'Order %s does not have a tracking number', 'mail-boxes-etc' ), $postId ) );
2099 }
2100
2101 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
2102 $order = wc_get_order( $postId );
2103 $masterTrackingNumber = $order===false?'':$order->get_meta(Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_NUMBER);
2104 } else {
2105 $masterTrackingNumber = get_post_meta( $postId, Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_NUMBER, true );
2106 }
2107
2108 $response = $ws->getPickupManifest( $masterTrackingNumber );
2109
2110 $outputPdf = $response->Label->Stream;
2111 $outputPdfPath = $this->helper->mbeUploadDir() . DIRECTORY_SEPARATOR . current_datetime()->getTimestamp() . rand( 0, 999 ) . '.pdf';
2112
2113 if ( file_put_contents( $outputPdfPath, $outputPdf ) !== false ) {
2114 $this->helper->mbe_download_file( $outputPdfPath, "pickup_manifest_$postId.pdf", 'application/pdf', true );
2115 } else {
2116 $errMess = __( 'MBE Download pickup manifest - no document to download', 'mail-boxes-etc' );
2117 $this->helper->logErrorAndSetWpAdminMessage( $errMess, $logger );
2118 }
2119 } catch ( \MbeExceptions\ValidationException $e ) {
2120 $errMess = __( 'MBE Download pickup manifest - ' . $e->getMessage(), 'mail-boxes-etc' );
2121 $this->helper->logErrorAndSetWpAdminMessage( $errMess, $logger );
2122 } catch ( \Exception $e ) {
2123 $errMess = __( 'MBE Download pickup manifest - Unexpected error', 'mail-boxes-etc' ) . ' - ' . $e->getMessage();
2124 $this->helper->logErrorAndSetWpAdminMessage( $errMess, $logger );
2125 }
2126 }
2127 wp_redirect( wp_get_referer() );
2128 }
2129
2130 public function mbe_download_delivery_point_waybill() {
2131 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_delivery_point_waybill' ) ) {
2132 $ws = new Mbe_Shipping_Model_Ws();
2133 $logger = new Mbe_Shipping_Helper_Logger();
2134 try {
2135 $postId = sanitize_text_field( $_REQUEST['mbe_delivery_point_postid'] );
2136
2137 if ( ! $this->helper->isDeliveryPointOrder( $postId ) ) {
2138 throw new \MbeExceptions\ValidationException( __( 'Please select only delivery point orders', 'mail-boxes-etc' ) );
2139 }
2140
2141 if ( ! $this->helper->hasTracking( $postId ) ) {
2142 throw new \MbeExceptions\ValidationException( sprintf( __( 'Order %s does not have a tracking number', 'mail-boxes-etc' ), $postId ) );
2143 }
2144
2145 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
2146 $order = wc_get_order( $postId );
2147 $masterTrackingNumber = $order===false?'':$order->get_meta(Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_NUMBER);
2148 } else {
2149 $masterTrackingNumber = get_post_meta( $postId, Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_NUMBER, true );
2150 }
2151
2152 $response = $ws->getDeliveryPointShippingDocument( $masterTrackingNumber );
2153
2154 if ( $response !== false && empty( $response->Errors ) ) {
2155 $outputPdf = file_get_contents( $response->CourierWaybill ); // load the remote pdf
2156 $outputPdfPath = $this->helper->mbeUploadDir() . DIRECTORY_SEPARATOR . current_datetime()->getTimestamp() . rand( 0, 999 ) . '.pdf';
2157
2158 if ( file_put_contents( $outputPdfPath, $outputPdf ) !== false ) {
2159 $this->helper->mbe_download_file( $outputPdfPath, "delivery_point_waybill_$postId.pdf", 'application/pdf', true );
2160 } else {
2161 $errMsg = __( 'Download waybill - no document to download. Please, retry later', 'mail-boxes-etc' );
2162 $this->helper->logErrorAndSetWpAdminMessage( $errMsg, $logger );
2163 }
2164 } else {
2165 $errMsg = __( "Download waybill", 'mail-boxes-etc' ) . " $postId - " . __( $response->Errors->Error->Description ?? '', 'mail-boxes-etc' );
2166 $this->helper->logErrorAndSetWpAdminMessage( $errMsg, $logger );
2167 }
2168 } catch ( \MbeExceptions\ValidationException $e ) {
2169 $errMess = __( 'Download waybill - ' . $e->getMessage(), 'mail-boxes-etc' );
2170 $this->helper->logErrorAndSetWpAdminMessage( $errMess, $logger );
2171 } catch ( \MbeExceptions\ShippingDocumentException $e ) {
2172 $errMsg = sprintf( __( "Download waybill", 'mail-boxes-etc' ) . " - " . __( "%s", 'mail-boxes-etc' ), $e->getMessage() );
2173 $this->helper->logErrorAndSetWpAdminMessage( $errMsg, $logger );
2174 } catch ( \Exception $e ) {
2175 $errMess = __( 'MBE Download pickup manifest - Unexpected error', 'mail-boxes-etc' ) . ' - ' . $e->getMessage();
2176 $this->helper->logErrorAndSetWpAdminMessage( $errMess, $logger );
2177 }
2178 }
2179 wp_redirect( wp_get_referer() );
2180 }
2181
2182 public function mbe_eship_wp_notification() {
2183 // Manage WP environment notification
2184 $wpAdminMessages = maybe_unserialize( get_option( 'mbe_shipping_wp_admin_messages' ) ) ?: [];
2185 delete_option( 'mbe_shipping_wp_admin_messages' );
2186 $printf = '';
2187 foreach ( $wpAdminMessages as $adminMessage ) {
2188 $messageStatus = urldecode( $adminMessage['status'] ?? '' );
2189 $messageText = urldecode( $adminMessage['message'] );
2190 switch ( $messageStatus ) {
2191 case 'error':
2192 $printf .= printf( '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Error' ) . ': %s</p></div>', esc_html( $messageText ) );
2193 break;
2194 case 'warning':
2195 $printf .= printf( '<div class="notice notice-warning is-dismissible"><p>%s</p></div>', esc_html( $messageText ) );
2196 break;
2197 default:
2198 $printf .= printf( '<div class="notice notice-info is-dismissible"><p>%s</p></div>', esc_html( $messageText ) );
2199 break;
2200 }
2201 }
2202
2203 return $printf;
2204 }
2205
2206 function csv_form_page_handler() {
2207 if ( isset( $_REQUEST['nonce'] ) && ( wp_verify_nonce( $_REQUEST['nonce'], 'csv_form_page_handler' ) || wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) ) ) {
2208
2209 global $wpdb;
2210
2211 $csvType = wc_clean( $_REQUEST['csv'] ) ?: null;
2212 $requestId = wc_clean( $_REQUEST['id'] ) ?: null;
2213 $csvFactory = new Mbe_Csv_Editor_Model_Factory();
2214 $csv = $csvFactory->create( $csvType );
2215 if ( ! empty( $csv ) ) {
2216 $message = '';
2217 $notice = '';
2218 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : 'woocommerce_mbe_csv_tabs&csv=' . $csvType . '&nonce=' . wp_create_nonce( 'woocommerce_mbe_csv_tabs' ) );
2219
2220 // default $item data to be used for new records
2221 $default = $csv->get_defaults();
2222
2223 $table_name = $csv->get_tablename();
2224
2225 // check post back and correct nonce
2226 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) ) {
2227 // combine default and request params
2228 $item = shortcode_atts( $default, $_REQUEST );
2229 // data validation
2230 $item_valid = $csv->validate_row( $item );
2231 try {
2232 if ( $item_valid === true ) {
2233 $ws = new Mbe_Shipping_Model_Ws();
2234 $result = true;
2235 if ( empty( $item[ $csv->get_ID() ] ) ) {
2236 do_action( MBE_ESHIP_ID . '_csv_editor_adding', $item );
2237 if ( ! $csv->get_isRemote() ) {
2238 $result = $wpdb->insert( $table_name, $item ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
2239 $item[ $csv->get_ID() ] = $wpdb->insert_id;
2240 } else {
2241 // Todo : check value online exist and = item - create a validateItem in class that extend Mbe_Shipping_Csv_Editor (eg.Mbe_Shipping_Csv_Editor_Pickup_Addresses)
2242 // set result = false if it fails
2243 }
2244 if ( $result !== false ) {
2245 $message = __( 'Item successfully saved', 'mail-boxes-etc' );
2246 do_action( MBE_ESHIP_ID . '_csv_editor_added', $item );
2247 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage . '&message=' . urlencode( $message ) ) ) );
2248 exit;
2249 } else {
2250 $notice = __( 'There was an error while saving the item', 'mail-boxes-etc' ) . ': ' . $wpdb->last_error;
2251 }
2252 } else {
2253 do_action( MBE_ESHIP_ID . '_csv_editor_updating', $item );
2254 if ( ! $csv->get_isRemote() ) {
2255 $result = $wpdb->update( $table_name, $item, array( 'id' => $item[ $csv->get_ID() ] ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
2256 } else {
2257 // Todo : check value online = item - create a validateItem in class that extend Mbe_Shipping_Csv_Editor (eg.Mbe_Shipping_Csv_Editor_Pickup_Addresses)
2258 // set result = false if it fails
2259 }
2260 if ( $result !== false ) {
2261 $message = __( 'Item successfully updated', 'mail-boxes-etc' );
2262 do_action( MBE_ESHIP_ID . '_csv_editor_updated', $item );
2263 wp_redirect( get_admin_url( get_current_blog_id(), 'admin.php?page=woocommerce_mbe_csv_tabs&csv=' . $csvType . '&message=' . urlencode( $message ) . '&nonce=' . wp_create_nonce( 'woocommerce_mbe_csv_tabs' ) ) );
2264 } else {
2265 $notice = __( 'There was an error while updating the item', 'mail-boxes-etc' ) . ': ' . $wpdb->last_error;
2266 }
2267 }
2268 } else {
2269 $notice = $item_valid;
2270 }
2271 } catch ( Exception $e ) {
2272 $notice = $e->getMessage();
2273 }
2274 } else {
2275 $item = $default;
2276 if ( isset( $requestId ) ) {
2277 if ( $csv->get_isRemote() ) {
2278 $item = $csv->get_remoteRow( $requestId );
2279 } else {
2280 $item = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d", $requestId ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
2281 }
2282 if ( ! $item ) {
2283 $item = $default;
2284 // $notice = __( 'Item not found', 'mail-boxes-etc' );
2285 }
2286 }
2287 }
2288
2289 // custom meta box is a method of $csv class
2290 add_meta_box( MBE_ESHIP_ID . '_csv_form_meta_box', $csv->get_title(),
2291 array( $csv, 'form_meta_box_handler' ),
2292 'csv-' . $csvType, 'normal', 'default' );
2293 ?>
2294
2295 <div class="wrap">
2296 <div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
2297 <h2><?php esc_html_e( 'Edit' ) . ' ' . $csv->get_title( false ) ?>
2298 <a class="add-new-h2"
2299 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ); ?>">
2300 <?php esc_html_e( 'Back to list', 'mail-boxes-etc' ) ?>
2301 </a>
2302 </h2>
2303
2304 <?php $this->mbe_eship_wp_notification() ?>
2305 <?php if ( ! empty( $notice ) ): ?>
2306 <div id="notice" class="notice notice-error is-dismissible">
2307 <p><?php echo wp_kses_post( $notice ) ?></p></div>
2308 <?php endif; ?>
2309 <?php if ( ! empty( $message ) ): ?>
2310 <div id="message" class="notice notice-success is-dismissible">
2311 <p><?php echo wp_kses_post( $message ) ?></p></div>
2312 <?php endif; ?>
2313
2314 <form id="form" method="POST">
2315 <input type="hidden" name="nonce"
2316 value="<?php esc_attr_e( wp_create_nonce( basename( __FILE__ ) ) ) ?>"/>
2317 <?php /* storing id to check if we need to add or update the item */ ?>
2318 <input type="hidden" name="id" value="<?php esc_attr_e( $item[ $csv->get_ID() ] ) ?>"/>
2319
2320 <div class="metabox-holder" id="poststuff">
2321 <div id="post-body">
2322 <div id="post-body-content">
2323 <?php /* render meta box */ ?>
2324 <?php do_meta_boxes( 'csv-' . $csvType, 'normal', $item ); ?>
2325 <input type="submit" value="<?php esc_attr_e( 'Save', 'mail-boxes-etc' ) ?>"
2326 id="submit"
2327 class="button-primary" name="submit">
2328 </div>
2329 </div>
2330 </div>
2331 </form>
2332 </div>
2333 <?php
2334 } else {
2335 ?>
2336 <div class="wrap">
2337 <h2><?php esc_html_e( 'Missing or wrong csv type', 'mail-boxes-etc' ) ?>
2338 <a class="add-new-h2"
2339 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?page=' . mbe_e_link_get_settings_url() . '&tab=' . MBE_ESHIP_ID . '&section=mbe_general' ) ); ?>">
2340 <?php esc_html_e( 'Back to settings', 'mail-boxes-etc' ) ?>
2341 </a>
2342 </h2>
2343 </div>
2344 <?php
2345 }
2346 } else {
2347 wp_redirect( wp_get_referer() );
2348 }
2349 }
2350
2351 public function pickup_data_form_page_handler() {
2352
2353 $pickupModel = new Mbe_Shipping_Model_Pickup_Custom_Data();
2354 $orderIds = isset( $_REQUEST['orderids'] ) ? json_decode( wc_clean( $_REQUEST['orderids'] ) ) : null;
2355 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2356 if ( ! empty( $orderIds )
2357 && isset( $_REQUEST['nonce'] )
2358 && (
2359 wp_verify_nonce( $_REQUEST['nonce'], 'mbe_edit_pickup' )
2360 || wp_verify_nonce( $_REQUEST['nonce'], 'mbe_pickup_return_from_address' )
2361 || wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) )
2362 )
2363 ) {
2364 $message = '';
2365 $notice = '';
2366 // $backPage = 'page=' . (isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE);
2367
2368 // default $item pickup data to be used for new records,
2369 // get local ones to avoid a call to the WS since very probably data will be verified and updated
2370 $default = $this->helper->getLocalPickupDefaultData();
2371
2372 // initialize the row id to be merged while editing an existing row
2373 $default['id'] = null;
2374
2375 // check Post back and correct nonce
2376 $requestId = wc_clean( $_REQUEST['id'] ?? null );
2377 if ( wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) ) {
2378 $default['date'] = '';
2379 $default['pickup_address_id'] = '';
2380 $default['pickup_batch_id'] = null;
2381
2382 $item = shortcode_atts( $default, $_REQUEST );
2383
2384 $item_valid = $pickupModel->validate_row( $item );
2385
2386 if ( $item_valid === true ) {
2387 // Save the custom pickup data
2388 $batchId = null;
2389 // If not updating
2390 if ( empty( $requestId ) ) {
2391 if ( count( $orderIds ) > 1 ) {
2392 $now = current_datetime();
2393 $batchId = $this->helper->getWsUsername() . '_' . $now->getTimestamp();
2394 $item['pickup_batch_id'] = $batchId;
2395 }
2396
2397 // Additional check to avoid creating a new custom data row if orders are already linked to pickup data
2398 $list = [];
2399 foreach ( $orderIds as $orderId ) {
2400 if ( ! empty( $this->helper->getOrderPickupBatchId( $orderId ) ) ) {
2401 $list[] = $orderId;
2402 }
2403 }
2404 if ( ! empty( $list ) ) {
2405 $errMess = sprintf( __( 'The orders %s are already linked to pickup data' ), implode( ',', $list ) );
2406 $this->helper->logErrorAndSetWpAdminMessage( $errMess );
2407 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
2408 exit;
2409 }
2410
2411 // Insert pickup custom data row
2412 $pickupCustomDataId = $pickupModel->insertRow( $item );
2413
2414 // Set order items meta fields
2415 foreach ( $orderIds as $orderId ) {
2416 // Additional check to avoid updating field for already existing shipments
2417 if ( ! $this->helper->hasTracking( $orderId ) ) {
2418 $this->helper->setOrderPickupCustomDataId( $orderId, $pickupCustomDataId );
2419 $this->helper->setOrderPickupBatchId( $orderId, $batchId );
2420 }
2421 }
2422 $action = 'created';
2423 } else {
2424 // Update the custom pickup data
2425 $pickupModel->updateRow( $item['id'], $item );
2426 $batchId = $item['pickup_batch_id'];
2427 $action = 'updated';
2428 }
2429 // Updating the backpage to the pickup batch list to show the newly created batch, but not if we have a single shipment
2430 // if(count($orderIds)>1) {
2431 $backPage = 'page=' . MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE;
2432 // }
2433
2434 if ( isset( $_REQUEST['submit_save'] ) ) {
2435 $this->helper->setWpAdminMessages( [
2436 'message' => urlencode( sprintf( __( 'The pickup %s has been %s', 'mail-boxes-etc' ), ( ! empty( $batchId ) ? 'batch ' . $batchId : '' ), __( $action, 'mail-boxes-etc' ) ) ),
2437 'status' => urlencode( 'success' )
2438 ] );
2439 } elseif ( isset( $_REQUEST['submit_savesend'] ) ) {
2440 $this->createPickup( $orderIds );
2441 }
2442 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
2443 exit;
2444 } else {
2445 $notice = $item_valid;
2446 }
2447 } else {
2448 $item = $default;
2449
2450 if ( isset( $requestId ) ) {
2451 $item = $pickupModel->getRow( $requestId );
2452 if ( ! $item ) {
2453 $item = $default;
2454 // $notice = __( 'Item not found', 'mail-boxes-etc' );
2455 }
2456 }
2457 }
2458
2459 $item['order_ids'] = is_array( $orderIds ) ? $orderIds : [ $orderIds ];
2460
2461 add_meta_box( MBE_ESHIP_ID . '_pickup_data_form_meta_box',
2462 ' ',
2463 array( $pickupModel, 'form_meta_box' ),
2464 'pickup-data-editor', 'normal', 'default'
2465 );
2466 ?>
2467 <div class="wrap">
2468 <div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
2469 <h2><?php esc_html_e( 'Pickup orders management', 'mail-boxes-etc' ) ?>
2470 <a class="add-new-h2"
2471 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ); ?>">
2472 <?php esc_html_e( 'Back to list', 'mail-boxes-etc' ) ?>
2473 </a>
2474 </h2>
2475
2476 <?php $this->mbe_eship_wp_notification() ?>
2477 <?php if ( ! empty( $notice ) ): ?>
2478 <div id="notice" class="notice notice-error is-dismissible">
2479 <p><?php echo wp_kses_post( $notice ) ?></p></div>
2480 <?php endif; ?>
2481 <?php if ( ! empty( $message ) ): ?>
2482 <div id="message" class="notice notice-success is-dismissible">
2483 <p><?php echo wp_kses_post( $message ) ?></p></div>
2484 <?php endif; ?>
2485 <form id="form" method="POST">
2486 <input type="hidden" name="nonce"
2487 value="<?php esc_attr_e( wp_create_nonce( basename( __FILE__ ) ) ) ?>"/>
2488 <input type="hidden" name="id" value="<?php esc_attr_e( $item['id'] ) ?>"
2489 <div class="metabox-holder" id="poststuff">
2490 <div id="post-body">
2491 <div id="post-body-content">
2492 <?php do_meta_boxes( 'pickup-data-editor', 'normal', $item ) ?>
2493 </div>
2494 </div>
2495 </div>
2496 </form>
2497 </div>
2498 <?php
2499 } else {
2500 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
2501 }
2502 }
2503
2504
2505 public function mbe_edit_pickup_data( $post_ids ) {
2506 if ( $this->helper->getPickupRequestEnabled() ) {
2507 switch ( $this->helper->getPickupRequestMode() ) {
2508 case Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_MANUAL :
2509 // Open default data editor and create a row for the batch ( pre-fill with default values from MOL ) and link it to the selected orders
2510 $backPage = '&backpage=' . urlencode( WOOCOMMERCE_MBE_TABS_PAGE );
2511 wp_redirect( esc_url_raw( admin_url( 'admin.php?page=' . MBE_ESHIP_ID . '_pickup_data_tabs&orderids=' . urlencode( json_encode( $post_ids ) ) . $backPage . '&nonce=' . wp_create_nonce( 'mbe_edit_pickup' ) ) ) );
2512 break;
2513 case Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_AUTOMATIC :
2514 $this->createPickup( $post_ids );
2515 wp_redirect( esc_url_raw( admin_url( 'admin.php?page=' . WOOCOMMERCE_MBE_TABS_PAGE ) ) );
2516 break;
2517 }
2518 }
2519 }
2520
2521
2522 public function mbe_delete_pickup_custom_data() {
2523 $logger = new \Mbe_Shipping_Helper_Logger();
2524 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_delete_pickup_custom_data' ) ) {
2525 global $wpdb;
2526 $id = wc_clean( $_REQUEST['id'] );
2527 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2528
2529 $pickupCustomData = new Mbe_Shipping_Model_Pickup_Custom_Data();
2530 $row = $pickupCustomData->getRow( $id );
2531
2532 // if ( 'ready' === strtolower( $row['status'] ) && isset( $row['pickup_batch_id'] ) ) {
2533 if ( 'ready' === strtolower( $row['status'] ) ) {
2534 // Detach all the order linked
2535 $selectOrderIds = $this->helper->select_pickup_orders_ids( $id );
2536 $orders = $wpdb->get_results( $selectOrderIds, ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
2537 $orderIds = array_map( 'absint', array_column( $orders, 'order_id' ) );
2538 $notDetached = [];
2539 foreach ( $orderIds as $orderId ) {
2540 if ( ! $this->helper->detachOrderFromPickupBatch( $orderId ) ) {
2541 $notDetached[] = $orderId;
2542 }
2543 }
2544 if ( empty( $notDetached ) ) {
2545 // Delete the custom data row
2546 $pickupCustomData->deleteRow( $id );
2547 } else {
2548 $message = sprintf( __( 'Cannot delete the pickup custom data row since order(s) %s cannot be detached as it seems to be a shipped pickup(s)', 'mail-boxes-etc' ), implode( ',', $notDetached ) );
2549 $this->helper->logErrorAndSetWpAdminMessage( $message, $logger );
2550 }
2551
2552 }
2553
2554 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
2555 }
2556 }
2557
2558 public function mbe_detach_order_from_batch() {
2559 $logger = new \Mbe_Shipping_Helper_Logger();
2560
2561 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_detach_order_from_batch' ) ) {
2562 $orderId = sanitize_text_field( $_REQUEST['mbe_pickup_postid'] );
2563 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2564 $pickupCustomDataId = $this->helper->getOrderPickupCustomDataId( $orderId );
2565
2566 if ( $this->helper->detachOrderFromPickupBatch( $orderId ) ) {
2567 do_action( MBE_ESHIP_ID . '_after_detach', $pickupCustomDataId );
2568 } else {
2569 $message = sprintf( __( 'Order %d cannot be detached as it is a shipped pickup', 'mail-boxes-etc' ), $orderId );
2570 $this->helper->logErrorAndSetWpAdminMessage( $message, $logger );
2571 }
2572 }
2573 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
2574 }
2575
2576 /**
2577 * Delete pickup batch if there are no items left
2578 *
2579 * @return void
2580 */
2581 // public function mbe_after_detach_check_pickup_batch_items($batchId) {
2582 // $pickupCustomData = new Mbe_Shipping_Model_Pickup_Custom_Data();
2583 //
2584 // if(empty($pickupCustomData->getBatchIdOrders($batchId))) {
2585 // $pickupCustomData->deleteRow( $pickupCustomData->getBatchIdRow($batchId)->id );
2586 // }
2587 // }
2588
2589 /**
2590 * Delete pickup if there are no items left
2591 *
2592 * @return void
2593 */
2594 public function mbe_after_detach_check_pickup_items( $pickupCustomDataId ) {
2595 $pickupCustomData = new Mbe_Shipping_Model_Pickup_Custom_Data();
2596
2597 if ( empty( $pickupCustomData->getPickupIdOrders( $pickupCustomDataId ) ) ) {
2598 $pickupCustomData->deleteRow( $pickupCustomDataId );
2599 }
2600 }
2601
2602
2603 public function mbe_send_pickup() {
2604 $logger = new \Mbe_Shipping_Helper_Logger();
2605 $logger->log( 'Send pickup Action - Start' );
2606 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2607 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_send_pickup' ) && isset( $_REQUEST['mbe_pickup_id'] ) && $this->helper->getPickupRequestEnabled() ) {
2608 $logger->log( 'Send pickup Action - Create pickup' );
2609 global $wpdb;
2610 $pickupCustomDataId = sanitize_text_field( $_REQUEST['mbe_pickup_id'] );
2611 $pickupCustomData = new Mbe_Shipping_Model_Pickup_Custom_Data();
2612 $hasPickupBatch = ! empty( $pickupCustomData->getRow( $pickupCustomDataId )['pickup_batch_id'] );
2613
2614 // $orders = $wpdb->get_results( $this->helper->select_pickup_batch_orders_ids( $pickupBatchId ), ARRAY_A );
2615 $orders = $wpdb->get_results( $this->helper->select_pickup_orders_ids( $pickupCustomDataId ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
2616 $orderIds = array_map( 'absint', array_column( $orders, 'order_id' ) );
2617 $this->createPickup( $orderIds, $hasPickupBatch );
2618 }
2619 if ( ! $this->helper->getPickupRequestEnabled() ) {
2620 $message = __( 'Pickup request cannot be enabled, please check the settings', 'mail-boxes-etc' );
2621 $this->helper->logErrorAndSetWpAdminMessage( $message, $logger );
2622 }
2623 $logger->log( 'Send pickup Action - End' );
2624 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
2625 }
2626
2627 public function mbe_create_return_shipment() {
2628 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2629 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_create_return_shipment' ) && isset( $_REQUEST['mbe_post_id'] ) ) {
2630 $orderId = array_map( 'absint', (array) sanitize_text_field( $_REQUEST['mbe_post_id'] ) );
2631 $this->createReturnShipment( $orderId );
2632 }
2633 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
2634 }
2635
2636 public function mbe_woocommerce_get_advanced_return_address_data( $post_id ) {
2637 if ( $this->helper->canAdvancedReturn() ) {
2638 // Open the address data editor and create the return shipment
2639 $backPage = '&backpage=' . urlencode( WOOCOMMERCE_MBE_TABS_PAGE );
2640 wp_redirect( esc_url_raw( admin_url( 'admin.php?page=' . MBE_ESHIP_ID . '_advanced_return_address_data_tabs&orderid=' . urlencode( $post_id ) . $backPage . '&nonce=' . wp_create_nonce( 'mbe_edit_advanced_return_address_data' ) ) ) );
2641 }
2642 }
2643
2644 public function advanced_return_address_data_form_page_handler() {
2645
2646 $orderId = isset( $_REQUEST['orderid'] ) ? wc_clean( $_REQUEST['orderid'] ) : null;
2647 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2648 if ( ! empty( $orderId )
2649 && isset( $_REQUEST['nonce'] )
2650 && (
2651 wp_verify_nonce( $_REQUEST['nonce'], 'mbe_edit_advanced_return_address_data' )
2652 || wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) // check nonce for post back (save)
2653 )
2654 ) {
2655 if ( wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) ) {
2656
2657 // Check Privince field
2658 $senderProvince = sanitize_text_field( $_POST['sender_province'] );
2659 $receiverProvince = sanitize_text_field( $_POST['receiver_province'] );
2660 $senderProvinceIsEmptyForItaly = $this->helper->getCountry() === 'IT' && empty( $senderProvince );
2661 $senderProvinceIsNotTwoChar = $senderProvince && ! strlen( $senderProvince ) == 2;
2662 $receiverProvinceIsEmptyForItaly = $this->helper->getCountry() === 'IT' && empty( $receiverProvince );
2663 $receiverProvinceIsNotTwoChar = $receiverProvince && ! strlen( $receiverProvince ) == 2;
2664
2665 try {
2666
2667 if ( $senderProvinceIsEmptyForItaly || $receiverProvinceIsEmptyForItaly || $senderProvinceIsNotTwoChar || $receiverProvinceIsNotTwoChar ) {
2668 throw new Exception( __( "The field \"Province\" must not exceed 2 characters.", 'mail-boxes-etc' ) );
2669 }
2670
2671 $returnData =
2672 array(
2673 'sender_trade_name' => sanitize_text_field( $_POST['sender_trade_name'] ),
2674 'sender_address_1' => sanitize_text_field( $_POST['sender_address_1'] ),
2675 'sender_address_2' => sanitize_text_field( $_POST['sender_address_2'] ),
2676 'sender_address_3' => sanitize_text_field( $_POST['sender_address_3'] ),
2677 'sender_postcode' => sanitize_text_field( $_POST['sender_postcode'] ),
2678 'sender_city' => sanitize_text_field( $_POST['sender_city'] ),
2679 'sender_province' => $senderProvince,
2680 'sender_country' => sanitize_text_field( $_POST['sender_country'] ),
2681 'sender_reference' => sanitize_text_field( $_POST['sender_reference'] ),
2682 'sender_telephone_1' => sanitize_text_field( $_POST['sender_telephone_1'] ),
2683 'sender_telephone_2' => sanitize_text_field( $_POST['sender_telephone_2'] ),
2684 'sender_email_1' => sanitize_email( $_POST['sender_email_1'] ),
2685 'sender_email_2' => sanitize_email( $_POST['sender_email_2'] ),
2686 'sender_fax' => sanitize_text_field( $_POST['sender_fax'] ),
2687 'receiver_trade_name' => sanitize_text_field( $_POST['receiver_trade_name'] ),
2688 'receiver_address_1' => sanitize_text_field( $_POST['receiver_address_1'] ),
2689 'receiver_address_2' => sanitize_text_field( $_POST['receiver_address_2'] ),
2690 'receiver_address_3' => sanitize_text_field( $_POST['receiver_address_3'] ),
2691 'receiver_postcode' => sanitize_text_field( $_POST['receiver_postcode'] ),
2692 'receiver_city' => sanitize_text_field( $_POST['receiver_city'] ),
2693 'receiver_province' => $receiverProvince,
2694 'receiver_country' => sanitize_text_field( $_POST['receiver_country'] ),
2695 'receiver_reference' => sanitize_text_field( $_POST['receiver_reference'] ),
2696 'receiver_telephone_1' => sanitize_text_field( $_POST['receiver_telephone_1'] ),
2697 'receiver_telephone_2' => sanitize_text_field( $_POST['receiver_telephone_2'] ),
2698 'receiver_email_1' => sanitize_email( $_POST['receiver_email_1'] ),
2699 'receiver_email_2' => sanitize_email( $_POST['receiver_email_2'] ),
2700 'receiver_fax' => sanitize_text_field( $_POST['receiver_fax'] ),
2701 'pickup_date' => sanitize_text_field( $_POST['pickup_date'] ),
2702 'pickup_time_preferred_from' => sanitize_text_field( $_POST['pickup_time_preferred_from'] ),
2703 'pickup_time_preferred_to' => sanitize_text_field( $_POST['pickup_time_preferred_to'] ),
2704 'pickup_time_alternative_from' => sanitize_text_field( $_POST['pickup_time_alternative_from'] ),
2705 'pickup_time_alternative_to' => sanitize_text_field( $_POST['pickup_time_alternative_to'] ),
2706 'pickup_notes' => sanitize_text_field( $_POST['pickup_notes'] ),
2707 );
2708
2709
2710 $result = $this->createAdvancedReturnShipment( $orderId, $returnData );
2711 if ( $result ) {
2712 $this->helper->setWpAdminMessages( [ 'message' => __( 'Return shipment created' ) ] );
2713 }
2714
2715 } catch ( Exception $e ) {
2716 $this->helper->setWpAdminMessages( [
2717 'message' => __( 'Return shipment', 'mail-boxes-etc' ) . ' - ' . __( $e->getMessage(), 'mail-boxes-etc' ),
2718 'status' => 'error'
2719 ] );
2720 }
2721
2722 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
2723 exit;
2724 }
2725
2726 \Metaboxes\AdvancedReturnAddressData::add( MBE_ESHIP_ID . '_advanced_return_address_data_form_meta_box', 'advanced-return-address-data-meta-box' );
2727
2728 ?>
2729 <div class="wrap">
2730 <?php $this->mbe_eship_wp_notification() ?>
2731
2732 <div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
2733 <h2><?php esc_html_e( 'Return address data', 'mail-boxes-etc' ) ?>
2734 <a class="add-new-h2"
2735 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ); ?>">
2736 <?php esc_html_e( 'Back to list', 'mail-boxes-etc' ) ?>
2737 </a>
2738 </h2>
2739
2740 <form id="form" method="POST">
2741 <input type="hidden" name="nonce"
2742 value="<?php esc_attr_e( wp_create_nonce( basename( __FILE__ ) ) ) ?>"/>
2743 <!-- <input type="hidden" name="id" value="-->
2744 <?php //esc_attr_e($item['id']) ?><!--"-->
2745 <div class="metabox-holder" id="advanced-return-address-data-meta-box">
2746 <div id="post-body">
2747 <div id="post-body-content">
2748 <?php do_meta_boxes( 'advanced-return-address-data-meta-box', 'normal', $orderId ) ?>
2749
2750 <table style="width: 100%; margin-top: 20px;">
2751 <tbody>
2752 <tr>
2753 <td colspan="2">
2754 <div style="float:right;">
2755 <a class="button button-secondary"
2756 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ); ?>">
2757 <?php esc_html_e( 'Cancel', 'mail-boxes-etc' ) ?>
2758 </a>
2759 <input type="submit"
2760 value="<?php esc_attr_e( 'Save and send', 'mail-boxes-etc' ); ?>"
2761 class="button button-primary">
2762 </div>
2763 </td>
2764 </tr>
2765 </tbody>
2766 </table>
2767
2768 </div>
2769 </div>
2770 </div>
2771 </form>
2772 </div>
2773 <?php
2774 } else {
2775 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
2776 }
2777 }
2778
2779 public function mbe_after_delete_pickup_address_disable_pickup_if_no_default_address( $ids, $csvType ) {
2780 $logger = new \Mbe_Shipping_Helper_Logger();
2781 $helper = new Mbe_Shipping_Helper_Data();
2782 if ( 'pickup-addresses' === $csvType
2783 && ! $helper->hasDefaultPickupAddress()
2784 && $helper->getPickupRequestEnabled()
2785 && $helper->getPickupRequestMode() === Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_AUTOMATIC
2786 ) {
2787 $helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_PICKUP_REQUEST_ENABLED, 0 );
2788 $message = __( 'Pickup request cannot be enabled, please set a default pickup address', 'mail-boxes-etc' );
2789 $this->helper->logErrorAndSetWpAdminMessage( $message );
2790 $logger->log( 'Default pickup address missing, disabling pickup' );
2791 }
2792 }
2793
2794 function mbe_eship_check_tax_and_duties_default_options() {
2795 $helper = new Mbe_Shipping_Helper_Data();
2796 $logger = new Mbe_Shipping_Helper_Logger();
2797 // Check if Activation flag exists and if the default value setter didn't already run
2798 if ( ! $helper->hasOption( Mbe_Shipping_Helper_Data::XML_PATH_TAX_DUTIES_ENABLED ) && $helper->getPermissionEnabledTaxAndDuties() ) {
2799 update_option( MBE_SCHEMA_FLAG_OPTION, 'yes' );
2800 $logger->log( 'Updating schema flag to run default value setter for Tax and Duties' );
2801 }
2802 }
2803
2804 function mbe_eship_add_tax_and_duties_fee($data) {
2805 $selectedMethod = WC()->session->get('chosen_shipping_methods');
2806 WC()->session->set( 'mbe_tax_and_duties_show_info_text', '');
2807
2808 if ( $this->helper->isMBEShippingMethod( $selectedMethod ) ) {
2809 $rateData = $this->getRateData( $selectedMethod[0] );
2810
2811 $rateMetaData = [];
2812 if(!empty($rateData)) {
2813 $rateMetaData = $rateData->get_meta_data() ?? [];
2814
2815 if ( ! empty( $rateMetaData ) ) {
2816 $customDutyGuaranteed = $rateMetaData['tax_and_duties_data']['custom_duties_guaranteed'] ?? false;
2817
2818 if ( $customDutyGuaranteed && $this->helper->addTaxAndDutiesToTotal() ) {
2819 WC()->session->set( 'mbe_tax_and_duties_show_info_text', 'DDP' );
2820 } else {
2821 WC()->session->set( 'mbe_tax_and_duties_show_info_text', 'DAP' );
2822 }
2823 WC()->session->set( 'mbe_tax_and_duties_info_text_value', $rateMetaData['tax_and_duties_data']['net_tax_and_duty_total_price'] ?? 0 );
2824 }
2825 }
2826
2827 }
2828 }
2829
2830 function mbe_show_tax_and_duties_checkout_message() {
2831 // If selected method is mbe and Tax&duty is not guaranteed or not DDP, show the message
2832 $taxAndDutiesDAP = WC()->session->get( 'mbe_tax_and_duties_show_info_text' ) ?? 'DAP';
2833 $taxAndDutiesValue = WC()->session->get( 'mbe_tax_and_duties_info_text_value' ) ?? null;
2834
2835 switch ( $taxAndDutiesDAP ) {
2836 case 'DAP':
2837 echo wp_kses_post( '<div style="font-size: 1rem; padding: 1rem; background: #eee;">
2838 ' . sprintf( __( 'As for all international shipments, customs requires a payment to clear goods through customs. It is a cost independent of our policies and tariffs. The <strong><span>%s</span></strong> figure shown may vary depending on the legislation of the country of destination.', 'mail-boxes-etc' ), wp_kses_post( wc_price( $taxAndDutiesValue ) ) ) . '
2839 </div>' );
2840 break;
2841 case 'DDP':
2842 echo wp_kses_post( '<div style="font-size: 1rem; padding: 1rem; background: #eee;">
2843 ' . sprintf( __( 'As with for all international shipments, customs requires a payment to clear goods through customs. It is a cost independent of our policies and tariffs, but the figure of <strong><span>%s</span></strong> charged ensures customs clearance, taken care of by us.', 'mail-boxes-etc' ), wp_kses_post( wc_price( $taxAndDutiesValue ) ) ) . '
2844 </div>' );
2845 break;
2846 default:
2847 break;
2848 }
2849 }
2850
2851 function mbe_eship_check_tax_and_duties() {
2852 if ( $this->helper->mustDisableTaxAndDuties() && $this->helper->isEnabledTaxAndDuties() ) {
2853 $this->helper->setEnabledTaxAndDuties( 0 );
2854 $this->helper->logErrorAndSetWCAdminMessage( __( 'Tax and Duties cannot be enabled, please check the pickup mode and courier and services settings', 'mail-boxes-etc' ), new Mbe_Shipping_Helper_Logger() );
2855 }
2856 }
2857
2858 public function wf_mbe_wooCommerce_shipping_hide_custom_order_meta_keys( $formatted_meta, $thisa ) {
2859 foreach ( $formatted_meta as $key => $meta ) {
2860 if ( in_array( $meta->key, array(
2861 Mbe_Shipping_Helper_Data::META_FIELD_DELIVERY_POINT_CUSTOM_DATA,
2862 Mbe_Shipping_Helper_Data::META_FIELD_DELIVERY_POINT_SHIPMENT,
2863 Mbe_Shipping_Helper_Data::META_FIELD_PICKUP_CUSTOM_DATA_ID,
2864 Mbe_Shipping_Helper_Data::META_FIELD_IS_PICKUP_SHIPPING,
2865 Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_MBE_STATUS,
2866 Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_RETURN_TRACKING_MBE_STATUS,
2867 Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_RETURN_TRACKING_NUMBER,
2868 Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_DEPARTMENTS_ADDRESS
2869 ) ) ) {
2870 unset( $formatted_meta[ $key ] );
2871 }
2872 }
2873
2874 return $formatted_meta;
2875 }
2876
2877 /**
2878 * @param array $shippingMethod
2879 *
2880 * @return bool
2881 */
2882 protected function isDeliveryPointServiceMethod( array $shippingMethod ): bool {
2883 $serviceOK = ! empty( preg_grep( '/^' . MBE_DELIVERY_POINT_SERVICE_METHOD . '/', $shippingMethod ) );
2884
2885 return $serviceOK;
2886 }
2887
2888 /**
2889 * @return array
2890 */
2891 protected function getShippingTaxPercentageFromCart(): float {
2892 $taxPercentage = 0;
2893 foreach ( WC()->cart->get_shipping_taxes() as $key => $shipping_tax ) {
2894 $taxPercentage += WC_Tax::get_rate_percent_value( $key );
2895 }
2896
2897 return $taxPercentage;
2898 }
2899
2900 protected function getRateData( $chosen_method_id ) {
2901 $found_rate = null;
2902 $packages = WC()->cart->get_shipping_packages();
2903
2904 foreach ( $packages as $package_key => $package ) {
2905 $shipping_for_package = WC()->session->get( 'shipping_for_package_' . $package_key );
2906
2907 if ( ! empty( $shipping_for_package['rates'][ $chosen_method_id ] ) ) {
2908 $found_rate = $shipping_for_package['rates'][ $chosen_method_id ];
2909 break;
2910 }
2911 }
2912
2913 return $found_rate;
2914 }
2915
2916 public function mbe_edit_department_address_data( $post_ids ) {
2917 if ( $this->helper->canSelectDepartmentForOrders() ) {
2918 // Open default data editor and create a row for the batch ( pre-fill with default values from MOL ) and link it to the selected orders
2919 $backPage = '&backpage=' . urlencode( WOOCOMMERCE_MBE_TABS_PAGE );
2920 wp_redirect( esc_url_raw( admin_url( 'admin.php?page=' . MBE_ESHIP_ID . '_department_address_data_tabs&orderids=' . urlencode( json_encode( $post_ids ) ) . $backPage . '&nonce=' . wp_create_nonce( 'mbe_select_department' ) ) ) );
2921 }
2922 }
2923
2924 public function department_address_data_form_page_handler() {
2925 $orderIds = isset( $_REQUEST['orderids'] ) ? json_decode( wc_clean( $_REQUEST['orderids'] ) ) : null;
2926 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2927 if ( ! empty( $orderIds )
2928 && isset( $_REQUEST['nonce'] )
2929 && (
2930 wp_verify_nonce( $_REQUEST['nonce'], 'mbe_select_department' )
2931 || wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) // check nonce for post back (save)
2932 )
2933 ) {
2934 if ( wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) ) {
2935 $departmentAddressId = sanitize_key( $_REQUEST['department_address_id'] );
2936 $failed = [];
2937 foreach ( $orderIds as $order_id ) {
2938 // get the old values to check if it needs to be updated
2939 $oldValue = $this->helper->getOrderDepartmentAddressId( $order_id );
2940 if ( $oldValue !== $departmentAddressId ) {
2941 // Update order's meta data
2942 if ( ! $this->helper->setOrderDepartmentAddressId( $order_id, $departmentAddressId ) ) {
2943 $failed[] = $order_id;
2944 }
2945 }
2946 }
2947 if ( count( $failed ) > 0 ) {
2948 $notice = __( 'There was an error while updating the orders: ', 'mail-boxes-etc' ) . implode( ',', $failed );
2949 } else {
2950 $this->helper->setWpAdminMessages( [
2951 'message' => __( 'Department data associated', 'mail-boxes-etc' ),
2952 'status' => 'success'
2953 ] );
2954 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
2955 exit;
2956 }
2957 }
2958
2959 \Metaboxes\DepartmentAddressData::add( MBE_ESHIP_ID . '_department_address_data_form_meta_box', 'department-address-data-selection' );
2960
2961 ?>
2962
2963 <div class="wrap">
2964 <div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
2965 <h2><?php esc_html_e( 'Department address selection', 'mail-boxes-etc' ) ?>
2966 <a class="add-new-h2"
2967 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ); ?>">
2968 <?php esc_html_e( 'Back to list', 'mail-boxes-etc' ) ?>
2969 </a>
2970 </h2>
2971
2972 <?php $this->mbe_eship_wp_notification() ?>
2973 <?php if ( ! empty( $notice ) ): ?>
2974 <div id="notice" class="notice notice-error is-dismissible">
2975 <p><?php echo wp_kses_post( $notice ) ?></p></div>
2976 <?php endif; ?>
2977 <?php if ( ! empty( $message ) ): ?>
2978 <div id="message" class="notice notice-success is-dismissible">
2979 <p><?php echo wp_kses_post( $message ) ?></p></div>
2980 <?php endif; ?>
2981 <form id="form" method="POST">
2982 <input type="hidden" name="nonce"
2983 value="<?php esc_attr_e( wp_create_nonce( basename( __FILE__ ) ) ) ?>"/>
2984 <!-- <input type="hidden" name="id" value="-->
2985 <?php //esc_attr_e($item['id']) ?><!--"-->
2986 <div class="metabox-holder" id="department-address-data-selection">
2987 <div id="post-body">
2988 <div id="post-body-content">
2989 <?php do_meta_boxes( 'department-address-data-selection', 'normal', $orderIds ) ?>
2990
2991 <input type="submit" value="<?php esc_html_e( 'Save', 'mail-boxes-etc' ) ?>"
2992 id="submit_save"
2993 class="button-primary" name="submit_save">
2994 </div>
2995 </div>
2996 </div>
2997 </form>
2998 </div>
2999 <?php
3000 } else {
3001 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
3002 }
3003 }
3004
3005 public function mbe_select_department_address_pickup() {
3006 $backPage = '&backpage=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
3007 $post_ids = array( (int) sanitize_key( $_REQUEST['mbe_pickup_postid'] ) );
3008
3009 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_select_department_address_pickup' ) && $this->helper->canSelectDepartmentForOrders() ) {
3010 wp_redirect( esc_url_raw( admin_url( 'admin.php?page=' . MBE_ESHIP_ID . '_department_address_data_tabs&orderids=' . urlencode( json_encode( $post_ids ) ) . $backPage . '&nonce=' . wp_create_nonce( 'mbe_select_department' ) ) ) );
3011 exit;
3012 }
3013 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
3014 }
3015
3016 }
3017 }
3018 new mbe_e_link_wooCommerce_shipping_setup();
3019
3020 }