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
8namespace Tiki\Command;
9
10use Symfony\Component\Console\Command\Command;
11use Symfony\Component\Console\Input\InputInterface;
12use Symfony\Component\Console\Output\OutputInterface;
13use Symfony\Component\Console\Input\InputArgument;
14use Symfony\Component\Console\Command\HelpCommand;
15use Exception;
16use Symfony\Component\Console\Formatter\OutputFormatterStyle;
17
18class OCRFileCommand extends Command
19{
20	protected function configure()
21	{
22		$this
23			->setName('ocr:file')
24			->setDescription(
25				'Attempt to OCR a file. Defaults to queued OCR job'
26			)
27			->addArgument(
28				'File ID',
29				InputArgument::OPTIONAL,
30				'File ID of the file to OCR.');
31	}
32
33	protected function execute(InputInterface $input, OutputInterface $output)
34	{
35		$ocrLib = \TikiLib::lib('ocr');
36		$outputStyle = new OutputFormatterStyle('red');
37		$output->getFormatter()->setStyle('error', $outputStyle);
38
39		try {
40			$ocrLib->checkOCRDependencies();
41		} catch (Exception $e) {
42			$output->writeln(
43				'<error>' . $e->getMessage() . '</error>');
44			return;
45		}
46
47		// Set $nextOCRFile with the fileid of the next file scheduled to be processed by the OCR engine.
48		$ocrLib->nextOCRFile = $ocrLib->table('tiki_files')->fetchOne('fileId', ['ocr_state' => $ocrLib::OCR_STATUS_PENDING]);
49
50		$fgalId = $input->getArgument('File ID');
51		if ($fgalId) {
52			if (preg_match('/^\d+$/', $fgalId)) {
53				$ocrLib->nextOCRFile = (int)$fgalId;
54			} else {
55				$help = new HelpCommand();
56				$help->setCommand($this);
57				$help->run($input, $output);
58				$output->writeln(
59					"<error>File ID must be an int, $fgalId is an illegal value."
60				);
61				return;
62			}
63		}
64
65		if (! $ocrLib->nextOCRFile) {
66			$output->writeln('<comment>No files to OCR</comment>');
67			return;
68		}
69
70		try {
71			$ocrLib->checkFileGalID();
72		} catch (Exception $e) {
73			$output->writeln('<error>' . $e->getMessage() . '</error>');
74			return;
75		}
76
77		try {
78			$ocrLib->OCRfile();
79			$output->writeln('<comment>Finished OCR of file</comment>');
80		} catch (Exception $e) {
81			$output->writeln('<error>' . $e->getMessage() . '</error>');
82		}
83	}
84}
85