44 lines
1.5 KiB
PHP
44 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use DOMDocument;
|
|
use LogicException;
|
|
|
|
/** Windows Task Scheduler XML transport only; no registration or business operation. */
|
|
final class WindowsTaskXml
|
|
{
|
|
public static function parse(string $bytes): DOMDocument
|
|
{
|
|
// schtasks can emit console bytes with a UTF-16 declaration but no UTF-16 byte stream.
|
|
if (! str_contains($bytes, "\0")) {
|
|
$bytes = preg_replace('/encoding=([\'\"])UTF-16\1/i', 'encoding="UTF-8"', $bytes);
|
|
}
|
|
$previous = libxml_use_internal_errors(true);
|
|
try {
|
|
$document = new DOMDocument;
|
|
if (! $document->loadXML($bytes, LIBXML_NONET) || $document->documentElement?->localName !== 'Task'
|
|
|| $document->documentElement->namespaceURI !== 'http://schemas.microsoft.com/windows/2004/02/mit/task') {
|
|
throw new LogicException('WINDOWS_TASK_XML_INVALID');
|
|
}
|
|
|
|
return $document;
|
|
} finally {
|
|
libxml_clear_errors();
|
|
libxml_use_internal_errors($previous);
|
|
}
|
|
}
|
|
|
|
public static function encode(string $xml): string
|
|
{
|
|
$document = self::parse($xml);
|
|
$document->encoding = 'UTF-16';
|
|
$bytes = $document->saveXML();
|
|
if (! is_string($bytes) || self::parse($bytes)->documentElement->C14N() !== $document->documentElement->C14N()) {
|
|
throw new LogicException('WINDOWS_TASK_XML_ENCODING_CHANGED_CONTENT');
|
|
}
|
|
|
|
return $bytes;
|
|
}
|
|
}
|