1<?php
2// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project
3//
4// All Rights Reserved. See copyright.txt for details and a complete list of authors.
5// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
6// $Id$
7
8use Symfony\Component\Console\Input\ArgvInput;
9use Symfony\Component\Console\Output\BufferedOutput;
10use Tiki\Command\Application;
11
12class Scheduler_Task_ConsoleCommandTask extends Scheduler_Task_CommandTask
13{
14
15	public function execute($params = null)
16	{
17		if (empty($params['console_command'])) {
18			$this->errorMessage = tra('Missing parameters to run the command.');
19			return false;
20		}
21
22		$this->logger->debug(sprintf(tra('Executing console command: %s'), $params['console_command']));
23
24		$consoleParams = 'console.php ' . $params['console_command'];
25		$args = $this->parseConsoleParams($consoleParams);
26
27		$commandName = $args[1];
28
29		try {
30			$consoleBuilder = new Tiki\Command\ConsoleApplicationBuilder(
31				isset($_SERVER['TIKI_VIRTUAL']) ? $_SERVER['TIKI_VIRTUAL'] : ''
32			);
33			$console = $consoleBuilder->create(true);
34
35			$command = $console->find($commandName);
36
37			$input = new ArgvInput($args);
38			$input->setInteractive(false);
39
40			$output = new BufferedOutput();
41			$statusCode = $command->run($input, $output);
42
43			$content = $output->fetch();
44			$this->errorMessage = $content;
45
46			return $statusCode === 0;
47		} catch (Exception $e) {
48			$this->errorMessage = $e->getMessage();
49
50			return false;
51		}
52	}
53
54	private function parseConsoleParams($params)
55	{
56
57		preg_match_all('/(?<=^|\s)([\'"]?)(.+?)(?<!\\\\)\1(?=$|\s)/', $params, $args);
58
59		return $args[2];
60	}
61
62	public function getParams()
63	{
64		return [
65			'console_command' => [
66				'name' => tra('Console command'),
67				'type' => 'textarea',
68				'required' => true,
69			],
70		];
71	}
72}
73