PluginProbe
MBE eShip / 2.7.2
MBE eShip v2.7.2
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.7.2, at mail-boxes-etc.php

3,024 lines 134.3 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.7.2
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: 10.1
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 MBE Easy Duty 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_package_rates', array(
741 $this,
742 'wf_mbe_delivery_point_update_package_for_cost_recalculation'
743 ), 10, 2 );
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 MBE Easy Duty 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 MBE Easy Duty 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}\s*$/', '', $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 price parameter for GEL map initialization - manage taxes based on woocommerce settings
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 // Set the delivery point price adding taxes
1646 $deliveryPointPrices[ $key ] += $this->helper->round( $price * $taxPercentage / 100 );
1647 }
1648 }
1649 }
1650
1651 // Add the form field to the section and set value in case of delivery point selection price refresh
1652 echo '<div style="margin-bottom: 0.5em; padding-left: 20px;">';
1653 $sessionDeliveryPoint = WC()->session->get( 'mbe_delivery_point' ) ?? null;
1654 $gelProximitySelectionLabel = null;
1655 $gelProximitySelection = null;
1656
1657 if ( ! empty( $sessionDeliveryPoint ) ) {
1658 $gelProximitySelection = json_encode( (array) $sessionDeliveryPoint );
1659 $gelProximitySelectionLabel = $sessionDeliveryPoint->networkName . ', ' . $sessionDeliveryPoint->address . ', ' . $sessionDeliveryPoint->zipCode . ', ' . $sessionDeliveryPoint->city;
1660 }
1661
1662 woocommerce_form_field( 'gel-proximity-selection-label', array(
1663 'id' => 'gel-proximity-selection-label',
1664 'class' => 'woocommerce-validated',
1665 'type' => 'text',
1666 'required' => true,
1667 'custom_attributes' => array(
1668 'style' => 'font-size: 0.8em;',
1669 'readonly' => 'readonly',
1670 'onclick' => 'openGELProximityModal()'
1671 ),
1672 'placeholder' => __( 'Click to select a delivery point', 'mail-boxes-etc' ),
1673 ), $gelProximitySelectionLabel
1674 );
1675
1676 woocommerce_form_field( 'gel-proximity-selection', array(
1677 'type' => 'hidden',
1678 'id' => 'gel-proximity-selection',
1679 ), $gelProximitySelection
1680 );
1681
1682 woocommerce_form_field( 'gel-proximity-selection-update', array(
1683 'type' => 'hidden',
1684 'id' => 'gel-proximity-selection-update',
1685 ), false // alway set the field to false, tha value must be true only when posting from gel-proximity-map-initilization.js
1686 );
1687
1688 echo '<script type="text/javascript">
1689 mbeGelSDK.options.networks = ' . json_encode( $method->get_meta_data()['delivery_point_services']['courier'] ) . '
1690 mbeGelSDK.options.prices = ' . json_encode( $deliveryPointPrices ) . '
1691 </script>';
1692
1693 echo '</div>';
1694 }
1695
1696 }
1697
1698 function wf_mbe_delivery_point_validation( $data, $errors ) {
1699 if ( isset( $_POST['gel-proximity-selection'] ) && empty( $data['mbe_delivery_point_data'] ) ) {
1700 $errors->add( 'validation', __( 'Select a delivery point to proceed', 'mail-boxes-etc' ) );
1701 }
1702 }
1703
1704 function wf_mbe_delivery_point_show_meta_field( $order ) {
1705 $order_meta_delvery_point = $this->helper->getOrderDeliveryPointShipment( $order->get_id() );
1706 if ( ! empty( $order_meta_delvery_point ) ) {
1707 echo '<p><strong>' . esc_html__( 'Delivery Point' ) . ':</strong> ' . esc_html__( $order_meta_delvery_point, 'mail-boxes-etc' ) . '</p>';
1708 }
1709 }
1710
1711 function wf_mbe_delivery_point_set_meta_field( $order_id, $data ) {
1712 $logger = new Mbe_Shipping_Helper_Logger();
1713 $order = wc_get_order( $order_id );
1714 if ( $this->helper->isMbeShipping( $order ) ) {
1715 if ( ! empty( $data['mbe_delivery_point_data'] ) ) {
1716 $this->helper->setOrderDeliveryPointShipment( $order_id, 'Yes' );
1717 $this->helper->setOrderDeliveryPointCustomData( $order_id, $data['mbe_delivery_point_data'] );
1718 } else {
1719 $logger->log( __( 'Missing Access Point ID in $_POST' ) );
1720 $this->helper->setOrderDeliveryPointShipment( $order_id, 'No' );
1721 }
1722 $order->save();
1723 }
1724 }
1725
1726 function wf_mbe_delivery_point_update_package_for_cost_recalculation( $rates, $package ) {
1727 $deliveryPoint = WC()->session->get( 'mbe_delivery_point' ) ?? null;
1728 if ( ! empty( $deliveryPoint ) ) {
1729 $rateTaxes = $rates[WC()->session->get( 'chosen_shipping_methods' )[0]]->get_taxes();
1730 if ( wc_tax_enabled() && WC()->cart->display_prices_including_tax() && ! empty( $rateTaxes ) && ( WC()->session->get( 'mbe_delivery_point_update' ) ?? false ) ) {
1731 $logger = new Mbe_Shipping_Helper_Logger();
1732 $logger->logVar( $deliveryPoint, 'Delivery Point recalculation - removing taxes from map cost' );
1733 $deliveryPoint->cost = $this->helper->round( $this->helper->calculateNetPriceFromGross( $deliveryPoint->cost, $this->getShippingTaxPercentageFromCart($rateTaxes) ) );
1734 $logger->logVar( $deliveryPoint, 'Delivery Point recalculation - taxes removed from map cost' );
1735 WC()->session->set( 'mbe_delivery_point', $deliveryPoint );
1736 WC()->session->set( 'mbe_delivery_point_update', null );
1737 WC()->session->set( 'mbe_delivery_point_markup', $this->helper->getHandlingFee() );
1738 }
1739
1740 // Always check if the markup / handling fee has been changed (valid only in the same session) and update the delivery point cost and the session option
1741 if ( $this->helper->getHandlingFee() !== WC()->session->get( 'mbe_delivery_point_markup' ) ) {
1742 $deliveryPoint->cost = $deliveryPoint->cost - WC()->session->get( 'mbe_delivery_point_markup' ) + $this->helper->getHandlingFee();
1743 WC()->session->set( 'mbe_delivery_point', $deliveryPoint );
1744 WC()->session->set( 'mbe_delivery_point_markup', $this->helper->getHandlingFee() );
1745 }
1746
1747 $package['delivery_point'] = $deliveryPoint;
1748
1749 }
1750
1751 return $rates;
1752 }
1753
1754 function wf_mbe_delivery_point_set_meta_field_review( $data ) {
1755 $logger = new Mbe_Shipping_Helper_Logger();
1756 WC()->session->set( 'mbe_delivery_point', null );
1757 $postData = array();
1758 parse_str( $data, $postData );
1759 $deliveryPoint = json_decode( $postData['gel-proximity-selection'] ?? '' );
1760 $deliveryPointUpdate = json_decode( $postData['gel-proximity-selection-update'] ?? false );
1761
1762 if ( ! empty( $deliveryPoint ) && $this->isDeliveryPointServiceMethod( $postData['shipping_method'] ) ) {
1763 $logger->logVar( $deliveryPoint, 'Delivery point selection, refresh rates' );
1764 WC()->session->set( 'mbe_delivery_point', $deliveryPoint );
1765 WC()->session->set( 'mbe_delivery_point_update', $deliveryPointUpdate );
1766 }
1767
1768 // Check if the session variable is empty due to a json_decode() error and log an error
1769 if ( ! empty( $postData['gel-proximity-selection'] ) && empty( $deliveryPoint ) ) {
1770 $message = __( 'Possible issue with delivery point content/escaping. This delivery point cannot be correctly selected' );
1771 $logger->logVar( $postData['gel-proximity-selection'], $message );
1772 WC()->session->set( 'mbe_delivery_point', null ); // remove the delivery point to be sure it's not retaining an old value
1773 wc_add_notice( $message, 'error' );
1774 }
1775 }
1776
1777 function wf_mbe_delivery_point_set_shipping_address( $data ) {
1778 $logger = new Mbe_Shipping_Helper_Logger();
1779 // convert $data['shipping_method'] to array to avoid issues with empty (virtual products) or string values
1780 $shippingMethod = is_array( $data['shipping_method'] ) ? $data['shipping_method'] : [ $data['shipping_method'] ];
1781 $serviceOK = $this->isDeliveryPointServiceMethod( $shippingMethod );
1782 $logger->logVar( $shippingMethod, 'wf_mbe_wooCommerce_shipping_uap_address - Shipping Method' );
1783 if ( ! empty( $_POST['gel-proximity-selection'] ) && $serviceOK ) {
1784 $deliveryPointAddress = json_decode( stripslashes( $_POST['gel-proximity-selection'] ) );
1785 $logger->logVar( $deliveryPointAddress->code, 'wf_mbe_gel_delivery_point_set_shipping_address - GEL PUDO' );
1786 // Set the Delivery Point address as shipping address
1787 // $_POST['mbe_delivery_point_data'] = sanitize_text_field( $deliveryPointAddress->pickupPointId );
1788 $mbeDeliveryPointData = wp_json_encode( $deliveryPointAddress );
1789 $data['mbe_delivery_point_data'] = $mbeDeliveryPointData !== false ? $mbeDeliveryPointData : ''; // encode to json again to run some sanitization
1790 $data['shipping_company'] = sanitize_text_field( $deliveryPointAddress->description );
1791 $data['shipping_address_1'] = sanitize_text_field( $deliveryPointAddress->address );
1792 $data['shipping_postcode'] = sanitize_text_field( $deliveryPointAddress->zipCode );
1793 $data['shipping_city'] = sanitize_text_field( $deliveryPointAddress->city );
1794 $data['shipping_country'] = sanitize_text_field( $deliveryPointAddress->country );
1795 $data['shipping_state'] = array_search( ucfirst( strtolower( sanitize_text_field( $deliveryPointAddress->city ) ) ), WC()->countries->get_states( sanitize_text_field( $deliveryPointAddress->country ) ) );
1796 }
1797
1798 return $data;
1799 }
1800
1801 /**
1802 * Remove the delivery point session variable
1803 *
1804 * This method removes the custom WC_Session variable 'mbe_delivery_point' that is used to store
1805 * the selected delivery point during checkout process.
1806 *
1807 * @return void
1808 */
1809 function wf_mbe_remove_delivery_point_session_variable() {
1810 // Remove the custom WC_Session variable
1811 WC()->session->set( 'mbe_delivery_point', null );
1812 }
1813
1814 function wf_mbe_wooCommerce_shipping_custom_mapping_meta_field( $order_id ) {
1815 if ( $this->helper->isMbeShippingCustomMapping( $this->helper->getShippingMethod( wc_get_order( $order_id ) ) ) ) {
1816 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
1817 $order = wc_get_order( $order_id );
1818 $order->update_meta_data( Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_CUSTOM_MAPPING, 'yes' );
1819 $order->save();
1820 } else {
1821 update_post_meta( $order_id, Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_CUSTOM_MAPPING, 'yes' );
1822 }
1823 }
1824 }
1825
1826 function wf_mbe_wooCommerce_shipping_custom_mapping_meta_field_checkout_block( WC_Order $order ) {
1827 if ( $this->helper->isMbeShippingCustomMapping( $this->helper->getShippingMethod( $order ) ) ) {
1828 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
1829 $order->update_meta_data( Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_CUSTOM_MAPPING, 'yes' );
1830 $order->save();
1831 } else {
1832 update_post_meta( $order->get_id(), Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_CUSTOM_MAPPING, 'yes' );
1833 }
1834 }
1835 }
1836
1837
1838 function mbe_woocommerce_email_track_id( $order, $sent_to_admin, $plain_text, $email ) {
1839 $mailArray = [ 'customer_invoice', 'customer_completed_order' ];
1840 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
1841 $trackingUrl = $order === false? '' : $order->get_meta( Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_URL );
1842 } else {
1843 $trackingUrl = get_post_meta( $order->get_id(), Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_URL, true );
1844 }
1845
1846 $trackId = $this->helper->getTrackingsString( $order->get_id() );
1847 if ( ! empty( $trackId ) && in_array( $email->id, $mailArray ) && $this->helper->getTrackingSetting() ) {
1848 echo '<table id="track_id" style="width: 100%; vertical-align: top; margin-bottom: 40px; padding: 0px; border:0px; border-spacing: 0; border-collapse: collapse;">
1849 <tbody>
1850 <tr>
1851 <td style="vertical-align: top; width: 40%; text-align: left; font-family: \'Helvetica Neue\', Helvetica, Roboto, Arial, sans-serif; border: 0; padding: 0;">
1852 <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>
1853 </td>
1854 </tr>
1855 <tr>
1856 <td style="vertical-align: top; width: 40%; text-align: left; font-family: \'Helvetica Neue\', Helvetica, Roboto, Arial, sans-serif; border: 0; padding: 0;">
1857 <strong>' . esc_html__( 'Tracking id: ', 'mail-boxes-etc' ) . '</strong>
1858 </td>
1859 <td style="vertical-align: top; width: 40%; text-align: left; font-family: \'Helvetica Neue\', Helvetica, Roboto, Arial, sans-serif; border: 0; padding: 0;">
1860 <a href="' . esc_url_raw( $trackingUrl . $trackId ) . '">
1861 ' . esc_html( $trackId ) . '
1862 </a>
1863 </td>
1864 </tr>
1865 </tbody>
1866 </table>';
1867 }
1868 }
1869
1870 function mbe_add_query_vars( $vars ) {
1871 $vars[] = "mbe_filetype";
1872
1873 return $vars;
1874 }
1875
1876 public function mbe_download_standard_package_file() {
1877 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_standard_package_file' ) ) {
1878 $fileType = sanitize_text_field( $_GET['mbe_filetype'] );
1879
1880 switch ( $fileType ) {
1881 case 'package':
1882 $this->helper->mbe_download_file( $this->helper->getCurrentCsvPackagesDir() );
1883 break;
1884 case 'package-template':
1885 $this->helper->mbe_download_file( $this->helper->getCsvTemplatePackagesDir() );
1886 break;
1887 case 'package-product':
1888 $this->helper->mbe_download_file( $this->helper->getCurrentCsvPackagesProductDir() );
1889 break;
1890 case 'package-product-template':
1891 $this->helper->mbe_download_file( $this->helper->getCsvTemplatePackagesProductDir() );
1892 break;
1893 default:
1894 break;
1895 }
1896 }
1897 }
1898
1899 public function mbe_download_shipping_file() {
1900 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_shipping_file' ) ) {
1901 $fileType = sanitize_text_field( $_GET['mbe_filetype'] );
1902
1903 switch ( $fileType ) {
1904 case 'shipping':
1905 $this->helper->mbe_download_file( $this->helper->getShipmentsCsvFileDir() );
1906 break;
1907 case 'shipping-template':
1908 $this->helper->mbe_download_file( $this->helper->getShipmentsCsvTemplateFileDir() );
1909 break;
1910 default:
1911 break;
1912 }
1913 }
1914 }
1915
1916 public function mbe_download_log_files() {
1917 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_log_files' ) ) {
1918 $zipfilepath = trailingslashit( $this->helper->getMbeLogDir() ) . 'log.zip';
1919 $wslogfilepath = $this->helper->getLogWsPath();
1920 $pluginfilepath = $this->helper->getLogPluginPath();
1921 $logZip = new \ZipArchive();
1922 if ( $logZip->open( $zipfilepath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE ) === true ) {
1923 $logZip->addFile( $wslogfilepath, substr( $wslogfilepath, strrpos( $wslogfilepath, '/' ) + 1 ) );
1924 $logZip->addFile( $pluginfilepath, substr( $pluginfilepath, strrpos( $pluginfilepath, '/' ) + 1 ) );
1925 if ( $logZip->count() > 0 && $logZip->close() ) {
1926 $this->helper->mbe_download_file( $zipfilepath, 'mbe_log.zip', 'application/zip', true );
1927 }
1928 }
1929 $logZip = null;
1930 error_log( __( 'MBE Download log - files not found' ) );
1931 }
1932 exit;
1933 }
1934
1935
1936 public function mbe_delete_log_files() {
1937 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_delete_log_files' ) ) {
1938 try {
1939 $wslogfilepath = $this->helper->getLogWsPath();
1940 $pluginfilepath = $this->helper->getLogPluginPath();
1941 if ( file_exists( $wslogfilepath ) ) {
1942 wp_delete_file( $wslogfilepath );
1943 }
1944 if ( file_exists( $pluginfilepath ) ) {
1945 wp_delete_file( $pluginfilepath );
1946 }
1947 } catch ( \Exception $e ) {
1948 error_log( __( 'MBE Delete log - Unexpected error' ) . ' - ' . $e->getMessage() );
1949 }
1950 }
1951 wp_redirect( wp_get_referer() );
1952 }
1953
1954
1955 public function mbe_goto_advanced_login() {
1956 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_goto_advanced_login' ) ) {
1957 $this->helper->setLoginMode( false );
1958 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_LOGIN_LINK_ADV, true );
1959 }
1960 wp_redirect( wp_get_referer() );
1961 }
1962
1963 public function mbe_sign_in() {
1964 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_sign_in' ) ) {
1965 $mbeUser = $_GET[ MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_MBE_USERNAME ];
1966 $mbePwd = $_GET[ MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_MBE_PASSWORD ];
1967 $mbeCountry = $_GET[ MBE_ESHIP_ID . '_' . Mbe_Shipping_Helper_Data::XML_PATH_COUNTRY ];
1968 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_LOGIN_LINK_ADV, false );
1969
1970 if ( ! empty( $mbePwd ) && ! empty( $mbeUser ) ) {
1971 // Set the option in case it wasn't saved before
1972 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_MBE_USERNAME, hash('sha256', $mbeUser) );
1973 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_MBE_PASSWORD, password_hash($mbePwd, PASSWORD_DEFAULT) );
1974 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_COUNTRY, $mbeCountry );
1975 $this->helper->setWsUrl( $mbeCountry );
1976
1977 if ( $this->mbe_generate_api_key($mbeUser, $mbePwd) ) {
1978 // set advanced
1979 $this->helper->setLoginMode( false );
1980 update_option( 'mbe_shipping_admin_messages', [
1981 'message' => urlencode( __( 'Logged in', 'mail-boxes-etc' ) ),
1982 'status' => urlencode( 'success' )
1983 ] );
1984 } else {
1985 update_option( 'mbe_shipping_admin_messages', [
1986 'message' => urlencode( __( 'Error Logging in. Please enable debug and check the log files for more details', 'mail-boxes-etc' ) ),
1987 'status' => urlencode( 'error' )
1988 ] );
1989 }
1990 } else {
1991 update_option( 'mbe_shipping_admin_messages', [
1992 'message' => urlencode( __( 'Missing MBE Online Login Information', 'mail-boxes-etc' ) ),
1993 'status' => urlencode( 'error' )
1994 ] );
1995 }
1996 }
1997
1998 wp_redirect( wp_get_referer() );
1999 }
2000
2001 public function mbe_reset_login() {
2002 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_reset_login' ) ) {
2003 $logger = new Mbe_Shipping_Helper_Logger();
2004
2005 $this->helper->setLoginMode();
2006 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_WS_USERNAME, '' );
2007 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_WS_PASSWORD, '' );
2008 $this->helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_WS_URL, '' );
2009
2010 // delete the api key so it will be regenerated by the control hooked on plugin save
2011 $user_id = username_exists( MBE_WC_REST_API_USERNAME );
2012 if ( $user_id && email_exists( MBE_WC_REST_API_USER_EMAIL ) ) {
2013 $logger->log( 'Reset login - Delete Api Key' );
2014 $this->helper->removeMbeRestApiKey( $user_id );
2015 }
2016 }
2017 wp_redirect( wp_get_referer() );
2018 }
2019
2020 public function mbe_generate_api_key($mbeUser, $mbePwd) {
2021 $logger = new Mbe_Shipping_Helper_Logger();
2022 $logger->log( 'MBE Generate API KEY - Start' );
2023 $status = 'success';
2024 try {
2025 $ws = new MbeWs( true );
2026 $response = $ws->generateApiKey( $mbeUser, $mbePwd );
2027 if ( ! empty( $response ) ) {
2028 $this->helper->setWsUsername( $response->apiKey );
2029 $this->helper->setWsPassword( $response->apiSecret );
2030 $logger->log( 'MBE Generate API KEY - Done' );
2031 $message = __( 'eShip credentials generated correctly', 'mail-boxes-etc' );
2032 } else {
2033 $logger->log( 'MBE Generate API KEY - Empty response' );
2034 $message = __( 'eShip credentials not generated - Empty response', 'mail-boxes-etc' );
2035 $status = 'error';
2036 }
2037
2038 } catch ( \Exception $e ) {
2039 $logger->log( __( 'MBE Generate API KEY' ) . ' - ' . $e->getMessage() );
2040 $message = __( 'eShip credentials not generated. Check the log files for more details', 'mail-boxes-etc' );
2041 $status = 'error';
2042 }
2043 update_option( 'mbe_shipping_admin_messages', [
2044 'message' => urlencode( $message ),
2045 'status' => urlencode( $status )
2046 ] );
2047
2048 if ( $status === 'success' ) {
2049 return true;
2050 } else {
2051 return false;
2052 }
2053 // wp_redirect(wp_get_referer());
2054
2055 }
2056
2057 public function mbe_shipping_admin_notices() {
2058 // Manage WC environment notification
2059 $apiKeyMessage = maybe_unserialize( get_option( 'mbe_shipping_admin_messages' ) );
2060 if ( ! empty( $apiKeyMessage ) ) {
2061 $messageStatus = urldecode( $apiKeyMessage['status'] );
2062 $messageText = urldecode( $apiKeyMessage['message'] );
2063 if ( $messageStatus === 'error' ) {
2064 WC_Admin_Settings::add_error( $messageText );
2065 } else {
2066 WC_Admin_Settings::add_message( $messageText );
2067 }
2068 }
2069 delete_option( 'mbe_shipping_admin_messages' );
2070 }
2071
2072 // Set the local pickup default data
2073 public function mbe_woocommerce_get_pickup_default_data() {
2074 $ws = new Mbe_Shipping_Model_Ws();
2075 // get MOL default data
2076 $pickupData = $ws->getPickupDefaultData();
2077 // set local default data
2078 $this->helper->setLocalPickupDefaultData( $pickupData );
2079 }
2080
2081 // Send the local pickup default data to MOL
2082 public function mbe_woocommerce_set_pickup_default_data() {
2083 $ws = new Mbe_Shipping_Model_Ws();
2084 $ws->setPickupDefaultData( $this->helper->getLocalPickupDefaultData() );
2085 }
2086
2087 public function mbe_download_pickup_manifest() {
2088 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_pickup_manifest' ) ) {
2089 $ws = new Mbe_Shipping_Model_Ws();
2090 $logger = new Mbe_Shipping_Helper_Logger();
2091 try {
2092 $postId = sanitize_text_field( $_REQUEST['mbe_pickup_postid'] );
2093
2094 if ( ! $this->helper->isPickupShipped( $postId ) ) {
2095 throw new \MbeExceptions\ValidationException( __( 'Please select only pickup batches', 'mail-boxes-etc' ) );
2096 }
2097
2098 if ( ! $this->helper->hasTracking( $postId ) ) {
2099 throw new \MbeExceptions\ValidationException( sprintf( __( 'Order %s does not have a tracking number', 'mail-boxes-etc' ), $postId ) );
2100 }
2101
2102 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
2103 $order = wc_get_order( $postId );
2104 $masterTrackingNumber = $order===false?'':$order->get_meta(Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_NUMBER);
2105 } else {
2106 $masterTrackingNumber = get_post_meta( $postId, Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_NUMBER, true );
2107 }
2108
2109 $response = $ws->getPickupManifest( $masterTrackingNumber );
2110
2111 $outputPdf = $response->Label->Stream;
2112 $outputPdfPath = $this->helper->mbeUploadDir() . DIRECTORY_SEPARATOR . current_datetime()->getTimestamp() . rand( 0, 999 ) . '.pdf';
2113
2114 if ( file_put_contents( $outputPdfPath, $outputPdf ) !== false ) {
2115 $this->helper->mbe_download_file( $outputPdfPath, "pickup_manifest_$postId.pdf", 'application/pdf', true );
2116 } else {
2117 $errMess = __( 'MBE Download pickup manifest - no document to download', 'mail-boxes-etc' );
2118 $this->helper->logErrorAndSetWpAdminMessage( $errMess, $logger );
2119 }
2120 } catch ( \MbeExceptions\ValidationException $e ) {
2121 $errMess = __( 'MBE Download pickup manifest - ' . $e->getMessage(), 'mail-boxes-etc' );
2122 $this->helper->logErrorAndSetWpAdminMessage( $errMess, $logger );
2123 } catch ( \Exception $e ) {
2124 $errMess = __( 'MBE Download pickup manifest - Unexpected error', 'mail-boxes-etc' ) . ' - ' . $e->getMessage();
2125 $this->helper->logErrorAndSetWpAdminMessage( $errMess, $logger );
2126 }
2127 }
2128 wp_redirect( wp_get_referer() );
2129 }
2130
2131 public function mbe_download_delivery_point_waybill() {
2132 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_download_delivery_point_waybill' ) ) {
2133 $ws = new Mbe_Shipping_Model_Ws();
2134 $logger = new Mbe_Shipping_Helper_Logger();
2135 try {
2136 $postId = sanitize_text_field( $_REQUEST['mbe_delivery_point_postid'] );
2137
2138 if ( ! $this->helper->isDeliveryPointOrder( $postId ) ) {
2139 throw new \MbeExceptions\ValidationException( __( 'Please select only delivery point orders', 'mail-boxes-etc' ) );
2140 }
2141
2142 if ( ! $this->helper->hasTracking( $postId ) ) {
2143 throw new \MbeExceptions\ValidationException( sprintf( __( 'Order %s does not have a tracking number', 'mail-boxes-etc' ), $postId ) );
2144 }
2145
2146 if ( \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
2147 $order = wc_get_order( $postId );
2148 $masterTrackingNumber = $order===false?'':$order->get_meta(Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_NUMBER);
2149 } else {
2150 $masterTrackingNumber = get_post_meta( $postId, Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_NUMBER, true );
2151 }
2152
2153 $response = $ws->getDeliveryPointShippingDocument( $masterTrackingNumber );
2154
2155 if ( $response !== false && empty( $response->Errors ) ) {
2156 $outputPdf = file_get_contents( $response->CourierWaybill ); // load the remote pdf
2157 $outputPdfPath = $this->helper->mbeUploadDir() . DIRECTORY_SEPARATOR . current_datetime()->getTimestamp() . rand( 0, 999 ) . '.pdf';
2158
2159 if ( file_put_contents( $outputPdfPath, $outputPdf ) !== false ) {
2160 $this->helper->mbe_download_file( $outputPdfPath, "delivery_point_waybill_$postId.pdf", 'application/pdf', true );
2161 } else {
2162 $errMsg = __( 'Download waybill - no document to download. Please, retry later', 'mail-boxes-etc' );
2163 $this->helper->logErrorAndSetWpAdminMessage( $errMsg, $logger );
2164 }
2165 } else {
2166 $errMsg = __( "Download waybill", 'mail-boxes-etc' ) . " $postId - " . __( $response->Errors->Error->Description ?? '', 'mail-boxes-etc' );
2167 $this->helper->logErrorAndSetWpAdminMessage( $errMsg, $logger );
2168 }
2169 } catch ( \MbeExceptions\ValidationException $e ) {
2170 $errMess = __( 'Download waybill - ' . $e->getMessage(), 'mail-boxes-etc' );
2171 $this->helper->logErrorAndSetWpAdminMessage( $errMess, $logger );
2172 } catch ( \MbeExceptions\ShippingDocumentException $e ) {
2173 $errMsg = sprintf( __( "Download waybill", 'mail-boxes-etc' ) . " - " . __( "%s", 'mail-boxes-etc' ), $e->getMessage() );
2174 $this->helper->logErrorAndSetWpAdminMessage( $errMsg, $logger );
2175 } catch ( \Exception $e ) {
2176 $errMess = __( 'MBE Download pickup manifest - Unexpected error', 'mail-boxes-etc' ) . ' - ' . $e->getMessage();
2177 $this->helper->logErrorAndSetWpAdminMessage( $errMess, $logger );
2178 }
2179 }
2180 wp_redirect( wp_get_referer() );
2181 }
2182
2183 public function mbe_eship_wp_notification() {
2184 // Manage WP environment notification
2185 $wpAdminMessages = maybe_unserialize( get_option( 'mbe_shipping_wp_admin_messages' ) ) ?: [];
2186 delete_option( 'mbe_shipping_wp_admin_messages' );
2187 $printf = '';
2188 foreach ( $wpAdminMessages as $adminMessage ) {
2189 $messageStatus = urldecode( $adminMessage['status'] ?? '' );
2190 $messageText = urldecode( $adminMessage['message'] );
2191 switch ( $messageStatus ) {
2192 case 'error':
2193 $printf .= printf( '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Error' ) . ': %s</p></div>', esc_html( $messageText ) );
2194 break;
2195 case 'warning':
2196 $printf .= printf( '<div class="notice notice-warning is-dismissible"><p>%s</p></div>', esc_html( $messageText ) );
2197 break;
2198 default:
2199 $printf .= printf( '<div class="notice notice-info is-dismissible"><p>%s</p></div>', esc_html( $messageText ) );
2200 break;
2201 }
2202 }
2203
2204 return $printf;
2205 }
2206
2207 function csv_form_page_handler() {
2208 if ( isset( $_REQUEST['nonce'] ) && ( wp_verify_nonce( $_REQUEST['nonce'], 'csv_form_page_handler' ) || wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) ) ) {
2209
2210 global $wpdb;
2211
2212 $csvType = wc_clean( $_REQUEST['csv'] ) ?: null;
2213 $requestId = wc_clean( $_REQUEST['id'] ) ?: null;
2214 $csvFactory = new Mbe_Csv_Editor_Model_Factory();
2215 $csv = $csvFactory->create( $csvType );
2216 if ( ! empty( $csv ) ) {
2217 $message = '';
2218 $notice = '';
2219 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : 'woocommerce_mbe_csv_tabs&csv=' . $csvType . '&nonce=' . wp_create_nonce( 'woocommerce_mbe_csv_tabs' ) );
2220
2221 // default $item data to be used for new records
2222 $default = $csv->get_defaults();
2223
2224 $table_name = $csv->get_tablename();
2225
2226 // check post back and correct nonce
2227 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) ) {
2228 // combine default and request params
2229 $item = shortcode_atts( $default, $_REQUEST );
2230 // data validation
2231 $item_valid = $csv->validate_row( $item );
2232 try {
2233 if ( $item_valid === true ) {
2234 $ws = new Mbe_Shipping_Model_Ws();
2235 $result = true;
2236 if ( empty( $item[ $csv->get_ID() ] ) ) {
2237 do_action( MBE_ESHIP_ID . '_csv_editor_adding', $item );
2238 if ( ! $csv->get_isRemote() ) {
2239 $result = $wpdb->insert( $table_name, $item ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
2240 $item[ $csv->get_ID() ] = $wpdb->insert_id;
2241 } else {
2242 // 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)
2243 // set result = false if it fails
2244 }
2245 if ( $result !== false ) {
2246 $message = __( 'Item successfully saved', 'mail-boxes-etc' );
2247 do_action( MBE_ESHIP_ID . '_csv_editor_added', $item );
2248 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage . '&message=' . urlencode( $message ) ) ) );
2249 exit;
2250 } else {
2251 $notice = __( 'There was an error while saving the item', 'mail-boxes-etc' ) . ': ' . $wpdb->last_error;
2252 }
2253 } else {
2254 do_action( MBE_ESHIP_ID . '_csv_editor_updating', $item );
2255 if ( ! $csv->get_isRemote() ) {
2256 $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
2257 } else {
2258 // Todo : check value online = item - create a validateItem in class that extend Mbe_Shipping_Csv_Editor (eg.Mbe_Shipping_Csv_Editor_Pickup_Addresses)
2259 // set result = false if it fails
2260 }
2261 if ( $result !== false ) {
2262 $message = __( 'Item successfully updated', 'mail-boxes-etc' );
2263 do_action( MBE_ESHIP_ID . '_csv_editor_updated', $item );
2264 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' ) ) );
2265 } else {
2266 $notice = __( 'There was an error while updating the item', 'mail-boxes-etc' ) . ': ' . $wpdb->last_error;
2267 }
2268 }
2269 } else {
2270 $notice = $item_valid;
2271 }
2272 } catch ( Exception $e ) {
2273 $notice = $e->getMessage();
2274 }
2275 } else {
2276 $item = $default;
2277 if ( isset( $requestId ) ) {
2278 if ( $csv->get_isRemote() ) {
2279 $item = $csv->get_remoteRow( $requestId );
2280 } else {
2281 $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
2282 }
2283 if ( ! $item ) {
2284 $item = $default;
2285 // $notice = __( 'Item not found', 'mail-boxes-etc' );
2286 }
2287 }
2288 }
2289
2290 // custom meta box is a method of $csv class
2291 add_meta_box( MBE_ESHIP_ID . '_csv_form_meta_box', $csv->get_title(),
2292 array( $csv, 'form_meta_box_handler' ),
2293 'csv-' . $csvType, 'normal', 'default' );
2294 ?>
2295
2296 <div class="wrap">
2297 <div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
2298 <h2><?php esc_html_e( 'Edit' ) . ' ' . $csv->get_title( false ) ?>
2299 <a class="add-new-h2"
2300 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ); ?>">
2301 <?php esc_html_e( 'Back to list', 'mail-boxes-etc' ) ?>
2302 </a>
2303 </h2>
2304
2305 <?php $this->mbe_eship_wp_notification() ?>
2306 <?php if ( ! empty( $notice ) ): ?>
2307 <div id="notice" class="notice notice-error is-dismissible">
2308 <p><?php echo wp_kses_post( $notice ) ?></p></div>
2309 <?php endif; ?>
2310 <?php if ( ! empty( $message ) ): ?>
2311 <div id="message" class="notice notice-success is-dismissible">
2312 <p><?php echo wp_kses_post( $message ) ?></p></div>
2313 <?php endif; ?>
2314
2315 <form id="form" method="POST">
2316 <input type="hidden" name="nonce"
2317 value="<?php esc_attr_e( wp_create_nonce( basename( __FILE__ ) ) ) ?>"/>
2318 <?php /* storing id to check if we need to add or update the item */ ?>
2319 <input type="hidden" name="id" value="<?php esc_attr_e( $item[ $csv->get_ID() ] ) ?>"/>
2320
2321 <div class="metabox-holder" id="poststuff">
2322 <div id="post-body">
2323 <div id="post-body-content">
2324 <?php /* render meta box */ ?>
2325 <?php do_meta_boxes( 'csv-' . $csvType, 'normal', $item ); ?>
2326 <input type="submit" value="<?php esc_attr_e( 'Save', 'mail-boxes-etc' ) ?>"
2327 id="submit"
2328 class="button-primary" name="submit">
2329 </div>
2330 </div>
2331 </div>
2332 </form>
2333 </div>
2334 <?php
2335 } else {
2336 ?>
2337 <div class="wrap">
2338 <h2><?php esc_html_e( 'Missing or wrong csv type', 'mail-boxes-etc' ) ?>
2339 <a class="add-new-h2"
2340 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' ) ); ?>">
2341 <?php esc_html_e( 'Back to settings', 'mail-boxes-etc' ) ?>
2342 </a>
2343 </h2>
2344 </div>
2345 <?php
2346 }
2347 } else {
2348 wp_redirect( wp_get_referer() );
2349 }
2350 }
2351
2352 public function pickup_data_form_page_handler() {
2353
2354 $pickupModel = new Mbe_Shipping_Model_Pickup_Custom_Data();
2355 $orderIds = isset( $_REQUEST['orderids'] ) ? json_decode( wc_clean( $_REQUEST['orderids'] ) ) : null;
2356 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2357 if ( ! empty( $orderIds )
2358 && isset( $_REQUEST['nonce'] )
2359 && (
2360 wp_verify_nonce( $_REQUEST['nonce'], 'mbe_edit_pickup' )
2361 || wp_verify_nonce( $_REQUEST['nonce'], 'mbe_pickup_return_from_address' )
2362 || wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) )
2363 )
2364 ) {
2365 $message = '';
2366 $notice = '';
2367 // $backPage = 'page=' . (isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE);
2368
2369 // default $item pickup data to be used for new records,
2370 // get local ones to avoid a call to the WS since very probably data will be verified and updated
2371 $default = $this->helper->getLocalPickupDefaultData();
2372
2373 // initialize the row id to be merged while editing an existing row
2374 $default['id'] = null;
2375
2376 // check Post back and correct nonce
2377 $requestId = wc_clean( $_REQUEST['id'] ?? null );
2378 if ( wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) ) {
2379 $default['date'] = '';
2380 $default['pickup_address_id'] = '';
2381 $default['pickup_batch_id'] = null;
2382
2383 $item = shortcode_atts( $default, $_REQUEST );
2384
2385 $item_valid = $pickupModel->validate_row( $item );
2386
2387 if ( $item_valid === true ) {
2388 // Save the custom pickup data
2389 $batchId = null;
2390 // If not updating
2391 if ( empty( $requestId ) ) {
2392 if ( count( $orderIds ) > 1 ) {
2393 $now = current_datetime();
2394 $batchId = $this->helper->getWsUsername() . '_' . $now->getTimestamp();
2395 $item['pickup_batch_id'] = $batchId;
2396 }
2397
2398 // Additional check to avoid creating a new custom data row if orders are already linked to pickup data
2399 $list = [];
2400 foreach ( $orderIds as $orderId ) {
2401 if ( ! empty( $this->helper->getOrderPickupBatchId( $orderId ) ) ) {
2402 $list[] = $orderId;
2403 }
2404 }
2405 if ( ! empty( $list ) ) {
2406 $errMess = sprintf( __( 'The orders %s are already linked to pickup data' ), implode( ',', $list ) );
2407 $this->helper->logErrorAndSetWpAdminMessage( $errMess );
2408 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
2409 exit;
2410 }
2411
2412 // Insert pickup custom data row
2413 $pickupCustomDataId = $pickupModel->insertRow( $item );
2414
2415 // Set order items meta fields
2416 foreach ( $orderIds as $orderId ) {
2417 // Additional check to avoid updating field for already existing shipments
2418 if ( ! $this->helper->hasTracking( $orderId ) ) {
2419 $this->helper->setOrderPickupCustomDataId( $orderId, $pickupCustomDataId );
2420 $this->helper->setOrderPickupBatchId( $orderId, $batchId );
2421 }
2422 }
2423 $action = 'created';
2424 } else {
2425 // Update the custom pickup data
2426 $pickupModel->updateRow( $item['id'], $item );
2427 $batchId = $item['pickup_batch_id'];
2428 $action = 'updated';
2429 }
2430 // Updating the backpage to the pickup batch list to show the newly created batch, but not if we have a single shipment
2431 // if(count($orderIds)>1) {
2432 $backPage = 'page=' . MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE;
2433 // }
2434
2435 if ( isset( $_REQUEST['submit_save'] ) ) {
2436 $this->helper->setWpAdminMessages( [
2437 'message' => urlencode( sprintf( __( 'The pickup %s has been %s', 'mail-boxes-etc' ), ( ! empty( $batchId ) ? 'batch ' . $batchId : '' ), __( $action, 'mail-boxes-etc' ) ) ),
2438 'status' => urlencode( 'success' )
2439 ] );
2440 } elseif ( isset( $_REQUEST['submit_savesend'] ) ) {
2441 $this->createPickup( $orderIds );
2442 }
2443 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
2444 exit;
2445 } else {
2446 $notice = $item_valid;
2447 }
2448 } else {
2449 $item = $default;
2450
2451 if ( isset( $requestId ) ) {
2452 $item = $pickupModel->getRow( $requestId );
2453 if ( ! $item ) {
2454 $item = $default;
2455 // $notice = __( 'Item not found', 'mail-boxes-etc' );
2456 }
2457 }
2458 }
2459
2460 $item['order_ids'] = is_array( $orderIds ) ? $orderIds : [ $orderIds ];
2461
2462 add_meta_box( MBE_ESHIP_ID . '_pickup_data_form_meta_box',
2463 ' ',
2464 array( $pickupModel, 'form_meta_box' ),
2465 'pickup-data-editor', 'normal', 'default'
2466 );
2467 ?>
2468 <div class="wrap">
2469 <div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
2470 <h2><?php esc_html_e( 'Pickup orders management', 'mail-boxes-etc' ) ?>
2471 <a class="add-new-h2"
2472 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ); ?>">
2473 <?php esc_html_e( 'Back to list', 'mail-boxes-etc' ) ?>
2474 </a>
2475 </h2>
2476
2477 <?php $this->mbe_eship_wp_notification() ?>
2478 <?php if ( ! empty( $notice ) ): ?>
2479 <div id="notice" class="notice notice-error is-dismissible">
2480 <p><?php echo wp_kses_post( $notice ) ?></p></div>
2481 <?php endif; ?>
2482 <?php if ( ! empty( $message ) ): ?>
2483 <div id="message" class="notice notice-success is-dismissible">
2484 <p><?php echo wp_kses_post( $message ) ?></p></div>
2485 <?php endif; ?>
2486 <form id="form" method="POST">
2487 <input type="hidden" name="nonce"
2488 value="<?php esc_attr_e( wp_create_nonce( basename( __FILE__ ) ) ) ?>"/>
2489 <input type="hidden" name="id" value="<?php esc_attr_e( $item['id'] ) ?>"
2490 <div class="metabox-holder" id="poststuff">
2491 <div id="post-body">
2492 <div id="post-body-content">
2493 <?php do_meta_boxes( 'pickup-data-editor', 'normal', $item ) ?>
2494 </div>
2495 </div>
2496 </div>
2497 </form>
2498 </div>
2499 <?php
2500 } else {
2501 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
2502 }
2503 }
2504
2505
2506 public function mbe_edit_pickup_data( $post_ids ) {
2507 if ( $this->helper->getPickupRequestEnabled() ) {
2508 switch ( $this->helper->getPickupRequestMode() ) {
2509 case Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_MANUAL :
2510 // 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
2511 $backPage = '&backpage=' . urlencode( WOOCOMMERCE_MBE_TABS_PAGE );
2512 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' ) ) ) );
2513 break;
2514 case Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_AUTOMATIC :
2515 $this->createPickup( $post_ids );
2516 wp_redirect( esc_url_raw( admin_url( 'admin.php?page=' . WOOCOMMERCE_MBE_TABS_PAGE ) ) );
2517 break;
2518 }
2519 }
2520 }
2521
2522
2523 public function mbe_delete_pickup_custom_data() {
2524 $logger = new \Mbe_Shipping_Helper_Logger();
2525 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_delete_pickup_custom_data' ) ) {
2526 global $wpdb;
2527 $id = wc_clean( $_REQUEST['id'] );
2528 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2529
2530 $pickupCustomData = new Mbe_Shipping_Model_Pickup_Custom_Data();
2531 $row = $pickupCustomData->getRow( $id );
2532
2533 // if ( 'ready' === strtolower( $row['status'] ) && isset( $row['pickup_batch_id'] ) ) {
2534 if ( 'ready' === strtolower( $row['status'] ) ) {
2535 // Detach all the order linked
2536 $selectOrderIds = $this->helper->select_pickup_orders_ids( $id );
2537 $orders = $wpdb->get_results( $selectOrderIds, ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
2538 $orderIds = array_map( 'absint', array_column( $orders, 'order_id' ) );
2539 $notDetached = [];
2540 foreach ( $orderIds as $orderId ) {
2541 if ( ! $this->helper->detachOrderFromPickupBatch( $orderId ) ) {
2542 $notDetached[] = $orderId;
2543 }
2544 }
2545 if ( empty( $notDetached ) ) {
2546 // Delete the custom data row
2547 $pickupCustomData->deleteRow( $id );
2548 } else {
2549 $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 ) );
2550 $this->helper->logErrorAndSetWpAdminMessage( $message, $logger );
2551 }
2552
2553 }
2554
2555 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
2556 }
2557 }
2558
2559 public function mbe_detach_order_from_batch() {
2560 $logger = new \Mbe_Shipping_Helper_Logger();
2561
2562 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_detach_order_from_batch' ) ) {
2563 $orderId = sanitize_text_field( $_REQUEST['mbe_pickup_postid'] );
2564 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2565 $pickupCustomDataId = $this->helper->getOrderPickupCustomDataId( $orderId );
2566
2567 if ( $this->helper->detachOrderFromPickupBatch( $orderId ) ) {
2568 do_action( MBE_ESHIP_ID . '_after_detach', $pickupCustomDataId );
2569 } else {
2570 $message = sprintf( __( 'Order %d cannot be detached as it is a shipped pickup', 'mail-boxes-etc' ), $orderId );
2571 $this->helper->logErrorAndSetWpAdminMessage( $message, $logger );
2572 }
2573 }
2574 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
2575 }
2576
2577 /**
2578 * Delete pickup batch if there are no items left
2579 *
2580 * @return void
2581 */
2582 // public function mbe_after_detach_check_pickup_batch_items($batchId) {
2583 // $pickupCustomData = new Mbe_Shipping_Model_Pickup_Custom_Data();
2584 //
2585 // if(empty($pickupCustomData->getBatchIdOrders($batchId))) {
2586 // $pickupCustomData->deleteRow( $pickupCustomData->getBatchIdRow($batchId)->id );
2587 // }
2588 // }
2589
2590 /**
2591 * Delete pickup if there are no items left
2592 *
2593 * @return void
2594 */
2595 public function mbe_after_detach_check_pickup_items( $pickupCustomDataId ) {
2596 $pickupCustomData = new Mbe_Shipping_Model_Pickup_Custom_Data();
2597
2598 if ( empty( $pickupCustomData->getPickupIdOrders( $pickupCustomDataId ) ) ) {
2599 $pickupCustomData->deleteRow( $pickupCustomDataId );
2600 }
2601 }
2602
2603
2604 public function mbe_send_pickup() {
2605 $logger = new \Mbe_Shipping_Helper_Logger();
2606 $logger->log( 'Send pickup Action - Start' );
2607 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2608 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_send_pickup' ) && isset( $_REQUEST['mbe_pickup_id'] ) && $this->helper->getPickupRequestEnabled() ) {
2609 $logger->log( 'Send pickup Action - Create pickup' );
2610 global $wpdb;
2611 $pickupCustomDataId = sanitize_text_field( $_REQUEST['mbe_pickup_id'] );
2612 $pickupCustomData = new Mbe_Shipping_Model_Pickup_Custom_Data();
2613 $hasPickupBatch = ! empty( $pickupCustomData->getRow( $pickupCustomDataId )['pickup_batch_id'] );
2614
2615 // $orders = $wpdb->get_results( $this->helper->select_pickup_batch_orders_ids( $pickupBatchId ), ARRAY_A );
2616 $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
2617 $orderIds = array_map( 'absint', array_column( $orders, 'order_id' ) );
2618 $this->createPickup( $orderIds, $hasPickupBatch );
2619 }
2620 if ( ! $this->helper->getPickupRequestEnabled() ) {
2621 $message = __( 'Pickup request cannot be enabled, please check the settings', 'mail-boxes-etc' );
2622 $this->helper->logErrorAndSetWpAdminMessage( $message, $logger );
2623 }
2624 $logger->log( 'Send pickup Action - End' );
2625 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
2626 }
2627
2628 public function mbe_create_return_shipment() {
2629 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2630 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_create_return_shipment' ) && isset( $_REQUEST['mbe_post_id'] ) ) {
2631 $orderId = array_map( 'absint', (array) sanitize_text_field( $_REQUEST['mbe_post_id'] ) );
2632 $this->createReturnShipment( $orderId );
2633 }
2634 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
2635 }
2636
2637 public function mbe_woocommerce_get_advanced_return_address_data( $post_id ) {
2638 if ( $this->helper->canAdvancedReturn() ) {
2639 // Open the address data editor and create the return shipment
2640 $backPage = '&backpage=' . urlencode( WOOCOMMERCE_MBE_TABS_PAGE );
2641 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' ) ) ) );
2642 }
2643 }
2644
2645 public function advanced_return_address_data_form_page_handler() {
2646
2647 $orderId = isset( $_REQUEST['orderid'] ) ? wc_clean( $_REQUEST['orderid'] ) : null;
2648 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2649 if ( ! empty( $orderId )
2650 && isset( $_REQUEST['nonce'] )
2651 && (
2652 wp_verify_nonce( $_REQUEST['nonce'], 'mbe_edit_advanced_return_address_data' )
2653 || wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) // check nonce for post back (save)
2654 )
2655 ) {
2656 if ( wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) ) {
2657
2658 // Check Privince field
2659 $senderProvince = sanitize_text_field( $_POST['sender_province'] );
2660 $receiverProvince = sanitize_text_field( $_POST['receiver_province'] );
2661 $senderProvinceIsEmptyForItaly = $this->helper->getCountry() === 'IT' && empty( $senderProvince );
2662 $senderProvinceIsNotTwoChar = $senderProvince && ! strlen( $senderProvince ) == 2;
2663 $receiverProvinceIsEmptyForItaly = $this->helper->getCountry() === 'IT' && empty( $receiverProvince );
2664 $receiverProvinceIsNotTwoChar = $receiverProvince && ! strlen( $receiverProvince ) == 2;
2665
2666 try {
2667
2668 if ( $senderProvinceIsEmptyForItaly || $receiverProvinceIsEmptyForItaly || $senderProvinceIsNotTwoChar || $receiverProvinceIsNotTwoChar ) {
2669 throw new Exception( __( "The field \"Province\" must not exceed 2 characters.", 'mail-boxes-etc' ) );
2670 }
2671
2672 $returnData =
2673 array(
2674 'sender_trade_name' => sanitize_text_field( $_POST['sender_trade_name'] ),
2675 'sender_address_1' => sanitize_text_field( $_POST['sender_address_1'] ),
2676 'sender_address_2' => sanitize_text_field( $_POST['sender_address_2'] ),
2677 'sender_address_3' => sanitize_text_field( $_POST['sender_address_3'] ),
2678 'sender_postcode' => sanitize_text_field( $_POST['sender_postcode'] ),
2679 'sender_city' => sanitize_text_field( $_POST['sender_city'] ),
2680 'sender_province' => $senderProvince,
2681 'sender_country' => sanitize_text_field( $_POST['sender_country'] ),
2682 'sender_reference' => sanitize_text_field( $_POST['sender_reference'] ),
2683 'sender_telephone_1' => sanitize_text_field( $_POST['sender_telephone_1'] ),
2684 'sender_telephone_2' => sanitize_text_field( $_POST['sender_telephone_2'] ),
2685 'sender_email_1' => sanitize_email( $_POST['sender_email_1'] ),
2686 'sender_email_2' => sanitize_email( $_POST['sender_email_2'] ),
2687 'sender_fax' => sanitize_text_field( $_POST['sender_fax'] ),
2688 'receiver_trade_name' => sanitize_text_field( $_POST['receiver_trade_name'] ),
2689 'receiver_address_1' => sanitize_text_field( $_POST['receiver_address_1'] ),
2690 'receiver_address_2' => sanitize_text_field( $_POST['receiver_address_2'] ),
2691 'receiver_address_3' => sanitize_text_field( $_POST['receiver_address_3'] ),
2692 'receiver_postcode' => sanitize_text_field( $_POST['receiver_postcode'] ),
2693 'receiver_city' => sanitize_text_field( $_POST['receiver_city'] ),
2694 'receiver_province' => $receiverProvince,
2695 'receiver_country' => sanitize_text_field( $_POST['receiver_country'] ),
2696 'receiver_reference' => sanitize_text_field( $_POST['receiver_reference'] ),
2697 'receiver_telephone_1' => sanitize_text_field( $_POST['receiver_telephone_1'] ),
2698 'receiver_telephone_2' => sanitize_text_field( $_POST['receiver_telephone_2'] ),
2699 'receiver_email_1' => sanitize_email( $_POST['receiver_email_1'] ),
2700 'receiver_email_2' => sanitize_email( $_POST['receiver_email_2'] ),
2701 'receiver_fax' => sanitize_text_field( $_POST['receiver_fax'] ),
2702 'pickup_date' => sanitize_text_field( $_POST['pickup_date'] ),
2703 'pickup_time_preferred_from' => sanitize_text_field( $_POST['pickup_time_preferred_from'] ),
2704 'pickup_time_preferred_to' => sanitize_text_field( $_POST['pickup_time_preferred_to'] ),
2705 'pickup_time_alternative_from' => sanitize_text_field( $_POST['pickup_time_alternative_from'] ),
2706 'pickup_time_alternative_to' => sanitize_text_field( $_POST['pickup_time_alternative_to'] ),
2707 'pickup_notes' => sanitize_text_field( $_POST['pickup_notes'] ),
2708 );
2709
2710
2711 $result = $this->createAdvancedReturnShipment( $orderId, $returnData );
2712 if ( $result ) {
2713 $this->helper->setWpAdminMessages( [ 'message' => __( 'Return shipment created' ) ] );
2714 }
2715
2716 } catch ( Exception $e ) {
2717 $this->helper->setWpAdminMessages( [
2718 'message' => __( 'Return shipment', 'mail-boxes-etc' ) . ' - ' . __( $e->getMessage(), 'mail-boxes-etc' ),
2719 'status' => 'error'
2720 ] );
2721 }
2722
2723 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
2724 exit;
2725 }
2726
2727 \Metaboxes\AdvancedReturnAddressData::add( MBE_ESHIP_ID . '_advanced_return_address_data_form_meta_box', 'advanced-return-address-data-meta-box' );
2728
2729 ?>
2730 <div class="wrap">
2731 <?php $this->mbe_eship_wp_notification() ?>
2732
2733 <div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
2734 <h2><?php esc_html_e( 'Return address data', 'mail-boxes-etc' ) ?>
2735 <a class="add-new-h2"
2736 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ); ?>">
2737 <?php esc_html_e( 'Back to list', 'mail-boxes-etc' ) ?>
2738 </a>
2739 </h2>
2740
2741 <form id="form" method="POST">
2742 <input type="hidden" name="nonce"
2743 value="<?php esc_attr_e( wp_create_nonce( basename( __FILE__ ) ) ) ?>"/>
2744 <!-- <input type="hidden" name="id" value="-->
2745 <?php //esc_attr_e($item['id']) ?><!--"-->
2746 <div class="metabox-holder" id="advanced-return-address-data-meta-box">
2747 <div id="post-body">
2748 <div id="post-body-content">
2749 <?php do_meta_boxes( 'advanced-return-address-data-meta-box', 'normal', $orderId ) ?>
2750
2751 <table style="width: 100%; margin-top: 20px;">
2752 <tbody>
2753 <tr>
2754 <td colspan="2">
2755 <div style="float:right;">
2756 <a class="button button-secondary"
2757 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ); ?>">
2758 <?php esc_html_e( 'Cancel', 'mail-boxes-etc' ) ?>
2759 </a>
2760 <input type="submit"
2761 value="<?php esc_attr_e( 'Save and send', 'mail-boxes-etc' ); ?>"
2762 class="button button-primary">
2763 </div>
2764 </td>
2765 </tr>
2766 </tbody>
2767 </table>
2768
2769 </div>
2770 </div>
2771 </div>
2772 </form>
2773 </div>
2774 <?php
2775 } else {
2776 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
2777 }
2778 }
2779
2780 public function mbe_after_delete_pickup_address_disable_pickup_if_no_default_address( $ids, $csvType ) {
2781 $logger = new \Mbe_Shipping_Helper_Logger();
2782 $helper = new Mbe_Shipping_Helper_Data();
2783 if ( 'pickup-addresses' === $csvType
2784 && ! $helper->hasDefaultPickupAddress()
2785 && $helper->getPickupRequestEnabled()
2786 && $helper->getPickupRequestMode() === Mbe_Shipping_Helper_Data::MBE_PICKUP_REQUEST_AUTOMATIC
2787 ) {
2788 $helper->setOption( Mbe_Shipping_Helper_Data::XML_PATH_PICKUP_REQUEST_ENABLED, 0 );
2789 $message = __( 'Pickup request cannot be enabled, please set a default pickup address', 'mail-boxes-etc' );
2790 $this->helper->logErrorAndSetWpAdminMessage( $message );
2791 $logger->log( 'Default pickup address missing, disabling pickup' );
2792 }
2793 }
2794
2795 function mbe_eship_check_tax_and_duties_default_options() {
2796 $helper = new Mbe_Shipping_Helper_Data();
2797 $logger = new Mbe_Shipping_Helper_Logger();
2798 // Check if Activation flag exists and if the default value setter didn't already run
2799 if ( ! $helper->hasOption( Mbe_Shipping_Helper_Data::XML_PATH_TAX_DUTIES_ENABLED ) && $helper->getPermissionEnabledTaxAndDuties() ) {
2800 update_option( MBE_SCHEMA_FLAG_OPTION, 'yes' );
2801 $logger->log( 'Updating schema flag to run default value setter for MBE Easy Duty' );
2802 }
2803 }
2804
2805 function mbe_eship_add_tax_and_duties_fee($data) {
2806 $selectedMethod = WC()->session->get('chosen_shipping_methods');
2807 WC()->session->set( 'mbe_tax_and_duties_show_info_text', '');
2808
2809 if ( $this->helper->isMBEShippingMethod( $selectedMethod ) ) {
2810 $rateData = $this->getRateData( $selectedMethod[0] );
2811
2812 $rateMetaData = [];
2813 if(!empty($rateData)) {
2814 $rateMetaData = $rateData->get_meta_data() ?? [];
2815
2816 if ( ! empty( $rateMetaData ) ) {
2817 $customDutyGuaranteed = $rateMetaData['tax_and_duties_data']['custom_duties_guaranteed'] ?? false;
2818
2819 if ( $customDutyGuaranteed && $this->helper->addTaxAndDutiesToTotal() ) {
2820 WC()->session->set( 'mbe_tax_and_duties_show_info_text', 'DDP' );
2821 } else {
2822 WC()->session->set( 'mbe_tax_and_duties_show_info_text', 'DAP' );
2823 }
2824 WC()->session->set( 'mbe_tax_and_duties_info_text_value', $rateMetaData['tax_and_duties_data']['net_tax_and_duty_total_price'] ?? 0 );
2825 }
2826 }
2827
2828 }
2829 }
2830
2831 function mbe_show_tax_and_duties_checkout_message() {
2832 if ($this->helper->isEnabledTaxAndDuties()) {
2833 // If the selected method is mbe and Tax&duty is not guaranteed or not DDP, show the message
2834 $taxAndDutiesDAP = WC()->session->get( 'mbe_tax_and_duties_show_info_text' ) ?? 'DAP';
2835 $taxAndDutiesValue = WC()->session->get( 'mbe_tax_and_duties_info_text_value' ) ?? null;
2836
2837 switch ( $taxAndDutiesDAP ) {
2838 case 'DAP':
2839 echo wp_kses_post( '<div style="font-size: 1rem; padding: 1rem; background: #eee;">
2840 ' . 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 ) ) ) . '
2841 </div>' );
2842 break;
2843 case 'DDP':
2844 echo wp_kses_post( '<div style="font-size: 1rem; padding: 1rem; background: #eee;">
2845 ' . 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 ) ) ) . '
2846 </div>' );
2847 break;
2848 default:
2849 break;
2850 }
2851 }
2852 }
2853
2854 function mbe_eship_check_tax_and_duties() {
2855 if ( $this->helper->mustDisableTaxAndDuties() && $this->helper->isEnabledTaxAndDuties() ) {
2856 $this->helper->setEnabledTaxAndDuties( 0 );
2857 $this->helper->logErrorAndSetWCAdminMessage( __( 'MBE Easy Duty cannot be enabled, please check the pickup mode and courier and services settings', 'mail-boxes-etc' ), new Mbe_Shipping_Helper_Logger() );
2858 }
2859 }
2860
2861 public function wf_mbe_wooCommerce_shipping_hide_custom_order_meta_keys( $formatted_meta, $thisa ) {
2862 foreach ( $formatted_meta as $key => $meta ) {
2863 if ( in_array( $meta->key, array(
2864 Mbe_Shipping_Helper_Data::META_FIELD_DELIVERY_POINT_CUSTOM_DATA,
2865 Mbe_Shipping_Helper_Data::META_FIELD_DELIVERY_POINT_SHIPMENT,
2866 Mbe_Shipping_Helper_Data::META_FIELD_PICKUP_CUSTOM_DATA_ID,
2867 Mbe_Shipping_Helper_Data::META_FIELD_IS_PICKUP_SHIPPING,
2868 Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_TRACKING_MBE_STATUS,
2869 Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_RETURN_TRACKING_MBE_STATUS,
2870 Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_RETURN_TRACKING_NUMBER,
2871 Mbe_Shipping_Helper_Data::SHIPMENT_SOURCE_DEPARTMENTS_ADDRESS
2872 ) ) ) {
2873 unset( $formatted_meta[ $key ] );
2874 }
2875 }
2876
2877 return $formatted_meta;
2878 }
2879
2880 /**
2881 * @param array $shippingMethod
2882 *
2883 * @return bool
2884 */
2885 protected function isDeliveryPointServiceMethod( array $shippingMethod ): bool {
2886 $serviceOK = ! empty( preg_grep( '/^' . MBE_DELIVERY_POINT_SERVICE_METHOD . '/', $shippingMethod ) );
2887
2888 return $serviceOK;
2889 }
2890
2891 /**
2892 * @return array
2893 */
2894 protected function getShippingTaxPercentageFromCart($taxes = null): float {
2895 $taxPercentage = 0;
2896 $rateTaxes = !empty(WC()->cart->get_shipping_taxes()) ? WC()->cart->get_shipping_taxes() : $taxes;
2897 foreach ($rateTaxes as $key => $shipping_tax ) {
2898 $taxPercentage += WC_Tax::get_rate_percent_value( $key );
2899 }
2900
2901 return $taxPercentage;
2902 }
2903
2904 protected function getRateData( $chosen_method_id ) {
2905 $found_rate = null;
2906 $packages = WC()->cart->get_shipping_packages();
2907
2908 foreach ( $packages as $package_key => $package ) {
2909 $shipping_for_package = WC()->session->get( 'shipping_for_package_' . $package_key );
2910
2911 if ( ! empty( $shipping_for_package['rates'][ $chosen_method_id ] ) ) {
2912 $found_rate = $shipping_for_package['rates'][ $chosen_method_id ];
2913 break;
2914 }
2915 }
2916
2917 return $found_rate;
2918 }
2919
2920 public function mbe_edit_department_address_data( $post_ids ) {
2921 if ( $this->helper->canSelectDepartmentForOrders() ) {
2922 // 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
2923 $backPage = '&backpage=' . urlencode( WOOCOMMERCE_MBE_TABS_PAGE );
2924 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' ) ) ) );
2925 }
2926 }
2927
2928 public function department_address_data_form_page_handler() {
2929 $orderIds = isset( $_REQUEST['orderids'] ) ? json_decode( wc_clean( $_REQUEST['orderids'] ) ) : null;
2930 $backPage = 'page=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
2931 if ( ! empty( $orderIds )
2932 && isset( $_REQUEST['nonce'] )
2933 && (
2934 wp_verify_nonce( $_REQUEST['nonce'], 'mbe_select_department' )
2935 || wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) // check nonce for post back (save)
2936 )
2937 ) {
2938 if ( wp_verify_nonce( $_REQUEST['nonce'], basename( __FILE__ ) ) ) {
2939 $departmentAddressId = sanitize_key( $_REQUEST['department_address_id'] );
2940 $failed = [];
2941 foreach ( $orderIds as $order_id ) {
2942 // get the old values to check if it needs to be updated
2943 $oldValue = $this->helper->getOrderDepartmentAddressId( $order_id );
2944 if ( $oldValue !== $departmentAddressId ) {
2945 // Update order's meta data
2946 if ( ! $this->helper->setOrderDepartmentAddressId( $order_id, $departmentAddressId ) ) {
2947 $failed[] = $order_id;
2948 }
2949 }
2950 }
2951 if ( count( $failed ) > 0 ) {
2952 $notice = __( 'There was an error while updating the orders: ', 'mail-boxes-etc' ) . implode( ',', $failed );
2953 } else {
2954 $this->helper->setWpAdminMessages( [
2955 'message' => __( 'Department data associated', 'mail-boxes-etc' ),
2956 'status' => 'success'
2957 ] );
2958 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
2959 exit;
2960 }
2961 }
2962
2963 \Metaboxes\DepartmentAddressData::add( MBE_ESHIP_ID . '_department_address_data_form_meta_box', 'department-address-data-selection' );
2964
2965 ?>
2966
2967 <div class="wrap">
2968 <div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
2969 <h2><?php esc_html_e( 'Department address selection', 'mail-boxes-etc' ) ?>
2970 <a class="add-new-h2"
2971 href="<?php echo esc_url( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ); ?>">
2972 <?php esc_html_e( 'Back to list', 'mail-boxes-etc' ) ?>
2973 </a>
2974 </h2>
2975
2976 <?php $this->mbe_eship_wp_notification() ?>
2977 <?php if ( ! empty( $notice ) ): ?>
2978 <div id="notice" class="notice notice-error is-dismissible">
2979 <p><?php echo wp_kses_post( $notice ) ?></p></div>
2980 <?php endif; ?>
2981 <?php if ( ! empty( $message ) ): ?>
2982 <div id="message" class="notice notice-success is-dismissible">
2983 <p><?php echo wp_kses_post( $message ) ?></p></div>
2984 <?php endif; ?>
2985 <form id="form" method="POST">
2986 <input type="hidden" name="nonce"
2987 value="<?php esc_attr_e( wp_create_nonce( basename( __FILE__ ) ) ) ?>"/>
2988 <!-- <input type="hidden" name="id" value="-->
2989 <?php //esc_attr_e($item['id']) ?><!--"-->
2990 <div class="metabox-holder" id="department-address-data-selection">
2991 <div id="post-body">
2992 <div id="post-body-content">
2993 <?php do_meta_boxes( 'department-address-data-selection', 'normal', $orderIds ) ?>
2994
2995 <input type="submit" value="<?php esc_html_e( 'Save', 'mail-boxes-etc' ) ?>"
2996 id="submit_save"
2997 class="button-primary" name="submit_save">
2998 </div>
2999 </div>
3000 </div>
3001 </form>
3002 </div>
3003 <?php
3004 } else {
3005 wp_redirect( esc_url_raw( admin_url( 'admin.php?' . $backPage ) ) );
3006 }
3007 }
3008
3009 public function mbe_select_department_address_pickup() {
3010 $backPage = '&backpage=' . ( isset( $_REQUEST['backpage'] ) ? sanitize_text_field( $_REQUEST['backpage'] ) : MBE_ESHIP_ID . '_' . WOOCOMMERCE_MBE_TABS_PICKUP_PAGE );
3011 $post_ids = array( (int) sanitize_key( $_REQUEST['mbe_pickup_postid'] ) );
3012
3013 if ( isset( $_REQUEST['nonce'] ) && wp_verify_nonce( $_REQUEST['nonce'], 'mbe_select_department_address_pickup' ) && $this->helper->canSelectDepartmentForOrders() ) {
3014 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' ) ) ) );
3015 exit;
3016 }
3017 wp_redirect( esc_url_raw( get_admin_url( get_current_blog_id(), 'admin.php?' . $backPage ) ) );
3018 }
3019
3020 }
3021 }
3022 new mbe_e_link_wooCommerce_shipping_setup();
3023
3024 }