-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli.php
More file actions
692 lines (625 loc) · 24 KB
/
cli.php
File metadata and controls
692 lines (625 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
<?php
/**
* Copyright (c) 2021. ComboStrap, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the GPL license found in the
* COPYING file in the root directory of this source tree.
*
* @license GPL 3 (https://www.gnu.org/licenses/gpl-3.0.en.html)
* @author ComboStrap <support@combostrap.com>
*
*/
use ComboStrap\DatabasePageRow;
use ComboStrap\Event;
use ComboStrap\ExceptionBadSyntax;
use ComboStrap\ExceptionCompile;
use ComboStrap\ExceptionNotExists;
use ComboStrap\ExceptionNotFound;
use ComboStrap\ExceptionRuntime;
use ComboStrap\ExceptionSqliteNotAvailable;
use ComboStrap\ExecutionContext;
use ComboStrap\FsWikiUtility;
use ComboStrap\LogUtility;
use ComboStrap\MarkupPath;
use ComboStrap\Meta\Field\BacklinkCount;
use ComboStrap\Meta\Field\PageH1;
use ComboStrap\MetadataFrontmatterStore;
use ComboStrap\Sqlite;
use splitbrain\phpcli\Options;
/**
* All dependency are loaded
*/
require_once(__DIR__ . '/vendor/autoload.php');
/**
* The memory of the server 128 is not enough
*/
ini_set('memory_limit', '256M');
/**
* Class cli_plugin_combo
*
* This is a cli:
* https://www.dokuwiki.org/devel:cli_plugins#example
*
* Usage:
*
* ```
* docker exec -ti $(CONTAINER) /bin/bash
* ```
* ```
* set animal=animal-directory-name
* php ./bin/plugin.php combo --help
* ```
* or via the IDE
*
*
* Example:
* https://www.dokuwiki.org/tips:grapher
*
*/
class cli_plugin_combo extends DokuWiki_CLI_Plugin
{
const METADATA_TO_DATABASE = "metadata-to-database";
const ANALYTICS = "analytics";
const METADATA_TO_FRONTMATTER = "metadata-to-frontmatter";
const BROKEN_LINKS = "broken-links";
const SYNC = "sync";
const PLUGINS_TO_UPDATE = "plugins-to-update";
const FORCE_OPTION = 'force';
const PORT_OPTION = 'port';
const HOST_OPTION = 'host';
const CANONICAL = "combo-cli";
/**
* register options and arguments
* @param Options $options
*
* Note the animal is set in {@link DokuWikiFarmCore::detectAnimal()}
* via the environment variable `animal` that is passed in the $_SERVER variable
*/
protected function setup(Options $options)
{
$help = <<<EOF
ComboStrap Administrative Commands
Example:
* Replicate all pages into the database
```bash
php ./bin/plugin.php combo metadata-to-database --host serverHostName --port 80 :
# or
php ./bin/plugin.php combo metadata-to-database --host serverHostName --port 80 /
```
* Replicate only the page `:namespace:my-page`
```bash
php ./bin/plugin.php combo metadata-to-database --host serverHostName --port 80 :namespace:my-page
# or
php ./bin/plugin.php combo metadata-to-database --host serverHostName --port 80 /namespace/my-page
```
Animal: If you want to use it for an animal farm, you need to set first the animal directory name in a environment variable
```bash
animal=animal-directory-name php ./bin/plugin.php combo
```
EOF;
/**
* Global Options
*/
$options->setHelp($help);
$options->registerOption('version', 'print version', 'v');
/** @noinspection PhpRedundantOptionalArgumentInspection */
$options->registerOption(
'dry',
"Optional, dry-run",
'd', false);
$options->registerOption(
'output',
"Optional, where to store the analytical data as csv eg. a filename.",
'o',
true
);
/**
* Command without options
*/
$options->registerCommand(self::ANALYTICS, "Start the analytics and export optionally the data");
$options->registerCommand(self::PLUGINS_TO_UPDATE, "List the plugins to update");
$options->registerCommand(self::BROKEN_LINKS, "Output Broken Links");
// Metadata to database command
$options->registerCommand(self::METADATA_TO_DATABASE, "Replicate the file system metadata into the database");
$options->registerOption(
self::HOST_OPTION,
"The http host name of your server. This value is used by dokuwiki in the rendering cache key",
null,
true,
self::METADATA_TO_DATABASE
);
$options->registerOption(
self::PORT_OPTION,
"The http host port of your server. This value is used by dokuwiki in the rendering cache key",
null,
true,
self::METADATA_TO_DATABASE
);
$options->registerOption(
self::FORCE_OPTION,
"Replicate with force",
'f',
false,
self::METADATA_TO_DATABASE
);
$startPathArgName = 'startPath';
$startPathHelpDescription = "The start path (a page or a directory). For all pages, type the root directory '/' or ':'";
$options->registerArgument(
$startPathArgName,
$startPathHelpDescription,
true,
self::METADATA_TO_DATABASE
);
// Metadata Command definition
$options->registerCommand(self::METADATA_TO_FRONTMATTER, "Replicate the file system metadata into the page frontmatter");
$options->registerArgument(
$startPathArgName,
$startPathHelpDescription,
true,
self::METADATA_TO_FRONTMATTER
);
// Sync Command Definition
$options->registerCommand(self::SYNC, "Delete the non-existing pages in the database");
$options->registerArgument(
$startPathArgName,
$startPathHelpDescription,
true,
self::SYNC
);
}
/**
* The main entry
* @param Options $options
*/
protected function main(Options $options)
{
if (isset($_REQUEST['animal'])) {
// on linux
echo "Animal detected: " . $_REQUEST['animal'] . "\n";
} else {
// on windows
echo "No Animal detected\n";
echo "Conf: " . DOKU_CONF . "\n";
}
$args = $options->getArgs();
$depth = $options->getOpt('depth', 0);
$cmd = $options->getCmd();
try {
switch ($cmd) {
case self::METADATA_TO_DATABASE:
$startPath = $this->getStartPath($args);
$force = $options->getOpt(self::FORCE_OPTION, false);
$hostOptionValue = $options->getOpt(self::HOST_OPTION, null);
if ($hostOptionValue === null) {
fwrite(STDERR, "The host name is mandatory");
return;
}
$_SERVER['HTTP_HOST'] = $hostOptionValue;
$portOptionName = $options->getOpt(self::PORT_OPTION, null);
if ($portOptionName === null) {
fwrite(STDERR, "The host port is mandatory");
return;
}
$_SERVER['SERVER_PORT'] = $portOptionName;
$this->index($startPath, $force, $depth);
break;
case self::METADATA_TO_FRONTMATTER:
$startPath = $this->getStartPath($args);
$this->frontmatter($startPath, $depth);
break;
case self::BROKEN_LINKS:
$this->brokenLinks();
break;
case self::ANALYTICS:
$startPath = $this->getStartPath($args);
$output = $options->getOpt('output', '');
//if ($output == '-') $output = 'php://stdout';
$this->analytics($startPath, $output, $depth);
break;
case self::SYNC:
// php "$DOKUWIKI_HOME"/bin/indexer.php -q
$this->deleteNonExistingPageFromDatabase();
break;
case self::PLUGINS_TO_UPDATE:
$this->pluginToUpdate();
break;
default:
if ($cmd !== "") {
fwrite(STDERR, "Combo: Command unknown (" . $cmd . ")");
} else {
echo $options->help();
}
exit(1);
}
} catch (Exception $exception) {
fwrite(STDERR, "An internal error has occurred. " . $exception->getMessage() . "\n" . $exception->getTraceAsString());
exit(1);
}
}
/**
* @param array $namespaces
* @param bool $rebuild
* @param int $depth recursion depth. 0 for unlimited
* @throws ExceptionCompile
*/
private function index($namespaces = array(), $rebuild = false, $depth = 0)
{
/**
* Run as admin to overcome the fact that
* anonymous user cannot see all links and backlinks
*/
global $USERINFO;
$USERINFO['grps'] = array('admin');
global $INPUT;
$INPUT->server->set('REMOTE_USER', "cli");
$pages = FsWikiUtility::getPages($namespaces, $depth);
$pageCounter = 0;
$totalNumberOfPages = sizeof($pages);
while ($pageArray = array_shift($pages)) {
$id = $pageArray['id'];
global $ID;
$ID = $id;
/**
* Indexing the page start the database replication
* See {@link action_plugin_combo_indexer}
*/
$pageCounter++;
$executionContext = ExecutionContext::getActualOrCreateFromEnv();
try {
/**
* If the page does not need to be indexed, there is no run
* and false is returned
*/
$indexedOrNot = idx_addPage($id, true, true);
if ($indexedOrNot) {
LogUtility::msg("The page {$id} ($pageCounter / $totalNumberOfPages) was indexed and replicated", LogUtility::LVL_MSG_INFO);
} else {
LogUtility::msg("The page {$id} ($pageCounter / $totalNumberOfPages) has an error", LogUtility::LVL_MSG_ERROR);
}
} catch (ExceptionRuntime $e) {
LogUtility::msg("The page {$id} ($pageCounter / $totalNumberOfPages) has an error: " . $e->getMessage(), LogUtility::LVL_MSG_ERROR);
} finally {
$executionContext->close();
}
}
/**
* Process all backlinks
*/
echo "Processing Replication Request\n";
Event::dispatchEvent(PHP_INT_MAX);
}
private function analytics($namespaces = array(), $output = null, $depth = 0)
{
$fileHandle = null;
if (!empty($output)) {
$fileHandle = @fopen($output, 'w');
if (!$fileHandle) $this->fatal("Failed to open $output");
}
/**
* Run as admin to overcome the fact that
* anonymous user cannot see all links and backlinks
*/
global $USERINFO;
$USERINFO['grps'] = array('admin');
global $INPUT;
$INPUT->server->set('REMOTE_USER', "cli");
$pages = FsWikiUtility::getPages($namespaces, $depth);
if (!empty($fileHandle)) {
$header = array(
'id',
'backlinks',
'broken_links',
'changes',
'chars',
'external_links',
'external_medias',
'h1',
'h2',
'h3',
'h4',
'h5',
'internal_links',
'internal_medias',
'words',
'score'
);
fwrite($fileHandle, implode(",", $header) . PHP_EOL);
}
$pageCounter = 0;
$totalNumberOfPages = sizeof($pages);
while ($pageArray = array_shift($pages)) {
$id = $pageArray['id'];
$page = MarkupPath::createMarkupFromId($id);
$pageCounter++;
/**
* Analytics
*/
echo "Analytics Processing for the page {$id} ($pageCounter / $totalNumberOfPages)\n";
$executionContext = ExecutionContext::getActualOrCreateFromEnv();
try {
$analyticsPath = $page->fetchAnalyticsPath();
} catch (ExceptionNotExists $e) {
LogUtility::error("The analytics document for the page ($page) was not found");
continue;
} catch (ExceptionCompile $e) {
LogUtility::error("Error when get the analytics.", self::CANONICAL, $e);
continue;
} finally {
$executionContext->close();
}
try {
$data = \ComboStrap\Json::createFromPath($analyticsPath)->toArray();
} catch (ExceptionBadSyntax $e) {
LogUtility::error("The analytics json of the page ($page) is not conform");
continue;
} catch (ExceptionNotFound|ExceptionNotExists $e) {
LogUtility::error("The analytics document ({$analyticsPath}) for the page ($page) was not found");
continue;
}
if (!empty($fileHandle)) {
$statistics = $data[renderer_plugin_combo_analytics::STATISTICS];
$row = array(
'id' => $id,
'backlinks' => $statistics[BacklinkCount::getPersistentName()],
'broken_links' => $statistics[renderer_plugin_combo_analytics::INTERNAL_LINK_BROKEN_COUNT],
'changes' => $statistics[renderer_plugin_combo_analytics::EDITS_COUNT],
'chars' => $statistics[renderer_plugin_combo_analytics::CHAR_COUNT],
'external_links' => $statistics[renderer_plugin_combo_analytics::EXTERNAL_LINK_COUNT],
'external_medias' => $statistics[renderer_plugin_combo_analytics::EXTERNAL_MEDIA_COUNT],
PageH1::PROPERTY_NAME => $statistics[renderer_plugin_combo_analytics::HEADING_COUNT][PageH1::PROPERTY_NAME],
'h2' => $statistics[renderer_plugin_combo_analytics::HEADING_COUNT]['h2'],
'h3' => $statistics[renderer_plugin_combo_analytics::HEADING_COUNT]['h3'],
'h4' => $statistics[renderer_plugin_combo_analytics::HEADING_COUNT]['h4'],
'h5' => $statistics[renderer_plugin_combo_analytics::HEADING_COUNT]['h5'],
'internal_links' => $statistics[renderer_plugin_combo_analytics::INTERNAL_LINK_COUNT],
'internal_medias' => $statistics[renderer_plugin_combo_analytics::INTERNAL_MEDIA_COUNT],
'words' => $statistics[renderer_plugin_combo_analytics::WORD_COUNT],
'low' => $data[renderer_plugin_combo_analytics::QUALITY]['low']
);
fwrite($fileHandle, implode(",", $row) . PHP_EOL);
}
}
if (!empty($fileHandle)) {
fclose($fileHandle);
}
}
/**
* @throws ExceptionSqliteNotAvailable
*/
private function deleteNonExistingPageFromDatabase()
{
LogUtility::msg("Starting: Deleting non-existing page from database");
$sqlite = Sqlite::createOrGetSqlite();
/** @noinspection SqlNoDataSourceInspection */
$request = $sqlite
->createRequest()
->setQuery("select id as \"id\" from pages");
$rows = [];
try {
$rows = $request
->execute()
->getRows();
} catch (ExceptionCompile $e) {
LogUtility::msg("Error while getting the id pages. {$e->getMessage()}");
return;
} finally {
$request->close();
}
$counter = 0;
foreach ($rows as $row) {
/**
* Context
* PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 20480 bytes)
* in /opt/www/datacadamia.com/inc/ErrorHandler.php on line 102
*/
$executionContext = ExecutionContext::getActualOrCreateFromEnv();
try {
$counter++;
$id = $row['id'];
if (!page_exists($id)) {
echo 'Page does not exist on the file system. Delete from the database (' . $id . ")\n";
try {
$dbRow = DatabasePageRow::getFromDokuWikiId($id);
$dbRow->delete();
} catch (ExceptionNotFound $e) {
// ok
}
}
} finally {
$executionContext->close();
}
}
LogUtility::msg("Sync finished ($counter pages checked)");
}
private function frontmatter($namespaces, $depth)
{
$pages = FsWikiUtility::getPages($namespaces, $depth);
$pageCounter = 0;
$totalNumberOfPages = sizeof($pages);
$pagesWithChanges = [];
$pagesWithError = [];
$pagesWithOthers = [];
$notChangedCounter = 0;
while ($pageArray = array_shift($pages)) {
$id = $pageArray['id'];
global $ID;
$ID = $id;
$page = MarkupPath::createMarkupFromId($id);
$pageCounter++;
LogUtility::msg("Processing page $id ($pageCounter / $totalNumberOfPages) ", LogUtility::LVL_MSG_INFO);
$executionContext = ExecutionContext::getActualOrCreateFromEnv();
try {
$message = MetadataFrontmatterStore::createFromPage($page)
->sync();
switch ($message->getStatus()) {
case syntax_plugin_combo_frontmatter::UPDATE_EXIT_CODE_NOT_CHANGED:
$notChangedCounter++;
break;
case syntax_plugin_combo_frontmatter::UPDATE_EXIT_CODE_DONE:
$pagesWithChanges[] = $id;
break;
case syntax_plugin_combo_frontmatter::UPDATE_EXIT_CODE_ERROR:
$pagesWithError[$id] = $message->getPlainTextContent();
break;
default:
$pagesWithOthers[$id] = $message->getPlainTextContent();
break;
}
} catch (ExceptionCompile $e) {
$pagesWithError[$id] = $e->getMessage();
} finally {
$executionContext->close();
}
}
echo "\n";
echo "Result:\n";
echo "$notChangedCounter pages without any frontmatter modifications\n";
if (sizeof($pagesWithError) > 0) {
echo "\n";
echo "The following pages had errors\n";
$pageCounter = 0;
$totalNumberOfPages = sizeof($pagesWithError);
foreach ($pagesWithError as $id => $message) {
$pageCounter++;
LogUtility::msg("Page $id ($pageCounter / $totalNumberOfPages): " . $message);
}
} else {
echo "No error\n";
}
if (sizeof($pagesWithChanges) > 0) {
echo "\n";
echo "The following pages had changed:\n";
$pageCounter = 0;
$totalNumberOfPages = sizeof($pagesWithChanges);
foreach ($pagesWithChanges as $id) {
$pageCounter++;
LogUtility::msg("Page $id ($pageCounter / $totalNumberOfPages) ");
}
} else {
echo "No changes\n";
}
if (sizeof($pagesWithOthers) > 0) {
echo "\n";
echo "The following pages had an other status";
$pageCounter = 0;
$totalNumberOfPages = sizeof($pagesWithOthers);
foreach ($pagesWithOthers as $id => $message) {
$pageCounter++;
LogUtility::msg("Page $id ($pageCounter / $totalNumberOfPages) " . $message, LogUtility::LVL_MSG_ERROR);
}
}
}
private function getStartPath($args)
{
$sizeof = sizeof($args);
switch ($sizeof) {
case 0:
fwrite(STDERR, "The start path is mandatory and was not given");
exit(1);
case 1:
$startPath = $args[0];
if (!in_array($startPath, [":", "/"])) {
// cleanId would return blank for a root
$startPath = cleanID($startPath);
}
break;
default:
fwrite(STDERR, "Too much arguments given $sizeof");
exit(1);
}
return $startPath;
}
/**
*
* Print the extension/plugin to update
*
* Note, there is also an Endpoint:
* self::EXTENSION_REPOSITORY_API.'?fmt=php&ext[]='.urlencode($name)
* `http://www.dokuwiki.org/lib/plugins/pluginrepo/api.php?fmt=php&ext[]=`.urlencode($name)
*
* @noinspection PhpUndefinedClassInspection
*/
private function pluginToUpdate()
{
if (class_exists(Local::class)) {
/**
* Release 2025-05-14 "Librarian"
* https://www.dokuwiki.org/changes#release_2025-05-14_librarian
* https://www.patreon.com/posts/new-extension-116501986
* ./bin/plugin.php extension list
* @link lib/plugins/extension/cli.php
* Code based on https://github.com/giterlizzi/dokuwiki-template-bootstrap3/pull/617/files
*/
try {
$extensions = (new Local())->getExtensions();
Repository::getInstance()->initExtensions(array_keys($extensions));
foreach ($extensions as $extension) {
if ($extension->isEnabled() && $extension->isUpdateAvailable()) {
echo "The extension {$extension->getDisplayName()} should be updated";
}
}
} /** @noinspection PhpUndefinedClassInspection */ catch (ExtensionException $ignore) {
// Ignore the exception
}
return;
}
$pluginList = plugin_list('', true);
$extension = $this->loadHelper('extension_extension');
foreach ($pluginList as $name) {
/* @var helper_plugin_extension_extension $extension
* old extension manager until Kaos
*/
$extension->setExtension($name);
/** @noinspection PhpUndefinedMethodInspection */
if ($extension->updateAvailable()) {
echo "The extension $name should be updated";
}
}
}
/**
* @return void
* Print the broken Links
* @throws ExceptionSqliteNotAvailable
*/
private function brokenLinks()
{
LogUtility::msg("Broken Links Started");
$sqlite = Sqlite::createOrGetSqlite();
$request = $sqlite
->createRequest()
->setQuery("with validPages as (select path, analytics
from pages
where json_valid(analytics) = 1)
select path,
json_extract(analytics, '$.statistics.internal_broken_link_count') as broken_link,
json_extract(analytics, '$.statistics.media.internal_broken_count') as broken_media
from validPages
where json_extract(analytics, '$.statistics.internal_broken_link_count') is not null
or json_extract(analytics, '$.statistics.media.internal_broken_count') != 0");
$rows = [];
try {
$rows = $request
->execute()
->getRows();
} catch (ExceptionCompile $e) {
LogUtility::msg("Error while getting the id pages. {$e->getMessage()}");
return;
} finally {
$request->close();
}
if (count($rows) == 0) {
LogUtility::msg("No Broken Links");
exit();
}
LogUtility::msg("Broken Links:");
foreach ($rows as $row) {
$path = $row["path"];
$broken_link = $row["broken_link"];
$broken_media = $row["broken_media"];
echo "$path (Page: $broken_link, Media: $broken_media) \n";
}
if (count($rows) != 0) {
exit(1);
}
}
}