PluginProbe
Packeta / 1.3.1
Packeta v1.3.1
2.3.2 2.3.1 trunk 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.3.0 1.3.1 1.3.2 1.4 1.4.1 1.4.2 1.4.3 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 All 56 releases
packeta / src / Packetery / Module / Plugin.php

Plugin.php in Packeta 1.3.1, at src/Packetery/Module/Plugin.php

877 lines 25.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Main Packeta plugin class.
4 *
5 * @package Packetery
6 */
7
8 declare( strict_types=1 );
9
10 namespace Packetery\Module;
11
12 use Packetery\Core\Log\ILogger;
13 use Packetery\Core\Log\Record;
14 use Packetery\Module\Carrier\Downloader;
15 use Packetery\Module\Carrier\OptionsPage;
16 use Packetery\Module\Carrier\Repository;
17 use Packetery\Module\Log;
18 use Packetery\Module\Options;
19 use Packetery\Module\Order;
20 use Packetery\Module\Product;
21 use PacketeryLatte\Engine;
22 use PacketeryNette\Http\Request;
23 use WC_Order;
24
25 /**
26 * Class Plugin
27 *
28 * @package Packetery
29 */
30 class Plugin {
31
32 public const VERSION = '1.3.1';
33 public const DOMAIN = 'packeta';
34 public const MIN_LISTENER_PRIORITY = -9998;
35
36 /**
37 * Options page.
38 *
39 * @var Options\Page Options page,
40 */
41 private $options_page;
42
43 /**
44 * PacketeryLatte engine.
45 *
46 * @var Engine
47 */
48 private $latte_engine;
49
50 /**
51 * Carrier downloader object.
52 *
53 * @var Downloader
54 */
55 private $carrier_downloader;
56
57 /**
58 * Carrier repository.
59 *
60 * @var Repository
61 */
62 private $carrierRepository;
63
64 /**
65 * Country options page.
66 *
67 * @var OptionsPage
68 */
69 private $carrierOptionsPage;
70
71 /**
72 * Path to main plugin file.
73 *
74 * @var string Path to main plugin file.
75 */
76 private $main_file_path;
77
78 /**
79 * Admin edit order page Packeta metabox.
80 *
81 * @var Order\Metabox
82 */
83 private $order_metabox;
84
85 /**
86 * Message manager.
87 *
88 * @var MessageManager
89 */
90 private $message_manager;
91
92 /**
93 * Checkout object.
94 *
95 * @var Checkout
96 */
97 private $checkout;
98
99 /**
100 * Order BulkActions.
101 *
102 * @var Order\BulkActions
103 */
104 private $orderBulkActions;
105
106 /**
107 * Label printing.
108 *
109 * @var Order\LabelPrint
110 */
111 private $labelPrint;
112
113 /**
114 * Order collection printing.
115 *
116 * @var Order\CollectionPrint
117 */
118 private $orderCollectionPrint;
119
120 /**
121 * Order grid extender.
122 *
123 * @var Order\GridExtender
124 */
125 private $gridExtender;
126
127 /**
128 * Product tab.
129 *
130 * @var Product\DataTab
131 */
132 private $productTab;
133
134 /**
135 * Log page.
136 *
137 * @var Log\Page
138 */
139 private $logPage;
140
141 /**
142 * Log manager.
143 *
144 * @var ILogger
145 */
146 private $logger;
147
148 /**
149 * Order controller.
150 *
151 * @var Order\Controller
152 */
153 private $orderController;
154
155 /**
156 * Order modal.
157 *
158 * @var Order\Modal
159 */
160 private $orderModal;
161
162 /**
163 * Options exporter.
164 *
165 * @var Options\Exporter
166 */
167 private $exporter;
168
169 /**
170 * Packet synchronizer.
171 *
172 * @var Order\PacketSynchronizer
173 */
174 private $packetSynchronizer;
175
176 /**
177 * Request.
178 *
179 * @var Request
180 */
181 private $request;
182
183 /**
184 * Order repository.
185 *
186 * @var Order\Repository
187 */
188 private $orderRepository;
189
190 /**
191 * Plugin upgrade.
192 *
193 * @var Upgrade
194 */
195 private $upgrade;
196
197 /**
198 * QueryProcessor.
199 *
200 * @var QueryProcessor
201 */
202 private $queryProcessor;
203
204 /**
205 * Log repository.
206 *
207 * @var Log\Repository
208 */
209 private $logRepository;
210
211 /**
212 * Options provider.
213 *
214 * @var Options\Provider
215 */
216 private $optionsProvider;
217
218 /**
219 * Plugin constructor.
220 *
221 * @param Order\Metabox $order_metabox Order metabox.
222 * @param MessageManager $message_manager Message manager.
223 * @param Options\Page $options_page Options page.
224 * @param Repository $carrierRepository Carrier repository.
225 * @param Downloader $carrier_downloader Carrier downloader object.
226 * @param Checkout $checkout Checkout class.
227 * @param Engine $latte_engine PacketeryLatte engine.
228 * @param OptionsPage $carrierOptionsPage Carrier options page.
229 * @param Order\BulkActions $orderBulkActions Order BulkActions.
230 * @param Order\LabelPrint $labelPrint Label printing.
231 * @param Order\GridExtender $gridExtender Order grid extender.
232 * @param Product\DataTab $productTab Product tab.
233 * @param Log\Page $logPage Log page.
234 * @param ILogger $logger Log manager.
235 * @param Order\Controller $orderController Order controller.
236 * @param Order\Modal $orderModal Order modal.
237 * @param Options\Exporter $exporter Options exporter.
238 * @param Order\CollectionPrint $orderCollectionPrint Order collection print.
239 * @param Order\PacketSynchronizer $packetSynchronizer Packet synchronizer.
240 * @param Request $request HTTP request.
241 * @param Order\Repository $orderRepository Order repository.
242 * @param Upgrade $upgrade Plugin upgrade.
243 * @param QueryProcessor $queryProcessor QueryProcessor.
244 * @param Log\Repository $logRepository Log repository.
245 * @param Options\Provider $optionsProvider Options provider.
246 */
247 public function __construct(
248 Order\Metabox $order_metabox,
249 MessageManager $message_manager,
250 Options\Page $options_page,
251 Repository $carrierRepository,
252 Downloader $carrier_downloader,
253 Checkout $checkout,
254 Engine $latte_engine,
255 OptionsPage $carrierOptionsPage,
256 Order\BulkActions $orderBulkActions,
257 Order\LabelPrint $labelPrint,
258 Order\GridExtender $gridExtender,
259 Product\DataTab $productTab,
260 Log\Page $logPage,
261 ILogger $logger,
262 Order\Controller $orderController,
263 Order\Modal $orderModal,
264 Options\Exporter $exporter,
265 Order\CollectionPrint $orderCollectionPrint,
266 Order\PacketSynchronizer $packetSynchronizer,
267 Request $request,
268 Order\Repository $orderRepository,
269 Upgrade $upgrade,
270 QueryProcessor $queryProcessor,
271 Log\Repository $logRepository,
272 Options\Provider $optionsProvider
273 ) {
274 $this->options_page = $options_page;
275 $this->latte_engine = $latte_engine;
276 $this->carrierRepository = $carrierRepository;
277 $this->carrier_downloader = $carrier_downloader;
278 $this->main_file_path = PACKETERY_PLUGIN_DIR . '/packeta.php';
279 $this->order_metabox = $order_metabox;
280 $this->message_manager = $message_manager;
281 $this->checkout = $checkout;
282 $this->carrierOptionsPage = $carrierOptionsPage;
283 $this->orderBulkActions = $orderBulkActions;
284 $this->labelPrint = $labelPrint;
285 $this->gridExtender = $gridExtender;
286 $this->productTab = $productTab;
287 $this->logPage = $logPage;
288 $this->logger = $logger;
289 $this->orderController = $orderController;
290 $this->orderModal = $orderModal;
291 $this->exporter = $exporter;
292 $this->orderCollectionPrint = $orderCollectionPrint;
293 $this->packetSynchronizer = $packetSynchronizer;
294 $this->request = $request;
295 $this->orderRepository = $orderRepository;
296 $this->upgrade = $upgrade;
297 $this->queryProcessor = $queryProcessor;
298 $this->logRepository = $logRepository;
299 $this->optionsProvider = $optionsProvider;
300 }
301
302 /**
303 * Method to register hooks
304 */
305 public function run(): void {
306 add_action( 'init', [ $this, 'loadTranslation' ] );
307
308 if ( ! self::isWooCommercePluginActive() ) {
309 add_action( 'admin_notices', [ $this, 'echoInactiveWooCommerceNotice' ] );
310
311 return;
312 }
313
314 add_action( 'init', [ $this->upgrade, 'check' ] );
315 add_action( 'init', [ $this->logger, 'register' ] );
316 add_action( 'init', [ $this->message_manager, 'init' ] );
317 add_action( 'rest_api_init', [ $this->orderController, 'registerRoutes' ] );
318
319 add_action( 'admin_enqueue_scripts', array( $this, 'enqueueAdminAssets' ) );
320 add_action( 'wp_enqueue_scripts', [ $this, 'enqueueFrontAssets' ] );
321
322 add_action(
323 'admin_notices',
324 function () {
325 $this->message_manager->render( MessageManager::RENDERER_WORDPRESS );
326 },
327 self::MIN_LISTENER_PRIORITY
328 );
329 add_action( 'init', array( $this, 'init' ) );
330
331 register_activation_hook( $this->main_file_path, array( $this, 'activate' ) );
332
333 // TODO: deactivation_hook.
334 register_deactivation_hook(
335 $this->main_file_path,
336 static function () {
337 }
338 );
339
340 register_uninstall_hook( $this->main_file_path, array( __CLASS__, 'uninstall' ) );
341
342 add_action( 'woocommerce_email_footer', array( $this, 'render_email_footer' ) );
343 add_filter( 'woocommerce_shipping_methods', array( $this, 'add_shipping_method' ) );
344
345 add_filter( 'views_edit-shop_order', [ $this->gridExtender, 'addFilterLinks' ] );
346 add_action( 'restrict_manage_posts', [ $this->gridExtender, 'renderOrderTypeSelect' ] );
347 $this->queryProcessor->register();
348
349 add_filter( 'manage_edit-shop_order_columns', [ $this->gridExtender, 'addOrderListColumns' ] );
350 add_action( 'manage_shop_order_posts_custom_column', [ $this->gridExtender, 'fillCustomOrderListColumns' ] );
351
352 add_filter( 'woocommerce_order_data_store_cpt_get_orders_query', [ $this->upgrade, 'handleCustomQueryVar' ], 10, 2 );
353
354 add_action( 'admin_menu', array( $this, 'add_menu_pages' ) );
355 add_action( 'admin_head', array( $this->labelPrint, 'hideFromMenus' ) );
356 add_action( 'admin_head', array( $this->orderCollectionPrint, 'hideFromMenus' ) );
357 $this->orderModal->register();
358 $this->order_metabox->register();
359
360 $this->checkout->register_hooks();
361 $this->productTab->register();
362
363 add_action(
364 'packetery_cron_carriers_hook',
365 function () {
366 $this->carrier_downloader->runAndRender();
367 }
368 );
369 if ( ! wp_next_scheduled( 'packetery_cron_carriers_hook' ) ) {
370 wp_schedule_event( time(), 'daily', 'packetery_cron_carriers_hook' );
371 }
372
373 // TODO: Packet status sync.
374 wp_clear_scheduled_hook( 'packetery_cron_packet_status_sync_hook' );
375
376 add_action( 'woocommerce_admin_order_data_after_shipping_address', [ $this, 'renderDeliveryDetail' ] );
377 add_action( 'woocommerce_order_details_after_order_table', [ $this, 'renderOrderDetail' ] );
378
379 // Adding custom actions to dropdown in admin order list.
380 add_filter( 'bulk_actions-edit-shop_order', [ $this->orderBulkActions, 'addActions' ], 20, 1 );
381 // Execute the action for selected orders.
382 add_filter(
383 'handle_bulk_actions-edit-shop_order',
384 [
385 $this->orderBulkActions,
386 'handleActions',
387 ],
388 10,
389 3
390 );
391 // Print packets export result.
392 add_action( 'admin_notices', [ $this->orderBulkActions, 'renderPacketsExportResult' ], self::MIN_LISTENER_PRIORITY );
393
394 add_action( 'admin_init', [ $this->labelPrint, 'outputLabelsPdf' ] );
395 add_action( 'admin_init', [ $this->orderCollectionPrint, 'print' ] );
396
397 add_action( 'admin_init', [ $this->exporter, 'outputExportTxt' ] );
398 add_filter( 'woocommerce_order_data_store_cpt_get_orders_query', [ $this, 'transformGetOrdersQuery' ] );
399
400 add_action( 'deleted_post', [ $this->orderRepository, 'deletedPostHook' ], 10, 2 );
401 }
402
403 /**
404 * Print inactive WooCommerce notice.
405 *
406 * @return void
407 */
408 public function echoInactiveWooCommerceNotice(): void {
409 if ( self::isWooCommercePluginActive() ) {
410 // When Packeta plugin is active and WooCommerce plugin is inactive.
411 // If user decides to activate WooCommerce plugin then invalid notice will not be rendered.
412 // Packeta plugin probably bootstraps twice in such case.
413 return;
414 }
415
416 $this->latte_engine->render(
417 PACKETERY_PLUGIN_DIR . '/template/admin-notice.latte',
418 [
419 'message' => [
420 'type' => 'error',
421 'message' => __( 'Packeta plugin requires WooCommerce. Please install and activate it first.', 'packeta' ),
422 ],
423 ]
424 );
425 }
426
427 /**
428 * Is WC plugin active.
429 *
430 * @return bool
431 */
432 private static function isWooCommercePluginActive(): bool {
433 return in_array( 'woocommerce/woocommerce.php', (array) get_option( 'active_plugins', [] ), true );
434 }
435
436 /**
437 * Filter queries.
438 *
439 * @param array $query Query.
440 *
441 * @return array
442 */
443 public function transformGetOrdersQuery( array $query ): array {
444 if ( ! empty( $query['packetery_meta_query'] ) ) {
445 // @codingStandardsIgnoreStart
446 $query['meta_query'] = $query['packetery_meta_query'];
447 // @codingStandardsIgnoreEnd
448 }
449
450 return $query;
451 }
452
453 /**
454 * Renders delivery detail for packetery orders.
455 *
456 * @param WC_Order $order WordPress order.
457 */
458 public function renderDeliveryDetail( WC_Order $order ): void {
459 $orderEntity = $this->orderRepository->getByWcOrder( $order );
460 if ( null === $orderEntity ) {
461 return;
462 }
463
464 $carrierId = $orderEntity->getCarrierId();
465 $carrierOptions = Carrier\Options::createByCarrierId( $carrierId );
466
467 $this->latte_engine->render(
468 PACKETERY_PLUGIN_DIR . '/template/order/delivery-detail.latte',
469 [
470 'pickupPoint' => $orderEntity->getPickupPoint(),
471 'validatedDeliveryAddress' => $orderEntity->getValidatedDeliveryAddress(),
472 'carrierAddressValidation' => $carrierOptions->getAddressValidation(),
473 'translations' => [
474 'packeta' => __( 'Packeta', 'packeta' ),
475 'pickupPointDetail' => __( 'Pickup Point Detail', 'packeta' ),
476 'name' => __( 'Name', 'packeta' ),
477 'address' => __( 'Address', 'packeta' ),
478 'pickupPointDetailCaps' => __( 'Pickup Point Detail', 'packeta' ),
479 'addressWasNotValidated' => __( 'Address was not validated', 'packeta' ),
480 'validatedAddress' => __( 'Validated address', 'packeta' ),
481 'street' => __( 'Street', 'packeta' ),
482 'houseNumber' => __( 'House number', 'packeta' ),
483 'city' => __( 'City', 'packeta' ),
484 'zip' => __( 'Zip', 'packeta' ),
485 'county' => __( 'County', 'packeta' ),
486 'gps' => __( 'GPS', 'packeta' ),
487 ],
488 ]
489 );
490 }
491
492 /**
493 * Renders delivery detail for packetery orders, on "thank you" page and in frontend detail.
494 *
495 * @param WC_Order $wcOrder WordPress order.
496 */
497 public function renderOrderDetail( WC_Order $wcOrder ): void {
498 $order = $this->orderRepository->getById( $wcOrder->get_id() );
499 if ( null === $order ) {
500 return;
501 }
502
503 $pickupPoint = $order->getPickupPoint();
504 $validatedDeliveryAddress = $order->getValidatedDeliveryAddress();
505 if ( null === $pickupPoint && null === $validatedDeliveryAddress ) {
506 return;
507 }
508
509 $this->latte_engine->render(
510 PACKETERY_PLUGIN_DIR . '/template/order/detail.latte',
511 [
512 'displayPickupPointInfo' => $this->shouldDisplayPickupPointInfo(),
513 'pickupPoint' => $pickupPoint,
514 'validatedDeliveryAddress' => $validatedDeliveryAddress,
515 'translations' => [
516 'packeta' => __( 'Packeta', 'packeta' ),
517 'selectedPickupPoint' => __( 'Selected pickup point', 'packeta' ),
518 'pickupPointName' => __( 'Pickup Point Name', 'packeta' ),
519 'pickupPointDetail' => __( 'Pickup Point Detail', 'packeta' ),
520 'validatedAddress' => __( 'Validated address', 'packeta' ),
521 'address' => __( 'Address', 'packeta' ),
522 ],
523 ]
524 );
525 }
526
527 /**
528 * Renders email footer.
529 *
530 * @param \WC_Email|null $email Email data.
531 */
532 public function render_email_footer( ?\WC_Email $email ): void {
533 if ( null === $email || ! $email->object instanceof \WC_Order ) {
534 return;
535 }
536
537 $packeteryOrder = $this->orderRepository->getByWcOrder( $email->object );
538 if ( null === $packeteryOrder ) {
539 return;
540 }
541
542 $pickupPoint = $packeteryOrder->getPickupPoint();
543 $validatedDeliveryAddress = $packeteryOrder->getValidatedDeliveryAddress();
544
545 $this->latte_engine->render(
546 PACKETERY_PLUGIN_DIR . '/template/email/footer.latte',
547 [
548 'displayPickupPointInfo' => $this->shouldDisplayPickupPointInfo(),
549 'pickupPoint' => $pickupPoint,
550 'validatedDeliveryAddress' => $validatedDeliveryAddress,
551 'translations' => [
552 'packeta' => __( 'Packeta', 'packeta' ),
553 'pickupPointDetail' => __( 'Pickup Point Detail', 'packeta' ),
554 'pickupPointName' => __( 'Pickup Point Name', 'packeta' ),
555 'link' => __( 'Link', 'packeta' ),
556 'pickupPointAddress' => __( 'Pickup Point Address', 'packeta' ),
557 'validatedDeliveryAddress' => __( 'validated delivery address', 'packeta' ),
558 'street' => __( 'Street', 'packeta' ),
559 'houseNumber' => __( 'House number', 'packeta' ),
560 'city' => __( 'City', 'packeta' ),
561 'zip' => __( 'Zip', 'packeta' ),
562 'county' => __( 'County', 'packeta' ),
563 ],
564 ]
565 );
566 }
567
568 /**
569 * Tells if pickup point info should be displayed.
570 *
571 * @return bool
572 */
573 public function shouldDisplayPickupPointInfo(): bool {
574 return ! $this->optionsProvider->replaceShippingAddressWithPickupPointAddress() || wc_ship_to_billing_address_only();
575 }
576
577 /**
578 * Enqueues admin JS file.
579 *
580 * @param string $name Name of script.
581 * @param string $file Relative file path.
582 * @param bool $inFooter Tells where to include script.
583 * @param array $deps Script dependencies.
584 */
585 private function enqueueScript( string $name, string $file, bool $inFooter, array $deps = [] ): void {
586 wp_enqueue_script(
587 $name,
588 plugin_dir_url( $this->main_file_path ) . $file,
589 $deps,
590 md5( (string) filemtime( PACKETERY_PLUGIN_DIR . '/' . $file ) ),
591 $inFooter
592 );
593 }
594
595 /**
596 * Enqueues CSS file.
597 *
598 * @param string $name Name of script.
599 * @param string $file Relative file path.
600 */
601 private function enqueueStyle( string $name, string $file ): void {
602 wp_enqueue_style(
603 $name,
604 plugin_dir_url( $this->main_file_path ) . $file,
605 [],
606 md5( (string) filemtime( PACKETERY_PLUGIN_DIR . '/' . $file ) )
607 );
608 }
609
610 /**
611 * Builds asset URL.
612 *
613 * @param string $asset Relative asset path without leading slash.
614 *
615 * @return string
616 */
617 public static function buildAssetUrl( string $asset ): string {
618 $url = plugin_dir_url( PACKETERY_PLUGIN_DIR . '/packeta.php' ) . $asset;
619 $filename = PACKETERY_PLUGIN_DIR . '/' . $asset;
620
621 return add_query_arg( [ 'v' => md5( (string) filemtime( $filename ) ) ], $url );
622 }
623
624 /**
625 * Enqueues javascript files and stylesheets for checkout.
626 */
627 public function enqueueFrontAssets(): void {
628 if ( is_checkout() ) {
629 $this->enqueueStyle( 'packetery-front-styles', 'public/front.css' );
630 $this->enqueueStyle( 'packetery-custom-front-styles', 'public/custom-front.css' );
631 $this->enqueueScript( 'packetery-checkout', 'public/checkout.js', true, [ 'jquery' ] );
632 wp_localize_script( 'packetery-checkout', 'packeteryCheckoutSettings', $this->checkout->createSettings() );
633 }
634 }
635
636 /**
637 * Enqueues javascript files and stylesheets for administration.
638 */
639 public function enqueueAdminAssets(): void {
640 global $pagenow, $typenow;
641
642 $page = $this->request->getQuery( 'page' );
643 $isOrderGridPage = $this->gridExtender->isOrderGridPage();
644 $isOrderDetailPage = 'post.php' === $pagenow && 'shop_order' === $typenow;
645
646 if ( $isOrderGridPage || $isOrderDetailPage || in_array( $page, [ Carrier\OptionsPage::SLUG, Options\Page::SLUG ], true ) ) {
647 $this->enqueueScript( 'live-form-validation-options', 'public/live-form-validation-options.js', false );
648 $this->enqueueScript( 'live-form-validation', 'public/libs/live-form-validation/live-form-validation.js', false, [ 'live-form-validation-options' ] );
649 $this->enqueueScript( 'live-form-validation-extension', 'public/live-form-validation-extension.js', false, [ 'live-form-validation' ] );
650 }
651
652 if ( Carrier\OptionsPage::SLUG === $page ) {
653 $this->enqueueScript( 'packetery-admin-country-carrier', 'public/admin-country-carrier.js', true, [ 'jquery' ] );
654 }
655
656 if ( $isOrderGridPage || $isOrderDetailPage || in_array( $page, [ Options\Page::SLUG, Carrier\OptionsPage::SLUG, Log\Page::SLUG, Order\labelPrint::MENU_SLUG ], true ) ) {
657 $this->enqueueStyle( 'packetery-admin-styles', 'public/admin.css' );
658 }
659
660 if ( $isOrderGridPage ) {
661 $this->enqueueScript( 'packetery-admin-grid-order-edit-js', 'public/admin-grid-order-edit.js', true, [ 'jquery', 'wp-util', 'backbone' ] );
662 }
663
664 if ( $isOrderDetailPage ) {
665 $this->enqueueScript( 'packetery-admin-pickup-point-picker', 'public/admin-pickup-point-picker.js', false, [ 'jquery' ] );
666 }
667 }
668
669 /**
670 * Add links to left admin menu.
671 */
672 public function add_menu_pages(): void {
673 $this->options_page->register();
674 $this->carrierOptionsPage->register();
675 $this->labelPrint->register();
676 $this->orderCollectionPrint->register();
677 $this->logPage->register();
678 }
679
680 /**
681 * Gets current locale.
682 */
683 private function getLocale(): string {
684 /**
685 * Applies plugin_locale filters.
686 *
687 * @since 1.0.0
688 */
689 return apply_filters(
690 'plugin_locale',
691 ( is_admin() ? get_user_locale() : get_locale() ),
692 self::DOMAIN
693 );
694 }
695
696 /**
697 * Loads plugin translation file by user locale.
698 */
699 public function loadTranslation(): void {
700 $domain = self::DOMAIN;
701 $locale = $this->getLocale();
702
703 $moFile = PACKETERY_PLUGIN_DIR . "/languages/$domain-$locale.mo";
704 $result = load_textdomain( $domain, $moFile );
705
706 if ( false === $result ) {
707 $moFile = PACKETERY_PLUGIN_DIR . "/languages/$domain-en_US.mo";
708 load_textdomain( $domain, $moFile );
709 }
710 }
711
712 /**
713 * Inits plugin.
714 */
715 public function init(): void {
716 add_filter(
717 'plugin_action_links_' . plugin_basename( $this->main_file_path ),
718 [
719 $this,
720 'addPluginActionLinks',
721 ]
722 );
723 add_filter( 'plugin_row_meta', [ $this, 'addPluginRowMeta' ], 10, 2 );
724 }
725
726 /**
727 * Activates plugin.
728 */
729 public function activate(): void {
730 global $wpdb;
731
732 $this->logRepository->createTable();
733 if ( false === PACKETERY_DEBUG ) {
734 $this->options_page->setDefaultValues();
735 }
736
737 $this->init();
738
739 $createResult = $this->carrierRepository->createTable();
740 if ( false === $createResult ) {
741 $lastError = $wpdb->last_error;
742 $this->message_manager->flash_message( __( 'Database carrier table was not created, you can find more information in Packeta log.', 'packeta' ), MessageManager::TYPE_ERROR );
743
744 $record = new Record();
745 $record->action = Record::ACTION_CARRIER_TABLE_NOT_CREATED;
746 $record->status = Record::STATUS_ERROR;
747 $record->title = __( 'Database carrier table was not created.', 'packeta' );
748 $record->params = [
749 'errorMessage' => $lastError,
750 ];
751 $this->logger->add( $record );
752 }
753
754 $createResult = $this->orderRepository->createTable();
755 if ( false === $createResult ) {
756 $lastError = $wpdb->last_error;
757 $this->message_manager->flash_message( __( 'Database order table was not created, you can find more information in Packeta log.', 'packeta' ), MessageManager::TYPE_ERROR );
758
759 $record = new Record();
760 $record->action = Record::ACTION_ORDER_TABLE_NOT_CREATED;
761 $record->status = Record::STATUS_ERROR;
762 $record->title = __( 'Database order table was not created.', 'packeta' );
763 $record->params = [
764 'errorMessage' => $lastError,
765 ];
766 $this->logger->add( $record );
767 }
768
769 $this->upgrade->check();
770 }
771
772 /**
773 * Uninstalls plugin and drops custom database table.
774 * Only a static class method or function can be used in an uninstall hook.
775 */
776 public static function uninstall(): void {
777 if ( defined( 'PACKETERY_DEBUG' ) && PACKETERY_DEBUG === true ) {
778 return;
779 }
780
781 $container = require PACKETERY_PLUGIN_DIR . '/bootstrap.php';
782
783 $optionsRepository = $container->getByType( Options\Repository::class );
784 $pluginOptions = $optionsRepository->getPluginOptions();
785 foreach ( $pluginOptions as $option ) {
786 delete_option( $option->option_name );
787 }
788
789 $logRepository = $container->getByType( Log\Repository::class );
790 $logRepository->drop();
791
792 $carrierRepository = $container->getByType( Carrier\Repository::class );
793 $carrierRepository->drop();
794
795 $orderRepository = $container->getByType( Order\Repository::class );
796 $orderRepository->drop();
797 }
798
799 /**
800 * Adds action links visible at the plugin screen.
801 *
802 * @link https://developer.wordpress.org/reference/hooks/plugin_action_links_plugin_file/
803 *
804 * @param array $links Plugin Action links.
805 *
806 * @return array
807 */
808 public function addPluginActionLinks( array $links ): array {
809 $settingsLink = '<a href="' . esc_url( admin_url( 'admin.php?page=' . Options\Page::SLUG ) ) . '" aria-label="' .
810 esc_attr__( 'View the plugin documentation', 'packeta' ) . '">' .
811 esc_html__( 'Settings', 'packeta' ) . '</a>';
812
813 array_unshift( $links, $settingsLink );
814
815 return $links;
816 }
817
818 /**
819 * Show row meta on the plugin screen.
820 *
821 * @link https://developer.wordpress.org/reference/hooks/plugin_row_meta/
822 *
823 * @param array $links Plugin Row Meta.
824 * @param string $pluginFileName Plugin Base file.
825 *
826 * @return array
827 */
828 public function addPluginRowMeta( array $links, string $pluginFileName ): array {
829 if ( ! strpos( $pluginFileName, basename( $this->main_file_path ) ) ) {
830 return $links;
831 }
832 $links[] = '<a href="' . esc_url( 'https://github.com/Zasilkovna/WooCommerce/wiki' ) . '" aria-label="' .
833 esc_attr__( 'View Packeta documentation', 'packeta' ) . '">' .
834 esc_html__( 'Documentation', 'packeta' ) . '</a>';
835
836 return $links;
837 }
838
839 /**
840 * Adds Packeta method to available shipping methods.
841 *
842 * @param array $methods Previous state.
843 *
844 * @return array
845 */
846 public function add_shipping_method( array $methods ): array {
847 $methods[ ShippingMethod::PACKETERY_METHOD_ID ] = ShippingMethod::class;
848
849 return $methods;
850 }
851
852 /**
853 * Hides submenu item. Must not be called too early.
854 *
855 * @param string $itemSlug Item slug.
856 */
857 public static function hideSubmenuItem( string $itemSlug ): void {
858 global $submenu;
859 if ( isset( $submenu[ Options\Page::SLUG ] ) ) {
860 foreach ( $submenu[ Options\Page::SLUG ] as $key => $menu ) {
861 if ( $itemSlug === $menu[2] ) {
862 unset( $submenu[ Options\Page::SLUG ][ $key ] );
863 }
864 }
865 }
866 }
867
868 /**
869 * Gets software identity for Packeta APIs.
870 *
871 * @return string
872 */
873 public static function getAppIdentity(): string {
874 return 'Woocommerce: ' . get_bloginfo( 'version' ) . ', WordPress: ' . WC_VERSION . ', plugin Packeta: ' . self::VERSION;
875 }
876 }
877