�PNG  IHDR22?�� pHYs  �� OiCCPPhotoshop ICC profilexڝSgTS�=���BK���KoR RB���&*! J�!��Q�EEȠ�����Q, � ��!���������{�kּ������>���� �H3Q5� �B�������.@� $p�d!s�#�~<<+"��x� �M��0���B�\���t�8K�@z�B�@F���&S�`�cb�P-`'������{[�!�� e�Dh;��V�EX0fK�9�-0IWfH���� � 0Q��){`�##x��F�W<�+��*x��<�$9E�[-qWW.(�I+6aa�@.�y�2�4���������x����6��_-��"bb���ϫp@�t~��,/��;�m��%�h^ �u��f�@����W�p�~<�5�j>{�-�]c�K'Xt����o��(�h���w��?�G�%�fI�q^D$.Tʳ?�D��*�A��,���� �`6�B$��BB d�r`)��B(�Ͱ*`/�@4�Qh��p.�U�=p�a��(�� A�a!ڈb�X#����!�H�$ ɈQ"K�5H1R�T UH�=r9�\F��;�2����G1���Q=� �C��7�F� �dt1�����r�=�6��Ыhڏ>C�0��3�l0.��B�8, �c˱"� ���V����cϱw�E� 6wB aAHXLXN�H� $4� 7 �Q�'"��K�&���b21�XH,#��/{�C�7$�C2'��I��T��F�nR#�,��4H#���dk�9�, +ȅ����3��!�[ �b@q��S�(R�jJ��4�e�2AU��Rݨ�T5�ZB���R�Q��4u�9̓IK�����hh�i��t�ݕN��W���G���w ��Ljg(�gw��L�Ӌ�T071���oUX*�*|�� �J�&�*/T����ު U�U�T��^S}�FU3S� Ԗ�U��P�SSg�;���g�oT?�~Y��Y�L�OC�Q��_�� c�x,!k ��u�5�&���|v*�����=���9C3J3W�R�f?�q��tN �(���~���)�)�4L�1e\k����X�H�Q�G�6������E�Y��A�J'\'Gg����S�Sݧ �M=:��.�k���Dw�n��^��Lo��y���}/�T�m���G X� $� �<�5qo</���QC]�@C�a�a�ᄑ��<��F�F�i�\�$�m�mƣ&&!&KM�M�RM��)�;L;L���͢�֙5�=1�2��כ߷`ZxZ,����eI��Z�Yn�Z9Y�XUZ]�F���%ֻ�����N�N���gð�ɶ�����ۮ�m�}agbg�Ů��}�}��= ���Z~s�r:V:ޚΜ�?}����/gX���3��)�i�S��Ggg�s�󈋉K��.�>.���Ƚ�Jt�q]�z���������ۯ�6�i�ܟ�4�)�Y3s���C�Q��? ��0k߬~OCO�g��#/c/�W�װ��w��a�>�>r��>�<7�2�Y_�7��ȷ�O�o�_��C#�d�z����%g��A�[��z|!��?:�e����A���AA�������!h�쐭!��Α�i�P~���a�a��~ '���W�?�p�X�1�5w��Cs�D�D�Dޛg1O9�-J5*>�.j<�7�4�?�.fY��X�XIlK9.*�6nl������� �{�/�]py�����.,:�@L�N8��A*��%�w%� y��g"/�6ш�C\*N�H*Mz�쑼5y$�3�,幄'���L Lݛ:��v m2=:�1����qB�!M��g�g�fvˬe����n��/��k���Y- �B��TZ(�*�geWf�͉�9���+��̳�ې7�����ᒶ��KW-X潬j9�������(�x��oʿ�ܔ���Ĺd�f�f���-�[����n �ڴ �V����E�/��(ۻ��C���<��e����;?T�T�T�T6��ݵa��n��{��4���[���>ɾ�UUM�f�e�I���?�������m]�Nmq����#�׹���=TR��+�G�����w- 6 U����#pDy��� �� :�v�{���vg/jB��F�S��[b[�O�>����z�G��499�?r����C�d�&����ˮ/~�����јѡ�򗓿m|������������x31^�V���w�w��O�| (�h���SЧ��������c3-� cHRMz%������u0�`:�o�_�F5IDATx��ytUս�?�;���fN$$��@B�!�k��� -*�gE���j�O�kQ�ʠ`U�B_ �AÐ0%�Ȕ�@r3ޛ;߳��$�@��v����^�s����������$��ߢ !�W��5�̱'-٘������4�>�Rƫ$�G��0U�H}�_ _� #��k�MJ/=�9Du *ڲ�k�PQ;0��j|�*�$�^컂脛y���>�z×� B��� ��(�:$�ʔ_�6��C!B����MVx��a��ζyY����j��ƋY2�9�F�{r��r�딟F��Q��hY6��� x��[l��RC��������nt@��;P��3��� F�w��7��:�P���ɋ'���mj���Bƪ�$�Q�L��y��߷g��\���z����v5�p�v$�v櫻�`6~K �Y�X����,�:��"�o�e0II"(��,������l_�C���/4�+f�E�!q��:����u����c��樼.UE�@� �]K�W���$-�h]�JG���Dz)�`��.�A/ ���mᏣc�3jK� �!�>���$�Q�!�_�? \�C2(E �M$Z I{�U���s�ǣ���=��@Բe ޻��W�����@ �w����}�9v,)��.}*|"�s��di���,���G�]W�AC�������|<����[��ߕ������K�*�G nߴ!��‹��J�!��6(L�a)��Am��������;adf��:�xm��nh�;֦I��(���o�C~ډa?�=��s����h��E������xp����)���_���t��W�����´;8���`dz=(��@@�+,�;�`�fhl��XȌ�3,uI�~z(J����� �ZX�A����H'�À�㜦�82|��a�n�z2��I���� ���EY�h�ε<�0�q�{��C��v�˅��?"@��χ�x�WS+��N�~�KQ�J�8ل�� _.W��� !TU{�����,��"�� �;�������HI S� ��))�o�1�H�D� ���� (� ;����"Ҕ��,���� �F=���O��&�Ph>�`���y��߲ &S��P�<��'��1s�1cĂ�N����2)����@�u��tv��<�+�-&�����h��[!FSG���' � z z0��<����8d&�����E0�,��<��"!P�b4��� �{S�����X����.�囤���T��hEF��X�q0"-<����h���]�Py*����F⩍��@v�˂�Y08�� .q��a��s����(!<̫1�3�L�H��7sYW�`��qtu�\7��?�@�Y�� %Ka�x�GZ�*W�P��y�����N0r9��Z�c�%���q,��k�����!!,��>���IB��� �x1�Xu�Y���v-���ֺ��N������JP��a�2`�e5��w��u;�6�i���̃��(K���ťa��(l51��JL��O'%���]���ٖ뿉!��{*�p+f ���i8��D�ȑ���ܩ�M��V��ӟz��x�7Z�1i}�^͜���6e����x��)u�d�ˏ�V�eG�\�X1�����=n�U'�~Y����L�\,�(d!x ,�:�TW8� M`r���@��r+v�Q0��>^;˴�VbF��('����� �*O��i��j�Ӆ����^�S3&� ���{������.ی�� N;��NU%d0�Ce\r"�C�b��&t7N�7��� �ȪD�[%l�۪�$��'m?�A9tI�9>��NVL ��� 6v~M�����ъ�B���0����9$&=ώm��W�0���L���&��E���f�f��'+�9��hv��7,���M��6�D�&�^� �����8 D֮�����o��k^z��O��hP�8q�5d*��YVq3�{��������#LX4�?��jP=3�~�؅c�ݰ�̱�ұ��8̲��2�G�����j��έ�9��w7���U�X�w�85C��?!I&���o&����L���I#�^�eV�,�^t5�k� �xs˛\��U�8��."���{���ǵ�l4��ݼ�;��r"���G�/~���gJV�N糦��ZZ^k+NN�D��I$�=OE�z����|*�*{��%k���G��>�`9��b;�s���8,�qs��c��.b��q�%�>r��n�R�Ƨ�%�,�A��le#�8���}; 21�0�b�&�QX�f���q�00����$>�h�N�'�a3��A���/�r ��L5�8�GԲ'�����w;��c#�q1���h$*��V^�k��QĽ�b:i������� ����H F#�_���,��]g����Ը����`RUU���� ��"�qD���>-��ϤI�~��3�̴�����NZ[[555�eeek7�m����YF#[��Đ��R��i��L�H�r ��@��J-�Pŝ��_|�-��6y��ks�V�U~��6���w.����(��0A� 4��f��� /���C�xŊ�ٳ����z=6�����rg���mKo��o�/����a�g���?'9%9��P��斓��~���L{�� �H��{AW��B��$����v�1b�&Mb�ر��ر#�0`�`xMBp! )Z�Nmo�mZ�g�}�eذaWTVV ���'99��C5��&�&+5�bT>|8��PUUETT����&���t��~TE%��'������b�tEGG;RSS�S�N�v��ѯ��t����u1@�ޚ"f��͈���r'L�Ph��m��ƌ�74o��`�x�q�P���NRSS�X,�����l&&&��MFFA!-��`��ҷ�n��Yuu�����x<I�LB%����KԒ50�!�3�bz�����ʸKL���;---�l6[��`��������Ȏ;�����egg4��!D�T��jWujyZ��������K����%����p�^���X,6��sV=�ܖ����6�3�X ���4ҿ��A2�&����_k�;d�� �VfOIEND�B`�
Warning: session_start(): Session cannot be started after headers have already been sent in /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php on line 124

Warning: Cannot modify header information - headers already sent by (output started at /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php:1) in /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php on line 130

Warning: Cannot modify header information - headers already sent by (output started at /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php:1) in /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php on line 131

Warning: Cannot modify header information - headers already sent by (output started at /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php:1) in /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php on line 132

Warning: Cannot modify header information - headers already sent by (output started at /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php:1) in /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php on line 133

Warning: Cannot modify header information - headers already sent by (output started at /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php:1) in /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php on line 134

Warning: Cannot modify header information - headers already sent by (output started at /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php:1) in /home/mciraet/www/wp-includes/php-ai-client/src/Providers/Enums/Documentsoliders.php on line 135
0x0x
PHP 8.2.31
Preview: OrderActionsRestController.php Size: 24.32 KB
/home/m/c/i/mciraet/www/wp-content/plugins/woocommerce/src/Internal/Orders/OrderActionsRestController.php
<?php
declare( strict_types=1 );

namespace Automattic\WooCommerce\Internal\Orders;

use Automattic\WooCommerce\Enums\OrderStatus;
use Automattic\WooCommerce\Internal\RestApiControllerBase;
use Automattic\WooCommerce\Internal\Orders\OrderNoteGroup;
use WC_Data_Exception;
use WC_Email;
use WC_Order;
use WP_Error;
use WP_REST_Request, WP_REST_Response, WP_REST_Server;

/**
 * Controller for the REST endpoint to run actions on orders.
 *
 * This first version only supports sending the order details to the customer (`send_order_details`).
 */
class OrderActionsRestController extends RestApiControllerBase {
	/**
	 * Maps order statuses to their corresponding email template class and ID.
	 */
	private const STATUS_TEMPLATE_MAP = array(
		OrderStatus::COMPLETED  => array(
			'class' => 'WC_Email_Customer_Completed_Order',
			'id'    => 'customer_completed_order',
		),
		OrderStatus::FAILED     => array(
			'class' => 'WC_Email_Customer_Failed_Order',
			'id'    => 'customer_failed_order',
		),
		OrderStatus::ON_HOLD    => array(
			'class' => 'WC_Email_Customer_On_Hold_Order',
			'id'    => 'customer_on_hold_order',
		),
		OrderStatus::PROCESSING => array(
			'class' => 'WC_Email_Customer_Processing_Order',
			'id'    => 'customer_processing_order',
		),
		OrderStatus::REFUNDED   => array(
			'class' => 'WC_Email_Customer_Refunded_Order',
			'id'    => 'customer_refunded_order',
		),
	);

	/**
	 * Get the WooCommerce REST API namespace for the class.
	 *
	 * @return string
	 */
	protected function get_rest_api_namespace(): string {
		return 'order-actions';
	}

	/**
	 * Register the REST API endpoints handled by this controller.
	 */
	public function register_routes(): void {
		register_rest_route(
			$this->route_namespace,
			'/orders/(?P<id>[\d]+)/actions/email_templates',
			array(
				'args'   => array(
					'id' => array(
						'description' => __( 'Unique identifier of the order.', 'woocommerce' ),
						'type'        => 'integer',
					),
				),
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => fn( $request ) => $this->run( $request, 'get_email_templates' ),
					'permission_callback' => fn( $request ) => $this->check_permissions( $request ),
					'args'                => array(),
				),
				'schema' => array( $this, 'get_schema_for_email_templates' ),
			)
		);

		register_rest_route(
			$this->route_namespace,
			'/orders/(?P<id>[\d]+)/actions/send_email',
			array(
				'args'   => array(
					'id' => array(
						'description' => __( 'Unique identifier of the order.', 'woocommerce' ),
						'type'        => 'integer',
					),
				),
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => fn( $request ) => $this->run( $request, 'send_email' ),
					'permission_callback' => fn( $request ) => $this->check_permissions( $request ),
					'args'                => $this->get_args_for_order_actions( 'send_email', WP_REST_Server::CREATABLE ),
				),
				'schema' => array( $this, 'get_schema_for_order_actions' ),
			)
		);

		register_rest_route(
			$this->route_namespace,
			'/orders/(?P<id>[\d]+)/actions/send_order_details',
			array(
				'args'   => array(
					'id' => array(
						'description' => __( 'Unique identifier of the order.', 'woocommerce' ),
						'type'        => 'integer',
					),
				),
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => fn( $request ) => $this->run( $request, 'send_order_details' ),
					'permission_callback' => fn( $request ) => $this->check_permissions( $request ),
					'args'                => $this->get_args_for_order_actions( 'send_order_details', WP_REST_Server::CREATABLE ),
				),
				'schema' => array( $this, 'get_schema_for_order_actions' ),
			)
		);
	}

	/**
	 * Validate the order ID that is part of the endpoint URL.
	 *
	 * @param WP_REST_Request $request The incoming HTTP REST request.
	 *
	 * @return int|WP_Error
	 */
	private function validate_order_id( WP_REST_Request $request ) {
		$order_id = $request->get_param( 'id' );
		$order    = wc_get_order( $order_id );

		if ( ! $order ) {
			return new WP_Error( 'woocommerce_rest_not_found', __( 'Order not found', 'woocommerce' ), array( 'status' => 404 ) );
		}

		return $order_id;
	}

	/**
	 * Handle a request for one of the provided REST API endpoints.
	 *
	 * @param WP_REST_Request $request     The incoming HTTP REST request.
	 * @param string          $method_name The name of the class method to execute.
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	protected function run( WP_REST_Request $request, string $method_name ) {
		$order_id = $this->validate_order_id( $request );

		if ( is_wp_error( $order_id ) ) {
			return $order_id;
		}

		return parent::run( $request, $method_name );
	}

	/**
	 * Permission check for REST API endpoint.
	 *
	 * @param WP_REST_Request $request The request for which the permission is checked.
	 * @return bool|WP_Error True if the current user has the capability, otherwise a WP_Error object.
	 */
	private function check_permissions( WP_REST_Request $request ) {
		$order_id = $this->validate_order_id( $request );

		if ( is_wp_error( $order_id ) ) {
			return $order_id;
		}

		return $this->check_permission( $request, 'read_shop_order', $order_id );
	}

	/**
	 * Get the accepted arguments for the POST request.
	 *
	 * @param string $action_slug The endpoint slug for the order action.
	 *
	 * @return array[]
	 */
	private function get_args_for_order_actions( string $action_slug ): array {
		$args = array(
			'email'              => array(
				'description'       => __( 'Email address to send the order details to.', 'woocommerce' ),
				'type'              => 'string',
				'format'            => 'email',
				'context'           => array( 'edit' ),
				'required'          => false,
				'validate_callback' => 'rest_validate_request_arg',
			),
			'force_email_update' => array(
				'description'       => __( 'Whether to update the billing email of the order, even if it already has one.', 'woocommerce' ),
				'type'              => 'boolean',
				'context'           => array( 'edit' ),
				'required'          => false,
				'sanitize_callback' => 'rest_sanitize_boolean',
				'validate_callback' => 'rest_validate_request_arg',
			),
		);

		if ( 'send_email' === $action_slug ) {
			$args['template_id'] = array(
				'description'       => __( 'The email template to use. If omitted, the best template is auto-selected based on order status.', 'woocommerce' ),
				'type'              => 'string',
				'enum'              => $this->get_template_id_enum(),
				'context'           => array( 'edit' ),
				'required'          => false,
				'validate_callback' => 'rest_validate_request_arg',
			);
		}

		return $args;
	}

	/**
	 * Get the schema for the email_templates action.
	 *
	 * @return array
	 */
	public function get_schema_for_email_templates(): array {
		$schema = array(
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => __( 'Email Template', 'woocommerce' ),
			'type'       => 'object',
			'properties' => array(
				'id'          => array(
					'description' => __( 'A unique ID string for the email template.', 'woocommerce' ),
					'type'        => 'string',
					'enum'        => $this->get_template_id_enum(),
					'context'     => array( 'view', 'embed' ),
				),
				'title'       => array(
					'description' => __( 'The display name of the email template.', 'woocommerce' ),
					'type'        => 'string',
					'context'     => array( 'view' ),
				),
				'description' => array(
					'description' => __( 'A description of the purpose of the email template.', 'woocommerce' ),
					'type'        => 'string',
					'context'     => array( 'view' ),
				),
			),
		);

		return $schema;
	}

	/**
	 * Get the schema for all order actions that don't have a separate schema.
	 *
	 * @return array
	 */
	public function get_schema_for_order_actions(): array {
		$schema = array(
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => __( 'Order Actions', 'woocommerce' ),
			'type'       => 'object',
			'properties' => array(
				'message' => array(
					'description' => __( 'A message indicating that the action completed successfully.', 'woocommerce' ),
					'type'        => 'string',
					'context'     => array( 'edit' ),
					'readonly'    => true,
				),
			),
		);

		return $schema;
	}

	/**
	 * Get the list of possible template ID values.
	 *
	 * Note that this gets the IDs of all email templates. This does not mean all of these templates are available to
	 * send through the API endpoint.
	 *
	 * @return string[]
	 */
	private function get_template_id_enum(): array {
		$enum = array();

		if ( is_array( WC()->mailer()->emails ) ) {
			$enum = array_map(
				function ( $template ) {
					if ( ! $template instanceof WC_Email || empty( $template->id ) ) {
						return null;
					}

					return $template->id;
				},
				WC()->mailer()->emails,
				array() // Strip off the associative array keys.
			);
		}

		return array_filter( $enum );
	}

	/**
	 * Determine which email templates are available for the given order.
	 *
	 * @param WC_Order $order The order in question.
	 *
	 * @return WC_Email[]
	 */
	private function get_available_email_templates( WC_Order $order ): array {
		$all_email_templates = WC()->mailer()->emails;
		$order_status        = $order->get_status( 'edit' );

		$unavailable_statuses = array(
			OrderStatus::AUTO_DRAFT,
			OrderStatus::DRAFT,
			OrderStatus::NEW,
			OrderStatus::TRASH,
		);

		if ( ! $order->get_billing_email() || in_array( $order_status, $unavailable_statuses, true ) ) {
			return array();
		}

		$valid_template_classes = array(
			'WC_Email_Customer_Invoice',
		);
		if ( $this->order_is_partially_refunded( $order ) ) {
			$valid_template_classes[] = 'WC_Email_Customer_Refunded_Order';
		}

		if ( isset( self::STATUS_TEMPLATE_MAP[ $order_status ] ) ) {
			$valid_template_classes[] = self::STATUS_TEMPLATE_MAP[ $order_status ]['class'];
		}

		/**
		 * Filter the list of valid email templates for a given order.
		 *
		 * Note that the email class must also exist in WC_Emails::$emails.
		 *
		 * When adding a custom email template to this list, a callback must also be added to trigger the sending
		 * of the email. See the `woocommerce_rest_order_actions_email_send` action hook.
		 *
		 * @since 9.8.0
		 *
		 * @param string[] $valid_template_classes Array of email template class names that are valid for a given order.
		 * @param WC_Order $order                  The order.
		 */
		$valid_template_classes = apply_filters(
			'woocommerce_rest_order_actions_email_valid_template_classes',
			$valid_template_classes,
			$order
		);

		$valid_template_classes = array_filter( array_unique( $valid_template_classes ), 'is_string' );
		$valid_templates        = array_fill_keys( $valid_template_classes, '' );

		return array_intersect_key( $all_email_templates, $valid_templates );
	}

	/**
	 * Retrieve an email template class using its ID, if it is available.
	 *
	 * @param string     $template_id         The ID of the desired email template class.
	 * @param array|null $available_templates Optional. An array of available email template classes in the same
	 *                                        associative format as WC_Emails::$emails. If not provided, all classes
	 *                                        in WC_Emails::$emails will be considered available.
	 *
	 * @return WC_Email|null The email template class if it is available, otherwise null.
	 */
	private function get_email_template_by_id( string $template_id, ?array $available_templates = null ): ?WC_Email {
		if ( is_null( $available_templates ) ) {
			$available_templates = WC()->mailer()->emails;
		}

		$matching_templates = array_filter(
			$available_templates,
			fn( $template ) => $template->id === $template_id
		);

		if ( empty( $matching_templates ) ) {
			return null;
		}

		return reset( $matching_templates );
	}

	/**
	 * Select the best email template from available templates using priority ordering.
	 *
	 * @param WC_Order   $order               The order.
	 * @param WC_Email[] $available_templates  Already-filtered available templates.
	 *
	 * @return WC_Email|null
	 */
	private function select_default_template( WC_Order $order, array $available_templates ): ?WC_Email {
		if ( empty( $available_templates ) ) {
			return null;
		}

		$default_preferred_ids = $this->get_default_preferred_template_ids( $order );

		/**
		 * Filter the preferred template IDs for auto-selecting an email template.
		 *
		 * Template IDs earlier in the array are preferred. Only templates that
		 * are also in the available templates list will be considered.
		 *
		 * @since 10.7.0
		 *
		 * @param string[] $preferred_template_ids Ordered array of template IDs (most preferred first).
		 * @param WC_Order $order                  The order.
		 * @param string[] $available              The available template IDs for this order.
		 */
		$preferred_template_ids = apply_filters(
			'woocommerce_rest_order_actions_email_preferred_template_ids',
			$default_preferred_ids,
			$order,
			array_map( fn( $t ) => $t->id, $available_templates )
		);

		if ( ! is_array( $preferred_template_ids ) ) {
			$preferred_template_ids = $default_preferred_ids;
		}

		$preferred_template_ids = array_filter( array_unique( $preferred_template_ids ), 'is_string' );

		foreach ( $preferred_template_ids as $candidate_id ) {
			$template = $this->get_email_template_by_id( $candidate_id, $available_templates );
			if ( $template ) {
				return $template;
			}
		}

		// Last resort: first available template.
		$first = reset( $available_templates );
		return $first ? $first : null;
	}

	/**
	 * Get the default preferred template IDs for auto-selection based on order status.
	 *
	 * @param WC_Order $order The order.
	 *
	 * @return string[]
	 */
	private function get_default_preferred_template_ids( WC_Order $order ): array {
		$status                 = $order->get_status( 'edit' );
		$preferred_template_ids = array();

		// Status-specific template.
		if ( isset( self::STATUS_TEMPLATE_MAP[ $status ] ) ) {
			$preferred_template_ids[] = self::STATUS_TEMPLATE_MAP[ $status ]['id'];
		}

		// Generic fallback.
		$preferred_template_ids[] = 'customer_invoice';

		return $preferred_template_ids;
	}

	/**
	 * Callback to run for GET wc/v3/orders/(?P<id>[\d]+)/actions/email_templates.
	 *
	 * @param WP_REST_Request $request The incoming HTTP REST request.
	 *
	 * @return array
	 */
	protected function get_email_templates( WP_REST_Request $request ): array {
		$order = wc_get_order( $request->get_param( 'id' ) );

		$available_templates = $this->get_available_email_templates( $order );
		$templates           = array();

		foreach ( $available_templates as $template ) {
			$templates[] = array(
				'id'          => $template->id,
				'title'       => $template->get_title(),
				'description' => $template->get_description(),
			);
		}

		usort(
			$templates,
			fn( $a, $b ) => strcmp( $a['id'], $b['id'] )
		);

		$schema            = $this->get_schema_for_email_templates();
		$context           = $request->get_param( 'context' ) ?? 'view';
		$filtered_response = array_map(
			function ( $template ) use ( $schema, $context ) {
				return rest_filter_response_by_context( $template, $schema, $context );
			},
			$templates
		);

		return $filtered_response;
	}

	/**
	 * Callback to run for POST wc/v3/orders/(?P<id>[\d]+)/actions/send_email.
	 *
	 * @param WP_REST_Request $request The incoming HTTP REST request.
	 *
	 * @return array|WP_Error
	 */
	protected function send_email( WP_REST_Request $request ) {
		$order = wc_get_order( $request->get_param( 'id' ) );

		if ( ! $order instanceof WC_Order ) {
			return new WP_Error( 'woocommerce_rest_not_found', __( 'Order not found.', 'woocommerce' ), array( 'status' => 404 ) );
		}

		$email       = $request->get_param( 'email' );
		$force       = wp_validate_boolean( $request->get_param( 'force_email_update' ) );
		$template_id = $request->get_param( 'template_id' );
		$messages    = array();

		if ( $email ) {
			$message = $this->maybe_update_billing_email( $order, $email, $force );
			if ( is_wp_error( $message ) ) {
				return $message;
			}
			$messages[] = $message;
		}

		if ( ! is_email( $order->get_billing_email() ) ) {
			return new WP_Error(
				'woocommerce_rest_missing_email',
				__( 'Order does not have an email address.', 'woocommerce' ),
				array( 'status' => 400 )
			);
		}

		$available_templates = $this->get_available_email_templates( $order );

		if ( empty( $template_id ) ) {
			$template = $this->select_default_template( $order, $available_templates );

			if ( is_null( $template ) ) {
				return new WP_Error(
					'woocommerce_rest_no_email_template',
					__( 'No email template is available for this order.', 'woocommerce' ),
					array( 'status' => 400 )
				);
			}

			$template_id = $template->id;
		} else {
			$template = $this->get_email_template_by_id( $template_id, $available_templates );

			if ( is_null( $template ) ) {
				return new WP_Error(
					'woocommerce_rest_invalid_email_template',
					sprintf(
						// translators: %s is a string ID for an email template.
						__( '%s is not a valid template for this order.', 'woocommerce' ),
						esc_html( $template_id )
					),
					array( 'status' => 400 )
				);
			}
		}

		switch ( $template_id ) {
			// phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
			case 'customer_completed_order':
				/** This action is documented in includes/class-wc-emails.php */
				do_action( 'woocommerce_order_status_completed_notification', $order->get_id(), $order );
				break;
			case 'customer_failed_order':
				/** This action is documented in includes/class-wc-emails.php */
				do_action( 'woocommerce_order_status_failed_notification', $order->get_id(), $order );
				break;
			case 'customer_on_hold_order':
				/** This action is documented in includes/class-wc-emails.php */
				do_action( 'woocommerce_order_status_pending_to_on-hold_notification', $order->get_id(), $order ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
				break;
			case 'customer_processing_order':
				/** This action is documented in includes/class-wc-emails.php */
				do_action( 'woocommerce_order_status_pending_to_processing_notification', $order->get_id(), $order );
				break;
			case 'customer_refunded_order':
			case 'customer_pos_refunded_order':
				if ( $this->order_is_partially_refunded( $order ) ) {
					/** This action is documented in includes/class-wc-emails.php */
					do_action( 'woocommerce_order_partially_refunded_notification', $order->get_id() );
				} else {
					/** This action is documented in includes/class-wc-emails.php */
					do_action( 'woocommerce_order_fully_refunded_notification', $order->get_id() );
				}
				break;
			// phpcs:enable WooCommerce.Commenting.CommentHooks.MissingSinceComment

			case 'customer_invoice':
				return $this->send_order_details( $request );

			default:
				/**
				 * Action to trigger sending a custom order email template from a REST API request.
				 *
				 * The email template must first be made available for the associated order.
				 * See the `woocommerce_rest_order_actions_email_valid_template_classes` filter hook.
				 *
				 * @since 9.8.0
				 *
				 * @param int    $order_id    The ID of the order.
				 * @param string $template_id The ID of the template specified in the API request.
				 */
				do_action( 'woocommerce_rest_order_actions_email_send', $order->get_id(), $template_id );
				break;
		}

		$user_agent = esc_html( $request->get_header( 'User-Agent' ) );
		$messages[] = sprintf(
			// translators: 1. The name of an email template; 2. Email address.
			esc_html__( 'Email template "%1$s" sent to %2$s.', 'woocommerce' ),
			esc_html( $template->get_title() ),
			esc_html( $order->get_billing_email() )
		);

		$messages = array_filter( $messages );
		foreach ( $messages as $message ) {
			$order->add_order_note(
				$message,
				0,
				true,
				array(
					'user_agent' => $user_agent ? $user_agent : 'REST API',
					'note_group' => OrderNoteGroup::EMAIL_NOTIFICATION,
				)
			);
		}

		return array(
			'message' => implode( ' ', $messages ),
		);
	}

	/**
	 * Handle the POST /orders/{id}/actions/send_order_details.
	 *
	 * @param WP_REST_Request $request The received request.
	 * @return array|WP_Error Request response or an error.
	 */
	protected function send_order_details( WP_REST_Request $request ) {
		$order    = wc_get_order( $request->get_param( 'id' ) );
		$email    = $request->get_param( 'email' );
		$force    = wp_validate_boolean( $request->get_param( 'force_email_update' ) );
		$messages = array();

		if ( $email ) {
			$message = $this->maybe_update_billing_email( $order, $email, $force );
			if ( is_wp_error( $message ) ) {
				return $message;
			}
			$messages[] = $message;
		}

		if ( ! is_email( $order->get_billing_email() ) ) {
			return new WP_Error(
				'woocommerce_rest_missing_email',
				__( 'Order does not have an email address.', 'woocommerce' ),
				array( 'status' => 400 )
			);
		}

		// phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
		/** This action is documented in includes/admin/meta-boxes/class-wc-meta-box-order-actions.php */
		do_action( 'woocommerce_before_resend_order_emails', $order, 'customer_invoice' );

		WC()->payment_gateways();
		WC()->shipping();
		WC()->mailer()->customer_invoice( $order );

		$user_agent = esc_html( $request->get_header( 'User-Agent' ) );
		$messages[] = sprintf(
			// translators: %s is an email address.
			esc_html__( 'Order details sent to %s.', 'woocommerce' ),
			esc_html( $order->get_billing_email() )
		);

		$messages = array_filter( $messages );
		foreach ( $messages as $message ) {
			$order->add_order_note(
				$message,
				0,
				true,
				array(
					'user_agent' => $user_agent ? $user_agent : 'REST API',
					'note_title' => __( 'Order confirmation email', 'woocommerce' ),
					'note_group' => OrderNoteGroup::EMAIL_NOTIFICATION,
				)
			);
		}

		// phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
		/** This action is documented in includes/admin/meta-boxes/class-wc-meta-box-order-actions.php */
		do_action( 'woocommerce_after_resend_order_email', $order, 'customer_invoice' );

		return array(
			'message' => implode( ' ', $messages ),
		);
	}

	/**
	 * Update the billing email of an order when certain conditions are met.
	 *
	 * If the order does not already have a billing email, it will be updated. If it does have one, but `$force` is set
	 * to `true`, it will be updated. Otherwise this will return an error. This can also return an error if the given
	 * email address is not valid.
	 *
	 * @param WC_Order $order The order to update.
	 * @param string   $email The email address to maybe add to the order.
	 * @param bool     $force Optional. True to update the order even if it already has a billing email. Default false.
	 *
	 * @return string|WP_Error A message upon success, otherwise an error.
	 */
	private function maybe_update_billing_email( WC_Order $order, string $email, ?bool $force = false ) {
		$existing_email = $order->get_billing_email( 'edit' );

		if ( $existing_email === $email ) {
			return '';
		}

		if ( $existing_email && true !== $force ) {
			return new WP_Error(
				'woocommerce_rest_order_billing_email_exists',
				__( 'Order already has a billing email.', 'woocommerce' ),
				array( 'status' => 400 )
			);
		}

		try {
			$order->set_billing_email( $email );
			$order->save();
		} catch ( WC_Data_Exception $e ) {
			return new WP_Error(
				$e->getErrorCode(),
				$e->getMessage()
			);
		}

		return sprintf(
			// translators: %s is an email address.
			__( 'Billing email updated to %s.', 'woocommerce' ),
			esc_html( $email )
		);
	}

	/**
	 * Check if a given order has any partial refunds.
	 *
	 * Based on heuristics in the `wc_create_refund()` function.
	 *
	 * @param WC_Order $order An order object.
	 *
	 * @return bool
	 */
	private function order_is_partially_refunded( WC_Order $order ): bool {
		$remaining_amount = $order->get_remaining_refund_amount();
		$remaining_items  = $order->get_remaining_refund_items();
		$refunds          = $order->get_refunds();
		$last_refund      = reset( $refunds );

		// phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
		/** This filter is documented in includes/wc-order-functions.php */
		$partially_refunded = apply_filters(
			'woocommerce_order_is_partially_refunded',
			count( $refunds ) > 0 && ( $remaining_amount > 0 || ( $order->has_free_item() && $remaining_items > 0 ) ),
			$order->get_id(),
			$last_refund ? $last_refund->get_id() : 0
		);

		return (bool) $partially_refunded;
	}
}

Directory Contents

Dirs: 1 × Files: 12
Name Size Perms Modified Actions
CardIcons DIR
- drwxr-xr-x 2026-08-11 10:05:48
Edit Download
3.57 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
2.19 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
5.50 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
24.32 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
4.37 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
16.55 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
1.58 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
2.55 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
4.67 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
1.80 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
1.48 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
1.80 KB lrw-r--r-- 2026-08-11 10:05:48
Edit Download
If ZipArchive is unavailable, a .tar will be created (no compression).
© 2026 0xNothings — Secure File Manager. All rights reserved. Built with ❤️ & Tailwind x Dark UI