xref: /plugin/combo/cli.php (revision edc352032a4ffea72ccdb7a3672675723bbf6d3b)
1007225e5Sgerardnico<?php
2007225e5Sgerardnico/**
3007225e5Sgerardnico * Copyright (c) 2021. ComboStrap, Inc. and its affiliates. All Rights Reserved.
4007225e5Sgerardnico *
5007225e5Sgerardnico * This source code is licensed under the GPL license found in the
6007225e5Sgerardnico * COPYING  file in the root directory of this source tree.
7007225e5Sgerardnico *
8007225e5Sgerardnico * @license  GPL 3 (https://www.gnu.org/licenses/gpl-3.0.en.html)
9007225e5Sgerardnico * @author   ComboStrap <support@combostrap.com>
10007225e5Sgerardnico *
11007225e5Sgerardnico */
12007225e5Sgerardnico
13*edc35203Sgerardnicouse ComboStrap\ExceptionNotExists;
14*edc35203Sgerardnicouse ComboStrap\ExecutionContext;
1504fd306cSNickeauuse ComboStrap\Meta\Field\BacklinkCount;
16c3437056SNickeauuse ComboStrap\Event;
1704fd306cSNickeauuse ComboStrap\ExceptionBadSyntax;
1804fd306cSNickeauuse ComboStrap\ExceptionCompile;
1904fd306cSNickeauuse ComboStrap\ExceptionNotFound;
2004fd306cSNickeauuse ComboStrap\ExceptionRuntime;
2137748cd8SNickeauuse ComboStrap\FsWikiUtility;
22c3437056SNickeauuse ComboStrap\LogUtility;
2304fd306cSNickeauuse ComboStrap\MarkupPath;
2404fd306cSNickeauuse ComboStrap\Meta\Field\PageH1;
25c3437056SNickeauuse ComboStrap\MetadataFrontmatterStore;
2671f916b9Sgerardnicouse ComboStrap\Sqlite;
27007225e5Sgerardnicouse splitbrain\phpcli\Options;
28007225e5Sgerardnico
29e8b2ff59SNickeau/**
3004fd306cSNickeau * All dependency are loaded
31e8b2ff59SNickeau */
3204fd306cSNickeaurequire_once(__DIR__ . '/vendor/autoload.php');
33007225e5Sgerardnico
34007225e5Sgerardnico/**
35007225e5Sgerardnico * The memory of the server 128 is not enough
36007225e5Sgerardnico */
37007225e5Sgerardnicoini_set('memory_limit', '256M');
38007225e5Sgerardnico
39c3437056SNickeau
40007225e5Sgerardnico/**
41007225e5Sgerardnico * Class cli_plugin_combo
42007225e5Sgerardnico *
43007225e5Sgerardnico * This is a cli:
44007225e5Sgerardnico * https://www.dokuwiki.org/devel:cli_plugins#example
45007225e5Sgerardnico *
46007225e5Sgerardnico * Usage:
47007225e5Sgerardnico *
48007225e5Sgerardnico * ```
49007225e5Sgerardnico * docker exec -ti $(CONTAINER) /bin/bash
50c3437056SNickeau * ```
51c3437056SNickeau * ```
52c3437056SNickeau * set animal=animal-directory-name
53c3437056SNickeau * php ./bin/plugin.php combo --help
54007225e5Sgerardnico * ```
55007225e5Sgerardnico * or via the IDE
56007225e5Sgerardnico *
57007225e5Sgerardnico *
58007225e5Sgerardnico * Example:
59007225e5Sgerardnico * https://www.dokuwiki.org/tips:grapher
60007225e5Sgerardnico *
61007225e5Sgerardnico */
62007225e5Sgerardnicoclass cli_plugin_combo extends DokuWiki_CLI_Plugin
63007225e5Sgerardnico{
64c3437056SNickeau
65c3437056SNickeau    const METADATA_TO_DATABASE = "metadata-to-database";
6671f916b9Sgerardnico    const ANALYTICS = "analytics";
67c3437056SNickeau    const METADATA_TO_FRONTMATTER = "metadata-to-frontmatter";
6871f916b9Sgerardnico    const SYNC = "sync";
69c3437056SNickeau    const PLUGINS_TO_UPDATE = "plugins-to-update";
70c3437056SNickeau    const FORCE_OPTION = 'force';
71c3437056SNickeau    const PORT_OPTION = 'port';
72c3437056SNickeau    const HOST_OPTION = 'host';
73*edc35203Sgerardnico    const CANONICAL = "combo-cli";
74c3437056SNickeau
75007225e5Sgerardnico
76007225e5Sgerardnico    /**
77007225e5Sgerardnico     * register options and arguments
78007225e5Sgerardnico     * @param Options $options
7982a60d03SNickeau     *
8082a60d03SNickeau     * Note the animal is set in {@link DokuWikiFarmCore::detectAnimal()}
8182a60d03SNickeau     * via the environment variable `animal` that is passed in the $_SERVER variable
82007225e5Sgerardnico     */
83007225e5Sgerardnico    protected function setup(Options $options)
84007225e5Sgerardnico    {
85c3437056SNickeau        $help = <<<EOF
86c3437056SNickeauComboStrap Administrative Commands
87c3437056SNickeau
88c3437056SNickeau
89c3437056SNickeauExample:
90c3437056SNickeau  * Replicate all pages into the database
91c3437056SNickeau```bash
9204fd306cSNickeauphp ./bin/plugin.php combo metadata-to-database --host serverHostName  --port 80 :
93c3437056SNickeau# or
9404fd306cSNickeauphp ./bin/plugin.php combo metadata-to-database --host serverHostName  --port 80 /
95c3437056SNickeau```
96c3437056SNickeau  * Replicate only the page `:namespace:my-page`
97c3437056SNickeau```bash
9804fd306cSNickeauphp ./bin/plugin.php combo metadata-to-database --host serverHostName  --port 80 :namespace:my-page
99c3437056SNickeau# or
10004fd306cSNickeauphp ./bin/plugin.php combo metadata-to-database --host serverHostName  --port 80 /namespace/my-page
101c3437056SNickeau```
102c3437056SNickeau
103c3437056SNickeauAnimal: If you want to use it for an animal farm, you need to set first the animal directory name in a environment variable
104c3437056SNickeau```bash
1054cadd4f8SNickeauanimal=animal-directory-name php ./bin/plugin.php combo
106c3437056SNickeau```
107c3437056SNickeau
108c3437056SNickeauEOF;
109c3437056SNickeau
110c3437056SNickeau        $options->setHelp($help);
111007225e5Sgerardnico        $options->registerOption('version', 'print version', 'v');
112c3437056SNickeau        $options->registerCommand(self::METADATA_TO_DATABASE, "Replicate the file system metadata into the database");
113c3437056SNickeau        $options->registerCommand(self::ANALYTICS, "Start the analytics and export optionally the data");
114c3437056SNickeau        $options->registerCommand(self::PLUGINS_TO_UPDATE, "List the plugins to update");
115c3437056SNickeau        $options->registerCommand(self::METADATA_TO_FRONTMATTER, "Replicate the file system metadata into the page frontmatter");
116c3437056SNickeau        $options->registerCommand(self::SYNC, "Delete the non-existing pages in the database");
117c3437056SNickeau        $options->registerArgument(
118c3437056SNickeau            'path',
119c3437056SNickeau            "The start path (a page or a directory). For all pages, type the root directory '/'",
120c3437056SNickeau            false
12171f916b9Sgerardnico        );
122007225e5Sgerardnico        $options->registerOption(
123007225e5Sgerardnico            'output',
124007225e5Sgerardnico            "Optional, where to store the analytical data as csv eg. a filename.",
125c3437056SNickeau            'o',
126c3437056SNickeau            true
127c3437056SNickeau        );
128007225e5Sgerardnico        $options->registerOption(
129c3437056SNickeau            self::HOST_OPTION,
130c3437056SNickeau            "The http host name of your server. This value is used by dokuwiki in the rendering cache key",
131c3437056SNickeau            null,
132c3437056SNickeau            true,
133c3437056SNickeau            self::METADATA_TO_DATABASE
134c3437056SNickeau        );
135c3437056SNickeau        $options->registerOption(
136c3437056SNickeau            self::PORT_OPTION,
137c3437056SNickeau            "The http host port of your server. This value is used by dokuwiki in the rendering cache key",
138c3437056SNickeau            null,
139c3437056SNickeau            true,
140c3437056SNickeau            self::METADATA_TO_DATABASE
141c3437056SNickeau        );
142c3437056SNickeau        $options->registerOption(
143c3437056SNickeau            self::FORCE_OPTION,
144c3437056SNickeau            "Replicate with force",
145c3437056SNickeau            'f',
146c3437056SNickeau            false,
147c3437056SNickeau            self::METADATA_TO_DATABASE
148c3437056SNickeau        );
14971f916b9Sgerardnico        $options->registerOption(
15071f916b9Sgerardnico            'dry',
15171f916b9Sgerardnico            "Optional, dry-run",
15271f916b9Sgerardnico            'd', false);
153c3437056SNickeau
154007225e5Sgerardnico
155007225e5Sgerardnico    }
156007225e5Sgerardnico
157007225e5Sgerardnico    /**
158007225e5Sgerardnico     * The main entry
159007225e5Sgerardnico     * @param Options $options
16004fd306cSNickeau     * @throws ExceptionCompile
161007225e5Sgerardnico     */
162007225e5Sgerardnico    protected function main(Options $options)
163007225e5Sgerardnico    {
164007225e5Sgerardnico
165007225e5Sgerardnico
16682a60d03SNickeau        if (isset($_REQUEST['animal'])) {
1674cadd4f8SNickeau            // on linux
16882a60d03SNickeau            echo "Animal detected: " . $_REQUEST['animal'] . "\n";
16982a60d03SNickeau        } else {
1704cadd4f8SNickeau            // on windows
17182a60d03SNickeau            echo "No Animal detected\n";
17282a60d03SNickeau            echo "Conf: " . DOKU_CONF . "\n";
17382a60d03SNickeau        }
17482a60d03SNickeau
175c3437056SNickeau        $args = $options->getArgs();
176c3437056SNickeau
177c3437056SNickeau
17871f916b9Sgerardnico        $depth = $options->getOpt('depth', 0);
17921913ab3SNickeau        $cmd = $options->getCmd();
18021913ab3SNickeau        switch ($cmd) {
181c3437056SNickeau            case self::METADATA_TO_DATABASE:
182c3437056SNickeau                $startPath = $this->getStartPath($args);
183c3437056SNickeau                $force = $options->getOpt(self::FORCE_OPTION, false);
184c3437056SNickeau                $hostOptionValue = $options->getOpt(self::HOST_OPTION, null);
185c3437056SNickeau                if ($hostOptionValue === null) {
186c3437056SNickeau                    fwrite(STDERR, "The host name is mandatory");
187c3437056SNickeau                    return;
188c3437056SNickeau                }
189c3437056SNickeau                $_SERVER['HTTP_HOST'] = $hostOptionValue;
190c3437056SNickeau                $portOptionName = $options->getOpt(self::PORT_OPTION, null);
191c3437056SNickeau                if ($portOptionName === null) {
192c3437056SNickeau                    fwrite(STDERR, "The host port is mandatory");
193c3437056SNickeau                    return;
194c3437056SNickeau                }
195c3437056SNickeau                $_SERVER['SERVER_PORT'] = $portOptionName;
196c3437056SNickeau                $this->index($startPath, $force, $depth);
197c3437056SNickeau                break;
198c3437056SNickeau            case self::METADATA_TO_FRONTMATTER:
199c3437056SNickeau                $startPath = $this->getStartPath($args);
200c3437056SNickeau                $this->frontmatter($startPath, $depth);
201c3437056SNickeau                break;
20271f916b9Sgerardnico            case self::ANALYTICS:
203c3437056SNickeau                $startPath = $this->getStartPath($args);
204007225e5Sgerardnico                $output = $options->getOpt('output', '');
205007225e5Sgerardnico                //if ($output == '-') $output = 'php://stdout';
206c3437056SNickeau                $this->analytics($startPath, $output, $depth);
20771f916b9Sgerardnico                break;
20871f916b9Sgerardnico            case self::SYNC:
209c3437056SNickeau                $this->deleteNonExistingPageFromDatabase();
210c3437056SNickeau                break;
211c3437056SNickeau            case self::PLUGINS_TO_UPDATE:
212c3437056SNickeau                /**
213c3437056SNickeau                 * Endpoint:
214c3437056SNickeau                 * self::EXTENSION_REPOSITORY_API.'?fmt=php&ext[]='.urlencode($name)
215c3437056SNickeau                 * `http://www.dokuwiki.org/lib/plugins/pluginrepo/api.php?fmt=php&ext[]=`.urlencode($name)
216c3437056SNickeau                 */
217c3437056SNickeau                $pluginList = plugin_list('', true);
218c3437056SNickeau                /* @var helper_plugin_extension_extension $extension */
219c3437056SNickeau                $extension = $this->loadHelper('extension_extension');
220c3437056SNickeau                foreach ($pluginList as $name) {
221c3437056SNickeau                    $extension->setExtension($name);
222c3437056SNickeau                    if ($extension->updateAvailable()) {
223c3437056SNickeau                        echo "The extension $name should be updated";
224c3437056SNickeau                    }
225c3437056SNickeau                }
22671f916b9Sgerardnico                break;
22771f916b9Sgerardnico            default:
228c3437056SNickeau                if ($cmd !== "") {
229c3437056SNickeau                    fwrite(STDERR, "Combo: Command unknown (" . $cmd . ")");
230c3437056SNickeau                } else {
231c3437056SNickeau                    echo $options->help();
232c3437056SNickeau                }
233c3437056SNickeau                exit(1);
23471f916b9Sgerardnico        }
235007225e5Sgerardnico
236007225e5Sgerardnico
237007225e5Sgerardnico    }
238007225e5Sgerardnico
239007225e5Sgerardnico    /**
24071f916b9Sgerardnico     * @param array $namespaces
241c3437056SNickeau     * @param bool $rebuild
242007225e5Sgerardnico     * @param int $depth recursion depth. 0 for unlimited
24304fd306cSNickeau     * @throws ExceptionCompile
244007225e5Sgerardnico     */
245c3437056SNickeau    private function index($namespaces = array(), $rebuild = false, $depth = 0)
246c3437056SNickeau    {
247c3437056SNickeau
248c3437056SNickeau        /**
249c3437056SNickeau         * Run as admin to overcome the fact that
250c3437056SNickeau         * anonymous user cannot see all links and backlinks
251c3437056SNickeau         */
252c3437056SNickeau        global $USERINFO;
253c3437056SNickeau        $USERINFO['grps'] = array('admin');
254c3437056SNickeau        global $INPUT;
255c3437056SNickeau        $INPUT->server->set('REMOTE_USER', "cli");
256c3437056SNickeau
257c3437056SNickeau        $pages = FsWikiUtility::getPages($namespaces, $depth);
258c3437056SNickeau
259c3437056SNickeau        $pageCounter = 0;
260c3437056SNickeau        $totalNumberOfPages = sizeof($pages);
261c3437056SNickeau        while ($pageArray = array_shift($pages)) {
262c3437056SNickeau            $id = $pageArray['id'];
2634cadd4f8SNickeau            global $ID;
2644cadd4f8SNickeau            $ID = $id;
265c3437056SNickeau            /**
266c3437056SNickeau             * Indexing the page start the database replication
26704fd306cSNickeau             * See {@link action_plugin_combo_indexer}
268c3437056SNickeau             */
269c3437056SNickeau            $pageCounter++;
270*edc35203Sgerardnico            $executionContext = ExecutionContext::getActualOrCreateFromEnv();
271c3437056SNickeau            try {
272c3437056SNickeau                /**
273c3437056SNickeau                 * If the page does not need to be indexed, there is no run
274c3437056SNickeau                 * and false is returned
275c3437056SNickeau                 */
276c3437056SNickeau                $indexedOrNot = idx_addPage($id, true, true);
277c3437056SNickeau                if ($indexedOrNot) {
278c3437056SNickeau                    LogUtility::msg("The page {$id} ($pageCounter / $totalNumberOfPages) was indexed and replicated", LogUtility::LVL_MSG_INFO);
279c3437056SNickeau                } else {
280c3437056SNickeau                    LogUtility::msg("The page {$id} ($pageCounter / $totalNumberOfPages) has an error", LogUtility::LVL_MSG_ERROR);
281c3437056SNickeau                }
28204fd306cSNickeau            } catch (ExceptionRuntime $e) {
283c3437056SNickeau                LogUtility::msg("The page {$id} ($pageCounter / $totalNumberOfPages) has an error: " . $e->getMessage(), LogUtility::LVL_MSG_ERROR);
284*edc35203Sgerardnico            } finally {
285*edc35203Sgerardnico                $executionContext->close();
286c3437056SNickeau            }
287c3437056SNickeau        }
288c3437056SNickeau        /**
289c3437056SNickeau         * Process all backlinks
290c3437056SNickeau         */
291c3437056SNickeau        echo "Processing Replication Request\n";
292c3437056SNickeau        Event::dispatchEvent(PHP_INT_MAX);
293c3437056SNickeau
294c3437056SNickeau    }
295c3437056SNickeau
296c3437056SNickeau    private function analytics($namespaces = array(), $output = null, $depth = 0)
297007225e5Sgerardnico    {
298007225e5Sgerardnico
299007225e5Sgerardnico        $fileHandle = null;
300007225e5Sgerardnico        if (!empty($output)) {
301007225e5Sgerardnico            $fileHandle = @fopen($output, 'w');
302007225e5Sgerardnico            if (!$fileHandle) $this->fatal("Failed to open $output");
303007225e5Sgerardnico        }
304007225e5Sgerardnico
30537748cd8SNickeau        /**
30637748cd8SNickeau         * Run as admin to overcome the fact that
30737748cd8SNickeau         * anonymous user cannot see all links and backlinks
30837748cd8SNickeau         */
30937748cd8SNickeau        global $USERINFO;
31037748cd8SNickeau        $USERINFO['grps'] = array('admin');
31137748cd8SNickeau        global $INPUT;
31237748cd8SNickeau        $INPUT->server->set('REMOTE_USER', "cli");
31337748cd8SNickeau
31437748cd8SNickeau        $pages = FsWikiUtility::getPages($namespaces, $depth);
315007225e5Sgerardnico
316007225e5Sgerardnico
317007225e5Sgerardnico        if (!empty($fileHandle)) {
318007225e5Sgerardnico            $header = array(
319007225e5Sgerardnico                'id',
320007225e5Sgerardnico                'backlinks',
321007225e5Sgerardnico                'broken_links',
322007225e5Sgerardnico                'changes',
323007225e5Sgerardnico                'chars',
324007225e5Sgerardnico                'external_links',
325007225e5Sgerardnico                'external_medias',
326007225e5Sgerardnico                'h1',
327007225e5Sgerardnico                'h2',
328007225e5Sgerardnico                'h3',
329007225e5Sgerardnico                'h4',
330007225e5Sgerardnico                'h5',
331007225e5Sgerardnico                'internal_links',
332007225e5Sgerardnico                'internal_medias',
333007225e5Sgerardnico                'words',
334007225e5Sgerardnico                'score'
335007225e5Sgerardnico            );
336007225e5Sgerardnico            fwrite($fileHandle, implode(",", $header) . PHP_EOL);
337007225e5Sgerardnico        }
3389da76789Sgerardnico        $pageCounter = 0;
339e8b2ff59SNickeau        $totalNumberOfPages = sizeof($pages);
340c3437056SNickeau        while ($pageArray = array_shift($pages)) {
341c3437056SNickeau            $id = $pageArray['id'];
34204fd306cSNickeau            $page = MarkupPath::createMarkupFromId($id);
343c3437056SNickeau
344007225e5Sgerardnico
3459da76789Sgerardnico            $pageCounter++;
346c3437056SNickeau            /**
347c3437056SNickeau             * Analytics
348c3437056SNickeau             */
349*edc35203Sgerardnico            echo "Analytics Processing for the page {$id} ($pageCounter / $totalNumberOfPages)\n";
350*edc35203Sgerardnico            $executionContext = ExecutionContext::getActualOrCreateFromEnv();
351*edc35203Sgerardnico            try {
35204fd306cSNickeau                $analyticsPath = $page->fetchAnalyticsPath();
353*edc35203Sgerardnico            } catch (ExceptionNotExists $e) {
354*edc35203Sgerardnico                LogUtility::error("The analytics document for the page ($page) was not found");
355*edc35203Sgerardnico                continue;
356*edc35203Sgerardnico            } catch (ExceptionCompile $e) {
357*edc35203Sgerardnico                LogUtility::error("Error when get the analytics.",self::CANONICAL,$e);
358*edc35203Sgerardnico                continue;
359*edc35203Sgerardnico            } finally {
360*edc35203Sgerardnico                $executionContext->close();
361*edc35203Sgerardnico            }
362*edc35203Sgerardnico
36304fd306cSNickeau            try {
36404fd306cSNickeau                $data = \ComboStrap\Json::createFromPath($analyticsPath)->toArray();
36504fd306cSNickeau            } catch (ExceptionBadSyntax $e) {
36604fd306cSNickeau                LogUtility::error("The analytics json of the page ($page) is not conform");
36704fd306cSNickeau                continue;
368*edc35203Sgerardnico            } catch (ExceptionNotFound|ExceptionNotExists $e) {
36904fd306cSNickeau                LogUtility::error("The analytics document ({$analyticsPath}) for the page ($page) was not found");
37004fd306cSNickeau                continue;
37104fd306cSNickeau            }
372c3437056SNickeau
373007225e5Sgerardnico            if (!empty($fileHandle)) {
37404fd306cSNickeau                $statistics = $data[renderer_plugin_combo_analytics::STATISTICS];
375007225e5Sgerardnico                $row = array(
376007225e5Sgerardnico                    'id' => $id,
377c3437056SNickeau                    'backlinks' => $statistics[BacklinkCount::getPersistentName()],
37804fd306cSNickeau                    'broken_links' => $statistics[renderer_plugin_combo_analytics::INTERNAL_LINK_BROKEN_COUNT],
37904fd306cSNickeau                    'changes' => $statistics[renderer_plugin_combo_analytics::EDITS_COUNT],
38004fd306cSNickeau                    'chars' => $statistics[renderer_plugin_combo_analytics::CHAR_COUNT],
38104fd306cSNickeau                    'external_links' => $statistics[renderer_plugin_combo_analytics::EXTERNAL_LINK_COUNT],
38204fd306cSNickeau                    'external_medias' => $statistics[renderer_plugin_combo_analytics::EXTERNAL_MEDIA_COUNT],
38304fd306cSNickeau                    PageH1::PROPERTY_NAME => $statistics[renderer_plugin_combo_analytics::HEADING_COUNT][PageH1::PROPERTY_NAME],
38404fd306cSNickeau                    'h2' => $statistics[renderer_plugin_combo_analytics::HEADING_COUNT]['h2'],
38504fd306cSNickeau                    'h3' => $statistics[renderer_plugin_combo_analytics::HEADING_COUNT]['h3'],
38604fd306cSNickeau                    'h4' => $statistics[renderer_plugin_combo_analytics::HEADING_COUNT]['h4'],
38704fd306cSNickeau                    'h5' => $statistics[renderer_plugin_combo_analytics::HEADING_COUNT]['h5'],
38804fd306cSNickeau                    'internal_links' => $statistics[renderer_plugin_combo_analytics::INTERNAL_LINK_COUNT],
38904fd306cSNickeau                    'internal_medias' => $statistics[renderer_plugin_combo_analytics::INTERNAL_MEDIA_COUNT],
39004fd306cSNickeau                    'words' => $statistics[renderer_plugin_combo_analytics::WORD_COUNT],
39104fd306cSNickeau                    'low' => $data[renderer_plugin_combo_analytics::QUALITY]['low']
392007225e5Sgerardnico                );
393007225e5Sgerardnico                fwrite($fileHandle, implode(",", $row) . PHP_EOL);
394007225e5Sgerardnico            }
395c3437056SNickeau
396007225e5Sgerardnico        }
397007225e5Sgerardnico        if (!empty($fileHandle)) {
398007225e5Sgerardnico            fclose($fileHandle);
399007225e5Sgerardnico        }
400007225e5Sgerardnico
401007225e5Sgerardnico    }
40271f916b9Sgerardnico
403325fe0c5Sgerardnico
404c3437056SNickeau    private function deleteNonExistingPageFromDatabase()
40571f916b9Sgerardnico    {
406c3437056SNickeau        LogUtility::msg("Starting: Deleting non-existing page from database");
407c3437056SNickeau        $sqlite = Sqlite::createOrGetSqlite();
408c3437056SNickeau        $request = $sqlite
409c3437056SNickeau            ->createRequest()
410c3437056SNickeau            ->setQuery("select id as \"id\" from pages");
411c3437056SNickeau        $rows = [];
412c3437056SNickeau        try {
413c3437056SNickeau            $rows = $request
414c3437056SNickeau                ->execute()
415c3437056SNickeau                ->getRows();
41604fd306cSNickeau        } catch (ExceptionCompile $e) {
417c3437056SNickeau            LogUtility::msg("Error while getting the id pages. {$e->getMessage()}");
418c3437056SNickeau            return;
419c3437056SNickeau        } finally {
420c3437056SNickeau            $request->close();
42171f916b9Sgerardnico        }
422c3437056SNickeau        $counter = 0;
423c3437056SNickeau        foreach ($rows as $row) {
424c3437056SNickeau            $counter++;
425c3437056SNickeau            $id = $row['id'];
42671f916b9Sgerardnico            if (!page_exists($id)) {
42771f916b9Sgerardnico                echo 'Page does not exist on the file system. Deleted from the database (' . $id . ")\n";
42804fd306cSNickeau                MarkupPath::createMarkupFromId($id)->getDatabasePage()->delete();
429c3437056SNickeau            }
430c3437056SNickeau        }
431c3437056SNickeau        LogUtility::msg("Sync finished ($counter pages checked)");
432c3437056SNickeau
433c3437056SNickeau
434c3437056SNickeau    }
435c3437056SNickeau
436c3437056SNickeau    private function frontmatter($namespaces, $depth)
437c3437056SNickeau    {
438c3437056SNickeau        $pages = FsWikiUtility::getPages($namespaces, $depth);
439c3437056SNickeau        $pageCounter = 0;
440c3437056SNickeau        $totalNumberOfPages = sizeof($pages);
441c3437056SNickeau        $pagesWithChanges = [];
442c3437056SNickeau        $pagesWithError = [];
443c3437056SNickeau        $pagesWithOthers = [];
444c3437056SNickeau        $notChangedCounter = 0;
445c3437056SNickeau        while ($pageArray = array_shift($pages)) {
446c3437056SNickeau            $id = $pageArray['id'];
4474cadd4f8SNickeau            global $ID;
4484cadd4f8SNickeau            $ID = $id;
44904fd306cSNickeau            $page = MarkupPath::createMarkupFromId($id);
450c3437056SNickeau            $pageCounter++;
451c3437056SNickeau            LogUtility::msg("Processing page {$id} ($pageCounter / $totalNumberOfPages) ", LogUtility::LVL_MSG_INFO);
452*edc35203Sgerardnico            $executionContext = ExecutionContext::getActualOrCreateFromEnv();
453c3437056SNickeau            try {
454c3437056SNickeau                $message = MetadataFrontmatterStore::createFromPage($page)
455c3437056SNickeau                    ->sync();
456c3437056SNickeau                switch ($message->getStatus()) {
457c3437056SNickeau                    case syntax_plugin_combo_frontmatter::UPDATE_EXIT_CODE_NOT_CHANGED:
458c3437056SNickeau                        $notChangedCounter++;
459c3437056SNickeau                        break;
460c3437056SNickeau                    case syntax_plugin_combo_frontmatter::UPDATE_EXIT_CODE_DONE:
461c3437056SNickeau                        $pagesWithChanges[] = $id;
462c3437056SNickeau                        break;
463c3437056SNickeau                    case syntax_plugin_combo_frontmatter::UPDATE_EXIT_CODE_ERROR:
464c3437056SNickeau                        $pagesWithError[$id] = $message->getPlainTextContent();
465c3437056SNickeau                        break;
466c3437056SNickeau                    default:
467c3437056SNickeau                        $pagesWithOthers[$id] = $message->getPlainTextContent();
468c3437056SNickeau                        break;
469c3437056SNickeau
470c3437056SNickeau                }
47104fd306cSNickeau            } catch (ExceptionCompile $e) {
472c3437056SNickeau                $pagesWithError[$id] = $e->getMessage();
473*edc35203Sgerardnico            } finally {
474*edc35203Sgerardnico                $executionContext->close();
475c3437056SNickeau            }
476c3437056SNickeau
477c3437056SNickeau        }
478c3437056SNickeau
479c3437056SNickeau        echo "\n";
480c3437056SNickeau        echo "Result:\n";
481c3437056SNickeau        echo "$notChangedCounter pages without any frontmatter modifications\n";
482c3437056SNickeau
483c3437056SNickeau        if (sizeof($pagesWithError) > 0) {
484c3437056SNickeau            echo "\n";
485c3437056SNickeau            echo "The following pages had errors\n";
486c3437056SNickeau            $pageCounter = 0;
487c3437056SNickeau            $totalNumberOfPages = sizeof($pagesWithError);
488c3437056SNickeau            foreach ($pagesWithError as $id => $message) {
489c3437056SNickeau                $pageCounter++;
490c3437056SNickeau                LogUtility::msg("Page {$id} ($pageCounter / $totalNumberOfPages): " . $message, LogUtility::LVL_MSG_ERROR);
491c3437056SNickeau            }
492c3437056SNickeau        } else {
493c3437056SNickeau            echo "No error\n";
494c3437056SNickeau        }
495c3437056SNickeau
496c3437056SNickeau        if (sizeof($pagesWithChanges) > 0) {
497c3437056SNickeau            echo "\n";
498c3437056SNickeau            echo "The following pages had changed:\n";
499c3437056SNickeau            $pageCounter = 0;
500c3437056SNickeau            $totalNumberOfPages = sizeof($pagesWithChanges);
501c3437056SNickeau            foreach ($pagesWithChanges as $id) {
502c3437056SNickeau                $pageCounter++;
503c3437056SNickeau                LogUtility::msg("Page {$id} ($pageCounter / $totalNumberOfPages) ", LogUtility::LVL_MSG_ERROR);
504c3437056SNickeau            }
505c3437056SNickeau        } else {
506c3437056SNickeau            echo "No changes\n";
507c3437056SNickeau        }
508c3437056SNickeau
509c3437056SNickeau        if (sizeof($pagesWithOthers) > 0) {
510c3437056SNickeau            echo "\n";
511c3437056SNickeau            echo "The following pages had an other status";
512c3437056SNickeau            $pageCounter = 0;
513c3437056SNickeau            $totalNumberOfPages = sizeof($pagesWithOthers);
514c3437056SNickeau            foreach ($pagesWithOthers as $id => $message) {
515c3437056SNickeau                $pageCounter++;
516c3437056SNickeau                LogUtility::msg("Page {$id} ($pageCounter / $totalNumberOfPages) " . $message, LogUtility::LVL_MSG_ERROR);
517c3437056SNickeau            }
51871f916b9Sgerardnico        }
51971f916b9Sgerardnico    }
52071f916b9Sgerardnico
521c3437056SNickeau    private function getStartPath($args)
522c3437056SNickeau    {
523c3437056SNickeau        $sizeof = sizeof($args);
524c3437056SNickeau        switch ($sizeof) {
525c3437056SNickeau            case 0:
526c3437056SNickeau                fwrite(STDERR, "The start path is mandatory and was not given");
527c3437056SNickeau                exit(1);
528c3437056SNickeau            case 1:
529c3437056SNickeau                $startPath = $args[0];
530c3437056SNickeau                if (!in_array($startPath, [":", "/"])) {
531c3437056SNickeau                    // cleanId would return blank for a root
532c3437056SNickeau                    $startPath = cleanID($startPath);
533c3437056SNickeau                }
534c3437056SNickeau                break;
535c3437056SNickeau            default:
536c3437056SNickeau                fwrite(STDERR, "Too much arguments given $sizeof");
537c3437056SNickeau                exit(1);
538c3437056SNickeau        }
539c3437056SNickeau        return $startPath;
54071f916b9Sgerardnico    }
541007225e5Sgerardnico}
542