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\Helper\ProgressBar;
14use Exception;
15use Symfony\Component\Console\Formatter\OutputFormatterStyle;
16
17
18class OCRAllCommand extends Command
19{
20	protected function configure()
21	{
22		$this
23			->setName('ocr:all')
24			->setDescription('OCR all queued files');
25	}
26
27	protected function execute(InputInterface $input, OutputInterface $output)
28	{
29		$ocrLib = \TikiLib::lib('ocr');
30		$outputStyle = new OutputFormatterStyle('red');
31		$output->getFormatter()->setStyle('error', $outputStyle);
32
33		try {
34			$ocrLib->checkOCRDependencies();
35		} catch (Exception $e) {
36			$output->writeln(
37				'<error>' . $e->getMessage() . '</error>');
38			return;
39		}
40
41		//Retrieve the number of files marked as waiting to be processed.
42		$db = $ocrLib->table('tiki_files');
43		$queueCount = $db->fetchCount(
44			['ocr_state' => $ocrLib::OCR_STATUS_PENDING]
45		);
46
47		$progress = new ProgressBar($output, $queueCount + 1);
48		if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
49			$progress->setOverwrite(false);
50		}
51		$progress->setFormatDefinition(
52			'custom', ' %current%/%max% [%bar%] -- %message%'
53		);
54		$progress->setFormat('custom');
55		$progress->setMessage('Preparatory checks');
56		$progress->start();
57		$OCRCount = 0;
58
59		// release old files that might have died while processing, and report as error
60		$processingNum = $ocrLib->releaseAllProcessing();
61		if ($processingNum) {
62			$progress->setMessage(
63				"<comment>Reset processing files, run again to perform OCR.</comment>\n"
64			);
65			$progress->finish();
66			return;
67		}
68
69		$ocrLib->setNextOCRFile();
70
71		if (! $ocrLib->nextOCRFile) {
72			$progress->setMessage("<comment>No files to OCR</comment>\n");
73			$progress->finish();
74			return;
75		}
76
77		while ($ocrLib->nextOCRFile) {
78			try {
79				$progress->setMessage('OCR processing file id ' . $ocrLib->nextOCRFile);
80				$progress->advance();
81				$ocrLib->OCRfile();
82				$output->write(': done');
83				$OCRCount++;
84			} catch (Exception $e) {
85				$output->write(': <error>failed</error>');
86				$output->write(": <error>" . $e->getMessage() . '</error>', OutputInterface::VERBOSITY_DEBUG);
87			}
88		}
89		$progress->setMessage(
90			"<comment>Finished the OCR of $OCRCount files.</comment>\n"
91		);
92		$progress->finish();
93	}
94}
95