repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Parser/Websocket/Payload.php
src/Parser/Websocket/Payload.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Parser\Websocket; /** * Payload for sending data through the websocket. * * Loosely based on the work of the following: * - Ludovic Barreca (@ludovicbarreca) * - Byeoung Wook (@kbu1564) * * @link https://tools.ietf.org/html/rfc6455#section-5.2 * @author Baptiste Clavié <baptiste@wisembly.com> */ abstract class Payload { public const OPCODE_CONTINUE = 0x0; public const OPCODE_TEXT = 0x1; public const OPCODE_BINARY = 0x2; public const OPCODE_CLOSE = 0x8; public const OPCODE_PING = 0x9; public const OPCODE_PONG = 0xA; public const OPCODE_NON_CONTROL_RESERVED_1 = 0x3; public const OPCODE_NON_CONTROL_RESERVED_2 = 0x4; public const OPCODE_NON_CONTROL_RESERVED_3 = 0x5; public const OPCODE_NON_CONTROL_RESERVED_4 = 0x6; public const OPCODE_NON_CONTROL_RESERVED_5 = 0x7; public const OPCODE_CONTROL_RESERVED_1 = 0xB; public const OPCODE_CONTROL_RESERVED_2 = 0xC; public const OPCODE_CONTROL_RESERVED_3 = 0xD; public const OPCODE_CONTROL_RESERVED_4 = 0xE; public const OPCODE_CONTROL_RESERVED_5 = 0xF; /** @var int */ protected $fin = 0b1; // only one frame is necessary /** @var int[] */ protected $rsv = [0b0, 0b0, 0b0]; // rsv1, rsv2, rsv3 /** @var bool */ protected $mask = false; /** @var string */ protected $maskKey = "\x00\x00\x00\x00"; /** @var int */ protected $opCode; /** @var int */ protected $maxPayload = 0; /** * Get maximum payload length. * * @return int */ public function getMaxPayload() { return $this->maxPayload; } /** * Set maximum payload length. * * @param int $length * @return \ElephantIO\Parser\Websocket\Payload */ public function setMaxPayload($length) { $this->maxPayload = $length; return $this; } /** * Mask a data according to the current mask key. * * @param string $data Data to mask * @return string Masked data */ protected function maskData($data) { $masked = ''; $data = str_split($data); $key = str_split($this->maskKey); foreach ($data as $i => $letter) { $masked .= $letter ^ $key[$i % 4]; } return $masked; } /** * Get payload opcode. * * @return int */ public function getOpCode() { return$this->opCode; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Parser/Websocket/Encoder.php
src/Parser/Websocket/Encoder.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Parser\Websocket; use ElephantIO\StringableInterface; /** * Encode the payload before sending it to a frame. * * Based on the work of the following: * - Ludovic Barreca (@ludovicbarreca), project founder * - Byeoung Wook (@kbu1564) in #49 * * @author Baptiste Clavié <baptiste@wisembly.com> */ class Encoder extends Payload implements StringableInterface { /** @var string */ private $data; /** @var string */ private $payload; /** @var string[] */ private $fragments = []; /** * @param string $data data to encode * @param integer $opCode OpCode to use (one of Payload's constant) * @param bool $mask Should we use a mask ? */ public function __construct($data, $opCode, $mask) { $this->data = $data; $this->opCode = $opCode; $this->mask = (bool) $mask; if (true === $this->mask) { $this->maskKey = random_bytes(4); } } /** * Get payload fragments. * * @return string[] */ public function getFragments() { return $this->fragments; } /** * Encode a data payload. * * @param string $data * @param int $opCode * @return string */ protected function doEncode($data, $opCode) { $pack = ''; $length = strlen($data); if (0xFFFF < $length) { $pack = pack('NN', ($length >> 0b100000) & 0xFFFFFFFF, $length & 0xFFFFFFFF); $length = 0x007F; } elseif (0x007D < $length) { $pack = pack('n*', $length); $length = 0x007E; } $payload = ($this->fin << 0b001) | $this->rsv[0]; $payload = ($payload << 0b001) | $this->rsv[1]; $payload = ($payload << 0b001) | $this->rsv[2]; $payload = ($payload << 0b100) | $opCode; $payload = ($payload << 0b001) | $this->mask; $payload = ($payload << 0b111) | $length; $payload = pack('n', $payload) . $pack; if (true === $this->mask) { $payload .= $this->maskKey; $data = $this->maskData($data); } return $payload . $data; } /** * Encode data. * * @return \ElephantIO\Parser\Websocket\Encoder */ public function encode() { if (null === $this->payload) { $data = $this->data; $length = strlen($data); $size = min($this->maxPayload > 0 ? $this->maxPayload : $length, $length); $this->fin = 0b0; $opCode = $this->opCode; while (strlen($data) > 0) { $count = $size; // reduce count with framing protocol size if ($count === $this->maxPayload) { if ($count > 125) { $count -= (0xFFFF >= $count) ? 2 : 8; } if (true === $this->mask) { $count -= strlen($this->maskKey); } $count -= 2; } // create payload fragment $s = substr($data, 0, $count); $data = substr($data, $count); if (0 === strlen($data)) { $this->fin = 0b1; } $this->fragments[] = $this->doEncode($s, $opCode); $opCode = static::OPCODE_CONTINUE; } $this->payload = implode('', $this->fragments); } return $this; } public function __toString() { $this->encode(); return $this->payload; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Parser/Websocket/Decoder.php
src/Parser/Websocket/Decoder.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Parser\Websocket; use Countable; use ElephantIO\StringableInterface; /** * Decode the payload from a received frame. * * Based on the work of Byeoung Wook (@kbu1564) in #49 * * @author Baptiste Clavié <baptiste@wisembly.com> */ class Decoder extends Payload implements Countable, StringableInterface { /** @var ?string */ private $payload = null; /** @var ?string */ private $data = null; /** @var ?int<0, max> */ private $length = null; /** @param string $payload Payload to decode */ public function __construct($payload) { $this->payload = $payload; } /** * Decode payload. * * @return void */ public function decode() { if (null !== $this->data) { return; } $length = count($this); // if ($payload !== null) and ($payload packet error)? // invalid websocket packet data or not (text, binary opCode) if (!$length) { return; } if ($this->payload) { $payload = array_map('ord', str_split($this->payload)); $this->fin = ($payload[0] >> 0b111); $this->rsv = [($payload[0] >> 0b110) & 0b1, // rsv1 ($payload[0] >> 0b101) & 0b1, // rsv2 ($payload[0] >> 0b100) & 0b1]; // rsv3 $this->opCode = $payload[0] & 0xF; $this->mask = (bool) ($payload[1] >> 0b111); $payloadOffset = 2; if ($length > 125) { $payloadOffset += (0xFFFF >= $length) ? 2 : 8; } $payload = implode('', array_map('chr', $payload)); if (true === $this->mask) { $this->maskKey = substr($payload, $payloadOffset, 4); $payloadOffset += 4; } $data = substr($payload, $payloadOffset, $length); if (true === $this->mask) { $data = $this->maskData($data); } $this->data = $data; } } public function count(): int { if (null === $this->payload) { return 0; } if (null === $this->length) { $length = ord($this->payload[1]) & 0x7F; if ($length === 126 || $length === 127) { if (false !== ($unpacked = unpack('H*', substr($this->payload, 2, ($length === 126 ? 2 : 8))))) { $length = (int) hexdec($unpacked[1]); } } if ($length >= 0) { $this->length = $length; } else { $this->length = 0; } } return $this->length; } public function __toString() { $this->decode(); return $this->data ?: ''; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Stream/Stream.php
src/Stream/Stream.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Stream; use ElephantIO\SocketUrl; use InvalidArgumentException; use Psr\Log\NullLogger; /** * Stream provides abstraction for socket client stream. * * @author Toha <tohenk@yahoo.com> */ abstract class Stream implements StreamInterface { /** * @var \ElephantIO\SocketUrl */ protected $url = null; /** * @var ?array<string, mixed> */ protected $context = null; /** * @var ?array<string, mixed> */ protected $options = null; /** * @var \Psr\Log\LoggerInterface */ protected $logger = null; /** * Constructor. * * @param string $url * @param array<string, mixed> $context * @param array<string, mixed> $options */ public function __construct($url, $context = [], $options = []) { $this->context = $context; $this->options = $options; $this->logger = isset($options['logger']) && $options['logger'] ? $options['logger'] : new NullLogger(); $this->url = new SocketUrl($url); if (isset($options['sio_path'])) { $this->url->setSioPath($options['sio_path']); } $this->initialize(); } /** * Destructor. */ public function __destruct() { $this->close(); } /** * Initialize. * * @return void */ protected function initialize() { } /** * Create socket stream. * * @param string $url * @param array<string, mixed> $context * @param array<string, mixed> $options * @return \ElephantIO\Stream\StreamInterface */ public static function create($url, $context = [], $options = []) { $class = SocketStream::class; if (isset($options['stream_factory'])) { $class = $options['stream_factory']; unset($options['stream_factory']); } if (!class_exists($class)) { throw new InvalidArgumentException(sprintf('Socket stream class %s not found!', $class)); } $clazz = new $class($url, $context, $options); if (!$clazz instanceof StreamInterface) { throw new InvalidArgumentException(sprintf('Class %s must implmenet StreamInterface!', $class)); } return $clazz; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Stream/StreamInterface.php
src/Stream/StreamInterface.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Stream; /** * An underlying socket stream to handle raw io. * * @author Toha <tohenk@yahoo.com> */ interface StreamInterface { public const EOL = "\r\n"; /** * Is stream available? * * @return bool */ public function available(); /** * Check if stream is currently readable. * * @return bool */ public function readable(); /** * Check if stream is already upgraded. * * @return bool */ public function upgraded(); /** * Open stream URL. * * @return void */ public function open(); /** * Close the stream. * * @return void */ public function close(); /** * Upgrade the stream. * * @return void */ public function upgrade(); /** * Is the stream was upgraded? * * @return bool */ public function wasUpgraded(); /** * Read data from underlying stream. * * @param int $size * @return string|false|null */ public function read($size = 0); /** * Write data to underlying stream. * * @param string $data * @return int */ public function write($data); /** * Get url. * * @return \ElephantIO\SocketUrl */ public function getUrl(); /** * Get errors from the last open attempts. * * @return array<int, mixed>|null */ public function getErrors(); /** * Get stream metadata. * * @return array<string, mixed>|null */ public function getMetadata(); /** * Get connection timeout (in second). * * @return float */ public function getTimeout(); /** * Set connection timeout. * * @param float $timeout Timeout in second * @return void */ public function setTimeout($timeout); }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Stream/SocketStream.php
src/Stream/SocketStream.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Stream; use ElephantIO\Util; use RuntimeException; /** * Basic stream to connect to the socket server which behave as an HTTP client. * * @author Toha <tohenk@yahoo.com> */ class SocketStream extends Stream { /** * @var ?resource */ protected $handle = null; /** * @var ?bool */ protected $upgraded = null; /** * @var ?bool */ protected $wasUpgraded = null; /** * @var ?array<int, mixed> */ protected $errors = null; /** * @var ?array<string, mixed> */ protected $metadata = null; protected function initialize() { $this->open(); } /** * Get connection timeout (in second). * * @return float */ public function getTimeout() { return isset($this->options['timeout']) ? $this->options['timeout'] : 5; } /** * Set connection timeout. * * @param float $timeout */ public function setTimeout($timeout) { if ($this->getTimeout() != $timeout) { $this->options['timeout'] = $timeout; $this->applyTimeout($timeout); } } /** * Apply connection timeout to underlying stream. * * @param float $timeout * @return void */ protected function applyTimeout($timeout) { if (is_resource($this->handle)) { stream_set_timeout($this->handle, (int) $timeout); } } /** * Read metadata from socket. * * @return array<string, mixed>|null */ protected function readMetadata() { if (is_resource($this->handle)) { $this->metadata = stream_get_meta_data($this->handle); return $this->metadata; } return null; } public function available() { return is_resource($this->handle); } public function readable() { // PATCH START: Native disconnect detection if (is_resource($this->handle) && feof($this->handle)) { return false; } // PATCH END if ($metadata = $this->readMetadata()) { return $metadata['eof'] ? false : true; } return false; } public function upgraded() { return $this->upgraded ? true : false; } public function open() { $errors = [null, null]; $timeout = $this->getTimeout(); $address = $this->url->getAddress(); $this->logger->info(sprintf('Stream connect: %s', $address)); $flags = STREAM_CLIENT_CONNECT; if (!isset($this->options['persistent']) || $this->options['persistent']) { $flags |= STREAM_CLIENT_PERSISTENT; } $context = !isset($this->context['headers']) ? $this->context : array_merge($this->context, ['headers' => Util::normalizeHeaders($this->context['headers'])]); $handle = @stream_socket_client( sprintf('%s/%s', $address, uniqid()), $errors[0], $errors[1], $timeout, $flags, stream_context_create($context) ); if (is_resource($handle)) { $this->handle = $handle; stream_set_blocking($this->handle, false); $this->applyTimeout($timeout); } else { $this->handle = null; $this->errors = $errors; } } public function upgrade() { if (null === $this->upgraded) { $this->upgraded = true; $this->wasUpgraded = true; } } public function wasUpgraded() { if ($this->wasUpgraded) { $this->wasUpgraded = false; return true; } return false; } public function close() { if (!is_resource($this->handle)) { return; } @stream_socket_shutdown($this->handle, STREAM_SHUT_RDWR); fclose($this->handle); $this->handle = null; } public function read($size = 0) { if (is_resource($this->handle)) { $data = $size > 0 ? fread($this->handle, $size) : fgets($this->handle); if (false !== $data && strlen($data)) { $this->logger->debug(sprintf('Stream receive: %s', Util::truncate(rtrim($data)))); } return $data; } return null; } public function write($data) { $bytes = null; if (is_resource($this->handle)) { $data = (string) $data; $len = strlen($data); while (true) { if (false === ($written = fwrite($this->handle, $data))) { throw new RuntimeException(sprintf('Unable to write %d data to stream!', strlen($data))); } if ($written > 0) { $lines = explode(static::EOL, substr($data, 0, $written)); foreach ($lines as $line) { $this->logger->debug(sprintf('Stream write: %s', Util::truncate($line))); } if (null === $bytes) { $bytes = $written; } else { $bytes += $written; } // all data has been written if ($len === $bytes) { break; } // this is the remaining data $data = substr($data, $written); } } } return (int) $bytes; } public function getUrl() { return $this->url; } public function getErrors() { return $this->errors; } public function getMetadata() { return $this->metadata; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Exception/ServerConnectionFailureException.php
src/Exception/ServerConnectionFailureException.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Exception; use Exception; use RuntimeException; class ServerConnectionFailureException extends RuntimeException { /** @var string php error message */ private $errorMessage; /** * Constructor. * * @param string $errorMessage * @param \Exception $previous */ public function __construct($errorMessage, ?Exception $previous = null) { parent::__construct(sprintf('An error occurred while trying to establish a connection to the server, %s', $errorMessage), 0, $previous); $this->errorMessage = $errorMessage; } /** * Get error message. * * @return string */ public function getErrorMessage() { return $this->errorMessage; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Exception/MalformedUrlException.php
src/Exception/MalformedUrlException.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Exception; use Exception; use InvalidArgumentException; class MalformedUrlException extends InvalidArgumentException { /** * Constructor. * * @param string $url * @param \Exception $previous */ public function __construct($url, ?Exception $previous = null) { parent::__construct(\sprintf('The url "%s" seems to be malformed', $url), 0, $previous); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Exception/SocketException.php
src/Exception/SocketException.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Exception; use Exception; use RuntimeException; class SocketException extends RuntimeException { /** * Constructor. * * @param int $errno * @param string $error * @param \Exception $previous */ public function __construct($errno, $error, ?Exception $previous = null) { parent::__construct( \sprintf( 'There was an error while attempting to open a connection to the socket (Err #%d : %s)', $errno, $error ), $errno, $previous ); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Exception/UnsuccessfulOperationException.php
src/Exception/UnsuccessfulOperationException.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Exception; use RuntimeException; class UnsuccessfulOperationException extends RuntimeException { }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Exception/UnsupportedActionException.php
src/Exception/UnsupportedActionException.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Exception; use BadMethodCallException; use ElephantIO\Engine\EngineInterface; use Exception; class UnsupportedActionException extends BadMethodCallException { /** * Constructor. * * @param \ElephantIO\Engine\EngineInterface $engine * @param string $action * @param \Exception $previous */ public function __construct(EngineInterface $engine, $action, ?Exception $previous = null) { parent::__construct( \sprintf('The action "%s" is not supported by the engine "%s"', $engine->getName(), $action), 0, $previous ); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/Transport.php
src/Engine/Transport.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine; use Psr\Log\LoggerAwareTrait; /** * Socket transport. * * @author Toha <tohenk@yahoo.com> */ abstract class Transport { use LoggerAwareTrait; /** * Socket interface. * * @var \ElephantIO\Engine\SocketInterface */ protected $sio; /** * Last operation timed out state. * * @var bool */ protected $timedout; /** * Constructor. * * @param \ElephantIO\Engine\SocketInterface $sio */ public function __construct($sio) { $this->sio = $sio; } /** * Send data. * * @param \ElephantIO\StringableInterface|string $data * @param array<string, mixed> $parameters * @return int|null Number of byte written */ abstract public function send($data, $parameters = []); /** * Receive data. * * @param float $timeout * @param array<string, mixed> $parameters * @return \ElephantIO\StringableInterface|string|null */ abstract public function recv($timeout = 0, $parameters = []); /** * Is last operation timed out? * * @return bool */ public function timedout() { return $this->timedout; } /** * Set last heartbeat. * * @return \ElephantIO\Engine\Transport */ protected function setHeartbeat() { if ($this->sio->getSession()) { $this->sio->getSession()->resetHeartbeat(); } return $this; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/Packet.php
src/Engine/Packet.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine; /** * Represents packet. * * @property int $proto Protocol id * @property int $type Message type * @property ?string $nsp Namespace * @property string $event Event name * @property ?int $ack Acknowledgement id * @property array<int|string, mixed> $args Event arguments * @property mixed $data Packet data * @property int $count Binary attachment count * @property \ElephantIO\Engine\Packet[] $next Nested packets * @author Toha <tohenk@yahoo.com> */ class Packet extends Store { protected function initialize() { $this->keys = ['+proto', 'type', 'nsp', 'event', 'ack', '!args', '!data', '_next', '_count']; } /** * Set arguments and data from first element of arguments. * * @param mixed $args * @return \ElephantIO\Engine\Packet */ public function setArgs($args) { if (is_array($args)) { $this->args = $args; $this->data = count($args) ? $args[0] : null; } return $this; } /** * Flatten packet into array of packet. * * @return \ElephantIO\Engine\Packet[] */ public function flatten() { $result = [$this]; foreach ((array) $this->next as $p) { $result = array_merge($result, $p->flatten()); } return $result; } /** * Peek packet with matched protocol. * * @param int $proto * @return \ElephantIO\Engine\Packet[] */ public function peek($proto) { $result = []; foreach ($this->flatten() as $p) { if ($p->proto === $proto) { $result[] = $p; } } return $result; } /** * Peek packet with matched protocol. * * @param int $proto * @return \ElephantIO\Engine\Packet|null */ public function peekOne($proto) { return count($packets = $this->peek($proto)) ? $packets[0] : null; } /** * Add nested packet. * * @param \ElephantIO\Engine\Packet $packet * @return \ElephantIO\Engine\Packet */ public function add($packet) { if (!$this->next) { $this->next = [$packet]; } else { $this->next = array_merge($this->next, [$packet]); } return $this; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/Store.php
src/Engine/Store.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine; use ElephantIO\Util; use InvalidArgumentException; /** * A key-value store used to store key-value data such as * session or packet. * * @author Toha <tohenk@yahoo.com> */ class Store { public const IDENTITY = '+'; public const PRIV = '_'; public const EXCLUSIVE = '!'; /** * Store keys, a key can be prefixed with flag: * - `+` to indicate an identifier, * - `_` to indicate a private key which will not be included when cast to string, or * - '!' to indicate mutually exclusive key (won't included if other was included) * * @var string[] */ protected $keys = []; /** * Normalized keys and flags. * * @var mixed[] */ protected $nkeys = []; /** * Store values. * * @var mixed[] */ protected $values = []; /** * Key flags. * * @var string[] */ protected $flags = [self::IDENTITY, self::PRIV, self::EXCLUSIVE]; /** * Values mapping. * * @var string[] */ protected $maps = []; /** * Constructor. */ final public function __construct() { $this->initialize(); foreach ($this->keys as $k) { $key = $this->getNormalizedKey($k); $flag = in_array($f = substr($k, 0, 1), $this->flags) ? $f : null; $this->nkeys[$key] = $flag; } } /** * Initialize store. * * @return void */ protected function initialize() { } /** * Set values mapping. * * @param array<int|string, mixed> $maps * @return \ElephantIO\Engine\Store */ public function setMaps($maps) { $this->maps = $maps; return $this; } /** * Get key and check its validity. * * @param string $key * @throws \InvalidArgumentException * @return string */ protected function getKey($key) { if (in_array($key, array_keys($this->nkeys))) { return $key; } throw new InvalidArgumentException(sprintf( 'Unexpected key %s, they are %s!', $key, implode(', ', array_keys($this->nkeys)) )); } /** * Get normalized key without flag. * * @param string $key * @return string */ protected function getNormalizedKey($key) { return in_array(substr($key, 0, 1), $this->flags) ? substr($key, 1) : $key; } /** * Get mapped value. * * @param string $key * @param mixed $value * @return string|null */ protected function getMappedValue($key, $value) { return isset($this->maps[$key]) ? $this->maps[$key][$value] : $value; } /** * Inspect data. * * @param array<int|string, mixed> $data * @return string */ public function inspect($data = null) { $data = null === $data && isset($this->data) ? $this->data : $data; return Util::toStr($data); } /** * Export key-value as array. * * @return array<string, mixed> */ public function toArray() { $result = []; foreach (array_keys($this->nkeys) as $key) { if (isset($this->values[$key])) { $result[$key] = $this->$key; } } return $result; } /** * Set key-value from array. * * @param array<string, mixed> $array * @return \ElephantIO\Engine\Store */ public function fromArray($array) { foreach (array_keys($this->nkeys) as $key) { if (isset($array[$key])) { $this->$key = $array[$key]; } } return $this; } /** * Get value. * * @param string $key * @return mixed */ public function __get($key) { $key = $this->getKey($key); return isset($this->values[$key]) ? $this->values[$key] : null; } /** * Set value. * * @param string $key * @param mixed $value * @return void */ public function __set($key, $value) { $key = $this->getKey($key); $this->values[$key] = $value; } /** * Check if key exists. * * @param string $key * @return bool */ public function __isset($key) { $key = $this->getKey($key); return isset($this->values[$key]); } public function __toString() { $title = null; $items = []; $xclusive = null; foreach ($this->nkeys as $key => $flag) { switch ($flag) { case static::PRIV: break; case static::IDENTITY: $title = $this->getMappedValue($key, $this->$key); break; default: if (isset($this->values[$key])) { $value = $this->getMappedValue($key, $this->$key); if (null !== $value && ($flag !== static::EXCLUSIVE || null === $xclusive)) { $items[$key] = $value; if ($flag === static::EXCLUSIVE) { $xclusive = true; } } } break; } } if (null === $title) { $clazz = get_class($this); $title = substr($clazz, strrpos($clazz, '\\') + 1); } return sprintf('%s%s', strtoupper($title), Util::toStr($items)); } /** * Create a key value store. * * @param array<string, mixed> $keyValuePair * @return static */ public static function create($keyValuePair) { $store = new static(); $store->fromArray($keyValuePair); return $store; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/Argument.php
src/Engine/Argument.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine; use \ElephantIO\Util; /** * Arguments to emit to server. * * To create any arguments to server: * * ```php * $args = new \ElephantIO\Engine\Argument('first', 2, ['data' => 3]); * ``` * * @author Toha <tohenk@yahoo.com> */ class Argument { /** * @var array<int|string, mixed> */ protected $args = []; /** * Constructor. */ public function __construct() { $this->args = func_get_args(); } /** * Get all arguments. * * @return array<int|string, mixed> */ public function getArguments() { return $this->args; } public function __toString() { return Util::toStr($this->args); } /** * Create argument from array. * * @param ?array<int|string, mixed> $array * @return \ElephantIO\Engine\Argument */ public static function from($array) { return null !== $array ? new self((array) $array) : new self(); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/EngineInterface.php
src/Engine/EngineInterface.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine; use Psr\Log\LoggerAwareInterface; /** * Represents an engine used within Elephant.io to send/receive messages from * a socket.io server. * * Loosely based on the work of the following: * - Ludovic Barreca (@ludovicbarreca) * - Mathieu Lallemand (@lalmat) * * @author Baptiste Clavié <baptiste@wisembly.com> * @author Toha <tohenk@yahoo.com> */ interface EngineInterface extends LoggerAwareInterface { /** * Get the name of the engine. * * @return string */ public function getName(); /** * Connect to the targeted server. * * @return \ElephantIO\Engine\EngineInterface */ public function connect(); /** * Is connected to server? * * @return bool */ public function connected(); /** * Disconnect from server. * * @return \ElephantIO\Engine\EngineInterface */ public function disconnect(); /** * Set socket namespace. * * @param string $namespace The namespace * @return \ElephantIO\Engine\Packet|null */ public function of($namespace); /** * Emit an event to server. * * @param string $event Event to emit * @param array<int|string, mixed>|\ElephantIO\Engine\Argument $args Arguments to send * @param bool $ack Set to true to request an ack * @return \ElephantIO\Engine\Packet|int|null Number of bytes written or acknowledged packet */ public function emit($event, $args, $ack = null); /** * Acknowledge a packet. * * @param \ElephantIO\Engine\Packet $packet Packet to acknowledge * @param array<int|string, mixed>|\ElephantIO\Engine\Argument $args Acknowledgement data * @return int|null Number of bytes written */ public function ack($packet, $args); /** * Wait for event to arrive. To wait for any event from server, simply pass null * as event name. * * @param ?string $event Event name * @param float $timeout Timeout in seconds * @return \ElephantIO\Engine\Packet|null */ public function wait($event, $timeout = 0); /** * Drain data from socket. * * @param float $timeout Timeout in seconds * @return \ElephantIO\Engine\Packet|null */ public function drain($timeout = 0); }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/SocketIO.php
src/Engine/SocketIO.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine; use ArrayObject; use ElephantIO\Engine\Argument; use ElephantIO\Engine\Packet; use ElephantIO\Engine\Transport\Polling; use ElephantIO\Engine\Transport\Websocket; use ElephantIO\Exception\SocketException; use ElephantIO\Exception\UnsupportedActionException; use ElephantIO\Stream\Stream; use ElephantIO\Util; use InvalidArgumentException; use RuntimeException; use Psr\Log\LoggerAwareTrait; /** * Elephant.io socket engine base class. * * @author Toha <tohenk@yahoo.com> */ abstract class SocketIO implements EngineInterface, SocketInterface { use LoggerAwareTrait; public const EIO_V1 = 1; // socket.io 0x public const EIO_V2 = 2; // socket.io 1x public const EIO_V3 = 3; // socket.io 2x public const EIO_V4 = 4; // socket.io 3x and newer public const TRANSPORT_POLLING = 'polling'; public const TRANSPORT_WEBSOCKET = 'websocket'; /** @var string Engine name */ protected $name = 'SocketIO'; /** @var string Socket url */ protected $url; /** @var ?string Normalized namespace without path prefix */ protected $namespace = ''; /** @var ?\ElephantIO\Engine\Session Session information */ protected $session; /** @var string[] Cookies received during handshake */ protected $cookies = []; /** @var \ElephantIO\Engine\Option Array of options for the engine */ protected $options; /** @var ?\ElephantIO\Stream\StreamInterface Resource to the connected stream */ protected $stream; /** @var ?string Current socket transport */ protected $transport = null; /** @var mixed[] Array of php stream context options */ protected $context = []; /** @var mixed[] Array of default options for the engine */ protected $defaults; /** @var array<string, array<int, string>> Array of packet maps */ protected $packetMaps = []; /** @var int[] Array of min and max of protocol */ protected $proto = [0, 0]; /** @var string Protocol delimiter */ protected $protoDelimiter = ''; /** @var ?\ElephantIO\Engine\Transport */ private $_transport = null; /** @var ?int Acknowledgement id */ private static $ack = null; /** * Constructor. * * @param string $url Socket URL * @param array<string, mixed> $options Engine options */ public function __construct($url, array $options = []) { $this->url = $url; if (isset($options['headers'])) { Util::handleDeprecatedHeaderOptions($options['headers']); } if (isset($options['context']['headers'])) { Util::handleDeprecatedHeaderOptions($options['context']['headers']); } if (isset($options['context'])) { $this->context = $options['context']; unset($options['context']); } $this->defaults = [ 'ua' => true, 'cors' => true, 'wait' => 10, 'timeout' => ini_get('default_socket_timeout'), 'reuse_connection' => true, 'transport' => static::TRANSPORT_POLLING, 'transports' => null, 'binary_as_resource' => true, ]; $this->initialize($options); $this->options = Option::create(array_replace($this->defaults, $options)); if (isset($this->packetMaps['proto']) && count($protos = array_keys($this->packetMaps['proto']))) { $this->proto = [min($protos), max($protos)]; } } /** * Do initilization. * * @param array<string, mixed> $options Engine options * @return void */ protected function initialize(&$options) { } /** * Set default options. * * @param array<string, mixed> $defaults Default options * @return void */ protected function setDefaults($defaults) { $this->defaults = array_merge($this->defaults, $defaults); } public function getName() { return $this->name; } /** * Get options. * * @return \ElephantIO\Engine\Option */ public function getOptions() { return $this->options; } /** * Get socket URL. * * @return string */ public function getUrl() { return $this->url; } /** * Get underlying socket stream. * * @param bool $create True to create the stream * @return \ElephantIO\Stream\StreamInterface|null */ public function getStream($create = false) { if ($create) { $this->createStream(); } return $this->stream; } /** * Get session. * * @return \ElephantIO\Engine\Session|null */ public function getSession() { return $this->session; } /** * Get cookies. * * @return string[] */ public function getCookies() { return $this->cookies; } /** * Get stream context. * * @return mixed[] */ public function getContext() { return $this->context; } /** * Get current socket transport. * * @return string|null */ public function getTransport() { return $this->transport; } /** * Set current socket transport. * * @param string $transport Socket transport name * @return \ElephantIO\Engine\SocketIO */ public function setTransport($transport) { if (!in_array($transport, $this->getTransports())) { throw new InvalidArgumentException(sprintf('Unsupported transport "%s"!', $transport)); } $this->transport = $transport; return $this; } /** * Get current transport. * * @return \ElephantIO\Engine\Transport|null */ protected function _transport() { if (null === $this->_transport || ($this->stream && $this->stream->wasUpgraded())) { $this->createStream(); if ($this->stream) { switch ($this->stream->upgraded()) { case true: $this->_transport = new Websocket($this); break; default: $this->_transport = new Polling($this); break; } if ($this->logger) { $this->_transport->setLogger($this->logger); } } } return $this->_transport; } public function connect() { if (!$this->connected()) { $this->setTransport($this->options->transport); $this->doHandshake(); $this->doAfterHandshake(); if ($this->isUpgradable()) { $this->doUpgrade(); } else { $this->doSkipUpgrade(); } $this->doConnected(); } return $this; } public function connected() { return $this->stream ? $this->stream->readable() : false; } public function disconnect() { if ($this->connected()) { if ($this->session) { $this->doClose(); } $this->reset(); } return $this; } public function of($namespace) { $normalized = Util::normalizeNamespace($namespace); if ($this->namespace !== $normalized) { $this->namespace = $normalized; return $this->doChangeNamespace(); } return null; } public function emit($event, $args, $ack = null) { if (!$args instanceof Argument) { $args = Argument::from($args); } list($proto, $data, $raws) = $this->createEvent($event, $args, $ack); $len = $this->send($proto, $data); if (is_array($raws)) { if ($transport = $this->_transport()) { foreach ($raws as $raw) { $len += $transport->send($raw); } } else { throw new RuntimeException('Unable to create transport!'); } } // wait for an ack if ($ack) { return $this->waitForPacket(function($packet) { return $this->matchAck($packet); }); } return $len; } public function ack($packet, $args) { if (!$args instanceof Argument) { $args = Argument::from($args); } list($proto, $data) = $this->createAck($packet, $args); return $this->send($proto, $data); } public function wait($event, $timeout = 0) { return $this->waitForPacket(function($packet) use ($event) { return $this->matchEvent($packet, $event); }, $timeout); } public function drain($timeout = 0) { if (($transport = $this->_transport()) && null !== ($data = $transport->recv($timeout))) { if ($this->logger) { $this->logger->debug(sprintf('Got data: %s', Util::truncate((string) $data))); } if ($data instanceof ArrayObject) { $data = (array) $data; } else { $data = (string) $data; } return $this->processData($data); } return null; } /** * Send protocol and its data to server. * * @param int $proto Protocol type * @param string $data Optional data to be sent * @return int|null Number of bytes written */ public function send($proto, $data = null) { if ($this->isProtocol($proto) && $transport = $this->_transport()) { $formatted = $this->formatProtocol($proto, $data); if ($this->logger) { $this->logger->debug(sprintf('Send data: %s', Util::truncate($formatted))); } return $transport->send($formatted); } return null; } /** * Send ping to server. * * @return bool */ public function ping() { if ($this->session && $this->session->needsHeartbeat()) { if ($this->logger) { $this->logger->debug('Sending ping to server'); } $this->doPing(); if ($this->session) { $this->session->resetHeartbeat(); } return true; } return false; } /** * Wait for a matched packet to arrive. * * @param callable $matcher * @param float $timeout * @return \ElephantIO\Engine\Packet|null */ protected function waitForPacket($matcher, $timeout = 0) { while (true) { if ($packet = $this->drain($timeout)) { if ($match = $matcher($packet)) { return $match; } if ($this->logger) { foreach ($packet->flatten() as $p) { $this->logger->info(sprintf('Ignoring packet: %s', Util::truncate((string) $p))); } } } if (($transport = $this->_transport()) && $transport->timedout()) { break; } } return null; } /** * Process one or more received data. If data contains more than one, * the next packet will be passed as first packet next attribute. * * @param string|array<int|string, mixed> $data Data to process * @return \ElephantIO\Engine\Packet|null */ protected function processData($data) { $result = null; $packets = (array) $data; while (count($packets)) { if ($packet = $this->decodePacket(array_shift($packets))) { $this->postPacket($packet, $packets); if (!$this->consumePacket($packet)) { if (null === $result) { $result = $packet; } else { $result->add($packet); } } } } return $result; } /** * Decode a packet. * * @param string $data * @return \ElephantIO\Engine\Packet|null */ abstract protected function decodePacket($data); /** * Post processing a packet. * * @param \ElephantIO\Engine\Packet $packet * @param string[] $more Remaining packet data to be processed * @return void */ protected function postPacket($packet, &$more) { } /** * Consume a packet. * * @param \ElephantIO\Engine\Packet $packet * @return bool */ protected function consumePacket($packet) { return false; } /** * Is namespace match? * * @param ?string $namespace * @return bool */ protected function matchNamespace($namespace) { if ((string) $namespace === $this->namespace || Util::normalizeNamespace($namespace) === $this->namespace) { return true; } return false; } /** * Create an event to sent to server. * * @param string $event * @param \ElephantIO\Engine\Argument $args * @param bool $ack * @return array<int, mixed> An indexed array which first element would be protocol id and second element is the data */ protected function createEvent($event, $args, $ack = null) { throw new UnsupportedActionException($this, 'createEvent'); } /** * Find matched event from packet. * * @param \ElephantIO\Engine\Packet $packet * @param ?string $event * @return \ElephantIO\Engine\Packet|null */ protected function matchEvent($packet, $event) { throw new UnsupportedActionException($this, 'matchEvent'); } /** * Create an acknowledgement. * * @param \ElephantIO\Engine\Packet $packet Packet to acknowledge * @param \ElephantIO\Engine\Argument $data Acknowledgement data * @return array<int, mixed> An indexed array which first element would be protocol id and second element is the data */ protected function createAck($packet, $data) { throw new UnsupportedActionException($this, 'createAck'); } /** * Find matched ack from packet. * * @param \ElephantIO\Engine\Packet $packet * @return \ElephantIO\Engine\Packet|null */ protected function matchAck($packet) { throw new UnsupportedActionException($this, 'matchAck'); } /** * Get or generate acknowledgement id. * * @param bool $generate * @return int|null */ protected function getAckId($generate = null) { if ($generate) { if (null === self::$ack) { self::$ack = 0; } else { self::$ack++; } } return self::$ack; } /** * Create a packet. * * @param int $proto * @return \ElephantIO\Engine\Packet */ protected function createPacket($proto) { $packet = new Packet(); $packet->proto = $proto; if (count($this->packetMaps)) { $packet->setMaps($this->packetMaps); } return $packet; } /** * Store successful connection handshake as session. * * @param array<string, mixed> $handshake * @param string[] $cookies * @return void */ protected function storeSession($handshake, $cookies = []) { $this->session = Session::from($handshake); $this->cookies = $cookies; } /** * Create socket stream. * * @throws \ElephantIO\Exception\SocketException * @return void */ protected function createStream() { if ($this->stream && !$this->stream->available()) { $this->stream = null; } if (!$this->stream) { $this->stream = Stream::create( $this->url, $this->context, array_merge($this->options->toArray(), ['logger' => $this->logger]) ); if ($errors = $this->stream->getErrors()) { throw new SocketException($errors[0], $errors[1]); } } } /** * Update or set connection timeout. * * @param float $timeout * @return \ElephantIO\Engine\SocketIO */ protected function setTimeout($timeout) { $this->options->timeout = $timeout; // stream already established? if ($this->stream) { $this->stream->setTimeout($timeout); } return $this; } /** * Check if socket transport is enabled. * * @param string $transport * @return bool */ protected function isTransportEnabled($transport) { $transports = $this->options->transports; return null === $transports || $transport === $transports || (is_array($transports) && in_array($transport, $transports)) ? true : false; } /** * Get supported socket transports. * * @return string[] */ protected function getTransports() { return [static::TRANSPORT_POLLING, static::TRANSPORT_WEBSOCKET]; } /** * Build query string parameters. * * @param ?string $transport * @return array<string, mixed> */ public function buildQueryParameters($transport) { return []; } /** * Build query from parameters. * * @param array<string, mixed> $query * @return string|null */ public function buildQuery($query) { if ($this->stream) { $path = null; if (isset($query['path'])) { $path = $query['path']; unset($query['path']); } return $this->stream->getUrl()->getUri($path, $query); } return null; } /** * Do reset. * * @return void */ protected function reset() { if ($this->stream) { $this->stream->close(); $this->stream = null; $this->session = null; $this->cookies = []; $this->_transport = null; } } /** * Check if protocol is valid. * * @param int $proto * @return bool True if it is a valid protocol */ protected function isProtocol($proto) { return $proto >= $this->proto[0] && $proto <= $this->proto[1] ? true : false; } /** * Format data for protocol. * * @param int $proto * @param string $data * @return string */ protected function formatProtocol($proto, $data = null) { return implode($this->protoDelimiter, $this->buildProtocol($proto, $data)); } /** * Build protocol data. * * @param int $proto * @param string $data * @return array<int, int|string|null> */ protected function buildProtocol($proto, $data = null) { return [$proto, $data]; } /** * Is transport can be upgraded to websocket? * * @return bool */ protected function isUpgradable() { return $this->session && in_array(static::TRANSPORT_WEBSOCKET, $this->session->upgrades) && $this->isTransportEnabled(static::TRANSPORT_WEBSOCKET) ? true : false; } /** * Do on handshake. * * @return void */ protected function doHandshake() { } /** * Do on after handshake. * * @return void */ protected function doAfterHandshake() { } /** * Do on transport upgrade. * * @return void */ protected function doUpgrade() { } /** * Do on skip upgrade. * * @return void */ protected function doSkipUpgrade() { } /** * Do on change namespace. * * @return \ElephantIO\Engine\Packet|null */ protected function doChangeNamespace() { return null; } /** * Do on connected. * * @return void */ protected function doConnected() { } /** * Do on ping. * * @return void */ protected function doPing() { } /** * Do on close. * * @return void */ protected function doClose() { } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/SocketInterface.php
src/Engine/SocketInterface.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine; /** * Socket host interface. * * @author Toha <tohenk@yahoo.com> */ interface SocketInterface { /** * Get options. * * @return \ElephantIO\Engine\Option */ public function getOptions(); /** * Get socket URL. * * @return string */ public function getUrl(); /** * Get socket stream. * * @param bool $create True to create the stream * @return \ElephantIO\Stream\StreamInterface|null */ public function getStream($create = false); /** * Get stream context. * * @return array<string, mixed> */ public function getContext(); /** * Get cookies. * * @return string[] */ public function getCookies(); /** * Get session. * * @return \ElephantIO\Engine\Session|null */ public function getSession(); /** * Send ping to server. * * @return bool */ public function ping(); /** * Build query string parameters. * * @param ?string $transport * @return array<string, mixed> */ public function buildQueryParameters($transport); /** * Build query from parameters. * * @param array<string, mixed> $query * @return string */ public function buildQuery($query); }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/Session.php
src/Engine/Session.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine; /** * Represents session. * * @property string $id Session id * @property float $heartbeat Last heartbeat time * @property float[] $timeouts Ping timeout and interval * @property string[] $upgrades Upgradable transports * @property ?int $max_payload Maximum payload length * @author Baptiste Clavié <baptiste@wisembly.com> * @author Toha <tohenk@yahoo.com> */ class Session extends Store { protected function initialize() { $this->keys = ['id', 'upgrades', 'timeouts', 'max_payload', '_heartbeat']; } /** * Get current time. * * @return float */ protected function getTime() { return \microtime(true); } /** * Get ping timeout. * * @return float */ public function getTimeout() { return $this->timeouts['timeout']; } /** * Get ping interval. * * @return float */ public function getInterval() { return $this->timeouts['interval']; } /** * Checks whether a new heartbeat is necessary, and does a new heartbeat if it is the case. * * @return bool true if there was a heartbeat, false otherwise */ public function needsHeartbeat() { if ($this->timeouts['interval'] > 0) { $time = $this->getTime(); $heartbeat = $this->timeouts['interval'] + $this->heartbeat - 5; if ($time > $heartbeat) { return true; } } return false; } /** * Reset heart beat. * * @return \ElephantIO\Engine\Session */ public function resetHeartbeat() { $this->heartbeat = $this->getTime(); return $this; } /** * Create session from array. * * @param array<string, mixed> $array * @return \ElephantIO\Engine\Session */ public static function from($array) { $mapped = []; foreach ($array as $k => $v) { $key = $k; switch ($k) { case 'sid': $key = 'id'; break; case 'pingInterval': $key = 'timeouts'; $v = ['interval' => $v]; break; case 'pingTimeout': $key = 'timeouts'; $v = ['timeout' => $v]; break; case 'maxPayload': $key = 'max_payload'; break; } if (is_array($v) && isset($mapped[$key])) { $mapped[$key] = array_merge($mapped[$key], $v); } else { $mapped[$key] = $v; } } return static::create($mapped); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/Option.php
src/Engine/Option.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine; /** * Represents options. * * @property int $version Engine version (EIO) * @property ?array<string, int> $auth Authentication handshake * @property array<string, string> $headers Request headers * @property int $wait A wait delay applied after reading from stream (in ms) * @property float $timeout Stream connection timeout (in second) * @property bool $reuse_connection Enable or disable existing connection reuse * @property string[]|string|null $transports Enabled transports * @property string $transport Initial transport * @property bool $persistent Enable or disable persistent connection * @property bool $binary_as_resource Return received binary data as resource * @property string $sio_path Socket.io path, default to socket.io * @property bool $cors True to send referer and origin * @property bool|string $ua True to send user agent or set user agent string * @property int $max_payload Maximum allowable payload length * @property int $binary_chunk_size Binary payload chunk size * @property string $stream_factory A custom socket stream class name * @author Toha <tohenk@yahoo.com> */ class Option extends Store { protected function initialize() { $this->keys = ['auth', 'headers', 'reuse_connection', 'timeout', 'transports', 'transport', 'version', 'wait', 'persistent', 'binary_as_resource', 'sio_path', 'cors', 'ua', '_max_payload', '_binary_chunk_size', '_stream_factory']; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/Transport/Websocket.php
src/Engine/Transport/Websocket.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine\Transport; use DomainException; use ElephantIO\Engine\Transport; use ElephantIO\Parser\Websocket\Decoder; use ElephantIO\Parser\Websocket\Encoder; use RuntimeException; /** * Websocket transport. * * @author Toha <tohenk@yahoo.com> */ class Websocket extends Transport { /** * Network safe fread wrapper. * * @param integer $bytes * @param float $timeout * @throws \RuntimeException * @return string */ protected function readBytes($bytes, $timeout = 0) { $data = ''; if ($stream = $this->sio->getStream()) { $chunk = null; $start = microtime(true); while ($bytes > 0) { if ($timeout > 0 && microtime(true) - $start >= $timeout) { $this->timedout = true; break; } if (!$stream->readable()) { throw new RuntimeException('Stream disconnected'); } if (false === ($chunk = $stream->read($bytes))) { break; } if ($chunk) { $bytes -= strlen($chunk); $data .= $chunk; $this->sio->ping(); } } if (false === $chunk) { throw new RuntimeException('Could not read from stream'); } } return $data; } /** * Be careful, this method may hang your script, as we're not in a non * blocking mode. * * @param float $timeout * @throws \DomainException * @throws \RuntimeException * @return \ElephantIO\Parser\Websocket\Decoder|null */ protected function doRead($timeout = 0) { $stream = $this->sio->getStream(); if (!$stream || !$stream->readable()) { return null; } /* * The first byte contains the FIN bit, the reserved bits, and the * opcode... We're not interested in them. Yet. * the second byte contains the mask bit and the payload's length */ $data = $this->readBytes(2, $timeout); $bytes = unpack('C*', $data); if (empty($bytes[2])) { return null; } $mask = ($bytes[2] & 0b10000000) >> 7; $length = $bytes[2] & 0b01111111; /* * Here is where it is getting tricky : * * - If the length <= 125, then we do not need to do anything ; * - if the length is 126, it means that it is coded over the next 2 bytes ; * - if the length is 127, it means that it is coded over the next 8 bytes. * * But, here's the trick : we cannot interpret a length over 127 if the * system does not support 64bits integers (such as Windows, or 32bits * processors architectures). */ switch ($length) { case 0x7D: // 125 break; case 0x7E: // 126 $data .= $bytes = $this->readBytes(2); $bytes = unpack('n', $bytes); if (empty($bytes[1])) { throw new RuntimeException('Invalid extended packet len'); } $length = $bytes[1]; break; case 0x7F: // 127 // are (at least) 64 bits not supported by the architecture ? if (8 > PHP_INT_SIZE) { throw new DomainException('64 bits unsigned integer are not supported on this architecture'); } /* * As (un)pack does not support unpacking 64bits unsigned * integer, we need to split the data * * {@link http://stackoverflow.com/questions/14405751/pack-and-unpack-64-bit-integer} */ $data .= $bytes = $this->readBytes(8); if (is_array($unpacked = unpack('N2', $bytes))) { list($left, $right) = array_values($unpacked); $length = $left << 32 | $right; } break; } // incorporate the mask key if the mask bit is 1 if (true === (bool) $mask) { $data .= $this->readBytes(4); } $data .= $this->readBytes($length); $this->setHeartbeat(); // decode the payload return new Decoder($data); } /** * Write to the stream. * * @param string $data * @return int */ public function doWrite($data) { $stream = $this->sio->getStream(); if (!$stream) { throw new RuntimeException('Stream not available!'); } $bytes = $stream->write($data); $this->setHeartbeat(); // wait a little bit of time after this message was sent usleep((int) $this->sio->getOptions()->wait); return $bytes; } /** * Create payload. * * @param string $data * @param int $encoding * @throws \RuntimeException * @return \ElephantIO\Parser\Websocket\Encoder */ public function getPayload($data, $encoding = Encoder::OPCODE_TEXT) { $maxPayload = $this->sio->getSession() && $this->sio->getSession()->max_payload ? $this->sio->getSession()->max_payload : $this->sio->getOptions()->max_payload; if (mb_strlen($data) > $maxPayload) { throw new RuntimeException(sprintf( 'Payload is exceed the maximum allowed length of %d!', $maxPayload )); } $encoder = new Encoder($data, $encoding, true); $encoder->setMaxPayload($maxPayload); return $encoder; } public function send($data, $parameters = []) { if (!$data instanceof Encoder) { $data = $this->getPayload($data, isset($parameters['encoding']) ? $parameters['encoding'] : Encoder::OPCODE_TEXT); } $bytes = 0; $fragments = $data->encode()->getFragments(); for ($i = 0; $i < count($fragments); $i++) { $bytes += $this->doWrite($fragments[$i]); } return $bytes; } public function recv($timeout = 0, $parameters = []) { $this->timedout = false; return $this->doRead($timeout); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/Transport/Polling.php
src/Engine/Transport/Polling.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine\Transport; use ElephantIO\Engine\SocketIO; use ElephantIO\Engine\Transport; use ElephantIO\Parser\Polling\Decoder; use ElephantIO\Parser\Polling\Encoder; use ElephantIO\Stream\StreamInterface; use ElephantIO\Util; /** * HTTP polling transport. * * @author Toha <tohenk@yahoo.com> */ class Polling extends Transport { public const MIMETYPE_OCTET_STREAM = 'application/octet-stream'; public const MIMETYPE_JSON = 'application/json'; public const MIMETYPE_PLAIN_TEXT = 'text/plain'; /** * @var ?array<string, mixed> */ protected $result = null; /** * @var ?int */ protected $bytesWritten = null; /** * Get connection default headers. * * @return array<string, mixed> */ protected function getDefaultHeaders() { $context = $this->sio->getContext(); $headers = ['Accept' => '*/*']; if ($this->sio->getOptions()->cors) { $headers['Origin'] = $context['headers']['Origin'] ?? $this->sio->getUrl(); $headers['Referer'] = $context['headers']['Referer'] ?? $this->sio->getUrl(); } if ($ua = $this->sio->getOptions()->ua) { if (is_string($ua)) { $headers['User-Agent'] = $ua; } else { $headers['User-Agent'] = sprintf('Elephant.io/%s', ($version = Util::getVersion()) ? $version : '*'); } } if (count($cookies = $this->sio->getCookies())) { $headers['Cookie'] = implode('; ', $cookies); } $headers['Connection'] = $this->sio->getOptions()->reuse_connection ? 'keep-alive' : 'close'; return $headers; } /** * Get websocket upgrade headers. * * @return array<string, mixed> */ protected function getUpgradeHeaders() { $hash = sha1(uniqid((string) mt_rand(), true), true); if ($this->sio->getOptions()->version >= SocketIO::EIO_V3) { $hash = substr($hash, 0, 16); } return array_merge($this->getDefaultHeaders(), [ 'Upgrade' => 'websocket', 'Connection' => 'Upgrade', 'Sec-WebSocket-Key' => base64_encode($hash), 'Sec-WebSocket-Version' => '13', ]); } /** * Perform HTTP request to server. * * @param string $uri * @param array<string, mixed> $headers Key-value pairs * @param array<string, mixed> $options Request options * @return bool */ protected function request($uri, $headers = [], $options = []) { $stream = $this->sio->getStream(true); if ($stream && $stream->available()) { $method = isset($options['method']) ? $options['method'] : 'GET'; $timeout = isset($options['timeout']) ? $options['timeout'] : 0; $skip_body = isset($options['skip_body']) ? $options['skip_body'] : false; $payload = isset($options['payload']) ? $options['payload'] : null; $encoding = isset($options['encoding']) ? $options['encoding'] : 'UTF-8'; if ($payload) { $charset = null; $contentType = $headers['Content-Type'] ?? null; if (null === $contentType) { if (false !== strpos($payload, "\x00")) { $contentType = static::MIMETYPE_OCTET_STREAM; } else { $contentType = static::MIMETYPE_PLAIN_TEXT; $charset = $encoding; $payload = mb_convert_encoding($payload, $charset, 'ISO-8859-1'); } } if ($contentType) { if ($charset) { if (false !== stripos($contentType, 'charset')) { $charset = null; } else { $charset = sprintf('charset=%s', $charset); } } $headers = array_merge([ 'Content-Type' => implode('; ', array_filter([$contentType, $charset])), 'Content-Length' => strlen($payload), ], $headers); } } $headers = array_merge(['Host' => $stream->getUrl()->getHost()], $headers); if (isset($this->sio->getOptions()->headers)) { $headers = array_merge($headers, $this->sio->getOptions()->headers); } $request = array_merge([ sprintf('%s %s HTTP/1.1', strtoupper($method), $uri), ], Util::normalizeHeaders($headers)); $request = implode(StreamInterface::EOL, $request) . StreamInterface::EOL . StreamInterface::EOL . $payload; $this->bytesWritten = $stream->write($request); $this->result = ['status' => null, 'headers' => [], 'body' => null]; // wait for response $header = true; $len = null; $closed = null; $contentType = null; $chunked = null; $start = microtime(true); while (true) { if ($timeout > 0 && microtime(true) - $start >= $timeout) { $this->timedout = true; break; } if (!$stream->readable()) { break; } if ($content = $stream->read($header ? 0 : (int) $len)) { if ($content === StreamInterface::EOL && $header && count($this->result['headers'])) { if ($skip_body) { break; } $header = false; } else { if ($header) { if ($content = trim($content)) { if (null === $this->result['status']) { $matches = null; if (preg_match('/^(?P<HTTP>(HTTP|http)\/(\d+(\.\d+)?))\s(?P<CODE>(\d+))\s(?P<STATUS>(.*))/', $content, $matches)) { $this->result['status'] = [$matches['HTTP'], (int) $matches['CODE'], $matches['STATUS']]; } } else { list($key, $value) = explode(':', $content, 2); $value = trim($value); if (null === $len && strtolower($key) === 'content-length') { $len = (int) $value; } if (null === $chunked && strtolower($key) === 'transfer-encoding' && strtolower($value) === 'chunked') { $chunked = true; } if (null === $contentType && strtolower($key) === 'content-type') { $contentType = $value; } if (null === $closed && strtolower($key) === 'connection' && strtolower($value) === 'close') { $closed = true; } // allow multiple values if (isset($this->result['headers'][$key])) { if (!is_array($this->result['headers'][$key])) { $this->result['headers'][$key] = [$this->result['headers'][$key]]; } $this->result['headers'][$key][] = $value; } else { $this->result['headers'][$key] = $value; } } } } else { $this->result['body'] .= $content; if ($chunked && null === $len && $content === '0' . StreamInterface::EOL) { $this->result['body'] = $this->decodeChunked($this->result['body']); break; } if ($len === strlen($this->result['body'])) { break; } } } } usleep($this->sio->getOptions()->wait); } // decode JSON if necessary if ($this->result['body'] && $contentType === static::MIMETYPE_JSON) { $this->result['body'] = json_decode($this->result['body'], true); } if ($closed) { if ($this->logger) { $this->logger->debug('Connection closed by server'); } $stream->close(); } if ($this->result['status']) { $this->setHeartbeat(); } return count($this->result['headers']) ? true : false; } return false; } /** * Get response headers. * * @return array<string, mixed>|null */ public function getHeaders() { return is_array($this->result) ? $this->result['headers'] : null; } /** * Get response body. * * @return array<int|string, mixed>|string|null */ public function getBody() { return is_array($this->result) ? $this->result['body'] : null; } /** * Get response status. * * @return array<int, mixed>|null Index 0 is HTTP version, index 1 is status code, and index 2 is status message */ public function getStatus() { return is_array($this->result) ? $this->result['status'] : null; } /** * Get response status code. * * @return int|null Status code */ public function getStatusCode() { return is_array($status = $this->getStatus()) ? $status[1] : null; } /** * Get response header. * * @param string $name Header name * @return array<string, mixed>|string|null */ public function getHeader($name) { if (is_array($headers = $this->getHeaders())) { foreach ($headers as $k => $v) { if (strtolower($name) === strtolower($k)) { return $v; } } } return null; } /** * Get cookies from response headers. * * @return string[] */ public function getCookies() { $cookies = []; if ($cookie = $this->getHeader('Set-Cookie')) { foreach ((array) $cookie as $value) { $value = explode(';', $value); $cookies[] = $value[0]; } } return $cookies; } /** * Decode chunked response. * * Copied from https://stackoverflow.com/questions/10793017/how-to-easily-decode-http-chunked-encoded-string-when-making-raw-http-request * * @param string $str Chunked string * @return string */ protected function decodeChunked($str) { for ($res = ''; !empty($str); $str = trim($str)) { if (false !== ($pos = strpos($str, StreamInterface::EOL))) { $len = (int) hexdec(substr($str, 0, $pos)); $res .= substr($str, $pos + 2, $len); $str = substr($str, $pos + 2 + $len); } } return $res; } public function send($data, $parameters = []) { if (!$data instanceof Encoder) { $data = new Encoder($data, $this->sio->getOptions()->version); } $options = ['method' => 'POST', 'payload' => $data, 'timeout' => $this->sio->getOptions()->timeout]; $headers = $this->getDefaultHeaders(); $code = 200; $transport = isset($parameters['transport']) ? $parameters['transport'] : $this->sio->getOptions()->transport; $uri = $this->sio->buildQuery($this->sio->buildQueryParameters($transport)); $this->request($uri, $headers, $options); if ($this->getStatusCode() === $code) { return $this->bytesWritten; } return null; } public function recv($timeout = 0, $parameters = []) { $this->timedout = false; $options = ['timeout' => $timeout]; if (isset($parameters['upgrade']) && $parameters['upgrade']) { $headers = $this->getUpgradeHeaders(); $options['skip_body'] = true; $code = 101; } else { $headers = $this->getDefaultHeaders(); $code = 200; } $transport = isset($parameters['transport']) ? $parameters['transport'] : $this->sio->getOptions()->transport; $uri = $this->sio->buildQuery($this->sio->buildQueryParameters($transport)); $this->request($uri, $headers, $options); if ($this->getStatusCode() === $code) { $body = $this->getBody(); if (is_string($body)) { return new Decoder($body, $this->sio->getOptions()->version, $this->getHeader('Content-Type') === static::MIMETYPE_OCTET_STREAM); } elseif (is_array($body)) { if ($encoded = json_encode($body)) { return $encoded; } } else { return (string) $this->getStatusCode(); } } return null; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/SocketIO/Version0X.php
src/Engine/SocketIO/Version0X.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine\SocketIO; use ElephantIO\Engine\SocketIO; use ElephantIO\Exception\ServerConnectionFailureException; use ElephantIO\SequenceReader; use ElephantIO\Util; use RuntimeException; /** * Implements the dialog with socket.io server 0.x. * * Based on the work of Baptiste Clavié (@Taluu) * * @auto ByeoungWook Kim <quddnr145@gmail.com> * @link https://tools.ietf.org/html/rfc6455#section-5.2 Websocket's RFC */ class Version0X extends SocketIO { public const PROTO_DISCONNECT = 0; public const PROTO_CONNECT = 1; public const PROTO_HEARTBEAT = 2; public const PROTO_MESSAGE = 3; public const PROTO_JSON = 4; public const PROTO_EVENT = 5; public const PROTO_ACK = 6; public const PROTO_ERROR = 7; public const PROTO_NOOP = 8; /** @var ?int */ private $ackId = null; protected function initialize(&$options) { $this->name = 'SocketIO Version 0.X'; $this->protoDelimiter = ':'; $this->packetMaps = [ 'proto' => [ static::PROTO_DISCONNECT => 'disconnect', static::PROTO_CONNECT => 'connect', static::PROTO_HEARTBEAT => 'heartbeat', static::PROTO_MESSAGE => 'message', static::PROTO_JSON => 'json', static::PROTO_EVENT => 'event', static::PROTO_ACK => 'ack', static::PROTO_ERROR => 'error', static::PROTO_NOOP => 'noop', ] ]; $this->setDefaults(['version' => static::EIO_V1]); } protected function matchEvent($packet, $event) { foreach ($packet->peek(static::PROTO_EVENT) as $found) { if ($this->matchNamespace($found->nsp) && ($found->event === $event || null === $event)) { return $found; } } return null; } protected function createEvent($event, $args, $ack = null) { $args = $args->getArguments(); $this->ackId = $ack ? $this->getAckId(true) : null; return [static::PROTO_EVENT, json_encode(['name' => $event, 'args' => $this->replaceResources($args)]), null]; } protected function matchAck($packet) { foreach ($packet->peek(static::PROTO_ACK) as $found) { if ($this->matchNamespace($found->nsp) && $found->ack == $this->getAckId()) { return $found; } } return null; } protected function createAck($packet, $data) { return [static::PROTO_ACK, implode('+', [$packet->ack, json_encode($data->getArguments())])]; } protected function decodePacket($data) { $seq = new SequenceReader($data); $proto = $seq->readUntil($this->protoDelimiter); if (null === $proto && is_numeric($seq->getData())) { $proto = $seq->getData(); } $proto = (int) $proto; if ($this->isProtocol($proto)) { $packet = $this->createPacket($proto); if ($ack = $seq->readUntil($this->protoDelimiter)) { if ('+' === substr($ack, -1)) { $ack = substr($ack, 0, -1); } $packet->ack = (int) $ack; } if (null === ($nsp = $seq->readUntil($this->protoDelimiter)) && !$seq->isEof()) { $nsp = $seq->read(null); } $packet->nsp = $nsp; $packet->data = !$seq->isEof() ? $seq->getData() : null; switch ($packet->proto) { case static::PROTO_JSON: if ($packet->data) { $packet->data = json_decode($packet->data, true); } break; case static::PROTO_EVENT: if ($packet->data) { $data = json_decode($packet->data, true); $this->replaceBuffers($data['args']); $packet->event = $data['name']; $packet->setArgs($data['args']); } break; case static::PROTO_ACK: if ($packet->data) { list($ack, $data) = explode('+', $packet->data, 2); $packet->ack = (int) $ack; $packet->setArgs(json_decode($data, true)); } break; } if ($this->logger) { $this->logger->info(sprintf('Got packet: %s', Util::truncate((string) $packet))); } return $packet; } return null; } protected function consumePacket($packet) { switch ($packet->proto) { case static::PROTO_DISCONNECT: if ($this->logger) { $this->logger->debug('Connection closed by server'); } $this->reset(); break; case static::PROTO_HEARTBEAT: if ($this->logger) { $this->logger->debug('Got HEARTBEAT'); } $this->send(static::PROTO_HEARTBEAT); break; case static::PROTO_NOOP: break; default: return false; } return true; } /** * Replace arguments with resource content. * * @param array<int|string, mixed> $array * @return array<int|string, mixed> */ protected function replaceResources($array) { if (count($array)) { foreach ($array as &$value) { if (is_resource($value)) { fseek($value, 0); if ($content = stream_get_contents($value)) { $value = $content; } else { $value = null; } } if (is_array($value)) { $value = $this->replaceResources($value); } } } return $array; } /** * Replace returned buffer content. * * @param array<int|string, mixed> $array * @return void */ protected function replaceBuffers(&$array) { if (count($array)) { foreach ($array as &$value) { if (is_array($value) && isset($value['type']) && isset($value['data'])) { if ($value['type'] === 'Buffer') { $value = implode(array_map('chr', $value['data'])); if ($this->options->binary_as_resource) { $value = Util::toResource($value); } } } if (is_array($value)) { $this->replaceBuffers($value); } } } } protected function buildProtocol($proto, $data = null) { $items = [$proto, $proto === static::PROTO_EVENT && null !== $this->ackId ? $this->ackId . '+' : '', $this->namespace]; if (null !== $data) { $items[] = $data; } return $items; } public function buildQueryParameters($transport) { $transports = [static::TRANSPORT_POLLING => 'xhr-polling']; if (null === $transport) { $transport = $this->options->transport; } if (isset($transports[$transport])) { $transport = $transports[$transport]; } $path = [$this->options->version, $transport]; if ($this->session) { $path[] = $this->session->id; } return ['path' => implode('/', $path)]; } protected function doHandshake() { if (null !== $this->session) { return; } if ($this->logger) { $this->logger->info('Starting handshake'); } // set timeout to default $this->setTimeout($this->defaults['timeout']); if ($transport = $this->_transport()) { if (null === ($data = $transport->recv($this->options->timeout))) { throw new ServerConnectionFailureException('unable to perform handshake'); } if ($this->protoDelimiter) { $sess = explode($this->protoDelimiter, (string) $data); $handshake = [ 'sid' => $sess[0], 'pingInterval' => (int) $sess[1], 'pingTimeout' => (int) $sess[2], 'upgrades' => explode(',', $sess[3]), ]; /** @var \ElephantIO\Engine\Transport\Polling $transport */ $this->storeSession($handshake, $transport->getCookies()); if ($this->logger) { $this->logger->info(sprintf('Handshake finished with %s', (string) $this->session)); } } } } protected function doUpgrade() { if ($this->logger) { $this->logger->info('Starting websocket upgrade'); } // set timeout based on handshake response if ($this->session) { $this->setTimeout($this->session->getTimeout()); } if ($transport = $this->_transport()) { if (null !== $transport->recv($this->options->timeout, ['transport' => static::TRANSPORT_WEBSOCKET, 'upgrade' => true])) { $this->setTransport(static::TRANSPORT_WEBSOCKET); if ($this->stream) { $this->stream->upgrade(); } else { throw new RuntimeException('Unable to perform websocket upgrade, stream is not avaialble!'); } if ($this->logger) { $this->logger->info('Websocket upgrade completed'); } } else { if ($this->logger) { $this->logger->info('Upgrade failed, skipping websocket'); } } } } protected function doSkipUpgrade() { // send get request to setup connection if ($transport = $this->_transport()) { $transport->recv($this->options->timeout); } } protected function doChangeNamespace() { $this->send(static::PROTO_CONNECT); $packet = $this->drain(); if ($packet && ($packet = $packet->peekOne(static::PROTO_CONNECT))) { if ($this->logger) { $this->logger->debug('Successfully connected'); } } return $packet; } protected function doPing() { $this->send(static::PROTO_HEARTBEAT); } protected function doClose() { $this->send(static::PROTO_DISCONNECT); // don't crash server, wait for disconnect packet to be received if ($this->transport === static::TRANSPORT_WEBSOCKET && '' === $this->namespace) { $this->drain($this->options->timeout); } } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/SocketIO/Version3X.php
src/Engine/SocketIO/Version3X.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine\SocketIO; /** * Implements the dialog with socket.io server 3.x. * * @author Toha <tohenk@yahoo.com> */ class Version3X extends Version1X { protected function initialize(&$options) { parent::initialize($options); $this->name = 'SocketIO Version 3.X'; $this->setDefaults(['version' => static::EIO_V4]); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/SocketIO/Version1X.php
src/Engine/SocketIO/Version1X.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine\SocketIO; use ElephantIO\Engine\SocketIO; use ElephantIO\Engine\Transport\Polling; use ElephantIO\Exception\ServerConnectionFailureException; use ElephantIO\Exception\UnsuccessfulOperationException; use ElephantIO\Parser\Polling\Decoder as PollingDecoder; use ElephantIO\Parser\Websocket\Encoder as WebsocketEncoder; use ElephantIO\SequenceReader; use ElephantIO\Util; use ElephantIO\Yeast; use InvalidArgumentException; use RuntimeException; /** * Implements the dialog with socket.io server 1.x. * * Based on the work of Mathieu Lallemand (@lalmat) * * @author Baptiste Clavié <baptiste@wisembly.com> * @link https://tools.ietf.org/html/rfc6455#section-5.2 Websocket's RFC */ class Version1X extends SocketIO { public const PROTO_OPEN = 0; public const PROTO_CLOSE = 1; public const PROTO_PING = 2; public const PROTO_PONG = 3; public const PROTO_MESSAGE = 4; public const PROTO_UPGRADE = 5; public const PROTO_NOOP = 6; public const PACKET_CONNECT = 0; public const PACKET_DISCONNECT = 1; public const PACKET_EVENT = 2; public const PACKET_ACK = 3; public const PACKET_ERROR = 4; public const PACKET_BINARY_EVENT = 5; public const PACKET_BINARY_ACK = 6; protected function initialize(&$options) { $this->name = 'SocketIO Version 1.X'; $this->packetMaps = [ 'proto' => [ static::PROTO_OPEN => 'open', static::PROTO_CLOSE => 'close', static::PROTO_PING => 'ping', static::PROTO_PONG => 'pong', static::PROTO_MESSAGE => 'message', static::PROTO_UPGRADE => 'upgrade', static::PROTO_NOOP => 'noop', ], 'type' => [ static::PACKET_CONNECT => 'connect', static::PACKET_DISCONNECT => 'disconnect', static::PACKET_EVENT => 'event', static::PACKET_ACK => 'ack', static::PACKET_ERROR => 'error', static::PACKET_BINARY_EVENT => 'binary-event', static::PACKET_BINARY_ACK => 'binary-ack', ] ]; $this->setDefaults(['version' => static::EIO_V2, 'max_payload' => 10e7, 'binary_chunk_size' => 8192]); } protected function matchEvent($packet, $event) { foreach ($packet->peek(static::PROTO_MESSAGE) as $found) { if ($this->matchNamespace($found->nsp) && ($found->event === $event || null === $event)) { return $found; } } return null; } protected function createEvent($event, $args, $ack = null) { $args = $args->getArguments(); $attachments = []; $this->getAttachments($args, $attachments); $type = count($attachments) ? static::PACKET_BINARY_EVENT : static::PACKET_EVENT; $data = ($ack ? $this->getAckId(true) : '') . json_encode(array_merge([$event], $args)); $data = Util::concatNamespace($this->namespace, $data); if ($type === static::PACKET_BINARY_EVENT) { $data = sprintf('%d-%s', count($attachments), $data); if ($this->logger) { $this->logger->debug(sprintf('Binary event arguments %s', Util::toStr($args))); } } $raws = null; if (count($attachments)) { switch ($this->transport) { case static::TRANSPORT_POLLING: if ($this->options->version >= static::EIO_V4) { foreach ($attachments as $attachment) { $data .= PollingDecoder::EIO_V4_SEPARATOR; $data .= 'b' . base64_encode($attachment); } } else { $raws = []; foreach ($attachments as $attachment) { $raws[] = 'b' . static::PROTO_MESSAGE . base64_encode($attachment); } } break; case static::TRANSPORT_WEBSOCKET: $raws = []; /** @var \ElephantIO\Engine\Transport\Websocket $transport */ $transport = $this->_transport(); foreach ($attachments as $attachment) { if ($this->options->version <= static::EIO_V3) { $attachment = pack('C', static::PROTO_MESSAGE) . $attachment; } $raws[] = $transport->getPayload($attachment, WebsocketEncoder::OPCODE_BINARY) ->setMaxPayload($this->options->binary_chunk_size); } break; } } return [static::PROTO_MESSAGE, $type . $data, $raws]; } protected function matchAck($packet) { foreach ($packet->peek(static::PROTO_MESSAGE) as $found) { if (in_array($found->type, [static::PACKET_ACK, static::PACKET_BINARY_ACK]) && $this->matchNamespace($found->nsp) && $found->ack === $this->getAckId()) { return $found; } } return null; } protected function createAck($packet, $data) { $type = $packet->count ? static::PACKET_BINARY_ACK : static::PACKET_ACK; $data = Util::concatNamespace($this->namespace, $packet->ack . json_encode($data->getArguments())); return [static::PROTO_MESSAGE, $type . $data]; } protected function decodePacket($data) { // @see https://socket.io/docs/v4/engine-io-protocol/ $seq = new SequenceReader($data); $proto = (int) $seq->read(); if ($this->isProtocol($proto)) { $packet = $this->createPacket($proto); $packet->data = null; switch ($packet->proto) { case static::PROTO_MESSAGE: $packet->type = (int) $seq->read(); if ($packet->type === static::PACKET_BINARY_EVENT) { $packet->count = (int) $seq->readUntil('-'); } // nsp is delimited by "," $openings = ['[', '{']; $packet->nsp = $seq->readWithin(',', $openings); // check for ack if (in_array($packet->type, [static::PACKET_EVENT, static::PACKET_BINARY_EVENT, static::PACKET_ACK, static::PACKET_BINARY_ACK])) { if (!in_array($seq->readData(), $openings) && '' !== ($ack = (string) $seq->readUntil(implode($openings), $openings))) { $packet->ack = (int) $ack; } } if ($data = $seq->getData()) { if (null !== ($data = json_decode($data, true))) { switch ($packet->type) { case static::PACKET_EVENT: case static::PACKET_BINARY_EVENT: $packet->event = array_shift($data); $packet->setArgs($data); break; case static::PACKET_ACK: case static::PACKET_BINARY_ACK: $packet->setArgs($data); break; default: $packet->data = $data; break; } } } break; default: if (!$seq->isEof()) { $packet->data = $seq->getData(); if ($packet->data && $packet->proto === static::PROTO_OPEN) { $packet->data = json_decode($packet->data, true); } } break; } if ($this->logger) { $this->logger->info(sprintf('Got packet: %s', Util::truncate((string) $packet))); } return $packet; } return null; } protected function postPacket($packet, &$more) { if ($packet->proto === static::PROTO_MESSAGE && $packet->type === static::PACKET_BINARY_EVENT) { $packet->type = static::PACKET_EVENT; for ($i = 0; $i < $packet->count; $i++) { $bindata = null; switch ($this->transport) { case static::TRANSPORT_POLLING: if ($this->options->version >= static::EIO_V4) { if ($bindata = array_shift($more)) { $prefix = substr($bindata, 0, 1); if ($prefix !== 'b') { throw new RuntimeException(sprintf('Unable to decode binary data with prefix "%s"!', $prefix)); } $bindata = base64_decode(substr($bindata, 1)); } } else { if ($bindata = array_shift($more)) { if (ord($bindata[0]) !== static::PROTO_MESSAGE) { throw new RuntimeException(sprintf('Invalid binary data at position %d!', $i)); } $bindata = substr($bindata, 1); } } break; case static::TRANSPORT_WEBSOCKET: if ($transport = $this->_transport()) { $bindata = (string) $transport->recv(); } break; } if (null === $bindata) { throw new RuntimeException(sprintf('Binary data unavailable for index %d!', $i)); } $packet->data = $this->replaceAttachment($packet->data, $i, $bindata); } } } protected function consumePacket($packet) { switch ($packet->proto) { case static::PROTO_CLOSE: if ($this->logger) { $this->logger->debug('Connection closed by server'); } $this->reset(); break; case static::PROTO_PING: if ($this->logger) { $this->logger->debug('Got PING, sending PONG'); } $this->send(static::PROTO_PONG); break; case static::PROTO_PONG: if ($this->logger) { $this->logger->debug('Got PONG'); } break; case static::PROTO_NOOP: break; default: return false; } return true; } /** * Get attachment from packet data. A packet data considered as attachment * if it's a resource and it has content. * * @param array<int|string, mixed> $array * @param array<int|string, mixed> $result * @return void */ protected function getAttachments(&$array, &$result) { if (count($array)) { foreach ($array as &$value) { if (is_resource($value)) { fseek($value, 0); if ($content = stream_get_contents($value)) { $idx = count($result); $result[] = $content; $value = ['_placeholder' => true, 'num' => $idx]; } else { $value = null; } } if (is_array($value)) { $this->getAttachments($value, $result); } } } } /** * Replace binary attachment. * * @param array<int|string, mixed> $array * @param int $index * @param string $data * @return array<int|string, mixed> */ protected function replaceAttachment($array, $index, $data) { if (count($array)) { foreach ($array as $key => &$value) { if (is_array($value)) { if (isset($value['_placeholder']) && $value['_placeholder'] && $value['num'] === $index) { if ($this->options->binary_as_resource) { $value = Util::toResource($data); } else { $value = $data; } if ($this->logger) { $this->logger->debug(sprintf('Replacing binary attachment for %d (%s)', $index, $key)); } } else { $value = $this->replaceAttachment($value, $index, $data); } } } } return $array; } /** * Get authentication payload handshake. * * @return string */ protected function getAuthPayload() { $auth = ''; if ($this->options->version >= static::EIO_V4 && is_array($this->options->auth) && count($this->options->auth)) { if (false === ($auth = json_encode($this->options->auth))) { throw new InvalidArgumentException(sprintf('Can\'t parse auth option JSON: %s!', json_last_error_msg())); } } return $auth; } /** * Get confirmed namespace result. Namespace is confirmed if the returned * value is true, otherwise failed. If the return value is a string, it's * indicated an error message. * * @param ?\ElephantIO\Engine\Packet $packet * @return bool|string */ protected function getConfirmedNamespace($packet) { if ($packet) { foreach ($packet->peek(static::PROTO_MESSAGE) as $found) { if ($found->type === static::PACKET_CONNECT) { return true; } if ($found->type === static::PACKET_ERROR) { return isset($found->data['message']) ? $found->data['message'] : false; } } } return false; } public function buildQueryParameters($transport) { if (null === $transport) { $transport = $this->transport; } $parameters = [ 'EIO' => $this->options->version, 'transport' => $transport, 't' => Yeast::yeast(), ]; if ($this->session) { $parameters['sid'] = $this->session->id; } return $parameters; } protected function doHandshake() { if (null !== $this->session) { return; } if ($this->logger) { $this->logger->info('Starting handshake'); } // set timeout to default $this->setTimeout($this->defaults['timeout']); if ($transport = $this->_transport()) { if (null === ($data = $transport->recv($this->options->timeout, ['upgrade' => $this->transport === static::TRANSPORT_WEBSOCKET]))) { throw new ServerConnectionFailureException('unable to perform handshake'); } if ($this->transport === static::TRANSPORT_WEBSOCKET) { if ($this->stream) { $this->stream->upgrade(); } else { throw new RuntimeException('Unable to perform websocket upgrade, stream is not avaialble!'); } $packet = $this->drain($this->options->timeout); } else { $packet = $this->processData($data); } $handshake = null; if ($packet && ($packet = $packet->peekOne(static::PROTO_OPEN))) { $handshake = $packet->data; } if (null === $handshake) { throw new RuntimeException('Handshake is successful but without data!'); } array_walk($handshake, function(&$value, $key) { if (in_array($key, ['pingInterval', 'pingTimeout'])) { $value /= 1000; } }); /** @var \ElephantIO\Engine\Transport\Polling $transport */ $this->storeSession($handshake, $transport->getCookies()); if ($this->logger) { $this->logger->info(sprintf('Handshake finished with %s', (string) $this->session)); } } } protected function doAfterHandshake() { // connect to namespace for protocol version 4 and later if ($this->options->version >= static::EIO_V4) { if ($this->logger) { $this->logger->info('Starting namespace connect'); } // set timeout based on handshake response if ($this->session) { $this->setTimeout($this->session->getTimeout()); } $this->doChangeNamespace(); if ($this->logger) { $this->logger->info('Namespace connect completed'); } } } protected function doUpgrade() { if ($this->logger) { $this->logger->info('Starting websocket upgrade'); } // set timeout based on handshake response if ($this->session) { $this->setTimeout($this->session->getTimeout()); } if (($transport = $this->_transport()) && $this->stream) { if (null !== $transport->recv($this->options->timeout, ['transport' => static::TRANSPORT_WEBSOCKET, 'upgrade' => true])) { $this->setTransport(static::TRANSPORT_WEBSOCKET); $this->stream->upgrade(); $this->send(static::PROTO_UPGRADE); // ensure got packet connect on socket.io 1.x if ($this->options->version === static::EIO_V2 && $packet = $this->drain($this->options->timeout)) { $confirm = null; foreach ($packet->peek(static::PROTO_MESSAGE) as $found) { if ($found->type === static::PACKET_CONNECT) { $confirm = $found; break; } } if ($this->logger) { if ($confirm) { $this->logger->debug('Upgrade successfully confirmed'); } else { $this->logger->debug('Upgrade not confirmed'); } } } if ($this->logger) { $this->logger->info('Websocket upgrade completed'); } } else { if ($this->logger) { $this->logger->info('Upgrade failed, skipping websocket'); } } } } protected function doChangeNamespace() { if (!$this->session) { throw new RuntimeException('To switch namespace, a session must has been established!'); } $this->send(static::PROTO_MESSAGE, static::PACKET_CONNECT . Util::concatNamespace($this->namespace, $this->getAuthPayload())); $packet = $this->drain($this->options->timeout); if (true === ($result = $this->getConfirmedNamespace($packet))) { return $packet; } if (null === $packet) { $transport = $this->_transport(); if ($transport instanceof Polling) { if (is_array($body = $transport->getBody()) && isset($body['message'])) { $result = $body['message']; } } } if (is_string($result)) { throw new UnsuccessfulOperationException(sprintf('Unable to switch namespace: %s!', $result)); } else { throw new UnsuccessfulOperationException('Unable to switch namespace!'); } } protected function doPing() { if ($this->options->version <= static::EIO_V3) { $this->send(static::PROTO_PING); } } protected function doClose() { $this->send(static::PROTO_CLOSE); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/SocketIO/Version4X.php
src/Engine/SocketIO/Version4X.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine\SocketIO; /** * Implements the dialog with socket.io server 4.x. * * @author Toha <tohenk@yahoo.com> */ class Version4X extends Version1X { protected function initialize(&$options) { parent::initialize($options); $this->name = 'SocketIO Version 4.X'; $this->setDefaults(['version' => static::EIO_V4, 'max_payload' => 1e6]); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/src/Engine/SocketIO/Version2X.php
src/Engine/SocketIO/Version2X.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Engine\SocketIO; /** * Implements the dialog with socket.io server 2.x. * * Based on the work of Mathieu Lallemand (@lalmat) * * @author Baptiste Clavié <baptiste@wisembly.com> * @link https://tools.ietf.org/html/rfc6455#section-5.2 Websocket's RFC */ class Version2X extends Version1X { protected function initialize(&$options) { parent::initialize($options); $this->name = 'SocketIO Version 2.X'; $this->setDefaults(['version' => static::EIO_V3]); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/test/StoreTest.php
test/StoreTest.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Test; use PHPUnit\Framework\TestCase; use ElephantIO\Engine\Store; use InvalidArgumentException; class StoreTest extends TestCase { public function testStore(): void { /** @var \ElephantIO\Test\TestStore $store */ $store = TestStore::create([ 'id' => 'ID', 'number' => 9, 'disp' => 'disp', 'empty' => null, 'nodisp' => 'nodisp', 'hidden' => 'hidden', 'non_existant' => true, ]); $this->assertSame("ID{\"number\":9,\"disp\":\"disp\"}", (string) $store, 'Properly cast store to string'); $store->id = 'the-id'; $this->assertEquals('the-id', $store->id, 'Store can retrieve the value by its key'); $values = $store->getValues(); $this->assertFalse(isset($values['non_existant']), 'Store excludes non existent key'); $this->assertNull($store->empty, 'Store can retrieve null value'); $this->expectException(InvalidArgumentException::class); $store->somekey = 'nothing'; $this->fail('Setting non existent key did not throw an exception!'); } } /** * @property string $id * @property int $number * @property bool|null $empty * @property bool|null $disp * @property bool|null $nodisp * @property bool|null $hidden * @property string $somekey */ class TestStore extends Store { protected function initialize() { $this->keys = ['+id', 'number', '!empty', '!disp', '!nodisp', '_hidden']; } /** * Get values. * * @return mixed[] */ public function getValues() { return $this->values; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/test/ClientTest.php
test/ClientTest.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Test; use ElephantIO\Client; use ElephantIO\Engine\EngineInterface; use PHPUnit\Framework\TestCase; class ClientTest extends TestCase { public function testIsConnectedDelegatesToEngine(): void { $engine = $this->createMock(EngineInterface::class); $engine->expects($this->any()) ->method('connected') ->willReturn(true); $client = new Client($engine); $this->assertTrue($client->isConnected()); } public function testIsConnectedReturnsFalseWhenEngineIsNotConnected(): void { $engine = $this->createMock(EngineInterface::class); $engine->expects($this->any()) ->method('connected') ->willReturn(false); $client = new Client($engine); $this->assertFalse($client->isConnected()); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/test/PacketTest.php
test/PacketTest.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Test; use PHPUnit\Framework\TestCase; use ElephantIO\Engine\Packet; class PacketTest extends TestCase { public function testPacket(): void { /** @var \ElephantIO\Engine\Packet $packet1 */ $packet1 = Packet::create(['proto' => 1]); $packet2 = Packet::create(['proto' => 2]); $packet1->add($packet2); $this->assertEquals([$packet1, $packet2], $packet1->flatten(), 'Packet can be flattened'); $this->assertEquals([$packet2], $packet1->peek(2), 'Packet can be picked by its protocol'); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/test/UtilTest.php
test/UtilTest.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Test; use PHPUnit\Framework\TestCase; use ElephantIO\Util; class UtilTest extends TestCase { public function testToStr(): void { $values = [ 'string' => 'The string', 'object' => new Stringable(), 'resource' => Util::toResource('1234567890'), 'number' => 49, 'other' => new NotStringable(), ]; $this->assertSame("{\"string\":\"The string\",\"object\":stringable,\"resource\":<1234567890>,\"number\":49,\"other\":{\"test\":1001.1}}", Util::toStr($values), 'Util can represents the values as string'); } public function testToStrWithEnum(): void { if (version_compare(PHP_VERSION, '8.1.0', '>=')) { require_once 'TestEnum.php'; $values = [ 'one' => TestEnum::One, 'two' => TestBackedEnum::Two, ]; $rootPath = version_compare(PHP_VERSION, '8.2.0', '>=') ? '\\' : ''; $this->assertSame("{\"one\":{$rootPath}ElephantIO\Test\TestEnum::One,\"two\":Two}", Util::toStr($values), 'Util can represents enum as string'); } else { $this->markTestSkipped('Test only for PHP >= 8.1.0'); } } } class Stringable { public function __toString() { return 'stringable'; } } class NotStringable { /** @var float */ public $test = 1001.1; }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/test/bootstrap.php
test/bootstrap.php
<?php error_reporting(E_ALL); set_error_handler('error_to_exception'); /** * Throw exceptions for all unhandled errors, deprecations and warnings while running the examples. * * @param int $code * @param string $message * @param string $filename * @param int $line * @return bool */ function error_to_exception($code, $message, $filename, $line) { if (error_reporting() & $code) { throw new ErrorException($message, 0, $code, $filename, $line); } return true; }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/test/TestEnum.php
test/TestEnum.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Test; enum TestEnum { case One; case Two; } enum TestBackedEnum: string { case One = 'One'; case Two = 'Two'; }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/test/SequenceReaderTest.php
test/SequenceReaderTest.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Test; use PHPUnit\Framework\TestCase; use ElephantIO\SequenceReader; class SequenceReaderTest extends TestCase { public function testRead(): void { $seq = new SequenceReader('1234567890'); $this->assertSame('1', $seq->read(), 'Read one character each'); $this->assertSame('2', $seq->readData(), 'Can read 1 remaining characters'); $this->assertSame('234', $seq->readData(3), 'Can read 3 remaining characters'); $this->assertSame('234567890', $seq->getData(), 'Data contains remaining characters'); $this->assertSame(false, $seq->isEof(), 'No EOF if remaining data is exist'); $this->assertSame('234567890', $seq->read(null), 'Can read remaining characters'); $this->assertSame(true, $seq->isEof(), 'EOF reached once remaining characters read'); $this->assertSame('', $seq->readData(), 'An empty string returned when remanining characters unavailable'); } public function testReadUntil(): void { $seq = new SequenceReader('1::3'); $this->assertSame('1', $seq->readUntil(':'), 'Read using delimiter'); $this->assertSame(':3', $seq->getData(), 'Data contains remaining characters'); $this->assertSame(false, $seq->isEof(), 'No EOF if remaining data is exist'); $this->assertSame('', $seq->readUntil(':'), 'Can read empty'); $this->assertSame('3', $seq->getData(), 'Remaining characters matched'); } public function testReadUntilNoSkip(): void { $seq = new SequenceReader('1,["A",3]'); $this->assertSame('1', $seq->readUntil(',[', ['[']), 'Read using delimiter with no skip character'); $this->assertSame('["A",3]', $seq->getData(), 'Remaining characters exclude delimiter'); $this->assertSame('["A",3]', $seq->read(null), 'Read remaining characters'); $this->assertSame(true, $seq->isEof(), 'No more characters'); } public function testReadWithin(): void { $seq = new SequenceReader('0,["A",2]'); $this->assertSame('0', $seq->readWithin(',', ['[']), 'Read using delimiter within boundary'); $this->assertSame('["A",2]', $seq->getData(), 'Remaining characters exclude delimiter'); $this->assertSame(null, $seq->readWithin(',', ['[']), 'Null returned when delimiter is beyond boundary'); $this->assertSame('["A",2]', $seq->read(null), 'Read remaining characters'); $this->assertSame(true, $seq->isEof(), 'No more characters'); } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/test/Websocket/DecoderTest.php
test/Websocket/DecoderTest.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Test\Websocket; use ElephantIO\Parser\Websocket\Decoder; use PHPUnit\Framework\TestCase; use ReflectionProperty; class DecoderTest extends TestCase { /** * Test with unmasked payload. * * @param string $payload * @param string $expected * @return void * @dataProvider providerUnmaskedPayload */ public function testUnmaskedPayload($payload, $expected) { if ($payload = hex2bin($payload)) { $decoder = new Decoder($payload); $this->assertSame($expected, (string) $decoder); $this->assertPropSame(0x1, $decoder, 'fin'); $this->assertPropSame([0x0, 0x0, 0x0], $decoder, 'rsv'); $this->assertPropSame(false, $decoder, 'mask'); $this->assertPropSame("\x00\x00\x00\x00", $decoder, 'maskKey'); $this->assertPropSame(Decoder::OPCODE_TEXT, $decoder, 'opCode'); } else { $this->fail('Payload must be hex encoded!'); } } /** * Provide unmasked payload. * * @return array<int, array<int, string>> */ public function providerUnmaskedPayload() { $short = 'foo'; $long = <<<EOF This payload length is over 125 chars, hence the length part inside the payload should now be 16 bits in length. There are still a little bit less than that to satisfy the fact that we need more than 125 characters, but less than 65536. So this should do the trick... EOF; $shortMask = '8103666f6f'; $longMask = '817e010b54686973207061796c6f6164206c656e677468206973206f76' . '6572203132352063686172732c2068656e636520746865206c656e6774' . '68207061727420696e7369646520746865207061796c6f61640a73686f' . '756c64206e6f77206265203136206269747320696e206c656e6774682e' . '20546865726520617265207374696c6c2061206c6974746c6520626974' . '206c657373207468616e207468617420746f0a73617469736679207468' . '6520666163742074686174207765206e656564206d6f7265207468616e' . '2031323520636861726163746572732c20627574206c65737320746861' . '6e2036353533362e20536f0a746869732073686f756c6420646f207468' . '6520747269636b2e2e2e'; return [[$shortMask, $short], [$longMask, $this->fixEol($long)]]; } /** * Test with a masked payload (the masked being "?EV!") * * @param string $payload * @param string $expected * @return void * @dataProvider providerMaskedPayload */ public function testMaskedPayload($payload, $expected) { if ($payload = hex2bin($payload)) { $decoder = new Decoder($payload); $this->assertSame($expected, (string) $decoder); $this->assertPropSame(0x1, $decoder, 'fin'); $this->assertPropSame([0x0, 0x0, 0x0], $decoder, 'rsv'); $this->assertPropSame(true, $decoder, 'mask'); $this->assertPropSame('?EV!', $decoder, 'maskKey'); $this->assertPropSame(Decoder::OPCODE_TEXT, $decoder, 'opCode'); } else { $this->fail('Payload must be hex encoded!'); } } /** * Provide masked payload. * * @return array<int, array<int, string>> */ public function providerMaskedPayload() { $short = 'foo'; $long = <<<EOF This payload length is over 125 chars, hence the length part inside the payload should now be 16 bits in length. There are still a little bit less than that to satisfy the fact that we need more than 125 characters, but less than 65536. So this should do the trick... EOF; $shortMask = '81833f455621592a39'; $longMask = '81fe010b3f4556216b2d3f521f353758532a37451f29334f58313e0156' . '36764e492024010e7763015c2d37534c6976495a2b35441f313e441f29' . '334f58313e014f2424551f2c3852562133014b2d33014f242f4d502432' . '2b4c2d39545321764f503276435a6567171f273f554c653f4f1f29334f' . '58313e0f1f113e444d2076404d2076524b2c3a4d1f24764d5631224d5a' . '6534484b653a444c367655572438014b2d37551f31392b4c2422484c23' . '2f014b2d3301592435551f313e404b6521441f2b33445b653b4e4d2076' . '55572438010e7763015c2d37535e2622444d367a015d30220153202552' . '1f313e40516560140a76600f1f16392b4b2d3f521f363e4e4a2932015b' . '2a7655572076554d2c354a116b78'; return [[$shortMask, $short], // data encoded with < 125 characters [$longMask, $this->fixEol($long)]]; // data encoded with > 125 characters but < 65536 characters } /** * Do property assertion. * * @param int|int[]|string|bool $expected * @param object $object * @param string $property * @return void */ private function assertPropSame($expected, $object, $property) { $refl = new ReflectionProperty(Decoder::class, $property); $refl->setAccessible(true); $this->assertSame($expected, $refl->getValue($object)); } /** * Fix end of line. * * @param string $str * @param string $from * @param string $to * @return string */ private function fixEol($str, $from = "\r\n", $to = "\n") { if (false !== strpos($str, $from)) { $str = str_replace($from, $to, $str); } return $str; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/test/Websocket/EncoderTest.php
test/Websocket/EncoderTest.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Test\Websocket; use ElephantIO\Parser\Websocket\Encoder; use ElephantIO\Parser\Websocket\Payload; use PHPUnit\Framework\TestCase; use ReflectionProperty; class EncoderTest extends TestCase { /** * Test with sort payload. * * @param string|null $maskKey * @param string $expected * @return void * @dataProvider providerShortPayload */ public function testShortPayload($maskKey, $expected) { $encoder = new Encoder('foo', Encoder::OPCODE_TEXT, null !== $maskKey); if (null !== $maskKey) { $refl = new ReflectionProperty(Payload::class, 'maskKey'); $refl->setAccessible(true); $refl->setValue($encoder, $maskKey); } $this->assertSame($expected, bin2hex((string) $encoder)); } /** * Provide short payload. * * @return array<int, array<int, string|null>> */ public function providerShortPayload() { return [[null, '8103666f6f'], ['?EV!', '81833f455621592a39']]; } /** * Test with a payload > 125 characters but < 65536 * * @param string|null $maskKey * @param string $expected * @return void * @dataProvider providerLongPayload */ public function testLongPayload($maskKey, $expected) { $payload = <<<EOF This payload length is over 125 chars, hence the length part inside the payload should now be 16 bits in length. There are still a little bit less than that to satisfy the fact that we need more than 125 characters, but less than 65536. So this should do the trick... EOF; $encoder = new Encoder($this->fixEol($payload), Encoder::OPCODE_TEXT, null !== $maskKey); if (null !== $maskKey) { $refl = new ReflectionProperty(Payload::class, 'maskKey'); $refl->setAccessible(true); $refl->setValue($encoder, $maskKey); } $this->assertSame($expected, bin2hex((string) $encoder)); } /** * Provide long payload. * * @return array<int, array<int, string|null>> */ public function providerLongPayload() { $noMask = '817e010b54686973207061796c6f6164206c656e677468206973206f76' . '6572203132352063686172732c2068656e636520746865206c656e6774' . '68207061727420696e7369646520746865207061796c6f61640a73686f' . '756c64206e6f77206265203136206269747320696e206c656e6774682e' . '20546865726520617265207374696c6c2061206c6974746c6520626974' . '206c657373207468616e207468617420746f0a73617469736679207468' . '6520666163742074686174207765206e656564206d6f7265207468616e' . '2031323520636861726163746572732c20627574206c65737320746861' . '6e2036353533362e20536f0a746869732073686f756c6420646f207468' . '6520747269636b2e2e2e'; $withMask = '81fe010b3f4556216b2d3f521f353758532a37451f29334f58313e0156' . '36764e492024010e7763015c2d37534c6976495a2b35441f313e441f29' . '334f58313e014f2424551f2c3852562133014b2d33014f242f4d502432' . '2b4c2d39545321764f503276435a6567171f273f554c653f4f1f29334f' . '58313e0f1f113e444d2076404d2076524b2c3a4d1f24764d5631224d5a' . '6534484b653a444c367655572438014b2d37551f31392b4c2422484c23' . '2f014b2d3301592435551f313e404b6521441f2b33445b653b4e4d2076' . '55572438010e7763015c2d37535e2622444d367a015d30220153202552' . '1f313e40516560140a76600f1f16392b4b2d3f521f363e4e4a2932015b' . '2a7655572076554d2c354a116b78'; return [[null, $noMask], ['?EV!', $withMask]]; } /** * Fix end of line. * * @param string $str * @param string $from * @param string $to * @return string */ private function fixEol($str, $from = "\r\n", $to = "\n") { if (false !== strpos($str, $from)) { $str = str_replace($from, $to, $str); } return $str; } }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/test/Websocket/PayloadTest.php
test/Websocket/PayloadTest.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace ElephantIO\Test\Websocket; use ElephantIO\Parser\Websocket\Decoder; use ElephantIO\Parser\Websocket\Encoder; use ElephantIO\Parser\Websocket\Payload as BasePayload; use PHPUnit\Framework\TestCase; use ReflectionMethod; use ReflectionProperty; class PayloadTest extends TestCase { public function testMaskData(): void { $payload = new Payload(); $refl = new ReflectionProperty(Payload::class, 'maskKey'); $refl->setAccessible(true); $refl->setValue($payload, '?EV!'); $refl = new ReflectionMethod(Payload::class, 'maskData'); $refl->setAccessible(true); $this->assertSame('592a39', bin2hex($refl->invoke($payload, 'foo'))); } /** * Do encode or decode. * * @param string $sz * @param string $filename * @return void */ protected function encodeDecode($sz, $filename) { if ($payload = file_get_contents($filename)) { $encoder = new Encoder($payload, Decoder::OPCODE_TEXT, false); $encoded = (string) $encoder; $decoder = new Decoder($encoded); $decoded = (string) $decoder; $this->assertEquals($payload, $decoded, 'Properly encode and decode payload '.$sz.' content'); } else { $this->fail(sprintf('Unable to load payload %s!', $filename)); } } public function testPayload7D(): void { $this->encodeDecode('125-bytes', __DIR__.'/data/payload-7d.txt'); } public function testPayloadFFFF(): void { $this->encodeDecode('64-kilobytes', __DIR__.'/data/payload-ffff.txt'); } public function testPayloadAboveFFFF(): void { $this->encodeDecode('100-kilobytes', __DIR__.'/data/payload-100k.txt'); } } /** Fixtures for these tests */ class Payload extends BasePayload { }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/example/client/keep-alive.php
example/client/keep-alive.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ require __DIR__ . '/common.php'; $namespace = 'keep-alive'; $event = 'message'; $client = setup_client($namespace); $timeout = 30; // in seconds $start = microtime(true); $sent = null; while (true) { $now = microtime(true); if (null === $sent) { $sent = $now; $client->emit($event, ['message' => 'A message']); if (is_object($retval = $client->wait($event))) { echo sprintf("Got a reply for first message: %s\n", $retval->inspect()); } continue; } if ($now - $start >= $timeout) { $client->emit($event, ['message' => 'Last message']); if (is_object($retval = $client->wait($event))) { echo sprintf("\nGot a reply for last message: %s\n", $retval->inspect()); } break; } $client->drain(1); echo '.'; } $client->disconnect();
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/example/client/polling.php
example/client/polling.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ require __DIR__ . '/common.php'; $namespace = 'polling'; $event = 'message'; // only enable polling transport $client = setup_client($namespace, null, ['transports' => 'polling']); $client->emit($event, ['message' => 'This is first message']); if (is_object($retval = $client->wait($event))) { echo sprintf("Got a reply for first message: %s\n", $retval->inspect()); } $client->emit($event, ['message' => 'Das höchste Gut und Uebel']); if (is_object($retval = $client->wait($event))) { echo sprintf("Got a reply for second message: %s\n", $retval->inspect()); } $client->disconnect();
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/example/client/binary-event.php
example/client/binary-event.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ require __DIR__ . '/common.php'; $namespace = 'binary-event'; $event = 'test-binary'; $event_attachment = 'test-binary-attachment'; $logger = setup_logger(); if (false === ($content = file_get_contents(__DIR__ . '/../../test/Websocket/data/payload-100k.txt'))) { echo "Payload file is not found!\n"; exit(1); } if (false === ($payload = fopen('php://memory', 'w+'))) { echo "Unable to create payload resource!\n"; exit(1); } // create 2MB binary payload $n = 20; for ($i = 0; $i < $n; $i++) { fwrite($payload, $content); } $size = 512 * 1024; // 512k foreach ([ 'websocket' => ['transport' => 'websocket'], 'polling' => ['transports' => 'polling'] ] as $transport => $options) { echo sprintf("Sending binary data using %s transport...\n", $transport); $client = setup_client($namespace, $logger, $options); // send big payload as parts $hash = uniqid(); fseek($payload, 0); while (!feof($payload)) { if (false === $part = fread($payload, $size)) { throw new Error('Unable to read attachment part!'); } if (false === $res = fopen('php://memory', 'r+')) { throw new Error('Unable to allocate attachment resource!'); } fwrite($res, $part); if ($client->emit($event_attachment, ['hash' => $hash, 'content' => $res])) { if (is_object($packet = $client->wait($event_attachment))) { if (!$packet->data['success']) { throw new Error('Send attachment part failed!'); } } } else { throw new Error('Unable to send attachment part!'); } } $client->emit($event, ['hash' => $hash]); if (is_object($retval = $client->wait($event))) { echo sprintf("Got a reply: %s\n", $retval->inspect()); } $client->disconnect(); }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/example/client/error-handling.php
example/client/error-handling.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ require __DIR__ . '/common.php'; $url = 'http://localhost:14001'; $namespace = 'error-handling'; $namespace_not_exist = 'non-existent-namespace'; $logger = setup_logger(); try { echo sprintf("Try connecting to %s...\n", $url); $client = setup_client($namespace, $logger, ['url' => $url]); } catch (\ElephantIO\Exception\SocketException $e) { echo sprintf("> Expected connection failure:\n%s\n\n", $e->getMessage()); } try { echo "Try connecting to non existent namespace...\n"; $client = setup_client($namespace_not_exist, $logger); } catch (\ElephantIO\Exception\UnsuccessfulOperationException $e) { echo sprintf("> Expected operation failure:\n%s\n\n", $e->getMessage()); } try { echo sprintf("Try connecting to %s...", $namespace); $client = setup_client($namespace, $logger); echo "connected\n"; echo "Sending message..."; $client->emit('message', ['message' => 'The message']); $timeout = 5; if (null === ($result = $client->wait('message-reply', $timeout))) { echo sprintf("no reply after %d seconds!\n\n", $timeout); } $client->disconnect(); } catch (\Exception $e) { echo sprintf("%s:\n", get_class($e)); echo $e->getMessage()."\n\n"; }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/example/client/common.php
example/client/common.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ use ElephantIO\Client; use ElephantIO\Util; use Monolog\Logger; use Monolog\Handler\StreamHandler; use Psr\Log\LogLevel; require __DIR__ . '/../../vendor/autoload.php'; error_reporting(E_ALL); set_error_handler('error_to_exception'); /** * Throw exceptions for all unhandled errors, deprecations and warnings while running the examples. * * @param int $code * @param string $message * @param string $filename * @param int $line * @return bool */ function error_to_exception($code, $message, $filename, $line) { if (error_reporting() & $code) { throw new ErrorException($message, 0, $code, $filename, $line); } return true; } /** * Get or set client version to use. * * @param int $version Version to set * @return int */ function client_version($version = null) { static $client = null; if (null === $client && is_readable($package = __DIR__ . '/../server/package.json') && false !== ($content = file_get_contents($package))) { $info = json_decode($content, true); if (isset($info['dependencies']) && isset($info['dependencies']['socket.io'])) { if (preg_match('/(?P<MAJOR>(\d+))\.(?P<MINOR>(\d+))\.(?P<PATCH>(\d+))/', $info['dependencies']['socket.io'], $matches)) { $client = (int) $matches['MAJOR']; echo sprintf("Server version detected: %s\n", $client); } } } if (null === $client) { $client = Client::CLIENT_4X; } if (null !== $version) { $client = $version; } return $client; } /** * Create a logger channel. * * @return \Monolog\Logger */ function setup_logger() { $logfile = __DIR__ . '/socket.log'; if (is_readable($logfile)) { @unlink($logfile); } $logger = new Logger('elephant.io'); $logger->pushHandler(new StreamHandler($logfile, LogLevel::DEBUG)); return $logger; } /** * Create a socket client. * * @param string|null $namespace * @param \Monolog\Logger|null $logger * @param array<string, mixed> $options * @return \ElephantIO\Client */ function setup_client($namespace, $logger = null, $options = []) { $url = 'http://localhost:14000'; if (isset($options['url'])) { $url = $options['url']; unset($options['url']); } if (isset($options['path'])) { $url .= '/' . $options['path']; unset($options['path']); } $logger = $logger ?? setup_logger(); $client = Client::create($url, array_merge(['client' => client_version(), 'logger' => $logger], $options)); $client->connect(); if ($namespace) { $client->of(sprintf('/%s', $namespace)); } return $client; } /** * Inspect data. * * @param mixed $data * @return string */ function inspect($data) { return Util::toStr($data); } /** * Create a resource from string. * * @param string $data * @return resource|null */ function create_resource($data) { return Util::toResource($data); }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/example/client/custom-path.php
example/client/custom-path.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ require __DIR__ . '/common.php'; $options = ['path' => 'my', 'sio_path' => 'my.io']; echo sprintf("Connecting to custom path /%s...\n", implode('/', [$options['path'], $options['sio_path']])); $client = setup_client(null, null, $options); while (true) { if ($packet = $client->wait(null, 1)) { echo sprintf("Got event %s\n", $packet->event); break; } } $client->disconnect();
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/example/client/basic.php
example/client/basic.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ use ElephantIO\Engine\Argument; require __DIR__ . '/common.php'; $logger = setup_logger(); foreach ([ 'basic event' => [], 'event without reuse connection' => ['reuse_connection' => false], ] as $type => $options) { echo sprintf("Listening %s...\n", $type); $client = setup_client(null, $logger, $options); while (true) { if ($packet = $client->wait(null, 1)) { echo sprintf("Got event %s\n", $packet->event); $client->emit('test', new Argument(1, 2, 'test')); if ($packet = $client->wait('test')) { echo sprintf("Got test: %s\n", inspect($packet->args)); break; } } } $client->disconnect(); }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/example/client/header-auth.php
example/client/header-auth.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ require __DIR__ . '/common.php'; $namespace = 'header-auth'; $token = 'this_is_peter_token'; $event = 'message'; $logger = setup_logger(); // create first instance $client = setup_client($namespace, $logger, [ 'headers' => [ 'X-My-Header' => 'websocket rocks', 'Authorization' => 'Bearer ' . $token, 'User' => 'peter', ] ]); $data = [ 'message' => 'How are you?', 'token' => $token, ]; echo sprintf("Sending message: %s\n", inspect($data)); $client->emit($event, $data); if (is_object($retval = $client->wait($event))) { echo sprintf("Got a reply: %s\n", $retval->inspect()); } $client->disconnect(); // create second instance $client = setup_client($namespace, $logger, [ 'headers' => [ 'X-My-Header' => 'websocket rocks', 'Authorization' => 'Bearer ' . $token, 'User' => 'peter', ] ]); $data = [ 'message' => 'Do you remember me?', 'token' => $token, ]; echo sprintf("Sending message: %s\n", inspect($data)); $client->emit($event, $data); if (is_object($retval = $client->wait($event))) { echo sprintf("Got a reply: %s\n", $retval->inspect()); } // send message with invalid token $invalidToken = 'this_is_invalid_peter_token'; $data = [ 'message' => 'Do you remember me?', 'token' => $invalidToken, ]; echo sprintf("Sending message: %s\n", inspect($data)); $client->emit($event, $data); if (is_object($retval = $client->wait($event))) { echo sprintf("Got a reply: %s\n", $retval->inspect()); } $client->disconnect();
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/example/client/ack.php
example/client/ack.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ require __DIR__ . '/common.php'; $namespace = 'ack'; $event = 'test-recv-ack'; $client = setup_client($namespace); echo "Emiting an event with acknowledgement...\n"; if (is_object($retval = $client->emit('test-send-ack', ['message' => 'An ack send test'], true))) { echo sprintf("Got ack: %s\n", $retval->inspect()); } echo "Acknowledge an event...\n"; $client->emit($event, ['message' => 'An ack recv test']); if (is_object($retval = $client->wait($event))) { echo sprintf("Got a reply: %s\n", $retval->inspect()); if (null !== $retval->ack) { echo "Send acknowledgement...\n"; $client->ack($retval, ["Okay"]); } } $client->disconnect();
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
ElephantIO/elephant.io
https://github.com/ElephantIO/elephant.io/blob/9f38be3b002156b2f6cc9ade30e1b58e7fea49cf/example/client/handshake-auth.php
example/client/handshake-auth.php
<?php /** * This file is part of the Elephant.io package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ require __DIR__ . '/common.php'; $namespace = 'handshake-auth'; $event = 'echo'; $logger = setup_logger(); // create first instance $client = setup_client($namespace, $logger, [ 'auth' => [ 'user' => 'random@example.com', 'token' => 'my-secret-token', ] ]); $data = [ 'message' => 'Hello!' ]; echo sprintf("Sending message: %s\n", inspect($data)); $client->emit($event, $data); if (is_object($retval = $client->wait($event))) { echo sprintf("Got a reply: %s\n", $retval->inspect()); } $client->disconnect(); try { // create second instance $client = setup_client($namespace, $logger, [ 'auth' => [ 'user' => 'random@example.com', 'password' => 'my-wrong-secret-password', ] ]); } catch (\ElephantIO\Exception\UnsuccessfulOperationException $e) { echo sprintf("Got expected authentication failure: %s\n", $e->getMessage()); }
php
MIT
9f38be3b002156b2f6cc9ade30e1b58e7fea49cf
2026-01-05T05:13:18.519422Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/meta.php
meta.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); \define('APP_NAME', 'tab-transfer'); \define('APP_VERSION', '0.5.1');
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Platform.php
src/Platform.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer; use Symfony\Component\Process\Process; final class Platform { private function __construct() {} /** * Detect whether the application is running on a Windows or Mac/Linux system. */ public static function isWindows(): bool { return 0 === \strpos(\PHP_OS, 'WIN'); } /** * Extract a reference to a class-private property. * * This is a last-resort approach. Use with care. You have been warned. * * @see https://ocramius.github.io/blog/accessing-private-php-class-members-without-reflection/ */ public static function & extractPropertyReference(object $object, string $propertyName): mixed { $value = & \Closure::bind(function & () use ($propertyName) { return $this->{$propertyName}; }, $object, $object)->__invoke(); return $value; } /** * Check whether the application is currently running as `phar` archive. * * @see https://github.com/box-project/box/blob/main/doc/faq.md#detecting-that-you-are-inside-a-phar */ public static function isPhar(): bool { return '' !== \Phar::running(false); } /** * Check if a given command is available in the shell environment context. * * If there are multiple binary executables available (checked ith `where` on Windows, `command` on Mac/Linux) * all of them are checked for actual existence and if they're executable. */ public static function isShellCommandAvailable(string $shellCommand): bool { $test = self::isWindows() ? 'cmd /c "where %s"' : 'command -v %s'; return \array_reduce( \explode("\n", (string)\shell_exec( \sprintf($test, $shellCommand) ) ), static function (bool $carry, string $entry): bool { $entry = \trim($entry); return $carry || (\file_exists($entry) && \is_executable($entry)); }, false ); } public static function isExecutable(string $filename): bool { return \is_executable($filename); } public static function openInBrowser(string $url, bool $secure = true, bool $debug = false): bool { $url = \filter_var($url, \FILTER_SANITIZE_URL); if ( ! \filter_var($url, \FILTER_VALIDATE_URL)) { return false; } if ($secure && ! \preg_match( '#^https?://#i', $url)) { return false; } if (Platform::isWindows()) { // Batch files require all `%` to be escaped with another `%`. $url = \str_replace('%', '%%', $url); $command = ['start', '', "{$url}"]; } elseif (\PHP_OS === 'Darwin') { // On Mac, we can use `open`, the URL must not be quoted for some reason. $command = ['open', '-u', "{$url}"]; } else { // Portable command across most Linux distros. $command = ['xdg-open', "{$url}"]; } $browser = new Process($command, timeout: null); $browser->start(); try { return 0 === $browser->wait(); } finally { if ($debug) { \fwrite(\STDOUT, $browser->getOutput()); \fwrite(\STDOUT, $browser->getErrorOutput()); } } } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Driver/AndroidDebugBridge.php
src/Driver/AndroidDebugBridge.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Driver; use Machinateur\ChromeTabTransfer\File\ReopenScriptFile; use Machinateur\ChromeTabTransfer\Shared\Console; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\Process; /** * Command process for `adb`. * * ``` * Android Debug Bridge version 1.0.41 * Version 35.0.2-12147458 * * global options: * -a listen on all network interfaces, not just localhost * -d use USB device (error if multiple devices connected) * -e use TCP/IP device (error if multiple TCP/IP devices available) * -s SERIAL use device with given serial (overrides $ANDROID_SERIAL) * -t ID use device with given transport id * -H name of adb server host [default=localhost] * -P port of adb server [default=5037] * -L SOCKET listen on given socket for adb server [default=tcp:localhost:5037] * --one-device SERIAL|USB only allowed with 'start-server' or 'server nodaemon', server will only connect to one USB device, specified by a serial number or USB device address. * --exit-on-write-error exit if stdout is closed * * general commands: * devices [-l] list connected devices (-l for long output) * help show this help message * version show version num * * networking: * forward --list list all forward socket connections * forward [--no-rebind] LOCAL REMOTE * forward socket connection using: * tcp:<port> (<local> may be "tcp:0" to pick any open port) * localabstract:<unix domain socket name> * localreserved:<unix domain socket name> * localfilesystem:<unix domain socket name> * dev:<character device name> * dev-raw:<character device name> (open device in raw mode) * jdwp:<process pid> (remote only) * vsock:<CID>:<port> (remote only) * acceptfd:<fd> (listen only) * forward --remove LOCAL remove specific forward socket connection * forward --remove-all remove all forward socket connections * reverse --list list all reverse socket connections from device * reverse [--no-rebind] REMOTE LOCAL * reverse socket connection using: * tcp:<port> (<remote> may be "tcp:0" to pick any open port) * localabstract:<unix domain socket name> * localreserved:<unix domain socket name> * localfilesystem:<unix domain socket name> * * environment variables: * $ADB_TRACE * comma/space separated list of debug info to log: * all,adb,sockets,packets,rwx,usb,sync,sysdeps,transport,jdwp,services,auth,fdevent,shell,incremental * $ADB_VENDOR_KEYS colon-separated list of keys (files or directories) * $ANDROID_SERIAL serial number to connect to (see -s) * $ANDROID_LOG_TAGS tags to be used by logcat (see logcat --help) * $ADB_LOCAL_TRANSPORT_MAX_PORT max emulator scan port (default 5585, 16 emus) * $ADB_MDNS_AUTO_CONNECT comma-separated list of mdns services to allow auto-connect (default adb-tls-connect) * * Online documentation: https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/user/adb.1.md * ``` */ final class AndroidDebugBridge extends AbstractDriver { /** * The default port on the `tcp` value. * * @var int */ public const DEFAULT_PORT = 9222; /** * The default timeout for requests to the endpoint. */ public const DEFAULT_TIMEOUT = 10; /** * The default socket name on the `localabstract` value. * * @var string */ public const DEFAULT_SOCKET = 'chrome_devtools_remote'; /** * The default amount of seconds to wait before returning from process start/stop calls. * * @var int */ public const DEFAULT_DELAY = 2; public function __construct( string $file, int $port = self::DEFAULT_PORT, bool $debug = false, int $timeout = self::DEFAULT_TIMEOUT, public readonly string $socket = self::DEFAULT_SOCKET, public readonly int $delay = self::DEFAULT_DELAY, public readonly bool $skipCleanup = false, ) { parent::__construct($file, $port, $debug, $timeout); } protected function run(Process $process, Console $console): void { $console->progressStart(1); $process->start(); $process->wait(); $console->progressFinish(); if ($this->debug) { $combinedProcessOutput = \array_filter( \array_map( static fn(string $line): string => "< {$line}", \array_merge( \explode(\PHP_EOL, $process->getOutput()), \explode(\PHP_EOL, $process->getErrorOutput()), ) ) ); $console->writeln($combinedProcessOutput); $console->newLine(); } $console->writeln("Waiting for {$this->delay} seconds...", OutputInterface::VERBOSITY_VERY_VERBOSE); \sleep($this->delay); } public function start(): void { $console = $this->getConsole(); $console->writeln(' ==> ' . __METHOD__ . ':', OutputInterface::VERBOSITY_DEBUG); $console->comment('Running `adb` command...'); $console->writeln("> adb -d forward tcp:{$this->port} localabstract:{$this->socket}", OutputInterface::VERBOSITY_DEBUG); $this->run( new Process(['adb', '-d', 'forward', "tcp:{$this->port}", "localabstract:{$this->socket}"]), console: $console ); $console->writeln(' ==> ' . __METHOD__ . ': Done.', OutputInterface::VERBOSITY_DEBUG); } public function stop(): void { $console = $this->getConsole(); $console->writeln(' ==> ' . __METHOD__ . ':', OutputInterface::VERBOSITY_DEBUG); if ($this->skipCleanup) { $console->writeln([ '<fg=black;bg=yellow>Skipping adb cleanup command... To dispose manually, run:</>', "<fg=black;bg=yellow;options=bold,underscore>> `adb -d forward --remove tcp:{$this->port}`</>", ]); } else { $console->comment('Running `adb` cleanup command...'); $console->writeln("> adb -d forward --remove tcp:{$this->port}", OutputInterface::VERBOSITY_DEBUG); $this->run( new Process(['adb', '-d', 'forward', '--remove', "tcp:{$this->port}"]), console: $console ); } $console->writeln(' ==> ' . __METHOD__ . ': Done.', OutputInterface::VERBOSITY_DEBUG); } public function getUrl(): string { return "http://localhost:{$this->port}/json/list"; } public function getFileTemplates(array $tabs): array { $fileTemplates = parent::getFileTemplates($tabs); // Only write the reopen script file, if the cleanup is done properly. // Otherwise, we are at risk of opening those tabs again on the same device. if ( ! $this->skipCleanup) { $this->output->writeln('Allow reopen script with cleanup enabled.', OutputInterface::VERBOSITY_VERY_VERBOSE); $fileTemplates[] = new ReopenScriptFile($this->file, $tabs, $this->port, $this->socket); } else { $this->output->writeln('Skipping reopen script with cleanup disabled.', OutputInterface::VERBOSITY_VERY_VERBOSE); } return $fileTemplates; } protected function getShellCommand(): string { return 'adb'; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Driver/DriverUrlInterface.php
src/Driver/DriverUrlInterface.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Driver; interface DriverUrlInterface { public function getUrl(): string; }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Driver/IosWebkitDebugProxy.php
src/Driver/IosWebkitDebugProxy.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Driver; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\Process; /** * Command process for `ios_webkit_debug_proxy`. * * ``` * Usage: ios_webkit_debug_proxy [OPTIONS] * iOS WebKit Remote Debugging Protocol Proxy v1.9.1. * * By default, the proxy will list all attached iOS devices on: * http://localhost:9221 * and assign each device an incremented port number, e.g.: * http://localhost:9222 * which lists the device's pages and provides inspector access. * * Your attached iOS device(s) must have the inspector enabled via: * Settings > Safari > Advanced > Web Inspector = ON * and have one or more open browser pages. * * To view the DevTools UI, either use the above links (which use the "frontend" * URL noted below) or use Chrome's built-in inspector, e.g.: * chrome-devtools://devtools/bundled/inspector.html?ws=localhost:9222/devtools/page/1 * * OPTIONS: * * -u UDID[:minPort-[maxPort]] Target a specific device by its digital ID. * minPort defaults to 9222. maxPort defaults to minPort. * This is shorthand for the following "-c" option. * * -c, --config CSV UDID-to-port(s) configuration. * Defaults to: * null:9221,:9222-9322 * which lists devices ("null:") on port 9221 and assigns * all other devices (":") to the next unused port in the * 9222-9322 range, in the (somewhat random) order that the * devices are detected. * The value can be the path to a file in the above format. * * -f, --frontend URL DevTools frontend UI path or URL. * Defaults to: * http://chrome-devtools-frontend.appspot.com/static/27.0.1453.93/devtools.html * Examples: * * Use Chrome's built-in inspector: * chrome-devtools://devtools/bundled/inspector.html * * Use a local WebKit checkout: * /usr/local/WebCore/inspector/front-end/inspector.html * * Use an online copy of the inspector pages: * http://chrome-devtools-frontend.appspot.com/static/33.0.1722.0/devtools.html * where other online versions include: * 18.0.1025.74 * 25.0.1364.169 * 28.0.1501.0 * 30.0.1599.92 * 31.0.1651.0 * 32.0.1689.3 * * -F, --no-frontend Disable the DevTools frontend. * * -s, --simulator-webinspector Simulator web inspector socket * address. Provided value needs to be in format * HOSTNAME:PORT or UNIX:PATH * Defaults to: * localhost:27753 * Examples: * * TCP socket: * 192.168.0.20:27753 * * Unix domain socket: * unix:/private/tmp/com.apple.launchd.2j5k1TMh6i/com.apple.webinspectord_sim.socket * * -d, --debug Enable debug output. * -h, --help Print this usage information. * -V, --version Print version information and exit. * ``` */ final class IosWebkitDebugProxy extends AbstractDriver { public const DEFAULT_PORT = AndroidDebugBridge::DEFAULT_PORT; public const DEFAULT_TIMEOUT = AndroidDebugBridge::DEFAULT_TIMEOUT; public const DEFAULT_DELAY = AndroidDebugBridge::DEFAULT_DELAY; private readonly Process $process; /** * Create a background process to open the debug proxy for iOS. * * In contrast to the {@see AndroidDebugBridge}, this process is blocking and will remain running while the application is running. */ public function __construct( string $file, int $port = self::DEFAULT_PORT, bool $debug = false, int $timeout = self::DEFAULT_TIMEOUT, public readonly int $delay = self::DEFAULT_DELAY, ) { parent::__construct($file, $port, $debug, $timeout); $command = ['ios_webkit_debug_proxy', '-F', '-c', 'null:9221,:9222-9322']; if ($debug) { $command[] = '--debug'; } $this->process = new Process($command); } public function start(): void { $console = $this->getConsole(); $console->writeln(' ==> ' . __METHOD__ . ':', OutputInterface::VERBOSITY_DEBUG); $console->comment('Starting `ios_webkit_debug_proxy` background process...'); $console->progressStart(1); $this->process->start(); $console->progressFinish(); $console->writeln("Waiting for {$this->delay} seconds...", OutputInterface::VERBOSITY_VERY_VERBOSE); \sleep($this->delay); $console->writeln(' ==> ' . __METHOD__ . ': Done.', OutputInterface::VERBOSITY_DEBUG); } public function stop(): void { $console = $this->getConsole(); $console->writeln(' ==> ' . __METHOD__ . ':', OutputInterface::VERBOSITY_DEBUG); $console->comment('Stopping `ios_webkit_debug_proxy` background process...'); $console->progressStart(1); $this->process->stop(); $this->process->wait(); $console->progressFinish(); if ($this->debug) { $combinedProcessOutput = \array_filter( \array_map( static fn(string $line): string => "< {$line}", \array_merge( \explode(\PHP_EOL, $this->process->getOutput()), \explode(\PHP_EOL, $this->process->getErrorOutput()), ) ) ); $console->writeln($combinedProcessOutput); $console->newLine(); } $console->writeln("Waiting for {$this->delay} seconds...", OutputInterface::VERBOSITY_VERY_VERBOSE); \sleep($this->delay); $console->writeln(' ==> ' . __METHOD__ . ': Done.', OutputInterface::VERBOSITY_DEBUG); } public function getUrl(): string { return "http://localhost:{$this->port}/json"; } protected function getShellCommand(): string { return 'ios_webkit_debug_proxy'; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Driver/DriverEnvironmentCheckInterface.php
src/Driver/DriverEnvironmentCheckInterface.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Driver; interface DriverEnvironmentCheckInterface { public function checkEnvironment(): bool; }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Driver/AbstractDriver.php
src/Driver/AbstractDriver.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Driver; use Machinateur\ChromeTabTransfer\File\FileTemplateInterface; use Machinateur\ChromeTabTransfer\File\JsonFile; use Machinateur\ChromeTabTransfer\File\MarkdownFile; use Machinateur\ChromeTabTransfer\Platform; use Machinateur\ChromeTabTransfer\Shared\Console; use Machinateur\ChromeTabTransfer\Shared\ConsoleTrait; use Machinateur\ChromeTabTransfer\Shared\FileDateTrait; use Machinateur\ChromeTabTransfer\TabLoader\CurlTabLoader; use Machinateur\ChromeTabTransfer\TabLoader\TabLoaderInterface; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @method $this setConsole(Console $console) * @method $this setInput(InputInterface $input) * @method $this setOutput(OutputInterface $output) * @method $this setFileDate(?\DateTimeInterface $date) */ abstract class AbstractDriver implements DriverLifecycleInterface, DriverUrlInterface, DriverEnvironmentCheckInterface { use ConsoleTrait { ConsoleTrait::__construct as private initializeConsole; } use FileDateTrait; public function __construct( public readonly string $file, public readonly int $port, public readonly bool $debug, public readonly int $timeout, ) { $this->initializeConsole(); } abstract public function start(): void; abstract public function stop(): void; abstract public function getUrl(): string; public function getTabLoader(): TabLoaderInterface { $url = $this->getUrl(); $this->output->writeln("Creating new tab loader for URL `{$url}` (timeout {$this->timeout}s)...", OutputInterface::VERBOSITY_DEBUG); return (new CurlTabLoader($url, $this->timeout)) ->setDebug($this->debug) ->setOutput($this->output); } /** * @return array<FileTemplateInterface> */ public function getFileTemplates(array $tabs): array { return [ new JsonFile($this->file, $tabs), new MarkdownFile($this->file, $tabs), ]; } public function checkEnvironment(): bool { $shellCommand = $this->getShellCommand(); if (empty($shellCommand)) { return true; } $console = $this->getConsole(); $console->writeln("Checking for availability of `$shellCommand`.", OutputInterface::VERBOSITY_VERY_VERBOSE); $commandAvailable = Platform::isShellCommandAvailable($shellCommand); // TODO: Support local path installation relative (in tools/). if ($commandAvailable) { $console->writeln("The `$shellCommand` executable is available.", OutputInterface::VERBOSITY_VERY_VERBOSE); } else { $console->writeln("The `$shellCommand` executable was not found!", OutputInterface::VERBOSITY_VERY_VERBOSE); } return $commandAvailable; } protected function getShellCommand(): ?string { return null; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Driver/DriverLifecycleInterface.php
src/Driver/DriverLifecycleInterface.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Driver; interface DriverLifecycleInterface { public function start(): void; public function stop(): void; }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Driver/RestoreTabsDriver.php
src/Driver/RestoreTabsDriver.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Driver; use Machinateur\ChromeTabTransfer\File\WebsocketWdpClient; use Machinateur\ChromeTabTransfer\Platform; use Machinateur\ChromeTabTransfer\Shared\Console; use Machinateur\ChromeTabTransfer\TabLoader\CurlReopenTabLoader; use Machinateur\ChromeTabTransfer\TabLoader\TabLoaderInterface; use Machinateur\ChromeTabTransfer\TabLoader\WdpReopenTabLoader; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Use this driver to control start/stop another diver, like a proxy object passing calls through. * * The logic is (likely) the same for both drivers, so the call goes to ghe same URL, but with different backends (processes) if that makes snse. */ class RestoreTabsDriver extends AbstractDriver { public function __construct( string $file, int $port, bool $debug, int $timeout, public readonly AbstractDriver $driver, ) { parent::__construct($file, $port, $debug, $timeout); } public function start(): void { // We have to enable the frontend accordingly, to be able to use the WDP script created above. if ($this->driver instanceof IosWebkitDebugProxy) { $process = Platform::extractPropertyReference($this->driver, 'process'); $commandline = & Platform::extractPropertyReference($process, 'commandline'); // Splice in the `-f` value into the $commandline array, to enable the WDP frontend. \array_splice($commandline, \array_search('-F', $commandline), 1, ['-f', WebsocketWdpClient::FILENAME]); } $this->driver->start(); } public function stop(): void { $this->driver->stop(); } public function getUrl(): string { // Note the `%s` which is used in the `CurlReopenTabLoader`. return "http://localhost:{$this->port}/json/new?%s"; } public function getTabLoader(): TabLoaderInterface { $console = $this->getConsole(); // On iphone, the `/json/new?...` endpoint is not supported. Bummer. But I've found a workaround using WDP directly. if ($this->driver instanceof IosWebkitDebugProxy) { // The first tab is the target page in almost all scenarios. Usually the ID is updated automatically on // establishing the connection (as well as on every opening of a new tab). $targetPage = (string)$console->input->getParameterOption('--wdp-target') ?: '1'; $console->writeln("Creating new tab restorer for iOS using WDP directly (page {$targetPage})."); $console->writeln('<fg=black;bg=yellow>This is an experimental feature and might be unstable.</>'); return (new WdpReopenTabLoader($this->port, $this->timeout, $this->file, $targetPage)) ->setDebug($this->debug) ->setOutput($this->output); } $url = $this->getUrl(); $console->writeln("Creating new tab restorer for URL `{$url}` (timeout {$this->timeout}s)...", OutputInterface::VERBOSITY_DEBUG); // Use the default `/json/new?...` endpoint for android. return (new CurlReopenTabLoader($url, $this->timeout, $this->file)) ->setOutput($this->output) ->setDebug($this->debug) ->setFileDate($this->date); } /** * No output files. */ public function getFileTemplates(array $tabs): array { return []; } /** * No check needed. The check is done through {@see \Machinateur\ChromeTabTransfer\Command\ReopenTabs::checkCommandEnvironment()}. */ public function checkEnvironment(): bool { return true; } public function setConsole(Console $console): static { $this->driver->setConsole($console); return parent::setConsole($console); } public function setInput(InputInterface $input): static { $this->driver->setInput($input); return parent::setInput($input); } public function setOutput(OutputInterface $output): static { $this->driver->setOutput($output); return parent::setOutput($output); } public function setFileDate(?\DateTimeInterface $date): static { $this->driver->setFileDate($date); return parent::setFileDate($date); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/TabLoader/JsonFileTabLoader.php
src/TabLoader/JsonFileTabLoader.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\TabLoader; use Machinateur\ChromeTabTransfer\Exception\JsonFileLoadingException; use Machinateur\ChromeTabTransfer\File\JsonFile; use Machinateur\ChromeTabTransfer\Shared\Console; use Machinateur\ChromeTabTransfer\Shared\ConsoleTrait; use Machinateur\ChromeTabTransfer\Shared\DebugFlagTrait; use Machinateur\ChromeTabTransfer\Shared\FileDateTrait; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Filesystem; /** * A loader that can read the files written through the {@see \Machinateur\ChromeTabTransfer\File\JsonFile} template. * * @method $this setConsole(Console $console) * @method $this setInput(InputInterface $input) * @method $this setOutput(OutputInterface $output) * @method $this setDebug(bool $debug) * @method $this setFileDate(?\DateTimeInterface $date) */ class JsonFileTabLoader implements TabLoaderInterface { use ConsoleTrait { ConsoleTrait::__construct as private initializeConsole; } use DebugFlagTrait; use FileDateTrait; private readonly Filesystem $filesystem; public function __construct( public readonly string $file, ) { $this->initializeConsole(); $this->filesystem = new Filesystem(); } /** * @throws JsonFileLoadingException */ public function load(): array { $console = $this->getConsole(); $console->writeln(' ==> ' . __METHOD__ . ':', OutputInterface::VERBOSITY_DEBUG); // We can only know the actual filename here, as the `--date` flag is injected only later. $file = (new JsonFile($this->file, [])) ->setFileDate($this->getFileDate()) ->getFilename(); $console->writeln("Looking for file `{$file}` to load stored tabs... ", OutputInterface::VERBOSITY_VERY_VERBOSE); if ( ! $this->filesystem->exists($file)) { $console->writeln("File `{$file}` not found!", OutputInterface::VERBOSITY_VERY_VERBOSE); throw JsonFileLoadingException::whenFileNotFound($file); } if ('json' !== \pathinfo($file, \PATHINFO_EXTENSION)) { $console->writeln('The file extension does not match `.json`!', OutputInterface::VERBOSITY_VERY_VERBOSE); throw JsonFileLoadingException::whenFileNotAJsonFile($file); } $result = @\file_get_contents($file); if ( ! $result) { $console->writeln("Error reading file `{$file}`: Falsy result.", OutputInterface::VERBOSITY_VERY_VERBOSE); throw JsonFileLoadingException::whenFileNotReadable($file); } if ($this->debug) { $console->writeln(\array_map(static fn(string $line): string => "< {$line}", \explode("\n", $result))); } try { $tabs = @\json_decode($result, true, flags: \JSON_THROW_ON_ERROR) ?? []; } catch (\JsonException $exception) { $console->writeln('Unable to decode JSON data!', OutputInterface::VERBOSITY_VERY_VERBOSE); throw JsonFileLoadingException::fromJsonException($exception); } $console->writeln('Successfully decoded json data.', OutputInterface::VERBOSITY_VERY_VERBOSE); if ( ! \is_array($tabs)) { $console->writeln('Warning: The JSON data type is not an array or object.', OutputInterface::VERBOSITY_VERY_VERBOSE); throw JsonFileLoadingException::forMalformedContent(); } foreach ($tabs as $tab) { if (\array_key_exists('url', $tab)) { continue; } $console->writeln('Warning: Tab without URL found in data. Make sure each tab entry has at least the `url` key assigned.', OutputInterface::VERBOSITY_VERY_VERBOSE); throw JsonFileLoadingException::forMalformedContent(); } return $tabs; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/TabLoader/CurlReopenTabLoader.php
src/TabLoader/CurlReopenTabLoader.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\TabLoader; use Machinateur\ChromeTabTransfer\Exception\TabReopenFailedException; use Machinateur\ChromeTabTransfer\File\ReopenScriptFile; use Machinateur\ChromeTabTransfer\Shared\Console; use Machinateur\ChromeTabTransfer\Shared\FileDateTrait; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class CurlReopenTabLoader extends CurlTabLoader { use FileDateTrait { FileDateTrait::setFileDate as private parent__setFileDate; } use JsonFileTabLoaderTrait { JsonFileTabLoaderTrait::__construct as private initializeJsonFileTabLoader; } public function __construct( string $url, int $timeout, public readonly string $file, ) { parent::__construct($url, $timeout); $this->initializeJsonFileTabLoader($this->file); } /** * @throws TabReopenFailedException */ public function load(): array { $this->loadTabs(); $console = $this->getConsole(); $console->writeln(' ==> ' . __METHOD__ . ':', OutputInterface::VERBOSITY_DEBUG); $tabs = []; $tabsCount = \count($this->tabs); $errors = 0; $console->comment("Uploading tabs {$tabsCount} to device..."); // The display will be messed up if using the progress bar while writing `-vv`/`-vvv` output. $useProgressBar = ! $console->isVeryVerbose() && ! $console->isDebug(); if ($useProgressBar) { $console->progressStart($tabsCount); } $tabIndex = 0; foreach ($this->tabs as $tab) { ++$tabIndex; [$url, $title] = ReopenScriptFile::parseTab($tab); if ($title !== $tab['url']) { $console->writeln("> Uploading tab #{$tabIndex} `{$title}` (`{$tab['url']}`)...", OutputInterface::VERBOSITY_VERY_VERBOSE); } else { $console->writeln("> Uploading tab #{$tabIndex} without title (`{$tab['url']}`)...", OutputInterface::VERBOSITY_VERY_VERBOSE); } $url = \sprintf($this->url, $url); $result = $this->exec($capturedErrorCode, $capturedErrorMessage, $url, $this->timeout, true); if (null !== $result) { // Print a warning message to the console. $console->writeln('< <fg=black;bg=yellow>Unexpected result for tab upload to device!</>', OutputInterface::VERBOSITY_VERY_VERBOSE); if ($this->debug) { $console->writeln(\array_map(static fn(string $line): string => "< {$line}", \explode("\n", $result))); } } else { $console->writeln('< <fg=black;bg=green>Done.</>', OutputInterface::VERBOSITY_VERY_VERBOSE); } if ($capturedErrorCode) { $console->writeln(' Captured curl error message from the request:', OutputInterface::VERBOSITY_VERY_VERBOSE); $console->writeln(" > {$capturedErrorMessage}", OutputInterface::VERBOSITY_VERY_VERBOSE); if (null === $capturedErrorMessage) { $console->writeln(' No curl error message captured, but an error was found.', OutputInterface::VERBOSITY_VERY_VERBOSE); } $errors++; } $tabs[] = [...$tab, 'transferred' => ! $capturedErrorCode]; if ($useProgressBar) { $console->progressAdvance(); } } // If not used before, at least display the total of processed tabs as progress bar. if ( ! $useProgressBar) { $console->progressStart($tabsCount); } $console->progressFinish(); $console->writeln(' ==> ' . __METHOD__ . ': Done.', OutputInterface::VERBOSITY_DEBUG); if ( ! $errors) { return $tabs; } elseif ($errors < $tabsCount) { throw TabReopenFailedException::forSomeErrors($errors, $tabsCount); } throw TabReopenFailedException::forErrors(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// public function setOutput(OutputInterface $output): static { $this->jsonFileLoader->setOutput($output); return parent::setOutput($output); } public function setInput(InputInterface $input): static { $this->jsonFileLoader->setInput($input); return parent::setInput($input); } public function setConsole(Console $console): static { $this->jsonFileLoader->setConsole($console); return parent::setConsole($console); } public function setDebug(bool $debug): static { $this->jsonFileLoader->setDebug($debug); return parent::setDebug($debug); } public function setFileDate(?\DateTimeInterface $date): static { $this->jsonFileLoader->setFileDate($date); return $this->parent__setFileDate($date); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/TabLoader/JsonFileTabLoaderTrait.php
src/TabLoader/JsonFileTabLoaderTrait.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\TabLoader; use Machinateur\ChromeTabTransfer\Exception\JsonFileLoadingException; use Machinateur\ChromeTabTransfer\Exception\TabReopenFailedException; trait JsonFileTabLoaderTrait { protected readonly JsonFileTabLoader $jsonFileLoader; public function __construct(string $file) { $this->jsonFileLoader = new JsonFileTabLoader($file); } private ?array $tabs = null; /** * Preload the tabs to open from disk. * * @throws TabReopenFailedException */ protected function loadTabs(): array { try { $this->tabs ??= $this->jsonFileLoader->load(); } catch (JsonFileLoadingException $exception) { throw TabReopenFailedException::fromJsonFileLoadingException($exception); } if (empty($this->tabs)) { throw TabReopenFailedException::forEmptyInput(); } return $this->tabs; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/TabLoader/CurlTabLoader.php
src/TabLoader/CurlTabLoader.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\TabLoader; use Machinateur\ChromeTabTransfer\Exception\CurlException; use Machinateur\ChromeTabTransfer\Exception\TabLoadingFailedException; use Machinateur\ChromeTabTransfer\Shared\Console; use Machinateur\ChromeTabTransfer\Shared\ConsoleTrait; use Machinateur\ChromeTabTransfer\Shared\DebugFlagTrait; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @method $this setConsole(Console $console) * @method $this setInput(InputInterface $input) * @method $this setOutput(OutputInterface $output) * @method $this setDebug(bool $debug) */ class CurlTabLoader implements TabLoaderInterface { use ConsoleTrait { ConsoleTrait::__construct as private initializeConsole; } use DebugFlagTrait; public function __construct( public readonly string $url, public readonly int $timeout, ) { $this->initializeConsole(); } final protected function exec( ?int &$capturedErrorCode = 0, ?string &$capturedErrorMessage = null, string $url = null, int $timeout = null, bool $isPutRequest = false, ): ?string { $url ??= $this->url; $timeout ??= $this->timeout; $console = $this->getConsole(); $console->writeln("> curl: {$url} ({$timeout})", OutputInterface::VERBOSITY_VERY_VERBOSE); $ch = \curl_init(); \curl_setopt($ch, \CURLOPT_URL, $url); \curl_setopt($ch, \CURLOPT_TIMEOUT, $timeout); //\curl_setopt($ch, \CURLOPT_CONNECTTIMEOUT, 10); if ($this->debug) { $console->newLine(); // This will enable output directly to the STDERR stream of PHP. \curl_setopt($ch, \CURLOPT_VERBOSE, true); } \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true); if ($isPutRequest) { \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'PUT'); } /** @var string|null $result */ $result = \curl_exec($ch) ?: null; $capturedErrorCode = \curl_errno($ch); $capturedErrorMessage = null; if (0 < $capturedErrorCode) { $capturedErrorMessage = \sprintf('%s (code %d)', \curl_error($ch), $capturedErrorCode); } \curl_close($ch); unset($url, $ch); if ($this->debug) { // New line after STDERR output from curl execution. $console->newLine(); } return $result; } /** * @throws TabLoadingFailedException */ public function load(): array { $console = $this->getConsole(); $console->comment('Downloading tabs from device...'); $result = $this->exec($capturedErrorCode, $capturedErrorMessage); if (null === $result) { $console->warning([ 'Unable to download tabs from device! Please check the device connection!', 'Also make sure google chrome is running on the connected device and USB debugging is active in the developer settings.', ]); if (null === $capturedErrorMessage) { $console->writeln('No curl error message captured, but result was `null`.', OutputInterface::VERBOSITY_VERY_VERBOSE); throw CurlException::withoutErrorMessage($capturedErrorCode); } $console->writeln('Captured curl error message from the request:', OutputInterface::VERBOSITY_VERY_VERBOSE); $console->writeln("> {$capturedErrorMessage}", OutputInterface::VERBOSITY_VERY_VERBOSE); throw new CurlException($capturedErrorMessage); } if ($this->debug) { $console->writeln(\array_map(static fn(string $line): string => "< {$line}", \explode("\n", $result))); } $console->success('Successfully downloaded tabs from device!'); try { $tabs = @\json_decode($result, true, flags: \JSON_THROW_ON_ERROR) ?? []; } catch (\JsonException $exception) { $console->writeln('Unable to decode JSON data!', OutputInterface::VERBOSITY_VERY_VERBOSE); throw TabLoadingFailedException::fromJsonException($exception); } $console->writeln('Successfully decoded json data.', OutputInterface::VERBOSITY_VERY_VERBOSE); return $tabs; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/TabLoader/WdpReopenTabLoader.php
src/TabLoader/WdpReopenTabLoader.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\TabLoader; use Machinateur\ChromeTabTransfer\Exception\FileTemplateDumpException; use Machinateur\ChromeTabTransfer\File\WebsocketWdpClient; use Machinateur\ChromeTabTransfer\Platform; use Machinateur\ChromeTabTransfer\Shared\Console; use Machinateur\ChromeTabTransfer\Shared\ConsoleTrait; use Machinateur\ChromeTabTransfer\Shared\DebugFlagTrait; use Machinateur\ChromeTabTransfer\Shared\FileDateTrait; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Filesystem\Filesystem; /** * A tab loader that will dump and open a new {@see \Machinateur\ChromeTabTransfer\File\WebsocketWdpClient} script in the browser. * * This implementation is to be used with iphone to restore tabs on the device. This is required to be done via websocket, * as the usual `/json/new`...` endpoint (used for android) is not supported by `ios_webkit_debug_proxy`. * See {@see } */ class WdpReopenTabLoader implements TabLoaderInterface { use ConsoleTrait { ConsoleTrait::__construct as private initializeConsole; ConsoleTrait::setOutput as private parent__setOutput; ConsoleTrait::setInput as private parent__setInput; ConsoleTrait::setConsole as private parent__setConsole; } use DebugFlagTrait { DebugFlagTrait::setDebug as private parent__setDebug; } use FileDateTrait { FileDateTrait::setFileDate as private parent__setFileDate; } use JsonFileTabLoaderTrait { JsonFileTabLoaderTrait::__construct as private initializeJsonFileTabLoader; } private readonly Filesystem $filesystem; public function __construct( public readonly int $port, public readonly int $timeout, public readonly string $file, public readonly string $targetPage, ) { $this->initializeConsole(); $this->initializeJsonFileTabLoader($this->file); $this->filesystem = new Filesystem(); } public function load(): array { $tabs = $this->loadTabs(); $tabsCount = \count($this->tabs); /** @var string $filename */ $this->dumpWdpClient($tabs, $filename); $console = $this->getConsole(); $console->writeln(' ==> ' . __METHOD__ . ':', OutputInterface::VERBOSITY_DEBUG); $console->comment("Uploading tabs {$tabsCount} to device..."); // Blocking process call to open the system's web-browser. $result = Platform::openInBrowser($wdpClientUrl = "http://localhost:{$this->port}/devtools/{$filename}"); if ( ! $result) { $console->writeln('Browser process failed with non-zero exit-code!', OutputInterface::VERBOSITY_VERY_VERBOSE); } $console->info([ "Please open `{$wdpClientUrl}` in your browser. The transfer should start immediately.", 'Simply close the page when the tabs were transferred.', ]); // This needs `setConsole()` instead of `setOutput()` (currently used everywhere) to work. if ($console->input->isInteractive()) { $console->confirm('Please press <info>[enter]</> to continue...'); } else { $console->writeln("Waiting for {$this->timeout} seconds (timeout on non-interactive console)...", OutputInterface::VERBOSITY_VERY_VERBOSE); \sleep($this->timeout); } // When not in debug mode, the WDP script will be removed again. if ( ! $this->debug) { $this->filesystem->remove($filename); } $console->progressStart($tabsCount); $tabs = \array_map(static fn(array $tab): array => [...$tab, 'transferred' => true], $tabs); $console->progressFinish(); $console->writeln(' ==> ' . __METHOD__ . ': Done.', OutputInterface::VERBOSITY_DEBUG); return $tabs; } /** * @throws FileTemplateDumpException */ final protected function dumpWdpClient(array $tabs, ?string & $filename): void { $console = $this->getConsole(); $fileTemplate = (new WebsocketWdpClient($tabs, $this->port, $this->targetPage)) ->setOutput($this->getOutput()) ->setFileDate($this->getFileDate()); $filename = $fileTemplate->getFilename(); $content = (string)$fileTemplate; try { $this->filesystem->dumpFile($filename, $content); } catch (IOException $exception) { $console->writeln('Error writing file: ' . $exception->getMessage(), OutputInterface::VERBOSITY_VERY_VERBOSE); throw FileTemplateDumpException::fromIOException($exception); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// public function setOutput(OutputInterface $output): static { $this->jsonFileLoader->setOutput($output); return $this->parent__setOutput($output); } public function setInput(InputInterface $input): static { $this->jsonFileLoader->setInput($input); return $this->parent__setInput($input); } public function setConsole(Console $console): static { $this->jsonFileLoader->setConsole($console); return $this->parent__setConsole($console); } public function setDebug(bool $debug): static { $this->jsonFileLoader->setDebug($debug); return $this->parent__setDebug($debug); } public function setFileDate(?\DateTimeInterface $date): static { $this->jsonFileLoader->setFileDate($date); return $this->parent__setFileDate($date); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/TabLoader/TabLoaderInterface.php
src/TabLoader/TabLoaderInterface.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\TabLoader; use Machinateur\ChromeTabTransfer\Exception\TabLoadingFailedException; interface TabLoaderInterface { /** * @throws TabLoadingFailedException */ public function load(): array; }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/File/ReopenScriptFile.php
src/File/ReopenScriptFile.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\File; use Machinateur\ChromeTabTransfer\Platform; class ReopenScriptFile extends AbstractFileTemplate { public function __construct( string $file, array $jsonArray, private readonly int $port, private readonly string $socket, ) { parent::__construct($file, $jsonArray); $this->filenameSuffix = '-reopen'; } public function getExtension(): string { return Platform::isWindows() ? 'cmd' : 'sh'; } public function render(): string { $port = $this->port; $socket = $this->socket; return Platform::isWindows() // Windows `cmd` script ? ( '@echo off' . \PHP_EOL . \PHP_EOL . ':: Created using machinateur/tab-transfer (https://github.com/machinateur/tab-transfer).' . \PHP_EOL . \PHP_EOL . "adb -d forward tcp:{$port} localabstract:{$socket}" . \PHP_EOL . \PHP_EOL . \join( \PHP_EOL, \array_map(static function (array $tab) use ($port): string { [$url, $title] = self::parseTab($tab); // Batch files require all `%` to be escaped with another `%`. $url = \str_replace('%', '%%', $url); return \sprintf(':: %s', $title) . \PHP_EOL // URLs must be double-quoted to work with curl, and double-quotes also escape other batch characters. . \sprintf("curl -X PUT \"http://localhost:{$port}/json/new?%s\"", $url) . \PHP_EOL; }, $this->tabs) ) . \PHP_EOL . \PHP_EOL . "adb -d forward --remove tcp:{$port}" . \PHP_EOL . \PHP_EOL . 'pause' . \PHP_EOL . \PHP_EOL ) // Linux/Mac bash script : ( '#!/bin/bash' . \PHP_EOL . \PHP_EOL . '# Created using machinateur/tab-transfer (https://github.com/machinateur/tab-transfer).' . \PHP_EOL . \PHP_EOL . "adb -d forward tcp:{$port} localabstract:{$socket}" . \PHP_EOL . \PHP_EOL . \join( \PHP_EOL, \array_map(static function (array $tab) use ($port): string { [$url, $title] = self::parseTab($tab); return \sprintf('# %s', $title) . \PHP_EOL . \sprintf("curl -X PUT 'http://localhost:{$port}/json/new?%s'", $url) . \PHP_EOL; }, $this->tabs) ) . \PHP_EOL . \PHP_EOL . "adb -d forward --remove tcp:{$port}" . \PHP_EOL ) ; } /** * Parses a tab entry for use in requests (URLs). * * The provided parameter must contain at least the `'url'` key (currently unchecked). * The `'title'` key, if not given, will default to the `'url'`. * * The output is a tuple of `'url'` and `'title'`, where the URL is {@see \rawurlencode()}d. * Keep in mind, that for script-file use on Windows systems, all `%` characters have to be replaced (in `.cmd` files). * * @return array{0: string, 1: string} */ public static function parseTab(array $tab): array { $url = $tab['url']; $title = $tab['title'] ?: $url; $url = \rawurlencode($url); return [$url, $title]; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/File/WebsocketWdpClient.php
src/File/WebsocketWdpClient.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\File; /** * A simple webkit dev-tools protocol client, using web-sockets (`ws:`). * It is used by the {@see \Machinateur\ChromeTabTransfer\TabLoader\WdpReopenTabLoader} to implement * automated tab restoration on iphone. * * This implementation is based on the * example {@see https://github.com/google/ios-webkit-debug-proxy/blob/master/examples/wdp_client.html from the `ios_webkit_debug_proxy` docs}. * * The chrome dev-tools protocol and webkit dev-tools protocol have diverged in recent versions, * which causes compatibility issues. A list of available protocol domains can be found here: * https://github.com/WebKit/webkit/tree/main/Source/JavaScriptCore/inspector/protocol * * The main commands by the client are `Target.sendCommandToTarget()` and `Runtime.evaluate()`. */ class WebsocketWdpClient extends AbstractFileTemplate { public const FILENAME = 'wdp_client.html'; protected const JSON_FLAGS = \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_PRETTY_PRINT; public function __construct( array $tabs, protected readonly int $port, protected readonly string $targetPage, ) { parent::__construct(self::FILENAME, $tabs); } public function getExtension(): string { return 'html'; } public function render(): string { $port = $this->port; $targetPage = $this->targetPage; $index = 0; $commandsList = \array_map(static fn(array $tab): array => [ 'id' => ++$index, 'method' => 'Target.sendMessageToTarget', 'params' => [ 'targetId' => "{$targetPage}", // Yes, this is json-in-json... :) 'message' => \json_encode([ 'id' => 1, 'method' => 'Runtime.evaluate', 'params' => [ 'expression' => "open('{$tab['url']}');", ], ], flags: self::JSON_FLAGS), ], ], $this->tabs); $commandsTotal = \count($commandsList); $commands = \json_encode($commandsList, flags: self::JSON_FLAGS); return <<<HTML <!-- ~ MIT License ~ ~ Copyright (c) 2021-2024 machinateur ~ ~ Permission is hereby granted, free of charge, to any person obtaining a copy ~ of this software and associated documentation files (the "Software"), to deal ~ in the Software without restriction, including without limitation the rights ~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ~ copies of the Software, and to permit persons to whom the Software is ~ furnished to do so, subject to the following conditions: ~ ~ The above copyright notice and this permission notice shall be included in all ~ copies or substantial portions of the Software. ~ ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ~ SOFTWARE. ~ ~ ------------------------------------------------------------------------------- ~ ~ Based on https://github.com/google/ios-webkit-debug-proxy/blob/master/examples/wdp_client.html. ~ ~ Google BSD license https://developers.google.com/google-bsd-license ~ Copyright 2012 Google Inc. wrightt@google.com ~ ~ An example browser-based client. --> <html lang="en"> <head> <title>tab-transfer - iOS WDP Script</title> <script type="text/javascript"> var wdpClient = (function () { var ws = undefined; var commands = {$commands}; var commandsTotal = {$commandsTotal}; var url = `ws://localhost:{$port}/devtools/page/{$targetPage}`; var targetId = '{$targetPage}'; function restore() { ws && ws.close(); ws = new WebSocket(url); ws.addEventListener('open', function () { console.log(`Opened socket to \${url}.`); }); ws.addEventListener('message', function (event) { console.log('Message:', event.data); // This feature is currently inhibited, see discussion at TODO. var message = JSON.parse(event.data); if (message.method === 'Target.targetCreated') { targetId = message.params.targetInfo.targetId; console.log('New target:', targetId); } sendNextCommand(); }); ws.addEventListener('close', function () { console.log(`Closed socket to \${url}.`); }); ws.addEventListener('error', function (error) { console.log('Error:', error.data); }); return ws; } function sendNextCommand() { if ( ! commands.length) { return; } var command = commands.shift(); command.params.targetId = targetId; var data = JSON.stringify(command); console.log('Command:', data); ws.send(data); updateProgress(); } function updateProgress() { var commandsSent = commandsTotal - commands.length; document.getElementById('bar').style.width = `\${(commandsSent / commandsTotal) * 100}%`; document.getElementById('title').textContent = `Restored \${commandsSent} of \${commandsTotal} tabs (\${commands.length ? commands.length : 'none'} left)...`; } return { restoreTabs: restore }; })(); </script> <style> #progress { width: 100%; background-color: grey; border: 1px solid black; } #bar { width: 0; background-color: green; border-right: 1px solid black; height: 30px; transition: width 100ms linear; } </style> </head> <body> <h1>tab-transfer: restore to phone</h1> <div id="progress"> <div id="bar"></div> </div> <p id="title">Waiting...</p> <hr/> <p style="color: gray;">You can open the dev-tools JavaScript console to see details on communication.</p> <hr/> <p>Created using <a href="https://github.com/machinateur/tab-transfer" target="_blank"><code>machinateur/tab-transfer</code></a>.</p> <script type="text/javascript"> window.addEventListener('load', wdpClient.restoreTabs); </script> </body> </html> HTML; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/File/MarkdownFile.php
src/File/MarkdownFile.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\File; class MarkdownFile extends AbstractFileTemplate { public function __construct(string $file, array $jsonArray) { parent::__construct($file, $jsonArray); $this->filenameSuffix = '-gist'; } public function getExtension(): string { return 'md'; } public function render(): string { return '# Tabs' . \PHP_EOL . \PHP_EOL . \join( \PHP_EOL, \array_map(static function (array $tab): string { $url = $tab['url']; $title = $tab['title'] ?: $url; return \sprintf('- [%s](%s)', $title, $url); }, $this->tabs) ) . \PHP_EOL . \PHP_EOL . 'Created using [machinateur/tab-transfer](https://github.com/machinateur/tab-transfer).' . \PHP_EOL; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/File/JsonFile.php
src/File/JsonFile.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\File; class JsonFile extends AbstractFileTemplate { public function getExtension(): string { return 'json'; } public function render(): string { try { return \json_encode($this->tabs, \JSON_PRETTY_PRINT | \JSON_THROW_ON_ERROR | \JSON_PRESERVE_ZERO_FRACTION); } catch (\JsonException) { // We must not throw an exception during the `__toString()` call. Therefor signal with an empty string // that the file should not be written at all (default behaviour with notice in output). return ''; } } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/File/FileTemplateInterface.php
src/File/FileTemplateInterface.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\File; interface FileTemplateInterface extends \Stringable { public function getFilename(): string; public function render(): string; }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/File/AbstractFileTemplate.php
src/File/AbstractFileTemplate.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\File; use Machinateur\ChromeTabTransfer\Shared\Console; use Machinateur\ChromeTabTransfer\Shared\ConsoleTrait; use Machinateur\ChromeTabTransfer\Shared\FileDateTrait; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Path; /** * @method AbstractFileTemplate setConsole(Console $console) * @method AbstractFileTemplate setInput(InputInterface $input) * @method AbstractFileTemplate setOutput(OutputInterface $output) * @method AbstractFileTemplate setFileDate(?\DateTimeInterface $date) */ abstract class AbstractFileTemplate implements FileTemplateInterface { use ConsoleTrait { ConsoleTrait::__construct as private initializeConsole; } use FileDateTrait; public const DATE_FORMAT = 'Y-m-d'; protected string $filenameSuffix = ''; public function __construct( protected readonly string $file, protected readonly array $tabs, ) { $this->initializeConsole(); } public function getFilename(): string { $file = \pathinfo($this->file, \PATHINFO_FILENAME); $dir = \pathinfo($this->file, \PATHINFO_DIRNAME); if ($this->date) { $file = "{$file}_{$this->date->format(self::DATE_FORMAT)}"; } $file = "{$file}{$this->filenameSuffix}.{$this->getExtension()}"; return Path::join($dir, $file); } abstract public function getExtension(): string; abstract public function render(): string; /** * @inheritDoc */ final public function __toString(): string { try { return $this->render(); } catch (\Throwable) { // Avoid throwing exceptions in `__toString()` invocation at any cost. return ''; } } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Exception/FileTemplateDumpException.php
src/Exception/FileTemplateDumpException.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Exception; use Symfony\Component\Filesystem\Exception\IOException; class FileTemplateDumpException extends TabLoadingFailedException { public static function forExistingFile(string $filename): self { return new self("Failed to write file template! File already exists: {$filename}."); } public static function forEmptyFileContent(string $filename): self { return new self("Failed to write file template! Empty content for file: {$filename}."); } public static function fromIOException(IOException $exception): self { return new self("Failed to write file template! Filesystem IO error: {$exception->getMessage()}"); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Exception/CurlException.php
src/Exception/CurlException.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Exception; class CurlException extends TabLoadingFailedException { public static function withoutErrorMessage(int $errorCode): self { return new self("Failed curl request with error {$errorCode}."); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Exception/TabLoadingFailedException.php
src/Exception/TabLoadingFailedException.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Exception; class TabLoadingFailedException extends \Exception { public static function fromJsonException(\JsonException $exception): self { return new self("Failed decoding JSON response with error: {$exception->getMessage()}.", previous: $exception); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Exception/TabReopenFailedException.php
src/Exception/TabReopenFailedException.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Exception; class TabReopenFailedException extends TabLoadingFailedException { public static function forErrors(): self { return new self('Tab reopen failed.'); } public static function forSomeErrors(int $errors, int $total): self { return new self("Failed to transfer {$errors} out of {$total} tabs."); } public static function forEmptyInput(): self { return new self('No tabs to reopen given as input.'); } public static function fromJsonFileLoadingException(JsonFileLoadingException $exception): self { return new self("Failed to load JSON file: {$exception->getMessage()}", previous: $exception); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Exception/EnvironmentCheckException.php
src/Exception/EnvironmentCheckException.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Exception; class EnvironmentCheckException extends CopyTabsException { public static function whenFailed(int $returnCode): self { return new self("Environment check failed with return code `{$returnCode}`."); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Exception/CopyTabsException.php
src/Exception/CopyTabsException.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Exception; class CopyTabsException extends \Exception { public static function fromTabLoadingFailedException(TabLoadingFailedException $exception): self { return new self("Failed to copy tabs from device! {$exception->getMessage()}", previous: $exception); } public static function fromTabReopenFailedException(TabReopenFailedException $exception): self { return new self("Failed to transfer tabs to device! {$exception->getMessage()}", previous: $exception); } public static function forEmptyResult(string $url): self { return new self("Failed to copy tabs from device! Empty result from URL `{$url}`."); } public static function fromFileTemplateDumpException(FileTemplateDumpException $exception): self { return new self("Failed to copy tabs from device! {$exception->getMessage()}", previous: $exception); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Exception/ReopenTabsException.php
src/Exception/ReopenTabsException.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Exception; class ReopenTabsException extends CopyTabsException { public static function withNoDriverSpecified(): self { return new self('No driver specified.'); } public static function forUnsupportedDriver(string $driver): self { return new self("Unsupported driver `{$driver}`."); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Exception/JsonFileLoadingException.php
src/Exception/JsonFileLoadingException.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Exception; class JsonFileLoadingException extends TabLoadingFailedException { public static function whenFileNotFound(string $file): self { return new self("Input file `{$file}` not found."); } public static function whenFileNotAJsonFile(string $file): self { return new self("Input file `{$file}` is not a `.json` file."); } public static function whenFileNotReadable(string $file): self { return new self("Input file `{$file}` is not readable."); } public static function fromJsonException(\JsonException $exception): self { return new self("Failed decoding JSON content with error: {$exception->getMessage()}.", previous: $exception); } public static function forMalformedContent(): self { return new self('Detected malformed JSON content.'); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Shared/DebugFlagTrait.php
src/Shared/DebugFlagTrait.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Shared; trait DebugFlagTrait { protected bool $debug = false; public function isDebug(): bool { return $this->debug; } public function setDebug(bool $debug): static { $this->debug = $debug; return $this; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Shared/Console.php
src/Shared/Console.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Shared; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; /** * Extends the symfony style without any changes. * * This class exposes input and output interfaces, thereby kind of depicting a "console". */ class Console extends SymfonyStyle { public function __construct( public readonly InputInterface $input, public readonly OutputInterface $output, ) { parent::__construct($input, $output); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Shared/ConsoleTrait.php
src/Shared/ConsoleTrait.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Shared; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\NullOutput; use Symfony\Component\Console\Output\OutputInterface; trait ConsoleTrait { protected ?Console $console = null; protected OutputInterface $output; protected InputInterface $input; public function __construct() { $this->output = new NullOutput(); $this->input = new ArrayInput([]); } public function getOutput(): OutputInterface { return $this->output; } public function setOutput(OutputInterface $output): static { $this->console = null; $this->output = $output; return $this; } public function getInput(): InputInterface { return $this->input; } public function setInput(InputInterface $input): static { $this->console = null; $this->input = $input; return $this; } public function getConsole(): Console { return $this->console ??= new Console($this->input, $this->output); } public function setConsole(Console $console): static { $this->console = $console; $this->input = $console->input; $this->output = $console->output; return $this; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Shared/FileDateTrait.php
src/Shared/FileDateTrait.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Shared; trait FileDateTrait { protected ?\DateTimeInterface $date = null; public function getFileDate(): ?\DateTimeInterface { return $this->date; } public function setFileDate(?\DateTimeInterface $date): static { $this->date = $date; return $this; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Shared/AccessibleInput.php
src/Shared/AccessibleInput.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Shared; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\Input; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputInterface; /** * This is like a little hack to modify the definition of any given {@see Input}, by simply extracting it. * * This final class inherits from a concrete implementation of the {@see Input}, {@see ArrayInput}, but has a * constructor with `private` visibility, effectively making this a _static class_. */ final class AccessibleInput extends ArrayInput { private function __construct() {} /** * @deprecated This is highly unstable and discouraged. */ public static function injectDefinition(InputInterface $input, InputDefinition $referenceDefinition): void { if ( ! $input instanceof Input) { throw new \LogicException('Incompatible input given.'); } $def = $input->definition; foreach ($referenceDefinition->getArguments() as $argument) { if ($def->hasArgument($argument->getName())) { continue; } $def->addArgument($argument); } foreach ($referenceDefinition->getOptions() as $option) { if ($def->hasOption($option->getName())) { continue; } $def->addOption($option); } } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Service/CopyTabsService.php
src/Service/CopyTabsService.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Service; use Machinateur\ChromeTabTransfer\Driver\AbstractDriver; use Machinateur\ChromeTabTransfer\Exception\CopyTabsException; use Machinateur\ChromeTabTransfer\Exception\FileTemplateDumpException; use Machinateur\ChromeTabTransfer\Exception\TabLoadingFailedException; use Machinateur\ChromeTabTransfer\Exception\TabReopenFailedException; use Machinateur\ChromeTabTransfer\File\AbstractFileTemplate; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Filesystem\Filesystem; class CopyTabsService { private readonly Filesystem $filesystem; public function __construct() { $this->filesystem = new Filesystem(); } /** * @throws CopyTabsException */ public function run(AbstractDriver $driver): array { $driver->start(); try { $tabLoader = $driver->getTabLoader(); // Q&D: Just check if the instance looks like it implements the `FileDateTrait`. if (\method_exists($tabLoader, 'setFileDate')) { $tabLoader->setFileDate($driver->getFileDate()); } $tabs = $tabLoader->load(); } catch (TabLoadingFailedException $exception) { // The exception has to be thrown only after the driver was stopped. } $driver->stop(); if (isset($exception)) { if ($exception instanceof TabReopenFailedException) { throw CopyTabsException::fromTabReopenFailedException($exception); } throw CopyTabsException::fromTabLoadingFailedException($exception); } if (empty($tabs)) { throw CopyTabsException::forEmptyResult($driver->getUrl()); } try { $this->dumpFileTemplates($driver, $this->getFileTemplates($driver, $tabs)); } catch (FileTemplateDumpException $exception) { throw CopyTabsException::fromFileTemplateDumpException($exception); } return $tabs; } /** * @param array<string, string> $files * @throws FileTemplateDumpException */ private function dumpFileTemplates(AbstractDriver $driver, array $files): void { if (empty($files)) { return; } $console = $driver->getConsole(); $console->note('Generating output files...'); foreach ($files as $filename => $content) { $filenameExtension = \pathinfo($filename, \PATHINFO_EXTENSION); $console->note("Writing {$filenameExtension} file..."); $console->writeln("> {$filename}", OutputInterface::VERBOSITY_VERY_VERBOSE); try { $this->filesystem->dumpFile($filename, $content); } catch (IOException $exception) { $console->writeln('Error writing file: ' . $exception->getMessage(), OutputInterface::VERBOSITY_VERY_VERBOSE); if ($driver->debug) { // Don't throw inside the loop, and never after download process was finished. //throw FileTemplateDumpException::fromIOException($exception); } $console->error("Failed to write {$filename} file!"); continue; } $filenameExtension = \ucfirst($filenameExtension); $console->success("{$filenameExtension} file written successfully!"); $console->writeln("< {$filename}", OutputInterface::VERBOSITY_VERY_VERBOSE); } } /** * @return array<string, string> * @throws FileTemplateDumpException */ private function getFileTemplates(AbstractDriver $driver, array $tabs): array { $console = $driver->getConsole(); $console->note('Generating output files...'); $files = []; foreach ($driver->getFileTemplates($tabs) as $fileTemplate) { // Make sure any output generated by the file will be actually written to the real output. if ($fileTemplate instanceof AbstractFileTemplate) { $fileTemplate->setOutput($driver->getOutput()); $fileTemplate->setFileDate($driver->getFileDate()); } $filename = $fileTemplate->getFilename(); $fileTemplateClass = $fileTemplate::class; $console->writeln("-> From {$fileTemplateClass} to file {$filename}.", OutputInterface::VERBOSITY_VERY_VERBOSE); if ($this->filesystem->exists($filename)) { $replace = $console->confirm("The file `{$filename}` already exists. Do you wish to overwrite it?"); if ( ! $replace) { if ($driver->debug) { // Don't throw inside the loop, and never after download process was finished. //throw FileTemplateDumpException::forExistingFile($filename); } $console->writeln("Skipping `{$filename}`, as it already exists.", OutputInterface::VERBOSITY_VERY_VERBOSE); continue; } } $content = (string) $fileTemplate; if (empty($content)) { if ($driver->debug) { // Don't throw inside the loop, and never after download process was finished. //throw FileTemplateDumpException::forEmptyFileContent($filename); } $console->writeln("Skipping `{$filename}`, as it has no content.", OutputInterface::VERBOSITY_VERY_VERBOSE); continue; } $files[$filename] = $content; $console->writeln("Added `{$filename}` for output.", OutputInterface::VERBOSITY_VERY_VERBOSE); } return $files; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Command/CopyTabsFromAndroid.php
src/Command/CopyTabsFromAndroid.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Command; use Machinateur\ChromeTabTransfer\Driver\AbstractDriver; use Machinateur\ChromeTabTransfer\Driver\AndroidDebugBridge; use Machinateur\ChromeTabTransfer\Platform; use Machinateur\ChromeTabTransfer\Shared\Console; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * A command implementation to copy tabs using the {@see AndroidDebugBridge} driver. * * This command supports the reopen script (`reopen.cmd`/`reopen.sh`) for legacy reasons with android users. * * @see LegacyCopyTabsCommand */ class CopyTabsFromAndroid extends AbstractCopyTabsCommand { public const DEFAULT_SOCKET = AndroidDebugBridge::DEFAULT_SOCKET; public const DEFAULT_WAIT = AndroidDebugBridge::DEFAULT_DELAY; public function __construct() { parent::__construct('android'); } protected function configure(): void { parent::configure(); $definition = $this->getDefinition(); // Here we use some black magic to extract a reference to the `$description` property of the InputOption. $argumentPortDescription = & Platform::extractPropertyReference($definition->getOption('port'), 'description'); // Next we simply write to that reference - et-voilà. $argumentPortDescription = 'The port to forward requests through `adb`.'; $this ->setDescription('Transfer tabs from your Android\'s Chrome browser.') ->addOption('socket', 's', InputOption::VALUE_REQUIRED, 'The socket to forward requests using `adb`.', self::DEFAULT_SOCKET) ->addOption('wait', 'w', InputOption::VALUE_REQUIRED, 'The time to wait before starting the download request (between 0 and 60 seconds).', self::DEFAULT_WAIT) ->addOption('skip-cleanup', null, InputOption::VALUE_NONE, 'Skip the `adb` cleanup command execution. If active, no reopen script will be written.') ; } private ?AndroidDebugBridge $driver = null; public function getDriver(Console $console): AbstractDriver { if ($this->driver) { $console->writeln("Loading {$this->driverName} driver...", OutputInterface::VERBOSITY_VERY_VERBOSE); $this->driver = null; } else { $console->writeln("Creating {$this->driverName} driver...", OutputInterface::VERBOSITY_VERY_VERBOSE); } return $this->driver ??= new AndroidDebugBridge( $this->getArgumentFile($console), $this->getArgumentPort($console), $this->getArgumentDebug($console), $this->getArgumentTimeout($console), $this->getArgumentSocket($console), $this->getArgumentWait($console), $this->getArgumentSkipCleanup($console), ); } protected function getArgumentSocket(Console $console): string { $argumentSocket = $console->input->getOption('socket'); if (0 === strlen($argumentSocket)) { $argumentSocket = self::DEFAULT_SOCKET; $console->warning("Invalid socket given, default to {$argumentSocket}."); } return $argumentSocket; } protected function getArgumentWait(Console $console): int { $argumentWait = (int)$console->input->getOption('wait'); if (0 >= $argumentWait || 60 < $argumentWait) { $argumentWait = self::DEFAULT_WAIT; $console->warning("Invalid wait given, default to {$argumentWait}s."); } return $argumentWait; } protected function getArgumentSkipCleanup(Console $console): bool { return (bool)$console->input->getOption('skip-cleanup'); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Command/CopyTabsFromIphone.php
src/Command/CopyTabsFromIphone.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Command; use Machinateur\ChromeTabTransfer\Driver\AbstractDriver; use Machinateur\ChromeTabTransfer\Driver\IosWebkitDebugProxy; use Machinateur\ChromeTabTransfer\Platform; use Machinateur\ChromeTabTransfer\Shared\Console; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * A command implementation to copy tabs using the {@see IosWebkitDebugProxy} driver. * * This command does not support the reopen script (for now, until I find a way to open tabs on iOS). * Maybe it's possible to use https://github.com/sirn-se/websocket-php to directly control the websocket. * The main issue here is that a bash/cmd script will not be possible then. Therefor the {@see ReopenTabs} command * should be used. The `reopen.cmd`/`reopen.sh` is only supported for legacy reasons with android users. * * @see https://github.com/google/ios-webkit-debug-proxy */ class CopyTabsFromIphone extends AbstractCopyTabsCommand { public const DEFAULT_WAIT = IosWebkitDebugProxy::DEFAULT_DELAY; public function __construct() { parent::__construct('iphone'); } protected function configure(): void { parent::configure(); $definition = $this->getDefinition(); // Here we use some black magic to extract a reference to the `$description` property of the InputOption. $argumentPortDescription = & Platform::extractPropertyReference($definition->getOption('port'), 'description'); // Next we simply write to that reference - et-voilà. $argumentPortDescription = 'The port to forward requests through `ios_webkit_debug_proxy`.'; $this ->setDescription('Transfer tabs from your iPhone\'s Chrome browser.') ->addOption('wait', 'w', InputOption::VALUE_REQUIRED, 'The time to wait before starting the download request (between 0 and 60 seconds).', self::DEFAULT_WAIT) ; } private ?IosWebkitDebugProxy $driver = null; public function getDriver(Console $console): AbstractDriver { if ($this->driver) { $console->writeln("Loading {$this->driverName} driver...", OutputInterface::VERBOSITY_VERY_VERBOSE); $this->driver = null; } else { $console->writeln("Creating {$this->driverName} driver...", OutputInterface::VERBOSITY_VERY_VERBOSE); } return $this->driver ??= new IosWebkitDebugProxy( $this->getArgumentFile($console), $this->getArgumentPort($console), $this->getArgumentDebug($console), $this->getArgumentTimeout($console), $this->getArgumentWait($console), ); } protected function getArgumentWait(Console $console): int { $argumentWait = (int)$console->input->getOption('wait'); if (0 >= $argumentWait || 60 < $argumentWait) { $argumentWait = self::DEFAULT_WAIT; $console->warning("Invalid wait given, default to {$argumentWait}s."); } return $argumentWait; } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Command/AbstractCopyTabsCommand.php
src/Command/AbstractCopyTabsCommand.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Command; use Machinateur\ChromeTabTransfer\Driver\AbstractDriver; use Machinateur\ChromeTabTransfer\Driver\AndroidDebugBridge; use Machinateur\ChromeTabTransfer\Driver\DriverEnvironmentCheckInterface; use Machinateur\ChromeTabTransfer\Exception\CopyTabsException; use Machinateur\ChromeTabTransfer\Exception\EnvironmentCheckException; use Machinateur\ChromeTabTransfer\File\AbstractFileTemplate; use Machinateur\ChromeTabTransfer\Service\CopyTabsService; use Machinateur\ChromeTabTransfer\Shared\AccessibleInput; use Machinateur\ChromeTabTransfer\Shared\Console; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\Input; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * The abstract base class containing common logic for {@see AbstractDriver} driver based commands to copy tabs. */ abstract class AbstractCopyTabsCommand extends Command { public const DEFAULT_FILE = 'tabs.json'; public const DEFAULT_PORT = AndroidDebugBridge::DEFAULT_PORT; public const DEFAULT_TIMEOUT = AndroidDebugBridge::DEFAULT_TIMEOUT; protected readonly \DateTimeInterface $date; protected readonly CopyTabsService $service; public function __construct( protected readonly string $driverName, ) { $this->date = new \DateTimeImmutable(); parent::__construct("copy-tabs:{$driverName}"); $this->service = new CopyTabsService(); } public function getDriverName(): string { return $this->driverName; } protected function configure(): void { $this ->addArgument('file', InputArgument::OPTIONAL, 'The relative filepath to write. The `--date` / `--no-date` flag applies as well.', self::DEFAULT_FILE) ->addOption('date', 'd', InputOption::VALUE_NEGATABLE, "Whether to add the date `{$this->date->format(AbstractFileTemplate::DATE_FORMAT)}` suffix to the filename. Active by Default.", true) ->addOption('port', 'p', InputOption::VALUE_REQUIRED, 'The port to forward requests through.', self::DEFAULT_PORT) ->addOption('timeout', 't', InputOption::VALUE_REQUIRED, 'The network timeout for the download request (at last 10 seconds).', self::DEFAULT_TIMEOUT) ->addOption('skip-check', null, InputOption::VALUE_NONE, 'Skip the check for required dependencies ony your system will be performed.') ; } /** * Call the {@see checkCommandEnvironment} command internally. * * @return int{0,2} */ protected function performEnvironmentCheck(Console $console): int { $command = $this->getApplication() ->get(CheckEnvironment::NAME); if ( ! $command instanceof CheckEnvironment) { throw new \LogicException(\sprintf('The application must contain the %s command.', $command->getName())); } // Warning: We can only pass the ínput directly in here, because the `driver` option (or any other) is never looked up inside the `CheckEnvironment` command // when a `$command` (here `$this`) is passed as third argument! return $command->execute($console->input, $console, $this); } protected function execute(InputInterface $input, OutputInterface $output): int { $console = new Console($input, $output); // Run the inner logic. This is extracted to a separate method, // to allow for easier changes in resulting output of the specific driver command. try { $tabs = $this->executeDriver($console); } catch (CopyTabsException $exception) { $console->error($exception->getMessage()); return Command::FAILURE; } $numberOfTabsTransferred = \count($tabs); if (!$numberOfTabsTransferred) { $console->note('No tabs were copied from the device.'); } $console->success("Successfully copied {$numberOfTabsTransferred} tabs from the device."); $console->newLine(); // With `-vvv` parameter, print the fetched tabs to stdout. Only if there were tabs downloaded, else skip this step. if (0 < $numberOfTabsTransferred && $output->isDebug()) { $table = $console->createTable() ->setHeaders(['Title', 'URL']); foreach ($tabs as $tab) { $title = $tab['title'] ?: '--'; $url = $tab['url']; $table->addRow([$title, $url]); } unset($tab, $title, $url); $table->render(); $console->newLine(); } return Command::SUCCESS; } /** * @throws CopyTabsException */ final protected function executeDriver(Console $console): array { if ( ! $this->getArgumentSkipCheck($console)) { $return = $this->performEnvironmentCheck($console); if (Command::SUCCESS !== $return) { throw EnvironmentCheckException::whenFailed($return); } } else { $console->note('Skipping environment check.'); } return $this->service->run( $this->getDriver($console) ->setConsole($console) ->setFileDate( $this->getArgumentDate($console) ) ); } abstract public function getDriver(Console $console): AbstractDriver; /** * This method should encapsulate the environment requirements for the specific command. * * Usually this simply calls through to the {@see DriverEnvironmentCheckInterface::checkEnvironment()} with some * additional debug output to the provided `$console`. * * It is not meant to be called directly from within this same class, but from {@see CheckEnvironment}, which will * add important contextual output to the provided `$console`. */ public function checkCommandEnvironment(Console $console): bool { $console->writeln("Checking environment for {$this->driverName} ({$this->getName()})...", OutputInterface::VERBOSITY_VERY_VERBOSE); return $this->getDriver($this->getDefaultConsole($console)) ->setConsole($console) ->checkEnvironment(); } /** * This is where the magic happens. Here, {@see AccessibleInput::injectDefinition()} is used to combine the original input definition with the definition of * this very command (i.e. the driver-specific command). */ protected function getDefaultConsole(Console $console): Console { AccessibleInput::injectDefinition($console->input, $this->getDefinition()); return new Console($console->input, $console->output); } protected function getArgumentFile(Console $console): string { try { return $console->input->getArgument('file'); } catch (InvalidArgumentException) { return self::DEFAULT_FILE; } } protected function getArgumentDate(Console $console): ?\DateTimeInterface { if ($console->input->hasParameterOption('--no-date')) { return null; } return $console->input->getOption('date') ? $this->date : null; } protected function getArgumentPort(Console $console): int { $argumentPort = (int)$console->input->getOption('port'); if (0 >= $argumentPort) { $argumentPort = self::DEFAULT_PORT; $console->warning("Invalid port given, default to {$argumentPort}."); } return $argumentPort; } protected function getArgumentDebug(Console $console): bool { return $console->output->isDebug(); } protected function getArgumentTimeout(Console $console): int { $argumentTimeout = (int)$console->input->getOption('timeout'); if (10 > $argumentTimeout) { $argumentTimeout = self::DEFAULT_TIMEOUT; $console->warning("Invalid timeout given, default to {$argumentTimeout}s."); } return $argumentTimeout; } protected function getArgumentSkipCheck(Console $console): bool { return (bool)$console->input->getOption('skip-check'); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Command/LegacyCopyTabsCommand.php
src/Command/LegacyCopyTabsCommand.php
<?php /* * MIT License * * Copyright (c) 2021-2023 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ namespace Machinateur\ChromeTabTransfer\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\ConsoleEvents; use Symfony\Component\Console\Event\ConsoleTerminateEvent; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Class CopyTabsCommand * * @package Machinateur\ChromeTabTransfer\Command * * @deprecated Will be removed at some point in the future. */ class LegacyCopyTabsCommand extends Command implements EventSubscriberInterface { /** * @inheritDoc */ public static function getSubscribedEvents(): array { return [ ConsoleEvents::TERMINATE => 'onConsoleTerminate', ]; } /** * @var int */ private const DEFAULT_PORT = 9222; /** * @var string */ private const DEFAULT_SOCKET = 'chrome_devtools_remote'; /** * @var string */ private const DEFAULT_FILE = 'tabs.json'; /** * @var int */ private const DEFAULT_TIMEOUT = 10; /** * @var int */ private const DEFAULT_WAIT = 2; /** * @var string */ protected static $defaultName = 'copy-tabs'; private bool $dirty = false; private readonly string $date; public function __construct() { $this->date = \date('Y-m-d'); parent::__construct(); } /** * @inheritDoc */ protected function configure(): void { $this ->setDescription('A tool to transfer tabs from your android phone to your computer using `adb`. [<info>Legacy</info>]') ->addArgument('file', InputArgument::OPTIONAL, 'The relative filepath to write. Only the filename is actually considered!', self::DEFAULT_FILE) ->addOption('date', 'd', InputOption::VALUE_NEGATABLE, "Whether to add the date `{$this->date}` suffix to the filename. Active by Default.", true) ->addOption('port', 'p', InputOption::VALUE_REQUIRED, 'The port to forward requests using `adb`.', self::DEFAULT_PORT) ->addOption('socket', 's', InputOption::VALUE_REQUIRED, 'The socket to forward requests using `adb`.', self::DEFAULT_SOCKET) ->addOption('timeout', 't', InputOption::VALUE_REQUIRED, 'The network timeout for the download request (at least 10 seconds).', self::DEFAULT_TIMEOUT) ->addOption('wait', 'w', InputOption::VALUE_REQUIRED, 'The time to wait before starting the download request (between 0 and 60 seconds).', self::DEFAULT_WAIT) ->addOption('skip-cleanup', null, InputOption::VALUE_NONE, 'Skip the `adb` cleanup command execution.'); } /** * @inheritDoc */ protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln('Warning: You are running the legacy version of tab-transfer.'); $output->writeln(' It has not been adapted for newer requirements and will be removed in the future.'); $output->writeln(''); // Check for `adb` command availability: if (!$this->isShellCommandAvailable('adb')) { $output->writeln('The adb executable is not available!'); return Command::FAILURE; } else { $output->writeln('The adb executable is available.'); } // Get `date` argument: $argumentDate = (bool)$input->getOption('date'); if (!$argumentDate) { $output->writeln("The date segment of the filename is {$this->date}."); } // Get `port` argument: $argumentPort = (int)$input->getOption('port'); if (0 >= $argumentPort) { $argumentPort = self::DEFAULT_PORT; $output->writeln("Invalid port given, default to {$argumentPort}."); } // Get `socket` argument: $argumentSocket = $input->getOption('socket'); if (0 === strlen($argumentSocket)) { $argumentSocket = self::DEFAULT_SOCKET; $output->writeln("Invalid socket given, default to {$argumentSocket}."); } // Get `timeout` argument: $argumentTimeout = (int)$input->getOption('timeout'); if (10 > $argumentTimeout) { $argumentTimeout = self::DEFAULT_TIMEOUT; $output->writeln("Invalid timeout given, default to {$argumentTimeout}s."); } // Get `wait` argument: $argumentWait = (int)$input->getOption('wait'); if (0 >= $argumentWait || 60 < $argumentWait) { $argumentWait = self::DEFAULT_WAIT; $output->writeln("Invalid wait given, default to {$argumentWait}s."); } // Run `adb` command: $output->writeln('Running adb command...'); $output->writeln("> adb -d forward tcp:{$argumentPort} localabstract:{$argumentSocket}"); $output->write( (string)\shell_exec("adb -d forward tcp:{$argumentPort} localabstract:{$argumentSocket}") ); // Mark the command state as dirty: $this->dirty = true; // Wait for two seconds, just to be safe: $output->writeln("Waiting for {$argumentWait} seconds..."); \sleep($argumentWait); // Download tabs from device: $url = "http://localhost:{$argumentPort}/json/list"; $output->writeln('Downloading tabs from device...'); $output->writeln("> {$url}"); $ch = \curl_init(); \curl_setopt($ch, \CURLOPT_URL, $url); \curl_setopt($ch, \CURLOPT_TIMEOUT, $argumentTimeout); //\curl_setopt($ch, \CURLOPT_CONNECTTIMEOUT, 10); if ($output->isDebug()) { \curl_setopt($ch, \CURLOPT_VERBOSE, true); } \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true); $jsonString = \curl_exec($ch) ?: null; $capturedErrorCode = \curl_errno($ch); $capturedErrorMessage = null; if (0 < $capturedErrorCode) { $capturedErrorMessage = \sprintf('%s (code %d)', \curl_error($ch), $capturedErrorCode); } \curl_close($ch); unset($url, $ch); if (null === $jsonString) { $output->writeln('Unable to download tabs from device! Please check the device connection!'); $output->writeln('Also make sure google chrome is running on the connected device and USB debugging is active in the developer settings.'); if (null !== $capturedErrorMessage && $output->isDebug()) { $output->writeln('Captured error message from the request:'); $output->writeln("> {$capturedErrorMessage}"); } return Command::FAILURE; } else { $output->writeln('Download successful!'); } // Decode json string: $output->writeln('Decoding data now...'); try { $jsonArray = @\json_decode($jsonString, true, 512, \JSON_THROW_ON_ERROR); } catch (\JsonException) { $jsonArray = null; } if (null === $jsonArray) { $output->writeln('Unable to decode JSON data!'); return Command::FAILURE; } else { $output->writeln('Successfully decoded data.'); } // Get `file` argument: $argumentFile = $input->getArgument('file'); /** @var string $argumentFile */ $argumentFile = \pathinfo($argumentFile, \PATHINFO_FILENAME); // Add `date` suffix: if ($argumentDate) { $argumentFile = "{$argumentFile}_{$this->date}"; } // Write `json` file: $this->writeFileContent($output, $argumentFile, 'json', $jsonString); // Write `md` file: $mdString = '# Tabs' . \PHP_EOL . \PHP_EOL . \join( \PHP_EOL, \array_map(static function (array $entry): string { $url = $entry['url']; $title = $entry['title'] ?: $url; return \sprintf('* [%s](%s)', $title, $url); }, $jsonArray) ) . \PHP_EOL . \PHP_EOL . 'Created using [machinateur/tab-transfer](https://github.com/machinateur/tab-transfer).' . \PHP_EOL; $this->writeFileContent($output, "{$argumentFile}-gist", 'md', $mdString); if ($this->isWindows()) { // Write `cmd` file: $cmdString = '@echo off' . \PHP_EOL . \PHP_EOL . ':: Created using machinateur/tab-transfer (https://github.com/machinateur/tab-transfer).' . \PHP_EOL . \PHP_EOL . "adb -d forward tcp:{$argumentPort} localabstract:{$argumentSocket}" . \PHP_EOL . \PHP_EOL . \join( \PHP_EOL, \array_map(static function (array $entry) use ($argumentPort): string { $url = $entry['url']; $title = $entry['title'] ?: $url; $url = \rawurlencode($url); // Batch files require all `%` to be escaped with another `%`. $url = \str_replace('%', '%%', $url); return \sprintf('# %s', $title) . \PHP_EOL // URLs must be double-quoted to work with curl, and double-quotes also escape other batch characters. . \sprintf("curl -X PUT \"http://localhost:{$argumentPort}/json/new?%s\"", $url) . \PHP_EOL; }, $jsonArray) ) . \PHP_EOL . \PHP_EOL . "adb -d forward --remove tcp:{$argumentPort}" . \PHP_EOL . \PHP_EOL . 'pause' . \PHP_EOL; $this->writeFileContent($output, "{$argumentFile}-reopen", 'cmd', $cmdString); } else { // Write `sh` file: $bashString = '#!/bin/bash' . \PHP_EOL . \PHP_EOL . '# Created using machinateur/tab-transfer (https://github.com/machinateur/tab-transfer).' . \PHP_EOL . \PHP_EOL . "adb -d forward tcp:{$argumentPort} localabstract:{$argumentSocket}" . \PHP_EOL . \PHP_EOL . \join( \PHP_EOL, \array_map(static function (array $entry) use ($argumentPort): string { $url = $entry['url']; $title = $entry['title'] ?: $url; $url = \rawurlencode($url); return \sprintf('# %s', $title) . \PHP_EOL . \sprintf("curl -X PUT 'http://localhost:{$argumentPort}/json/new?%s'", $url) . \PHP_EOL; }, $jsonArray) ) . \PHP_EOL . \PHP_EOL . "adb -d forward --remove tcp:{$argumentPort}" . \PHP_EOL; $this->writeFileContent($output, "{$argumentFile}-reopen", 'sh', $bashString); } return Command::SUCCESS; } /** * @param string $shellCommand * @return bool */ private function isShellCommandAvailable(string $shellCommand): bool { $test = $this->isWindows() ? 'cmd /c "where %s"' : 'command -v %s'; return \array_reduce( \explode("\n", (string)\shell_exec( \sprintf($test, $shellCommand) ) ), static function (bool $carry, string $entry): bool { $entry = \trim($entry); return $carry || (\file_exists($entry) && \is_executable($entry)); }, false ); } /** * @return bool */ private function isWindows(): bool { return 0 === \strpos(\PHP_OS, 'WIN'); } /** * @param OutputInterface $output * @param string $file * @param string $fileExtension * @param string $fileContent * @return void */ private function writeFileContent(OutputInterface $output, string $file, string $fileExtension, string $fileContent): void { $basePath = $this->getBasePath(); $filePath = "{$basePath}/{$file}.{$fileExtension}"; $output->writeln("Writing {$fileExtension} file..."); $output->writeln("> {$filePath}"); $bytesWritten = @\file_put_contents($filePath, $fileContent) ?: null; if (null === $bytesWritten) { $message = "Failed to write {$fileExtension} file!"; $output->writeln($message); throw new \RuntimeException($message); } else { $fileExtension = \ucfirst($fileExtension); $output->writeln("{$fileExtension} file written successfully!"); } } /** * @return string */ private function getBasePath(): string { if (\extension_loaded('phar') && \strlen($path = \Phar::running(false)) > 0) { return \dirname($path); } return \dirname(__DIR__, 2); } /** * @param ConsoleTerminateEvent $event * @return void */ public function onConsoleTerminate(ConsoleTerminateEvent $event): void { $command = $event->getCommand(); if ($command instanceof LegacyCopyTabsCommand && true === $command->dirty) { $input = $event->getInput(); $output = $event->getOutput(); // Get `cleanup` argument: $argumentSkipCleanup = !(bool)$input->getOption('skip-cleanup'); // Get `port` argument: $argumentPort = (int)$input->getOption('port'); if (0 >= $argumentPort) { $argumentPort = self::DEFAULT_PORT; } // Run `adb` cleanup command: if (!$argumentSkipCleanup) { $output->writeln('Skipping adb cleanup command... To dispose manually, run:'); $output->writeln("> adb -d forward --remove tcp:{$argumentPort}"); return; } $output->writeln('Running `adb` cleanup command...'); $this->dirty = false; $output->writeln("> adb -d forward --remove tcp:{$argumentPort}"); $output->write( (string)\shell_exec("adb -d forward --remove tcp:{$argumentPort}") ); } } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Command/ReopenTabs.php
src/Command/ReopenTabs.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Command; use Machinateur\ChromeTabTransfer\Driver\AbstractDriver; use Machinateur\ChromeTabTransfer\Driver\RestoreTabsDriver; use Machinateur\ChromeTabTransfer\Exception\CopyTabsException; use Machinateur\ChromeTabTransfer\Exception\ReopenTabsException; use Machinateur\ChromeTabTransfer\File\ReopenScriptFile; use Machinateur\ChromeTabTransfer\Platform; use Machinateur\ChromeTabTransfer\Shared\Console; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * A command providing tab restoration capabilities. * * The command aims to replace the `copy-tabs.sh` the reopen script (`reopen.cmd`/`reopen.sh`) * and operates based on the `tabs.json`. * * @see ReopenScriptFile */ class ReopenTabs extends AbstractCopyTabsCommand { /** * Override the command name. */ public const NAME = 'reopen-tabs'; public function __construct() { parent::__construct('restore'); } protected function configure(): void { $this->ignoreValidationErrors(); parent::configure(); $definition = $this->getDefinition(); // Here we use some black magic to extract a reference to the `$description` property of the InputOption. $argumentPortDescription = & Platform::extractPropertyReference($definition->getArgument('file'), 'description'); // Next we simply write to that reference - et-voilà. $argumentPortDescription = 'The relative filepath to read. The `--date` / `--no-date` flag applies as well.'; $this ->setName(self::NAME) ->setDescription('Restore tabs to your phone\'s Chrome browser.') ->addOption('driver', 'i', InputOption::VALUE_REQUIRED, 'The driver to use for restoration.') // TODO: Add `--call` `-c` `some_script.php` option. ; } private ?AbstractCopyTabsCommand $command = null; protected function execute(InputInterface $input, OutputInterface $output, ?AbstractCopyTabsCommand $command = null): int { $console = new Console($input, $output); $this->command = $command; // Run the inner logic. This is extracted to a separate method, // to allow for easier changes in resulting output of the specific driver command. try { $tabs = $this->executeDriver($console); } catch (CopyTabsException $exception) { $console->error($exception->getMessage()); return Command::FAILURE; } $numberOfTabsTransferred = \count($tabs); if (!$numberOfTabsTransferred) { $console->note('No tabs were transferred to the device.'); } $console->success("Successfully transferred {$numberOfTabsTransferred} tabs to the device."); $console->newLine(); // With `-vvv` parameter, print the fetched tabs to stdout. Only if there were tabs downloaded, else skip this step. if (0 < $numberOfTabsTransferred && $output->isDebug()) { $table = $console->createTable() ->setHeaders(['Title', 'URL', 'Transferred']); foreach ($tabs as $tab) { $title = $tab['title'] ?: '--'; $url = $tab['url']; $transferred = $tab['transferred'] ?? false; $table->addRow([$title, $url, $transferred ? 'yes' : 'no']); } unset($tab, $title, $url, $transferred); $table->render(); $console->newLine(); } return Command::SUCCESS; } /** * @throws ReopenTabsException */ public function getDriver(Console $console): AbstractDriver { $command = $this->getDriverCommand($console); return new RestoreTabsDriver( $this->getArgumentFile($console), $this->getArgumentPort($console), $this->getArgumentDebug($console), $this->getArgumentTimeout($console), $command->getDriver( $command->getDefaultConsole($console) ), ); } /** * @throws ReopenTabsException */ protected function getDriverCommand(Console $console): AbstractCopyTabsCommand { $command = $this->command ?? null; // When no `$command` is provided with the call (i.e. direct invocation via CLI). if ( ! $command instanceof AbstractCopyTabsCommand) { $driverName = $this->getArgumentDriver($console); $console->writeln("No command provided.", OutputInterface::VERBOSITY_VERY_VERBOSE); // Only check the specified driver, if the `--driver` (`-i`) option was specified. if (null !== $driverName) { $console->writeln("Driver name specified: {$driverName}.", OutputInterface::VERBOSITY_VERY_VERBOSE); $command = $this->findCommand($console, $driverName); } } if (null === $command) { if (isset($driverName)) { throw ReopenTabsException::forUnsupportedDriver($driverName); } throw ReopenTabsException::withNoDriverSpecified(); } return $command; } public function checkCommandEnvironment(Console $console): bool { try { return $this->getDriverCommand($console) ->checkCommandEnvironment($console); } catch (ReopenTabsException $exception) { $console->error($exception->getMessage()); } return false; } protected function findCommand(Console $console, string $driverName): ?AbstractCopyTabsCommand { $command = $this->getApplication() ->get(CheckEnvironment::NAME); if ( ! $command instanceof CheckEnvironment) { throw new \LogicException(\sprintf('The application must contain the %s command.', $command->getName())); } return $command->findCommand($console, $driverName); } protected function getArgumentDriver(Console $console): ?string { return $console->input->getOption('driver'); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/src/Command/CheckEnvironment.php
src/Command/CheckEnvironment.php
<?php /* * MIT License * * Copyright (c) 2021-2024 machinateur * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare(strict_types=1); namespace Machinateur\ChromeTabTransfer\Command; use Machinateur\ChromeTabTransfer\Shared\Console; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\CommandNotFoundException; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class CheckEnvironment extends Command { public const NAME = 'check-environment'; protected function configure(): void { $this ->setName(self::NAME) ->setDescription('Check environment for required dependencies on your system. Implicitly executed before copying tabs.') ->addOption('driver', 'i', InputOption::VALUE_REQUIRED, 'The driver name to use for the check. If not given (default) check for all drivers.') ; } protected function execute(InputInterface $input, OutputInterface $output, ?AbstractCopyTabsCommand $command = null): int { $console = new Console($input, $output); // When no `$command` is provided with the call (i.e. direct invocation via CLI). if ( ! $command instanceof AbstractCopyTabsCommand) { $driverName = $this->getArgumentDriver($console); $console->writeln("No command provided.", OutputInterface::VERBOSITY_VERY_VERBOSE); // Only check the specified driver, if the `--driver` (`-i`) option was specified. if (null !== $driverName) { $console->writeln("Driver name specified: {$driverName}.", OutputInterface::VERBOSITY_VERY_VERBOSE); $command = $this->findCommand($console, $driverName); } } if ($command instanceof AbstractCopyTabsCommand) { $result = $this->check($console, $command); } else { $console->writeln('Falling back to checking all available drivers...', OutputInterface::VERBOSITY_VERY_VERBOSE); $result = true; // Perform checks on all of them, if no single one is specified (default). foreach ($this->getCommands() as $command) { $result = $result && $this->check($console, $command); } } if (!$result) { $console->error('Environment check failed!'); return Command::FAILURE; } $console->success('Environment check successful!'); return Command::SUCCESS; } protected function check(Console $console, AbstractCopyTabsCommand $command): bool { return $command->checkCommandEnvironment($console); } public function findCommand(Console $console, string $driverName): ?AbstractCopyTabsCommand { $console->writeln("Searching for command with driver `{$driverName}`.", OutputInterface::VERBOSITY_VERY_VERBOSE); try { $command = $this->getApplication() ->find($commandName = "copy-tabs:{$driverName}"); if ( ! $command instanceof AbstractCopyTabsCommand) { $console->writeln(\sprintf("Found command `{$commandName}` but not not compatible with interface (driver was `{$driverName}`)."), OutputInterface::VERBOSITY_VERY_VERBOSE); return null; } $console->writeln("Found command `{$command->getName()}` for driver `{$driverName}`.", OutputInterface::VERBOSITY_VERY_VERBOSE); return $command; } catch (CommandNotFoundException $exception) { if ($alternatives = $exception->getAlternatives()) { $console->writeln(\sprintf("No command `{$commandName}` found for driver `{$driverName}`: %s", \implode('`, `', $alternatives)), OutputInterface::VERBOSITY_VERY_VERBOSE); } else { $console->writeln("No command `{$commandName}` found for driver `{$driverName}.`", OutputInterface::VERBOSITY_VERY_VERBOSE); } } return null; } /** * Load all the available commands inside the `copy-tabs` namespace from the application. * * @return array<AbstractCopyTabsCommand> */ private function getCommands(): array { $commands = $this->getApplication() ->all('copy-tabs'); // Make sure only actual instances of the `AbstractCOpyTabsCommand` base class are returned. return \array_filter($commands, static fn(Command $command): bool => $command instanceof AbstractCopyTabsCommand); } protected function getArgumentDriver(Console $console): ?string { return $console->input->getOption('driver'); } }
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
machinateur/tab-transfer
https://github.com/machinateur/tab-transfer/blob/edcd71b6519bf442a068fe56ea6d80f3559c0742/tests/test_isShellCommandAvailable.php
tests/test_isShellCommandAvailable.php
<?php require_once __DIR__ . '/vendor/autoload.php'; // Gain insights into the expression from `\Machinateur\ChromeTabTransfer\Platform::isShellCommandAvailable()`. $shellCommand = 'adb'; $test = \Machinateur\ChromeTabTransfer\Platform::isWindows() ? 'cmd /c "where %s"' : 'command -v %s'; $result = \array_reduce( \explode("\n", (string)\shell_exec( \sprintf($test, $shellCommand) ) ), static function (bool $carry, string $entry): bool { $entry = \trim($entry); #$entry = \str_replace('\\', '/', $entry); echo $entry, \PHP_EOL; $valid = $carry || (\file_exists($entry) && \is_executable($entry)); \var_dump('is_file', \is_file($entry)); \var_dump('file_exists', \file_exists($entry)); \var_dump('is_executable', \is_executable($entry)); echo \PHP_EOL; return $valid; }, false ); \var_dump($result);
php
MIT
edcd71b6519bf442a068fe56ea6d80f3559c0742
2026-01-05T05:13:19.554683Z
false
panicsteve/w2wiki
https://github.com/panicsteve/w2wiki/blob/d98486580d3ebb0709c03e6c1b04998a33d37d2b/config.php
config.php
<?php /* * W2 * * Copyright (C) 2007-2009 Steven Frank <http://stevenf.com/> * Code may be re-used as long as the above copyright notice is retained. * See README.txt for full details. * * Written with Coda: <http://panic.com/coda/> * */ // -------------------- // Site layout settings // -------------------- // BASE_PATH // // The base system path to W2. You only need to change this if we guess wrong. // You should not use a trailing slash. define('BASE_PATH', getcwd()); // PAGE_FOLDER and IMAGE_FOLDER // ============================ // The path to the raw text documents maintained by W2 // You should not use a trailing slash. define('IMAGE_FOLDER', '/img'); define( 'PAGE_FOLDER', '/txt'); // IMAGE_PATH // // The path to the raw text documents maintained by W2 // You should not use a trailing slash. define('IMAGE_PATH', BASE_PATH . IMAGE_FOLDER); // PAGE_PATH // // The path to the raw text documents maintained by W2 // You should not use a trailing slash. define('PAGE_PATH', BASE_PATH . PAGE_FOLDER); // BASE_URI // // The base URI for this W2 installation. You only need to change this if we guess wrong. // You should not use a trailing slash. define('BASE_URI', str_replace('/index.php', '', $_SERVER['SCRIPT_NAME'])); // IMAGE_URI // // The base URI for this W2 installation. You only need to change this if we guess wrong. // You should not use a trailing slash. define('IMAGE_URI', BASE_URI . IMAGE_FOLDER); // SELF // // The path component of the URL to the main script, such as: /w2/index.php define('SELF', $_SERVER['SCRIPT_NAME']); // VIEW // // Needed only if your web server spawns PHP as a CGI instead of an internal module. // For example: define('VIEW', '?action=view&page='); define('VIEW', ''); // DEFAULT_PAGE // // The name of the page to show as the "Home" page. // Value is a string, the title of a page (case-sensitive!) define('DEFAULT_PAGE', 'Home'); // CSS_FILE // // The CSS file to load to style the wiki, relative to BASE_URI define('CSS_FILE', 'index.css'); // -------------------- // File upload settings // -------------------- // DISABLE_UPLOADS // // Globally enable/disable file uploads define('DISABLE_UPLOADS', false); // VALID_UPLOAD_TYPES // // Acceptable file types for file uploads. This is a good idea for security. // Value is a comma-separated string of MIME types. define('VALID_UPLOAD_TYPES', 'image/jpeg,image/pjpeg,image/png,image/gif,application/pdf,application/zip,application/x-diskcopy'); // VALID_UPLOAD_EXTS // // Acceptable filename extensions for file uploads // Value is a comma-separated string of filename extensions (case-sensitive!) define('VALID_UPLOAD_EXTS', 'jpg,jpeg,png,gif,pdf,zip,dmg'); // ------------------ // Interface settings // ------------------ // TITLE_DATE // // The format to use when displaying page modification times. // See the manual for the PHP 'date()' function for the specification: // http://php.net/manual/en/function.date.php define('TITLE_DATE', 'j-M-Y g:i A'); define('TITLE_DATE_NO_TIME', 'j-M-Y'); // EDIT_ROWS // // Default size of the text editing area in text rows. define('EDIT_ROWS', 18); // AUTOLINK_PAGE_TITLES // // Automatically converts any page titles appearing in text into links // to the named page. This might degrade performance if you have many // thousands of pages. define('AUTOLINK_PAGE_TITLES', false); // ----------------------------- // Security and session settings // ----------------------------- // REQUIRE_PASSWORD // // Is a password required to access this wiki? define('REQUIRE_PASSWORD', false); // W2_PASSWORD // // The password for the wiki, if REQUIRE_PASSWORD is true // Replace 'secret' with your password to set your password. define('W2_PASSWORD', 'secret'); // W2_PASSWORD_HASH // // Alternate (more secure) password storage. // To use a hashed password, Comment out the W2_PASSWORD definition above and uncomment // this one, using the result of sha1('your_password') as the value. // // In Mac OS X, you can do this from the Terminal: // echo -n 'your_password' | openssl sha1 // // define('W2_PASSWORD_HASH', 'e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4'); define('W2_PASSWORD_HASH', ''); // allowedIPs // // A whitelist of IP addresses that are allowed access to the wiki. // If empty, all IPs are allowed. $allowedIPs = array(); // W2_SESSION_LIFETIME // // How long before a login session expires? Default is 30 days define('W2_SESSION_LIFETIME', 60 * 60 * 24 * 30); // W2_SESSION_NAME // // Name for session (used in the cookie) define('W2_SESSION_NAME', 'W2'); ?>
php
MIT
d98486580d3ebb0709c03e6c1b04998a33d37d2b
2026-01-05T05:13:32.288033Z
false
panicsteve/w2wiki
https://github.com/panicsteve/w2wiki/blob/d98486580d3ebb0709c03e6c1b04998a33d37d2b/index.php
index.php
<?php /* * W2 * * Copyright (C) 2007-2011 Steven Frank <http://stevenf.com/> * * Code may be re-used as long as the above copyright notice is retained. * See README.txt for full details. * * Written with Coda: <http://panic.com/coda/> * */ // Install PSR-4-compatible class autoloader spl_autoload_register(function($class){ require str_replace('\\', DIRECTORY_SEPARATOR, ltrim($class, '\\')).'.php'; }); // Get Markdown class use Michelf\MarkdownExtra; // User configurable options: include_once "config.php"; ini_set('session.gc_maxlifetime', W2_SESSION_LIFETIME); session_set_cookie_params(W2_SESSION_LIFETIME); session_name(W2_SESSION_NAME); session_start(); if ( count($allowedIPs) > 0 ) { $ip = $_SERVER['REMOTE_ADDR']; $accepted = false; foreach ( $allowedIPs as $allowed ) { if ( strncmp($allowed, $ip, strlen($allowed)) == 0 ) { $accepted = true; break; } } if ( !$accepted ) { print "<html><body>Access from IP address $ip is not allowed"; print "</body></html>"; exit; } } if ( REQUIRE_PASSWORD && !isset($_SESSION['password']) ) { if ( !defined('W2_PASSWORD_HASH') || W2_PASSWORD_HASH == '' ) define('W2_PASSWORD_HASH', sha1(W2_PASSWORD)); if ( (isset($_POST['p'])) && (sha1($_POST['p']) == W2_PASSWORD_HASH) ) $_SESSION['password'] = W2_PASSWORD_HASH; else { print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"; print "<html>\n"; print "<head>\n"; print "<link rel=\"apple-touch-icon\" href=\"apple-touch-icon.png\"/>"; print "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, user-scalable=false\" />\n"; print "<link type=\"text/css\" rel=\"stylesheet\" href=\"" . BASE_URI . "/" . CSS_FILE ."\" />\n"; print "<title>Log In</title>\n"; print "</head>\n"; print "<body><form method=\"post\">"; print "<input type=\"password\" name=\"p\">\n"; print "<input type=\"submit\" value=\"Go\"></form>"; print "</body></html>"; exit; } } // Support functions function _handle_links($match) { return "<a href=\"" . SELF . VIEW . "/" . htmlentities($match[1]) . "\">" . htmlentities($match[1]) . "</a>"; } function _handle_images($match) { return "<img src=\"" . IMAGE_URI . "/" . htmlentities($match[1]) . "\" alt=\"" . htmlentities($match[1]) . "\" />"; } function _handle_message($match) { return "[<a href=\"message:" . htmlentities($match[1]) . "\">email</a>]"; } function printToolbar() { global $upage, $page, $action; print "<div class=\"toolbar\">"; print "<a class=\"tool first\" href=\"" . SELF . "?action=edit&amp;page=$upage\">Edit</a> "; print "<a class=\"tool\" href=\"" . SELF . "?action=new\">New</a> "; if ( !DISABLE_UPLOADS ) print "<a class=\"tool\" href=\"" . SELF . VIEW . "?action=upload\">Upload</a> "; print "<a class=\"tool\" href=\"" . SELF . "?action=all_name\">All</a> "; print "<a class=\"tool\" href=\"" . SELF . "?action=all_date\">Recent</a> "; print "<a class=\"tool\" href=\"" . SELF . "\">". DEFAULT_PAGE . "</a>"; if ( REQUIRE_PASSWORD ) print '<a class="tool" href="' . SELF . '?action=logout">Exit</a>'; print "<form method=\"post\" action=\"" . SELF . "?action=search\">\n"; print "<input class=\"tool\" placeholder=\"Search\" size=\"6\" id=\"search\" type=\"text\" name=\"q\" /></form>\n"; print "</div>\n"; } function descLengthSort($val_1, $val_2) { $retVal = 0; $firstVal = strlen($val_1); $secondVal = strlen($val_2); if ( $firstVal > $secondVal ) $retVal = -1; else if ( $firstVal < $secondVal ) $retVal = 1; return $retVal; } function toHTML($inText) { global $page; $inText = preg_replace("/<[\/]*script>/", "", $inText); $dir = opendir(PAGE_PATH); while ( $filename = readdir($dir) ) { if ( $filename[0] == '.' ) continue; $filename = preg_replace("/(.*?)\.txt/", "\\1", $filename); $filenames[] = $filename; } closedir($dir); uasort($filenames, "descLengthSort"); if ( AUTOLINK_PAGE_TITLES ) { foreach ( $filenames as $filename ) { $inText = preg_replace("/(?<![\>\[\/])($filename)(?!\]\>)/im", "<a href=\"" . SELF . VIEW . "/$filename\">\\1</a>", $inText); } } $inText = preg_replace_callback("/\[\[(.*?)\]\]/", '_handle_links', $inText); $inText = preg_replace_callback("/\{\{(.*?)\}\}/", '_handle_images', $inText); $inText = preg_replace_callback("/message:(.*?)\s/", '_handle_message', $inText); $html = MarkdownExtra::defaultTransform($inText); $inText = htmlentities($inText); return $html; } function sanitizeFilename($inFileName) { return str_replace(array('..', '~', '/', '\\', ':'), '-', $inFileName); } function destroy_session() { if ( isset($_COOKIE[session_name()]) ) setcookie(session_name(), '', time() - 42000, '/'); session_destroy(); unset($_SESSION["password"]); unset($_SESSION); } // Support PHP4 by defining file_put_contents if it doesn't already exist if ( !function_exists('file_put_contents') ) { function file_put_contents($n, $d) { $f = @fopen($n, "w"); if ( !$f ) { return false; } else { fwrite($f, $d); fclose($f); return true; } } } // Support PHP 8.1 by setting two predefined variables to empty strings if // not already defined. Fixes a bunch of deprecation warnings. if (!isset($_SERVER["PATH_INFO"])) $_SERVER["PATH_INFO"] = ''; if (!isset($_REQUEST['page'])) $_REQUEST['page'] = ''; // Main code if ( isset($_REQUEST['action']) ) $action = $_REQUEST['action']; else $action = 'view'; // Look for page name following the script name in the URL, like this: // http://stevenf.com/w2demo/index.php/Markdown%20Syntax // // Otherwise, get page name from 'page' request variable. if ( preg_match('@^/@', @$_SERVER["PATH_INFO"]) ) $page = sanitizeFilename(substr($_SERVER["PATH_INFO"], 1)); else $page = sanitizeFilename(@$_REQUEST['page']); $upage = urlencode($page); if ( $page == "" ) $page = DEFAULT_PAGE; $filename = PAGE_PATH . "/$page.txt"; if ( file_exists($filename) ) { $text = file_get_contents($filename); } else { if ( $action != "save" && $action != "all_name" && $action != "all_date" && $action != "upload" && $action != "new" && $action != "logout" && $action != "uploaded" && $action != "search" && $action != "view" ) { $action = "edit"; } } if ( $action == "edit" || $action == "new" ) { $formAction = SELF . (($action == 'edit') ? "/$page" : ""); $html = "<form id=\"edit\" method=\"post\" action=\"$formAction\">\n"; if ( $action == "edit" ) $html .= "<input type=\"hidden\" name=\"page\" value=\"$page\" />\n"; else $html .= "<p>Title: <input id=\"title\" type=\"text\" name=\"page\" /></p>\n"; if ( $action == "new" ) $text = ""; $html .= "<p><textarea id=\"text\" name=\"newText\" rows=\"" . EDIT_ROWS . "\">$text</textarea></p>\n"; $html .= "<p><input type=\"hidden\" name=\"action\" value=\"save\" />"; $html .= "<input id=\"save\" type=\"submit\" value=\"Save\" />\n"; $html .= "<input id=\"cancel\" type=\"button\" onclick=\"history.go(-1);\" value=\"Cancel\" /></p>\n"; $html .= "</form>\n"; } else if ( $action == "logout" ) { destroy_session(); header("Location: " . SELF); exit; } else if ( $action == "upload" ) { if ( DISABLE_UPLOADS ) { $html = "<p>Image uploading has been disabled on this installation.</p>"; } else { $html = "<form id=\"upload\" method=\"post\" action=\"" . SELF . "\" enctype=\"multipart/form-data\"><p>\n"; $html .= "<input type=\"hidden\" name=\"action\" value=\"uploaded\" />"; $html .= "<input id=\"file\" type=\"file\" name=\"userfile\" />\n"; $html .= "<input id=\"upload\" type=\"submit\" value=\"Upload\" />\n"; $html .= "<input id=\"cancel\" type=\"button\" onclick=\"history.go(-1);\" value=\"Cancel\" />\n"; $html .= "</p></form>\n"; } } else if ( $action == "uploaded" ) { if ( !DISABLE_UPLOADS ) { $dstName = sanitizeFilename($_FILES['userfile']['name']); $fileType = $_FILES['userfile']['type']; preg_match('/\.([^.]+)$/', $dstName, $matches); $fileExt = isset($matches[1]) ? $matches[1] : null; if (in_array($fileType, explode(',', VALID_UPLOAD_TYPES)) && in_array($fileExt, explode(',', VALID_UPLOAD_EXTS))) { $errLevel = error_reporting(0); if ( move_uploaded_file($_FILES['userfile']['tmp_name'], BASE_PATH . "/img/$dstName") === true ) { $html = "<p class=\"note\">File '$dstName' uploaded</p>\n"; } else { $html = "<p class=\"note\">Upload error</p>\n"; } error_reporting($errLevel); } else { $html = "<p class=\"note\">Upload error: invalid file type</p>\n"; } } $html .= toHTML($text); } else if ( $action == "save" ) { $newText = $_REQUEST['newText']; $errLevel = error_reporting(0); $success = file_put_contents($filename, $newText); error_reporting($errLevel); if ( $success ) $html = "<p class=\"note\">Saved</p>\n"; else $html = "<p class=\"note\">Error saving changes! Make sure your web server has write access to " . PAGE_PATH . "</p>\n"; $html .= toHTML($newText); } /* else if ( $action == "rename" ) { $html = "<form id=\"rename\" method=\"post\" action=\"" . SELF . "\">"; $html .= "<p>Title: <input id=\"title\" type=\"text\" name=\"page\" value=\"" . htmlspecialchars($page) . "\" />"; $html .= "<input id=\"rename\" type=\"submit\" value=\"Rename\">"; $html .= "<input id=\"cancel\" type=\"button\" onclick=\"history.go(-1);\" value=\"Cancel\" />\n"; $html .= "<input type=\"hidden\" name=\"action\" value=\"renamed\" />"; $html .= "<input type=\"hidden\" name=\"prevpage\" value=\"" . htmlspecialchars($page) . "\" />"; $html .= "</p></form>"; } else if ( $action == "renamed" ) { $pp = $_REQUEST['prevpage']; $pg = $_REQUEST['page']; $prevpage = sanitizeFilename($pp); $prevpage = urlencode($prevpage); $prevfilename = PAGE_PATH . "/$prevpage.txt"; if ( rename($prevfilename, $filename) ) { // Success. Change links in all pages to point to new page if ( $dh = opendir(PAGE_PATH) ) { while ( ($file = readdir($dh)) !== false ) { $content = file_get_contents($file); $pattern = "/\[\[" . $pp . "\]\]/g"; preg_replace($pattern, "[[$pg]]", $content); file_put_contents($file, $content); } } } else { $html = "<p class=\"note\">Error renaming file</p>\n"; } } */ else if ( $action == "all_name" ) { $dir = opendir(PAGE_PATH); $filelist = array(); $color = "#ffffff"; while ( $file = readdir($dir) ) { if ( $file[0] == "." ) continue; $afile = preg_replace("/(.*?)\.txt/", "<a href=\"" . SELF . VIEW . "/\\1\">\\1</a>", $file); $efile = preg_replace("/(.*?)\.txt/", "<a href=\"?action=edit&amp;page=\\1\">edit</a>", urlencode($file)); array_push($filelist, "<tr style=\"background-color: $color;\"><td>$afile</td><td width=\"20\"></td><td>$efile</td></tr>"); if ( $color == "#ffffff" ) $color = "#f4f4f4"; else $color = "#ffffff"; } closedir($dir); natcasesort($filelist); $html = "<table>"; for ($i = 0; $i < count($filelist); $i++) { $html .= $filelist[$i]; } $html .= "</table>\n"; } else if ( $action == "all_date" ) { $html = "<table>\n"; $dir = opendir(PAGE_PATH); $filelist = array(); while ( $file = readdir($dir) ) { if ( $file[0] == "." ) continue; $filelist[preg_replace("/(.*?)\.txt/", "<a href=\"" . SELF . VIEW . "/\\1\">\\1</a>", $file)] = filemtime(PAGE_PATH . "/$file"); } closedir($dir); $color = "#ffffff"; arsort($filelist, SORT_NUMERIC); foreach ($filelist as $key => $value) { $html .= "<tr style=\"background-color: $color;\"><td valign=\"top\">$key</td><td width=\"20\"></td><td valign=\"top\"><nobr>" . date(TITLE_DATE_NO_TIME, $value) . "</nobr></td></tr>\n"; if ( $color == "#ffffff" ) $color = "#f4f4f4"; else $color = "#ffffff"; } $html .= "</table>\n"; } else if ( $action == "search" ) { $matches = 0; $q = $_REQUEST['q']; $html = "<h1>Search: $q</h1>\n<ul>\n"; if ( trim($q) != "" ) { $dir = opendir(PAGE_PATH); while ( $file = readdir($dir) ) { if ( $file[0] == "." ) continue; $text = file_get_contents(PAGE_PATH . "/$file"); if ( preg_match("/{$q}/i", $text) || preg_match("/{$q}/i", $file) ) { ++$matches; $file = preg_replace("/(.*?)\.txt/", "<a href=\"" . SELF . VIEW . "/\\1\">\\1</a>", $file); $html .= "<li>$file</li>\n"; } } closedir($dir); } $html .= "</ul>\n"; $html .= "<p>$matches matched</p>\n"; } else { $html = toHTML($text); } $datetime = ''; if ( ($action == "all_name") || ($action == "all_date")) $title = "All Pages"; else if ( $action == "upload" ) $title = "Upload Image"; else if ( $action == "new" ) $title = "New"; else if ( $action == "search" ) $title = "Search"; else { $title = $page; if ( TITLE_DATE ) { $datetime = "<span class=\"titledate\">" . date(TITLE_DATE, @filemtime($filename)) . "</span>"; } } // Disable caching on the client (the iPhone is pretty agressive about this // and it can cause problems with the editing function) header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"; print "<html>\n"; print "<head>\n"; print "<link rel=\"apple-touch-icon\" href=\"apple-touch-icon.png\"/>"; print "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, user-scalable=false\" />\n"; print "<link type=\"text/css\" rel=\"stylesheet\" href=\"" . BASE_URI . "/" . CSS_FILE ."\" />\n"; print "<title>$title</title>\n"; print "</head>\n"; print "<body>\n"; print "<div class=\"titlebar\">$title <span style=\"font-weight: normal;\">$datetime</span></div>\n"; printToolbar(); print "<div class=\"main\">\n"; print "$html\n"; print "</div>\n"; print "</body>\n"; print "</html>\n"; ?>
php
MIT
d98486580d3ebb0709c03e6c1b04998a33d37d2b
2026-01-05T05:13:32.288033Z
false
panicsteve/w2wiki
https://github.com/panicsteve/w2wiki/blob/d98486580d3ebb0709c03e6c1b04998a33d37d2b/Michelf/MarkdownInterface.inc.php
Michelf/MarkdownInterface.inc.php
<?php // Use this file if you cannot use class autoloading. It will include all the // files needed for the MarkdownInterface interface. // // Take a look at the PSR-0-compatible class autoloading implementation // in the Readme.php file if you want a simple autoloader setup. require_once dirname(__FILE__) . '/MarkdownInterface.php';
php
MIT
d98486580d3ebb0709c03e6c1b04998a33d37d2b
2026-01-05T05:13:32.288033Z
false
panicsteve/w2wiki
https://github.com/panicsteve/w2wiki/blob/d98486580d3ebb0709c03e6c1b04998a33d37d2b/Michelf/Markdown.php
Michelf/Markdown.php
<?php /** * Markdown - A text-to-HTML conversion tool for web writers * * @package php-markdown * @author Michel Fortin <michel.fortin@michelf.com> * @copyright 2004-2019 Michel Fortin <https://michelf.com/projects/php-markdown/> * @copyright (Original Markdown) 2004-2006 John Gruber <https://daringfireball.net/projects/markdown/> */ namespace Michelf; /** * Markdown Parser Class */ class Markdown implements MarkdownInterface { /** * Define the package version * @var string */ const MARKDOWNLIB_VERSION = "2.0"; /** * Simple function interface - Initialize the parser and return the result * of its transform method. This will work fine for derived classes too. * * @api * * @param string $text * @return string */ public static function defaultTransform($text) { // Take parser class on which this function was called. $parser_class = static::class; // Try to take parser from the static parser list static $parser_list; $parser =& $parser_list[$parser_class]; // Create the parser it not already set if (!$parser) { $parser = new $parser_class; } // Transform text using parser. return $parser->transform($text); } /** * Configuration variables */ /** * Change to ">" for HTML output. */ public $empty_element_suffix = " />"; /** * The width of indentation of the output markup */ public $tab_width = 4; /** * Change to `true` to disallow markup or entities. */ public $no_markup = false; public $no_entities = false; /** * Change to `true` to enable line breaks on \n without two trailling spaces * @var boolean */ public $hard_wrap = false; /** * Predefined URLs and titles for reference links and images. */ public $predef_urls = array(); public $predef_titles = array(); /** * Optional filter function for URLs * @var callable|null */ public $url_filter_func = null; /** * Optional header id="" generation callback function. * @var callable|null */ public $header_id_func = null; /** * Optional function for converting code block content to HTML * @var callable|null */ public $code_block_content_func = null; /** * Optional function for converting code span content to HTML. * @var callable|null */ public $code_span_content_func = null; /** * Class attribute to toggle "enhanced ordered list" behaviour * setting this to true will allow ordered lists to start from the index * number that is defined first. * * For example: * 2. List item two * 3. List item three * * Becomes: * <ol start="2"> * <li>List item two</li> * <li>List item three</li> * </ol> */ public $enhanced_ordered_list = false; /** * Parser implementation */ /** * Regex to match balanced [brackets]. * Needed to insert a maximum bracked depth while converting to PHP. */ protected $nested_brackets_depth = 6; protected $nested_brackets_re; protected $nested_url_parenthesis_depth = 4; protected $nested_url_parenthesis_re; /** * Table of hash values for escaped characters: */ protected $escape_chars = '\`*_{}[]()>#+-.!'; protected $escape_chars_re; /** * Constructor function. Initialize appropriate member variables. * @return void */ public function __construct() { $this->_initDetab(); $this->prepareItalicsAndBold(); $this->nested_brackets_re = str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth). str_repeat('\])*', $this->nested_brackets_depth); $this->nested_url_parenthesis_re = str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth). str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth); $this->escape_chars_re = '['.preg_quote($this->escape_chars).']'; // Sort document, block, and span gamut in ascendent priority order. asort($this->document_gamut); asort($this->block_gamut); asort($this->span_gamut); } /** * Internal hashes used during transformation. */ protected $urls = array(); protected $titles = array(); protected $html_hashes = array(); /** * Status flag to avoid invalid nesting. */ protected $in_anchor = false; /** * Status flag to avoid invalid nesting. */ protected $in_emphasis_processing = false; /** * Called before the transformation process starts to setup parser states. * @return void */ protected function setup() { // Clear global hashes. $this->urls = $this->predef_urls; $this->titles = $this->predef_titles; $this->html_hashes = array(); $this->in_anchor = false; $this->in_emphasis_processing = false; } /** * Called after the transformation process to clear any variable which may * be taking up memory unnecessarly. * @return void */ protected function teardown() { $this->urls = array(); $this->titles = array(); $this->html_hashes = array(); } /** * Main function. Performs some preprocessing on the input text and pass * it through the document gamut. * * @api * * @param string $text * @return string */ public function transform($text) { $this->setup(); # Remove UTF-8 BOM and marker character in input, if present. $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); # Standardize line endings: # DOS to Unix and Mac to Unix $text = preg_replace('{\r\n?}', "\n", $text); # Make sure $text ends with a couple of newlines: $text .= "\n\n"; # Convert all tabs to spaces. $text = $this->detab($text); # Turn block-level HTML blocks into hash entries $text = $this->hashHTMLBlocks($text); # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ ]*\n+/ . $text = preg_replace('/^[ ]+$/m', '', $text); # Run document gamut methods. foreach ($this->document_gamut as $method => $priority) { $text = $this->$method($text); } $this->teardown(); return $text . "\n"; } /** * Define the document gamut */ protected $document_gamut = array( // Strip link definitions, store in hashes. "stripLinkDefinitions" => 20, "runBasicBlockGamut" => 30, ); /** * Strips link definitions from text, stores the URLs and titles in * hash references * @param string $text * @return string */ protected function stripLinkDefinitions($text) { $less_than_tab = $this->tab_width - 1; // Link defs are in the form: ^[id]: url "optional title" $text = preg_replace_callback('{ ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 [ ]* \n? # maybe *one* newline [ ]* (?: <(.+?)> # url = $2 | (\S+?) # url = $3 ) [ ]* \n? # maybe one newline [ ]* (?: (?<=\s) # lookbehind for whitespace ["(] (.*?) # title = $4 [")] [ ]* )? # title is optional (?:\n+|\Z) }xm', array($this, '_stripLinkDefinitions_callback'), $text ); return $text; } /** * The callback to strip link definitions * @param array $matches * @return string */ protected function _stripLinkDefinitions_callback($matches) { $link_id = strtolower($matches[1]); $url = $matches[2] == '' ? $matches[3] : $matches[2]; $this->urls[$link_id] = $url; $this->titles[$link_id] =& $matches[4]; return ''; // String that will replace the block } /** * Hashify HTML blocks * @param string $text * @return string */ protected function hashHTMLBlocks($text) { if ($this->no_markup) { return $text; } $less_than_tab = $this->tab_width - 1; /** * Hashify HTML blocks: * * We only want to do this for block-level HTML tags, such as headers, * lists, and tables. That's because we still want to wrap <p>s around * "paragraphs" that are wrapped in non-block-level tags, such as * anchors, phrase emphasis, and spans. The list of tags we're looking * for is hard-coded: * * * List "a" is made of tags which can be both inline or block-level. * These will be treated block-level when the start tag is alone on * its line, otherwise they're not matched here and will be taken as * inline later. * * List "b" is made of tags which are always block-level; */ $block_tags_a_re = 'ins|del'; $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. 'script|noscript|style|form|fieldset|iframe|math|svg|'. 'article|section|nav|aside|hgroup|header|footer|'. 'figure|details|summary'; // Regular expression for the content of a block tag. $nested_tags_level = 4; $attr = ' (?> # optional tag attributes \s # starts with whitespace (?> [^>"/]+ # text outside quotes | /+(?!>) # slash not followed by ">" | "[^"]*" # text inside double quotes (tolerate ">") | \'[^\']*\' # text inside single quotes (tolerate ">") )* )? '; $content = str_repeat(' (?> [^<]+ # content without tag | <\2 # nested opening tag '.$attr.' # attributes (?> /> | >', $nested_tags_level). // end of opening tag '.*?'. // last level nested tag content str_repeat(' </\2\s*> # closing nested tag ) | <(?!/\2\s*> # other tags with a different name ) )*', $nested_tags_level); $content2 = str_replace('\2', '\3', $content); /** * First, look for nested blocks, e.g.: * <div> * <div> * tags for inner block must be indented. * </div> * </div> * * The outermost tags must start at the left margin for this to match, * and the inner nested divs must be indented. * We need to do this before the next, more liberal match, because the * next match will start at the first `<div>` and stop at the * first `</div>`. */ $text = preg_replace_callback('{(?> (?> (?<=\n) # Starting on its own line | # or \A\n? # the at beginning of the doc ) ( # save in $1 # Match from `\n<tag>` to `</tag>\n`, handling nested tags # in between. [ ]{0,'.$less_than_tab.'} <('.$block_tags_b_re.')# start tag = $2 '.$attr.'> # attributes followed by > and \n '.$content.' # content, support nesting </\2> # the matching end tag [ ]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document | # Special version for tags of group a. [ ]{0,'.$less_than_tab.'} <('.$block_tags_a_re.')# start tag = $3 '.$attr.'>[ ]*\n # attributes followed by > '.$content2.' # content, support nesting </\3> # the matching end tag [ ]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document | # Special case just for <hr />. It was easier to make a special # case than to make the other regex more complicated. [ ]{0,'.$less_than_tab.'} <(hr) # start tag = $2 '.$attr.' # attributes /?> # the matching end tag [ ]* (?=\n{2,}|\Z) # followed by a blank line or end of document | # Special case for standalone HTML comments: [ ]{0,'.$less_than_tab.'} (?s: <!-- .*? --> ) [ ]* (?=\n{2,}|\Z) # followed by a blank line or end of document | # PHP and ASP-style processor instructions (<? and <%) [ ]{0,'.$less_than_tab.'} (?s: <([?%]) # $2 .*? \2> ) [ ]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) )}Sxmi', array($this, '_hashHTMLBlocks_callback'), $text ); return $text; } /** * The callback for hashing HTML blocks * @param string $matches * @return string */ protected function _hashHTMLBlocks_callback($matches) { $text = $matches[1]; $key = $this->hashBlock($text); return "\n\n$key\n\n"; } /** * Called whenever a tag must be hashed when a function insert an atomic * element in the text stream. Passing $text to through this function gives * a unique text-token which will be reverted back when calling unhash. * * The $boundary argument specify what character should be used to surround * the token. By convension, "B" is used for block elements that needs not * to be wrapped into paragraph tags at the end, ":" is used for elements * that are word separators and "X" is used in the general case. * * @param string $text * @param string $boundary * @return string */ protected function hashPart($text, $boundary = 'X') { // Swap back any tag hash found in $text so we do not have to `unhash` // multiple times at the end. $text = $this->unhash($text); // Then hash the block. static $i = 0; $key = "$boundary\x1A" . ++$i . $boundary; $this->html_hashes[$key] = $text; return $key; // String that will replace the tag. } /** * Shortcut function for hashPart with block-level boundaries. * @param string $text * @return string */ protected function hashBlock($text) { return $this->hashPart($text, 'B'); } /** * Define the block gamut - these are all the transformations that form * block-level tags like paragraphs, headers, and list items. */ protected $block_gamut = array( "doHeaders" => 10, "doHorizontalRules" => 20, "doLists" => 40, "doCodeBlocks" => 50, "doBlockQuotes" => 60, ); /** * Run block gamut tranformations. * * We need to escape raw HTML in Markdown source before doing anything * else. This need to be done for each block, and not only at the * begining in the Markdown function since hashed blocks can be part of * list items and could have been indented. Indented blocks would have * been seen as a code block in a previous pass of hashHTMLBlocks. * * @param string $text * @return string */ protected function runBlockGamut($text) { $text = $this->hashHTMLBlocks($text); return $this->runBasicBlockGamut($text); } /** * Run block gamut tranformations, without hashing HTML blocks. This is * useful when HTML blocks are known to be already hashed, like in the first * whole-document pass. * * @param string $text * @return string */ protected function runBasicBlockGamut($text) { foreach ($this->block_gamut as $method => $priority) { $text = $this->$method($text); } // Finally form paragraph and restore hashed blocks. $text = $this->formParagraphs($text); return $text; } /** * Convert horizontal rules * @param string $text * @return string */ protected function doHorizontalRules($text) { return preg_replace( '{ ^[ ]{0,3} # Leading space ([-*_]) # $1: First marker (?> # Repeated marker group [ ]{0,2} # Zero, one, or two spaces. \1 # Marker character ){2,} # Group repeated at least twice [ ]* # Tailing spaces $ # End of line. }mx', "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n", $text ); } /** * These are all the transformations that occur *within* block-level * tags like paragraphs, headers, and list items. */ protected $span_gamut = array( // Process character escapes, code spans, and inline HTML // in one shot. "parseSpan" => -30, // Process anchor and image tags. Images must come first, // because ![foo][f] looks like an anchor. "doImages" => 10, "doAnchors" => 20, // Make links out of things like `<https://example.com/>` // Must come after doAnchors, because you can use < and > // delimiters in inline links like [this](<url>). "doAutoLinks" => 30, "encodeAmpsAndAngles" => 40, "doItalicsAndBold" => 50, "doHardBreaks" => 60, ); /** * Run span gamut transformations * @param string $text * @return string */ protected function runSpanGamut($text) { foreach ($this->span_gamut as $method => $priority) { $text = $this->$method($text); } return $text; } /** * Do hard breaks * @param string $text * @return string */ protected function doHardBreaks($text) { if ($this->hard_wrap) { return preg_replace_callback('/ *\n/', array($this, '_doHardBreaks_callback'), $text); } else { return preg_replace_callback('/ {2,}\n/', array($this, '_doHardBreaks_callback'), $text); } } /** * Trigger part hashing for the hard break (callback method) * @param array $matches * @return string */ protected function _doHardBreaks_callback($matches) { return $this->hashPart("<br$this->empty_element_suffix\n"); } /** * Turn Markdown link shortcuts into XHTML <a> tags. * @param string $text * @return string */ protected function doAnchors($text) { if ($this->in_anchor) { return $text; } $this->in_anchor = true; // First, handle reference-style links: [link text] [id] $text = preg_replace_callback('{ ( # wrap whole match in $1 \[ ('.$this->nested_brackets_re.') # link text = $2 \] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (.*?) # id = $3 \] ) }xs', array($this, '_doAnchors_reference_callback'), $text); // Next, inline-style links: [link text](url "optional title") $text = preg_replace_callback('{ ( # wrap whole match in $1 \[ ('.$this->nested_brackets_re.') # link text = $2 \] \( # literal paren [ \n]* (?: <(.+?)> # href = $3 | ('.$this->nested_url_parenthesis_re.') # href = $4 ) [ \n]* ( # $5 ([\'"]) # quote char = $6 (.*?) # Title = $7 \6 # matching quote [ \n]* # ignore any spaces/tabs between closing quote and ) )? # title is optional \) ) }xs', array($this, '_doAnchors_inline_callback'), $text); // Last, handle reference-style shortcuts: [link text] // These must come last in case you've also got [link text][1] // or [link text](/foo) $text = preg_replace_callback('{ ( # wrap whole match in $1 \[ ([^\[\]]+) # link text = $2; can\'t contain [ or ] \] ) }xs', array($this, '_doAnchors_reference_callback'), $text); $this->in_anchor = false; return $text; } /** * Callback method to parse referenced anchors * @param array $matches * @return string */ protected function _doAnchors_reference_callback($matches) { $whole_match = $matches[1]; $link_text = $matches[2]; $link_id =& $matches[3]; if ($link_id == "") { // for shortcut links like [this][] or [this]. $link_id = $link_text; } // lower-case and turn embedded newlines into spaces $link_id = strtolower($link_id); $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); if (isset($this->urls[$link_id])) { $url = $this->urls[$link_id]; $url = $this->encodeURLAttribute($url); $result = "<a href=\"$url\""; if ( isset( $this->titles[$link_id] ) ) { $title = $this->titles[$link_id]; $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } $link_text = $this->runSpanGamut($link_text); $result .= ">$link_text</a>"; $result = $this->hashPart($result); } else { $result = $whole_match; } return $result; } /** * Callback method to parse inline anchors * @param array $matches * @return string */ protected function _doAnchors_inline_callback($matches) { $link_text = $this->runSpanGamut($matches[2]); $url = $matches[3] === '' ? $matches[4] : $matches[3]; $title =& $matches[7]; // If the URL was of the form <s p a c e s> it got caught by the HTML // tag parser and hashed. Need to reverse the process before using // the URL. $unhashed = $this->unhash($url); if ($unhashed !== $url) $url = preg_replace('/^<(.*)>$/', '\1', $unhashed); $url = $this->encodeURLAttribute($url); $result = "<a href=\"$url\""; if ($title) { $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } $link_text = $this->runSpanGamut($link_text); $result .= ">$link_text</a>"; return $this->hashPart($result); } /** * Turn Markdown image shortcuts into <img> tags. * @param string $text * @return string */ protected function doImages($text) { // First, handle reference-style labeled images: ![alt text][id] $text = preg_replace_callback('{ ( # wrap whole match in $1 !\[ ('.$this->nested_brackets_re.') # alt text = $2 \] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (.*?) # id = $3 \] ) }xs', array($this, '_doImages_reference_callback'), $text); // Next, handle inline images: ![alt text](url "optional title") // Don't forget: encode * and _ $text = preg_replace_callback('{ ( # wrap whole match in $1 !\[ ('.$this->nested_brackets_re.') # alt text = $2 \] \s? # One optional whitespace character \( # literal paren [ \n]* (?: <(\S*)> # src url = $3 | ('.$this->nested_url_parenthesis_re.') # src url = $4 ) [ \n]* ( # $5 ([\'"]) # quote char = $6 (.*?) # title = $7 \6 # matching quote [ \n]* )? # title is optional \) ) }xs', array($this, '_doImages_inline_callback'), $text); return $text; } /** * Callback to parse references image tags * @param array $matches * @return string */ protected function _doImages_reference_callback($matches) { $whole_match = $matches[1]; $alt_text = $matches[2]; $link_id = strtolower($matches[3]); if ($link_id == "") { $link_id = strtolower($alt_text); // for shortcut links like ![this][]. } $alt_text = $this->encodeAttribute($alt_text); if (isset($this->urls[$link_id])) { $url = $this->encodeURLAttribute($this->urls[$link_id]); $result = "<img src=\"$url\" alt=\"$alt_text\""; if (isset($this->titles[$link_id])) { $title = $this->titles[$link_id]; $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } $result .= $this->empty_element_suffix; $result = $this->hashPart($result); } else { // If there's no such link ID, leave intact: $result = $whole_match; } return $result; } /** * Callback to parse inline image tags * @param array $matches * @return string */ protected function _doImages_inline_callback($matches) { $whole_match = $matches[1]; $alt_text = $matches[2]; $url = $matches[3] == '' ? $matches[4] : $matches[3]; $title =& $matches[7]; $alt_text = $this->encodeAttribute($alt_text); $url = $this->encodeURLAttribute($url); $result = "<img src=\"$url\" alt=\"$alt_text\""; if (isset($title)) { $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; // $title already quoted } $result .= $this->empty_element_suffix; return $this->hashPart($result); } /** * Parse Markdown heading elements to HTML * @param string $text * @return string */ protected function doHeaders($text) { /** * Setext-style headers: * Header 1 * ======== * * Header 2 * -------- */ $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx', array($this, '_doHeaders_callback_setext'), $text); /** * atx-style headers: * # Header 1 * ## Header 2 * ## Header 2 with closing hashes ## * ... * ###### Header 6 */ $text = preg_replace_callback('{ ^(\#{1,6}) # $1 = string of #\'s [ ]* (.+?) # $2 = Header text [ ]* \#* # optional closing #\'s (not counted) \n+ }xm', array($this, '_doHeaders_callback_atx'), $text); return $text; } /** * Setext header parsing callback * @param array $matches * @return string */ protected function _doHeaders_callback_setext($matches) { // Terrible hack to check we haven't found an empty list item. if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) { return $matches[0]; } $level = $matches[2][0] == '=' ? 1 : 2; // ID attribute generation $idAtt = $this->_generateIdFromHeaderValue($matches[1]); $block = "<h$level$idAtt>".$this->runSpanGamut($matches[1])."</h$level>"; return "\n" . $this->hashBlock($block) . "\n\n"; } /** * ATX header parsing callback * @param array $matches * @return string */ protected function _doHeaders_callback_atx($matches) { // ID attribute generation $idAtt = $this->_generateIdFromHeaderValue($matches[2]); $level = strlen($matches[1]); $block = "<h$level$idAtt>".$this->runSpanGamut($matches[2])."</h$level>"; return "\n" . $this->hashBlock($block) . "\n\n"; } /** * If a header_id_func property is set, we can use it to automatically * generate an id attribute. * * This method returns a string in the form id="foo", or an empty string * otherwise. * @param string $headerValue * @return string */ protected function _generateIdFromHeaderValue($headerValue) { if (!is_callable($this->header_id_func)) { return ""; } $idValue = call_user_func($this->header_id_func, $headerValue); if (!$idValue) { return ""; } return ' id="' . $this->encodeAttribute($idValue) . '"'; } /** * Form HTML ordered (numbered) and unordered (bulleted) lists. * @param string $text * @return string */ protected function doLists($text) { $less_than_tab = $this->tab_width - 1; // Re-usable patterns to match list item bullets and number markers: $marker_ul_re = '[*+-]'; $marker_ol_re = '\d+[\.]'; $markers_relist = array( $marker_ul_re => $marker_ol_re, $marker_ol_re => $marker_ul_re, ); foreach ($markers_relist as $marker_re => $other_marker_re) { // Re-usable pattern to match any entirel ul or ol list: $whole_list_re = ' ( # $1 = whole list ( # $2 ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces ('.$marker_re.') # $4 = first list item marker [ ]+ ) (?s:.+?) ( # $5 \z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ ]* '.$marker_re.'[ ]+ ) | (?= # Lookahead for another kind of list \n \3 # Must have the same indentation '.$other_marker_re.'[ ]+ ) ) ) '; // mx // We use a different prefix before nested lists than top-level lists. //See extended comment in _ProcessListItems(). if ($this->list_level) { $text = preg_replace_callback('{ ^ '.$whole_list_re.' }mx', array($this, '_doLists_callback'), $text); } else { $text = preg_replace_callback('{ (?:(?<=\n)\n|\A\n?) # Must eat the newline '.$whole_list_re.' }mx', array($this, '_doLists_callback'), $text); } } return $text; } /** * List parsing callback * @param array $matches * @return string */ protected function _doLists_callback($matches) { // Re-usable patterns to match list item bullets and number markers: $marker_ul_re = '[*+-]'; $marker_ol_re = '\d+[\.]'; $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; $marker_ol_start_re = '[0-9]+'; $list = $matches[1]; $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol"; $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re ); $list .= "\n"; $result = $this->processListItems($list, $marker_any_re); $ol_start = 1; if ($this->enhanced_ordered_list) { // Get the start number for ordered list. if ($list_type == 'ol') { $ol_start_array = array(); $ol_start_check = preg_match("/$marker_ol_start_re/", $matches[4], $ol_start_array); if ($ol_start_check){ $ol_start = $ol_start_array[0]; } } } if ($ol_start > 1 && $list_type == 'ol'){ $result = $this->hashBlock("<$list_type start=\"$ol_start\">\n" . $result . "</$list_type>"); } else { $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>"); } return "\n". $result ."\n\n"; } /** * Nesting tracker for list levels */ protected $list_level = 0; /** * Process the contents of a single ordered or unordered list, splitting it * into individual list items. * @param string $list_str * @param string $marker_any_re * @return string */ protected function processListItems($list_str, $marker_any_re) { /** * The $this->list_level global keeps track of when we're inside a list. * Each time we enter a list, we increment it; when we leave a list, * we decrement. If it's zero, we're not in a list anymore. * * We do this because when we're not inside a list, we want to treat * something like this: * * I recommend upgrading to version * 8. Oops, now this line is treated * as a sub-list. * * As a single paragraph, despite the fact that the second line starts * with a digit-period-space sequence. * * Whereas when we're inside a list (or sub-list), that line will be * treated as the start of a sub-list. What a kludge, huh? This is * an aspect of Markdown's syntax that's hard to parse perfectly * without resorting to mind-reading. Perhaps the solution is to * change the syntax rules such that sub-lists must start with a * starting cardinal number; e.g. "1." or "a.". */ $this->list_level++; // Trim trailing blank lines: $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); $list_str = preg_replace_callback('{ (\n)? # leading line = $1 (^[ ]*) # leading whitespace = $2 ('.$marker_any_re.' # list marker and space = $3 (?:[ ]+|(?=\n)) # space only required if item is not empty ) ((?s:.*?)) # list item text = $4 (?:(\n+(?=\n))|\n) # tailing blank line = $5 (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n)))) }xm', array($this, '_processListItems_callback'), $list_str); $this->list_level--; return $list_str; } /** * List item parsing callback * @param array $matches * @return string */ protected function _processListItems_callback($matches) { $item = $matches[4]; $leading_line =& $matches[1]; $leading_space =& $matches[2]; $marker_space = $matches[3]; $tailing_blank_line =& $matches[5]; if ($leading_line || $tailing_blank_line || preg_match('/\n{2,}/', $item)) { // Replace marker with the appropriate whitespace indentation $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item; $item = $this->runBlockGamut($this->outdent($item)."\n"); } else { // Recursion for sub-lists: $item = $this->doLists($this->outdent($item)); $item = $this->formParagraphs($item, false); } return "<li>" . $item . "</li>\n"; } /** * Process Markdown `<pre><code>` blocks. * @param string $text * @return string */ protected function doCodeBlocks($text) { $text = preg_replace_callback('{ (?:\n\n|\A\n?) ( # $1 = the code block -- one or more lines, starting with a space/tab (?> [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces .*\n+ )+ ) ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc }xm', array($this, '_doCodeBlocks_callback'), $text); return $text; } /** * Code block parsing callback * @param array $matches * @return string */ protected function _doCodeBlocks_callback($matches) { $codeblock = $matches[1]; $codeblock = $this->outdent($codeblock); if (is_callable($this->code_block_content_func)) { $codeblock = call_user_func($this->code_block_content_func, $codeblock, ""); } else { $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES); } # trim leading newlines and trailing newlines $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock); $codeblock = "<pre><code>$codeblock\n</code></pre>"; return "\n\n" . $this->hashBlock($codeblock) . "\n\n"; } /** * Create a code span markup for $code. Called from handleSpanToken. * @param string $code * @return string */ protected function makeCodeSpan($code) { if (is_callable($this->code_span_content_func)) { $code = call_user_func($this->code_span_content_func, $code); } else { $code = htmlspecialchars(trim($code), ENT_NOQUOTES); } return $this->hashPart("<code>$code</code>"); } /** * Define the emphasis operators with their regex matches * @var array */ protected $em_relist = array( '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?![\.,:;]?\s)', '*' => '(?<![\s*])\*(?!\*)', '_' => '(?<![\s_])_(?!_)', ); /** * Define the strong operators with their regex matches * @var array */
php
MIT
d98486580d3ebb0709c03e6c1b04998a33d37d2b
2026-01-05T05:13:32.288033Z
true
panicsteve/w2wiki
https://github.com/panicsteve/w2wiki/blob/d98486580d3ebb0709c03e6c1b04998a33d37d2b/Michelf/MarkdownExtra.inc.php
Michelf/MarkdownExtra.inc.php
<?php // Use this file if you cannot use class autoloading. It will include all the // files needed for the MarkdownExtra parser. // // Take a look at the PSR-0-compatible class autoloading implementation // in the Readme.php file if you want a simple autoloader setup. require_once dirname(__FILE__) . '/MarkdownInterface.php'; require_once dirname(__FILE__) . '/Markdown.php'; require_once dirname(__FILE__) . '/MarkdownExtra.php';
php
MIT
d98486580d3ebb0709c03e6c1b04998a33d37d2b
2026-01-05T05:13:32.288033Z
false
panicsteve/w2wiki
https://github.com/panicsteve/w2wiki/blob/d98486580d3ebb0709c03e6c1b04998a33d37d2b/Michelf/MarkdownInterface.php
Michelf/MarkdownInterface.php
<?php /** * Markdown - A text-to-HTML conversion tool for web writers * * @package php-markdown * @author Michel Fortin <michel.fortin@michelf.com> * @copyright 2004-2021 Michel Fortin <https://michelf.com/projects/php-markdown/> * @copyright (Original Markdown) 2004-2006 John Gruber <https://daringfireball.net/projects/markdown/> */ namespace Michelf; /** * Markdown Parser Interface */ interface MarkdownInterface { /** * Initialize the parser and return the result of its transform method. * This will work fine for derived classes too. * * @api * * @param string $text * @return string */ public static function defaultTransform($text); /** * Main function. Performs some preprocessing on the input text * and pass it through the document gamut. * * @api * * @param string $text * @return string */ public function transform($text); }
php
MIT
d98486580d3ebb0709c03e6c1b04998a33d37d2b
2026-01-05T05:13:32.288033Z
false
panicsteve/w2wiki
https://github.com/panicsteve/w2wiki/blob/d98486580d3ebb0709c03e6c1b04998a33d37d2b/Michelf/MarkdownExtra.php
Michelf/MarkdownExtra.php
<?php /** * Markdown Extra - A text-to-HTML conversion tool for web writers * * @package php-markdown * @author Michel Fortin <michel.fortin@michelf.com> * @copyright 2004-2019 Michel Fortin <https://michelf.com/projects/php-markdown/> * @copyright (Original Markdown) 2004-2006 John Gruber <https://daringfireball.net/projects/markdown/> */ namespace Michelf; /** * Markdown Extra Parser Class */ class MarkdownExtra extends \Michelf\Markdown { /** * Configuration variables */ /** * Prefix for footnote ids. */ public $fn_id_prefix = ""; /** * Optional title attribute for footnote links. */ public $fn_link_title = ""; /** * Optional class attribute for footnote links and backlinks. */ public $fn_link_class = "footnote-ref"; public $fn_backlink_class = "footnote-backref"; /** * Content to be displayed within footnote backlinks. The default is '↩'; * the U+FE0E on the end is a Unicode variant selector used to prevent iOS * from displaying the arrow character as an emoji. * Optionally use '^^' and '%%' to refer to the footnote number and * reference number respectively. {@see parseFootnotePlaceholders()} */ public $fn_backlink_html = '&#8617;&#xFE0E;'; /** * Optional title and aria-label attributes for footnote backlinks for * added accessibility (to ensure backlink uniqueness). * Use '^^' and '%%' to refer to the footnote number and reference number * respectively. {@see parseFootnotePlaceholders()} */ public $fn_backlink_title = ""; public $fn_backlink_label = ""; /** * Class name for table cell alignment (%% replaced left/center/right) * For instance: 'go-%%' becomes 'go-left' or 'go-right' or 'go-center' * If empty, the align attribute is used instead of a class name. */ public $table_align_class_tmpl = ''; /** * Optional class prefix for fenced code block. */ public $code_class_prefix = ""; /** * Class attribute for code blocks goes on the `code` tag; * setting this to true will put attributes on the `pre` tag instead. */ public $code_attr_on_pre = false; /** * Predefined abbreviations. */ public $predef_abbr = array(); /** * Only convert atx-style headers if there's a space between the header and # */ public $hashtag_protection = false; /** * Determines whether footnotes should be appended to the end of the document. * If true, footnote html can be retrieved from $this->footnotes_assembled. */ public $omit_footnotes = false; /** * After parsing, the HTML for the list of footnotes appears here. * This is available only if $omit_footnotes == true. * * Note: when placing the content of `footnotes_assembled` on the page, * consider adding the attribute `role="doc-endnotes"` to the `div` or * `section` that will enclose the list of footnotes so they are * reachable to accessibility tools the same way they would be with the * default HTML output. */ public $footnotes_assembled = null; /** * Parser implementation */ /** * Constructor function. Initialize the parser object. * @return void */ public function __construct() { // Add extra escapable characters before parent constructor // initialize the table. $this->escape_chars .= ':|'; // Insert extra document, block, and span transformations. // Parent constructor will do the sorting. $this->document_gamut += array( "doFencedCodeBlocks" => 5, "stripFootnotes" => 15, "stripAbbreviations" => 25, "appendFootnotes" => 50, ); $this->block_gamut += array( "doFencedCodeBlocks" => 5, "doTables" => 15, "doDefLists" => 45, ); $this->span_gamut += array( "doFootnotes" => 5, "doAbbreviations" => 70, ); $this->enhanced_ordered_list = true; parent::__construct(); } /** * Extra variables used during extra transformations. */ protected $footnotes = array(); protected $footnotes_ordered = array(); protected $footnotes_ref_count = array(); protected $footnotes_numbers = array(); protected $abbr_desciptions = array(); protected $abbr_word_re = ''; /** * Give the current footnote number. */ protected $footnote_counter = 1; /** * Ref attribute for links */ protected $ref_attr = array(); /** * Setting up Extra-specific variables. */ protected function setup() { parent::setup(); $this->footnotes = array(); $this->footnotes_ordered = array(); $this->footnotes_ref_count = array(); $this->footnotes_numbers = array(); $this->abbr_desciptions = array(); $this->abbr_word_re = ''; $this->footnote_counter = 1; $this->footnotes_assembled = null; foreach ($this->predef_abbr as $abbr_word => $abbr_desc) { if ($this->abbr_word_re) $this->abbr_word_re .= '|'; $this->abbr_word_re .= preg_quote($abbr_word); $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); } } /** * Clearing Extra-specific variables. */ protected function teardown() { $this->footnotes = array(); $this->footnotes_ordered = array(); $this->footnotes_ref_count = array(); $this->footnotes_numbers = array(); $this->abbr_desciptions = array(); $this->abbr_word_re = ''; if ( ! $this->omit_footnotes ) $this->footnotes_assembled = null; parent::teardown(); } /** * Extra attribute parser */ /** * Expression to use to catch attributes (includes the braces) */ protected $id_class_attr_catch_re = '\{((?>[ ]*[#.a-z][-_:a-zA-Z0-9=]+){1,})[ ]*\}'; /** * Expression to use when parsing in a context when no capture is desired */ protected $id_class_attr_nocatch_re = '\{(?>[ ]*[#.a-z][-_:a-zA-Z0-9=]+){1,}[ ]*\}'; /** * Parse attributes caught by the $this->id_class_attr_catch_re expression * and return the HTML-formatted list of attributes. * * Currently supported attributes are .class and #id. * * In addition, this method also supports supplying a default Id value, * which will be used to populate the id attribute in case it was not * overridden. * @param string $tag_name * @param string $attr * @param mixed $defaultIdValue * @param array $classes * @return string */ protected function doExtraAttributes($tag_name, $attr, $defaultIdValue = null, $classes = array()) { if (empty($attr) && !$defaultIdValue && empty($classes)) { return ""; } // Split on components preg_match_all('/[#.a-z][-_:a-zA-Z0-9=]+/', $attr, $matches); $elements = $matches[0]; // Handle classes and IDs (only first ID taken into account) $attributes = array(); $id = false; foreach ($elements as $element) { if ($element[0] === '.') { $classes[] = substr($element, 1); } else if ($element[0] === '#') { if ($id === false) $id = substr($element, 1); } else if (strpos($element, '=') > 0) { $parts = explode('=', $element, 2); $attributes[] = $parts[0] . '="' . $parts[1] . '"'; } } if ($id === false || $id === '') { $id = $defaultIdValue; } // Compose attributes as string $attr_str = ""; if (!empty($id)) { $attr_str .= ' id="'.$this->encodeAttribute($id) .'"'; } if (!empty($classes)) { $attr_str .= ' class="'. implode(" ", $classes) . '"'; } if (!$this->no_markup && !empty($attributes)) { $attr_str .= ' '.implode(" ", $attributes); } return $attr_str; } /** * Strips link definitions from text, stores the URLs and titles in * hash references. * @param string $text * @return string */ protected function stripLinkDefinitions($text) { $less_than_tab = $this->tab_width - 1; // Link defs are in the form: ^[id]: url "optional title" $text = preg_replace_callback('{ ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 [ ]* \n? # maybe *one* newline [ ]* (?: <(.+?)> # url = $2 | (\S+?) # url = $3 ) [ ]* \n? # maybe one newline [ ]* (?: (?<=\s) # lookbehind for whitespace ["(] (.*?) # title = $4 [")] [ ]* )? # title is optional (?:[ ]* '.$this->id_class_attr_catch_re.' )? # $5 = extra id & class attr (?:\n+|\Z) }xm', array($this, '_stripLinkDefinitions_callback'), $text); return $text; } /** * Strip link definition callback * @param array $matches * @return string */ protected function _stripLinkDefinitions_callback($matches) { $link_id = strtolower($matches[1]); $url = $matches[2] == '' ? $matches[3] : $matches[2]; $this->urls[$link_id] = $url; $this->titles[$link_id] =& $matches[4]; $this->ref_attr[$link_id] = $this->doExtraAttributes("", $dummy =& $matches[5]); return ''; // String that will replace the block } /** * HTML block parser */ /** * Tags that are always treated as block tags */ protected $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend|article|section|nav|aside|hgroup|header|footer|figcaption|figure|details|summary'; /** * Tags treated as block tags only if the opening tag is alone on its line */ protected $context_block_tags_re = 'script|noscript|style|ins|del|iframe|object|source|track|param|math|svg|canvas|audio|video'; /** * Tags where markdown="1" default to span mode: */ protected $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address'; /** * Tags which must not have their contents modified, no matter where * they appear */ protected $clean_tags_re = 'script|style|math|svg'; /** * Tags that do not need to be closed. */ protected $auto_close_tags_re = 'hr|img|param|source|track'; /** * Hashify HTML Blocks and "clean tags". * * We only want to do this for block-level HTML tags, such as headers, * lists, and tables. That's because we still want to wrap <p>s around * "paragraphs" that are wrapped in non-block-level tags, such as anchors, * phrase emphasis, and spans. The list of tags we're looking for is * hard-coded. * * This works by calling _HashHTMLBlocks_InMarkdown, which then calls * _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1" * attribute is found within a tag, _HashHTMLBlocks_InHTML calls back * _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag. * These two functions are calling each other. It's recursive! * @param string $text * @return string */ protected function hashHTMLBlocks($text) { if ($this->no_markup) { return $text; } // Call the HTML-in-Markdown hasher. list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text); return $text; } /** * Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags. * * * $indent is the number of space to be ignored when checking for code * blocks. This is important because if we don't take the indent into * account, something like this (which looks right) won't work as expected: * * <div> * <div markdown="1"> * Hello World. <-- Is this a Markdown code block or text? * </div> <-- Is this a Markdown code block or a real tag? * <div> * * If you don't like this, just don't indent the tag on which * you apply the markdown="1" attribute. * * * If $enclosing_tag_re is not empty, stops at the first unmatched closing * tag with that name. Nested tags supported. * * * If $span is true, text inside must treated as span. So any double * newline will be replaced by a single newline so that it does not create * paragraphs. * * Returns an array of that form: ( processed text , remaining text ) * * @param string $text * @param integer $indent * @param string $enclosing_tag_re * @param boolean $span * @return array */ protected function _hashHTMLBlocks_inMarkdown($text, $indent = 0, $enclosing_tag_re = '', $span = false) { if ($text === '') return array('', ''); // Regex to check for the presense of newlines around a block tag. $newline_before_re = '/(?:^\n?|\n\n)*$/'; $newline_after_re = '{ ^ # Start of text following the tag. (?>[ ]*<!--.*?-->)? # Optional comment. [ ]*\n # Must be followed by newline. }xs'; // Regex to match any tag. $block_tag_re = '{ ( # $2: Capture whole tag. </? # Any opening or closing tag. (?> # Tag name. ' . $this->block_tags_re . ' | ' . $this->context_block_tags_re . ' | ' . $this->clean_tags_re . ' | (?!\s)'.$enclosing_tag_re . ' ) (?: (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name. (?> ".*?" | # Double quotes (can contain `>`) \'.*?\' | # Single quotes (can contain `>`) .+? # Anything but quotes and `>`. )*? )? > # End of tag. | <!-- .*? --> # HTML Comment | <\?.*?\?> | <%.*?%> # Processing instruction | <!\[CDATA\[.*?\]\]> # CData Block ' . ( !$span ? ' # If not in span. | # Indented code block (?: ^[ ]*\n | ^ | \n[ ]*\n ) [ ]{' . ($indent + 4) . '}[^\n]* \n (?> (?: [ ]{' . ($indent + 4) . '}[^\n]* | [ ]* ) \n )* | # Fenced code block marker (?<= ^ | \n ) [ ]{0,' . ($indent + 3) . '}(?:~{3,}|`{3,}) [ ]* (?: \.?[-_:a-zA-Z0-9]+ )? # standalone class name [ ]* (?: ' . $this->id_class_attr_nocatch_re . ' )? # extra attributes [ ]* (?= \n ) ' : '' ) . ' # End (if not is span). | # Code span marker # Note, this regex needs to go after backtick fenced # code blocks but it should also be kept outside of the # "if not in span" condition adding backticks to the parser `+ ) }xs'; $depth = 0; // Current depth inside the tag tree. $parsed = ""; // Parsed text that will be returned. // Loop through every tag until we find the closing tag of the parent // or loop until reaching the end of text if no parent tag specified. do { // Split the text using the first $tag_match pattern found. // Text before pattern will be first in the array, text after // pattern will be at the end, and between will be any catches made // by the pattern. $parts = preg_split($block_tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); // If in Markdown span mode, add a empty-string span-level hash // after each newline to prevent triggering any block element. if ($span) { $void = $this->hashPart("", ':'); $newline = "\n$void"; $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void; } $parsed .= $parts[0]; // Text before current tag. // If end of $text has been reached. Stop loop. if (count($parts) < 3) { $text = ""; break; } $tag = $parts[1]; // Tag to handle. $text = $parts[2]; // Remaining text after current tag. // Check for: Fenced code block marker. // Note: need to recheck the whole tag to disambiguate backtick // fences from code spans if (preg_match('{^\n?([ ]{0,' . ($indent + 3) . '})(~{3,}|`{3,})[ ]*(?:\.?[-_:a-zA-Z0-9]+)?[ ]*(?:' . $this->id_class_attr_nocatch_re . ')?[ ]*\n?$}', $tag, $capture)) { // Fenced code block marker: find matching end marker. $fence_indent = strlen($capture[1]); // use captured indent in re $fence_re = $capture[2]; // use captured fence in re if (preg_match('{^(?>.*\n)*?[ ]{' . ($fence_indent) . '}' . $fence_re . '[ ]*(?:\n|$)}', $text, $matches)) { // End marker found: pass text unchanged until marker. $parsed .= $tag . $matches[0]; $text = substr($text, strlen($matches[0])); } else { // No end marker: just skip it. $parsed .= $tag; } } // Check for: Indented code block. else if ($tag[0] === "\n" || $tag[0] === " ") { // Indented code block: pass it unchanged, will be handled // later. $parsed .= $tag; } // Check for: Code span marker // Note: need to check this after backtick fenced code blocks else if ($tag[0] === "`") { // Find corresponding end marker. $tag_re = preg_quote($tag); if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)' . $tag_re . '(?!`)}', $text, $matches)) { // End marker found: pass text unchanged until marker. $parsed .= $tag . $matches[0]; $text = substr($text, strlen($matches[0])); } else { // Unmatched marker: just skip it. $parsed .= $tag; } } // Check for: Opening Block level tag or // Opening Context Block tag (like ins and del) // used as a block tag (tag is alone on it's line). else if (preg_match('{^<(?:' . $this->block_tags_re . ')\b}', $tag) || ( preg_match('{^<(?:' . $this->context_block_tags_re . ')\b}', $tag) && preg_match($newline_before_re, $parsed) && preg_match($newline_after_re, $text) ) ) { // Need to parse tag and following text using the HTML parser. list($block_text, $text) = $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true); // Make sure it stays outside of any paragraph by adding newlines. $parsed .= "\n\n$block_text\n\n"; } // Check for: Clean tag (like script, math) // HTML Comments, processing instructions. else if (preg_match('{^<(?:' . $this->clean_tags_re . ')\b}', $tag) || $tag[1] === '!' || $tag[1] === '?') { // Need to parse tag and following text using the HTML parser. // (don't check for markdown attribute) list($block_text, $text) = $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false); $parsed .= $block_text; } // Check for: Tag with same name as enclosing tag. else if ($enclosing_tag_re !== '' && // Same name as enclosing tag. preg_match('{^</?(?:' . $enclosing_tag_re . ')\b}', $tag)) { // Increase/decrease nested tag count. if ($tag[1] === '/') { $depth--; } else if ($tag[strlen($tag)-2] !== '/') { $depth++; } if ($depth < 0) { // Going out of parent element. Clean up and break so we // return to the calling function. $text = $tag . $text; break; } $parsed .= $tag; } else { $parsed .= $tag; } } while ($depth >= 0); return array($parsed, $text); } /** * Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags. * * * Calls $hash_method to convert any blocks. * * Stops when the first opening tag closes. * * $md_attr indicate if the use of the `markdown="1"` attribute is allowed. * (it is not inside clean tags) * * Returns an array of that form: ( processed text , remaining text ) * @param string $text * @param string $hash_method * @param bool $md_attr Handle `markdown="1"` attribute * @return array */ protected function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) { if ($text === '') return array('', ''); // Regex to match `markdown` attribute inside of a tag. $markdown_attr_re = ' { \s* # Eat whitespace before the `markdown` attribute markdown \s*=\s* (?> (["\']) # $1: quote delimiter (.*?) # $2: attribute value \1 # matching delimiter | ([^\s>]*) # $3: unquoted attribute value ) () # $4: make $3 always defined (avoid warnings) }xs'; // Regex to match any tag. $tag_re = '{ ( # $2: Capture whole tag. </? # Any opening or closing tag. [\w:$]+ # Tag name. (?: (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name. (?> ".*?" | # Double quotes (can contain `>`) \'.*?\' | # Single quotes (can contain `>`) .+? # Anything but quotes and `>`. )*? )? > # End of tag. | <!-- .*? --> # HTML Comment | <\?.*?\?> | <%.*?%> # Processing instruction | <!\[CDATA\[.*?\]\]> # CData Block ) }xs'; $original_text = $text; // Save original text in case of faliure. $depth = 0; // Current depth inside the tag tree. $block_text = ""; // Temporary text holder for current text. $parsed = ""; // Parsed text that will be returned. $base_tag_name_re = ''; // Get the name of the starting tag. // (This pattern makes $base_tag_name_re safe without quoting.) if (preg_match('/^<([\w:$]*)\b/', $text, $matches)) $base_tag_name_re = $matches[1]; // Loop through every tag until we find the corresponding closing tag. do { // Split the text using the first $tag_match pattern found. // Text before pattern will be first in the array, text after // pattern will be at the end, and between will be any catches made // by the pattern. $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); if (count($parts) < 3) { // End of $text reached with unbalenced tag(s). // In that case, we return original text unchanged and pass the // first character as filtered to prevent an infinite loop in the // parent function. return array($original_text[0], substr($original_text, 1)); } $block_text .= $parts[0]; // Text before current tag. $tag = $parts[1]; // Tag to handle. $text = $parts[2]; // Remaining text after current tag. // Check for: Auto-close tag (like <hr/>) // Comments and Processing Instructions. if (preg_match('{^</?(?:' . $this->auto_close_tags_re . ')\b}', $tag) || $tag[1] === '!' || $tag[1] === '?') { // Just add the tag to the block as if it was text. $block_text .= $tag; } else { // Increase/decrease nested tag count. Only do so if // the tag's name match base tag's. if (preg_match('{^</?' . $base_tag_name_re . '\b}', $tag)) { if ($tag[1] === '/') { $depth--; } else if ($tag[strlen($tag)-2] !== '/') { $depth++; } } // Check for `markdown="1"` attribute and handle it. if ($md_attr && preg_match($markdown_attr_re, $tag, $attr_m) && preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3])) { // Remove `markdown` attribute from opening tag. $tag = preg_replace($markdown_attr_re, '', $tag); // Check if text inside this tag must be parsed in span mode. $mode = $attr_m[2] . $attr_m[3]; $span_mode = $mode === 'span' || ($mode !== 'block' && preg_match('{^<(?:' . $this->contain_span_tags_re . ')\b}', $tag)); // Calculate indent before tag. if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) { $strlen = $this->utf8_strlen; $indent = $strlen($matches[1], 'UTF-8'); } else { $indent = 0; } // End preceding block with this tag. $block_text .= $tag; $parsed .= $this->$hash_method($block_text); // Get enclosing tag name for the ParseMarkdown function. // (This pattern makes $tag_name_re safe without quoting.) preg_match('/^<([\w:$]*)\b/', $tag, $matches); $tag_name_re = $matches[1]; // Parse the content using the HTML-in-Markdown parser. list ($block_text, $text) = $this->_hashHTMLBlocks_inMarkdown($text, $indent, $tag_name_re, $span_mode); // Outdent markdown text. if ($indent > 0) { $block_text = preg_replace("/^[ ]{1,$indent}/m", "", $block_text); } // Append tag content to parsed text. if (!$span_mode) { $parsed .= "\n\n$block_text\n\n"; } else { $parsed .= (string) $block_text; } // Start over with a new block. $block_text = ""; } else $block_text .= $tag; } } while ($depth > 0); // Hash last block text that wasn't processed inside the loop. $parsed .= $this->$hash_method($block_text); return array($parsed, $text); } /** * Called whenever a tag must be hashed when a function inserts a "clean" tag * in $text, it passes through this function and is automaticaly escaped, * blocking invalid nested overlap. * @param string $text * @return string */ protected function hashClean($text) { return $this->hashPart($text, 'C'); } /** * Turn Markdown link shortcuts into XHTML <a> tags. * @param string $text * @return string */ protected function doAnchors($text) { if ($this->in_anchor) { return $text; } $this->in_anchor = true; // First, handle reference-style links: [link text] [id] $text = preg_replace_callback('{ ( # wrap whole match in $1 \[ (' . $this->nested_brackets_re . ') # link text = $2 \] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (.*?) # id = $3 \] ) }xs', array($this, '_doAnchors_reference_callback'), $text); // Next, inline-style links: [link text](url "optional title") $text = preg_replace_callback('{ ( # wrap whole match in $1 \[ (' . $this->nested_brackets_re . ') # link text = $2 \] \( # literal paren [ \n]* (?: <(.+?)> # href = $3 | (' . $this->nested_url_parenthesis_re . ') # href = $4 ) [ \n]* ( # $5 ([\'"]) # quote char = $6 (.*?) # Title = $7 \6 # matching quote [ \n]* # ignore any spaces/tabs between closing quote and ) )? # title is optional \) (?:[ ]? ' . $this->id_class_attr_catch_re . ' )? # $8 = id/class attributes ) }xs', array($this, '_doAnchors_inline_callback'), $text); // Last, handle reference-style shortcuts: [link text] // These must come last in case you've also got [link text][1] // or [link text](/foo) $text = preg_replace_callback('{ ( # wrap whole match in $1 \[ ([^\[\]]+) # link text = $2; can\'t contain [ or ] \] ) }xs', array($this, '_doAnchors_reference_callback'), $text); $this->in_anchor = false; return $text; } /** * Callback for reference anchors * @param array $matches * @return string */ protected function _doAnchors_reference_callback($matches) { $whole_match = $matches[1]; $link_text = $matches[2]; $link_id =& $matches[3]; if ($link_id == "") { // for shortcut links like [this][] or [this]. $link_id = $link_text; } // lower-case and turn embedded newlines into spaces $link_id = strtolower($link_id); $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); if (isset($this->urls[$link_id])) { $url = $this->urls[$link_id]; $url = $this->encodeURLAttribute($url); $result = "<a href=\"$url\""; if ( isset( $this->titles[$link_id] ) ) { $title = $this->titles[$link_id]; $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } if (isset($this->ref_attr[$link_id])) $result .= $this->ref_attr[$link_id]; $link_text = $this->runSpanGamut($link_text); $result .= ">$link_text</a>"; $result = $this->hashPart($result); } else { $result = $whole_match; } return $result; } /** * Callback for inline anchors * @param array $matches * @return string */ protected function _doAnchors_inline_callback($matches) { $link_text = $this->runSpanGamut($matches[2]); $url = $matches[3] === '' ? $matches[4] : $matches[3]; $title_quote =& $matches[6]; $title =& $matches[7]; $attr = $this->doExtraAttributes("a", $dummy =& $matches[8]); // if the URL was of the form <s p a c e s> it got caught by the HTML // tag parser and hashed. Need to reverse the process before using the URL. $unhashed = $this->unhash($url); if ($unhashed !== $url) $url = preg_replace('/^<(.*)>$/', '\1', $unhashed); $url = $this->encodeURLAttribute($url); $result = "<a href=\"$url\""; if (isset($title) && $title_quote) { $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } $result .= $attr; $link_text = $this->runSpanGamut($link_text); $result .= ">$link_text</a>"; return $this->hashPart($result); } /** * Turn Markdown image shortcuts into <img> tags. * @param string $text * @return string */ protected function doImages($text) { // First, handle reference-style labeled images: ![alt text][id] $text = preg_replace_callback('{ ( # wrap whole match in $1 !\[ (' . $this->nested_brackets_re . ') # alt text = $2 \] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (.*?) # id = $3 \] ) }xs', array($this, '_doImages_reference_callback'), $text); // Next, handle inline images: ![alt text](url "optional title") // Don't forget: encode * and _ $text = preg_replace_callback('{ ( # wrap whole match in $1 !\[ (' . $this->nested_brackets_re . ') # alt text = $2 \] \s? # One optional whitespace character \( # literal paren [ \n]* (?: <(\S*)> # src url = $3 | (' . $this->nested_url_parenthesis_re . ') # src url = $4 ) [ \n]* ( # $5 ([\'"]) # quote char = $6 (.*?) # title = $7 \6 # matching quote [ \n]* )? # title is optional \) (?:[ ]? ' . $this->id_class_attr_catch_re . ' )? # $8 = id/class attributes ) }xs', array($this, '_doImages_inline_callback'), $text); return $text; } /** * Callback for referenced images * @param array $matches * @return string */ protected function _doImages_reference_callback($matches) { $whole_match = $matches[1]; $alt_text = $matches[2]; $link_id = strtolower($matches[3]); if ($link_id === "") { $link_id = strtolower($alt_text); // for shortcut links like ![this][]. } $alt_text = $this->encodeAttribute($alt_text); if (isset($this->urls[$link_id])) { $url = $this->encodeURLAttribute($this->urls[$link_id]); $result = "<img src=\"$url\" alt=\"$alt_text\""; if (isset($this->titles[$link_id])) { $title = $this->titles[$link_id]; $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; } if (isset($this->ref_attr[$link_id])) { $result .= $this->ref_attr[$link_id]; } $result .= $this->empty_element_suffix; $result = $this->hashPart($result); } else { // If there's no such link ID, leave intact: $result = $whole_match; } return $result; } /** * Callback for inline images * @param array $matches * @return string */ protected function _doImages_inline_callback($matches) { $alt_text = $matches[2]; $url = $matches[3] === '' ? $matches[4] : $matches[3]; $title_quote =& $matches[6]; $title =& $matches[7]; $attr = $this->doExtraAttributes("img", $dummy =& $matches[8]); $alt_text = $this->encodeAttribute($alt_text); $url = $this->encodeURLAttribute($url); $result = "<img src=\"$url\" alt=\"$alt_text\""; if (isset($title) && $title_quote) { $title = $this->encodeAttribute($title); $result .= " title=\"$title\""; // $title already quoted } $result .= $attr; $result .= $this->empty_element_suffix; return $this->hashPart($result); } /** * Process markdown headers. Redefined to add ID and class attribute support. * @param string $text * @return string */ protected function doHeaders($text) { // Setext-style headers: // Header 1 {#header1} // ======== // // Header 2 {#header2 .class1 .class2} // -------- // $text = preg_replace_callback( '{ (^.+?) # $1: Header text (?:[ ]+ ' . $this->id_class_attr_catch_re . ' )? # $3 = id/class attributes [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer }mx', array($this, '_doHeaders_callback_setext'), $text); // atx-style headers: // # Header 1 {#header1} // ## Header 2 {#header2} // ## Header 2 with closing hashes ## {#header3.class1.class2} // ... // ###### Header 6 {.class2} // $text = preg_replace_callback('{ ^(\#{1,6}) # $1 = string of #\'s [ ]'.($this->hashtag_protection ? '+' : '*').' (.+?) # $2 = Header text [ ]* \#* # optional closing #\'s (not counted) (?:[ ]+ ' . $this->id_class_attr_catch_re . ' )? # $3 = id/class attributes [ ]* \n+ }xm', array($this, '_doHeaders_callback_atx'), $text); return $text; } /** * Callback for setext headers * @param array $matches * @return string */ protected function _doHeaders_callback_setext($matches) { if ($matches[3] === '-' && preg_match('{^- }', $matches[1])) { return $matches[0]; } $level = $matches[3][0] === '=' ? 1 : 2; $defaultId = is_callable($this->header_id_func) ? call_user_func($this->header_id_func, $matches[1]) : null; $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[2], $defaultId); $block = "<h$level$attr>" . $this->runSpanGamut($matches[1]) . "</h$level>"; return "\n" . $this->hashBlock($block) . "\n\n"; } /**
php
MIT
d98486580d3ebb0709c03e6c1b04998a33d37d2b
2026-01-05T05:13:32.288033Z
true
panicsteve/w2wiki
https://github.com/panicsteve/w2wiki/blob/d98486580d3ebb0709c03e6c1b04998a33d37d2b/Michelf/Markdown.inc.php
Michelf/Markdown.inc.php
<?php // Use this file if you cannot use class autoloading. It will include all the // files needed for the Markdown parser. // // Take a look at the PSR-0-compatible class autoloading implementation // in the Readme.php file if you want a simple autoloader setup. require_once dirname(__FILE__) . '/MarkdownInterface.php'; require_once dirname(__FILE__) . '/Markdown.php';
php
MIT
d98486580d3ebb0709c03e6c1b04998a33d37d2b
2026-01-05T05:13:32.288033Z
false
willdurand/Propilex
https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/app/stack.php
app/stack.php
<?php return (new Stack\Builder()) ->push('Negotiation\Stack\Negotiation', $app['format.negotiator']) ->push('Asm89\Stack\Cors', [ 'allowedOrigins' => [ '*' ], ]) ->resolve($app);
php
MIT
c983bed65d1cef3ff1bb635cda6c1cb02452cf18
2026-01-05T05:13:52.563402Z
false
willdurand/Propilex
https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/app/build.php
app/build.php
<?php require_once __DIR__.'/../vendor/autoload.php'; Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists'); use Hateoas\Serializer\XmlHalSerializer; use Hateoas\Representation\Factory\PagerfantaFactory; use Hateoas\UrlGenerator\SymfonyUrlGenerator; use Hautelook\TemplatedUriRouter\Routing\Generator\Rfc6570Generator; use Propilex\Model\Document; use Propilex\Model\DocumentQuery; use Propilex\Model\Repository\PropelDocumentRepository; use Propilex\View\Error; use Propilex\View\FormErrors; use Propilex\View\ViewHandler; use Propilex\Hateoas\CuriesConfigurationExtension; use Propilex\Hateoas\TransExpressionFunction; use Propilex\Hateoas\VndErrorRepresentation; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Validator\Mapping\ClassMetadataFactory; use Symfony\Component\Validator\Mapping\Loader\YamlFileLoader; $app = new Silex\Application(); // Providers $app->register(new Silex\Provider\ValidatorServiceProvider()); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Propel\Silex\PropelServiceProvider(), array( 'propel.config_file' => __DIR__ . '/config/propel/propilex.php', 'propel.model_path' => __DIR__ . '/../src/Propilex/Model', )); // Configure the validator service $app['validator.mapping.class_metadata_factory'] = new ClassMetadataFactory( new YamlFileLoader(__DIR__ . '/config/validation.yml') ); // Configure Hateoas serializer $app['serializer'] = $app->share(function () use ($app) { $jmsSerializerBuilder = JMS\Serializer\SerializerBuilder::create() ->setMetadataDirs(array( '' => __DIR__ . '/config/serializer', 'Propilex' => __DIR__ . '/config/serializer', )) ->setDebug($app['debug']) ->setCacheDir(__DIR__ . '/cache/serializer') ; return Hateoas\HateoasBuilder::create($jmsSerializerBuilder) ->setMetadataDirs(array( '' => __DIR__ . '/config/serializer', 'Propilex' => __DIR__ . '/config/serializer', )) ->setDebug($app['debug']) ->setCacheDir(__DIR__ . '/cache/hateoas') ->setUrlGenerator(null, new SymfonyUrlGenerator($app['url_generator'])) ->setUrlGenerator('templated', new SymfonyUrlGenerator($app['templated_uri_generator'])) ->setXmlSerializer(new XmlHalSerializer()) ->addConfigurationExtension(new CuriesConfigurationExtension( $app['curies_route_name'], 'templated' )) ->setExpressionContextVariable('curies_prefix', $app['curies_prefix']) ->registerExpressionFunction(new TransExpressionFunction($app['translator'])) ->build(); }); $app['hateoas.pagerfanta_factory'] = $app->share(function () use ($app) { return new PagerfantaFactory(); }); // Translation $app->register(new Silex\Provider\TranslationServiceProvider()); $app->before(function (Request $request) use ($app) { $validatorFile = __DIR__ . '/../vendor/symfony/validator/Symfony/Component/Validator/Resources/translations/validators.%s.xlf'; $locale = $request->attributes->get('_language', 'en'); $app['translator']->setLocale($locale); $app['translator']->addLoader('xlf', new Symfony\Component\Translation\Loader\XliffFileLoader()); $app['translator']->addResource('xlf', sprintf($validatorFile, $locale), $locale, 'validators'); $messagesLocale = $locale; if (!is_file($messagesFile = __DIR__ . '/config/messages.' . $messagesLocale . '.yml')) { $messagesFile = sprintf(__DIR__ . '/config/messages.%s.yml', $app['translation.fallback']); $messagesLocale = $app['translation.fallback']; } $app['translator']->addLoader('yml', new Symfony\Component\Translation\Loader\YamlFileLoader()); $app['translator']->addResource('yml', $messagesFile, $messagesLocale); }); $app['templated_uri_generator'] = $app->share(function () use ($app) { return new Rfc6570Generator($app['routes'], $app['request_context']); }); // Markdown $app->register(new Nicl\Silex\MarkdownServiceProvider()); // Negotiation $app->register(new KPhoen\Provider\NegotiationServiceProvider([ 'json' => [ 'application/hal+json', 'application/json' ], 'xml' => [ 'application/hal+xml', 'application/xml' ], ])); // Document validator $app['document_validator'] = $app->protect(function (Document $document) use ($app) { $errors = $app['validator']->validate($document); if (0 < count($errors)) { return new FormErrors($errors); } return true; }); // View $app['view_handler'] = $app->share(function () use ($app) { return new ViewHandler($app['serializer'], $app['request'], $app['acceptable_mime_types']); }); // Error handler $app->error(function (\Exception $e, $code) use ($app) { if (405 === $code) { return new Response($e->getMessage(), 405, array_merge( $e->getHeaders(), [ 'Content-Type' => 'text/plain' ] )); } if (406 === $code) { return new Response($e->getMessage(), 406, [ 'Content-Type' => 'text/plain' ]); } return $app['view_handler']->handle( new VndErrorRepresentation($e->getMessage()), $code ); }); // Model Layer $app['document_repository'] = $app->share(function () { return new PropelDocumentRepository(DocumentQuery::create()); }); return $app;
php
MIT
c983bed65d1cef3ff1bb635cda6c1cb02452cf18
2026-01-05T05:13:52.563402Z
false
willdurand/Propilex
https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/app/propilex.php
app/propilex.php
<?php $app = require __DIR__ . '/build.php'; // Config $app['debug'] = 'dev' === getenv('APPLICATION_ENV'); $app['translation.fallback'] = 'en'; $app['acceptable_mime_types'] = [ 'application/hal+xml', 'application/hal+json' ]; $app['curies_prefix'] = 'p'; $app['curies_route_name'] = 'curies_get'; /** * Entry point */ $app ->get('/', 'Propilex\Controller\HomeController::indexAction') ->bind('home'); /** * Documents */ $app ->get('/documents', 'Propilex\Controller\DocumentController::listAction') ->bind('document_list'); $app ->get('/documents/{id}', 'Propilex\Controller\DocumentController::getAction') ->assert('id', '\d+') ->bind('document_get'); $app ->post('/documents', 'Propilex\Controller\DocumentController::postAction') ->bind('document_post'); $app ->put('/documents/{id}', 'Propilex\Controller\DocumentController::putAction') ->assert('id', '\d+') ->bind('document_put'); $app ->delete('/documents/{id}', 'Propilex\Controller\DocumentController::deleteAction') ->assert('id', '\d+') ->bind('document_delete'); /** * Curies */ $app->get('/rels/{rel}', function ($rel) use ($app) { if (is_file($file = sprintf(__DIR__ . '/../src/Propilex/Resources/%s.md', $rel))) { return $app['markdown']->transformMarkdown(file_get_contents($file)); } $app->abort(404); })->bind($app['curies_route_name']); return $app;
php
MIT
c983bed65d1cef3ff1bb635cda6c1cb02452cf18
2026-01-05T05:13:52.563402Z
false