| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Shell; |
| 4 |
|
| 5 |
use GuzzleHttp\Psr7\Uri; |
| 6 |
use GuzzleHttp\RequestOptions; |
| 7 |
use MediaWiki\Http\HttpRequestFactory; |
| 8 |
use RuntimeException; |
| 9 |
use Shellbox\Client; |
| 10 |
use Shellbox\RPC\LocalRpcClient; |
| 11 |
use Shellbox\RPC\RpcClient; |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
class ShellboxClientFactory { |
| 20 |
|
| 21 |
private $requestFactory; |
| 22 |
|
| 23 |
private $urls; |
| 24 |
|
| 25 |
private $key; |
| 26 |
|
| 27 |
|
| 28 |
public const DEFAULT_TIMEOUT = 10; |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
public function __construct( HttpRequestFactory $requestFactory, $urls, $key ) { |
| 38 |
$this->requestFactory = $requestFactory; |
| 39 |
$this->urls = $urls; |
| 40 |
$this->key = $key; |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
public function isEnabled( ?string $service = null ): bool { |
| 50 |
return $this->getUrl( $service ) !== null; |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
public function getClient( array $options = [] ) { |
| 64 |
$url = $this->getUrl( $options['service'] ?? null ); |
| 65 |
if ( $url === null ) { |
| 66 |
throw new RuntimeException( 'To use a remote shellbox to run shell commands, ' . |
| 67 |
'$wgShellboxUrls and $wgShellboxSecretKey must be configured.' ); |
| 68 |
} |
| 69 |
|
| 70 |
return new Client( |
| 71 |
$this->requestFactory->createGuzzleClient( [ |
| 72 |
RequestOptions::TIMEOUT => $options['timeout'] ?? self::DEFAULT_TIMEOUT, |
| 73 |
RequestOptions::HTTP_ERRORS => false, |
| 74 |
] ), |
| 75 |
new Uri( $url ), |
| 76 |
$this->key, |
| 77 |
[ 'allowUrlFiles' => true ] |
| 78 |
); |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
public function getRemoteRpcClient( array $options = [] ): RpcClient { |
| 92 |
return $this->getClient( $options ); |
| 93 |
} |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
public function getRpcClient( array $options = [] ): RpcClient { |
| 103 |
$url = $this->getUrl( $options['service'] ?? null ); |
| 104 |
if ( $url === null ) { |
| 105 |
return new LocalRpcClient(); |
| 106 |
} |
| 107 |
return $this->getRemoteRpcClient( $options ); |
| 108 |
} |
| 109 |
|
| 110 |
private function getUrl( ?string $service ): ?string { |
| 111 |
if ( $this->urls === null || $this->key === null || $this->key === '' ) { |
| 112 |
return null; |
| 113 |
} |
| 114 |
$url = $this->urls[$service ?? ''] ?? $this->urls['default'] ?? null; |
| 115 |
if ( !is_string( $url ) ) { |
| 116 |
return null; |
| 117 |
} |
| 118 |
return $url; |
| 119 |
} |
| 120 |
|
| 121 |
} |