Repository navigation
Expand file tree
/
Copy pathcli_core.php
More file actions
900 lines (768 loc) · 24.7 KB
/
Copy pathcli_core.php
File metadata and controls
900 lines (768 loc) · 24.7 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
<?php
if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
final class PwgCli {
// "'pagination' => true" in a spec adds these two, so every listing paginates the same way
private const PAGINATION_ARGS = [
'page' => [
'info' => 'Which page of results to show',
'default' => 1,
],
'limit' => [
'short' => 'l',
'info' => 'How many results per page',
'default' => 20,
],
];
private const GLOBAL_ARGS = [
'help' => [
'short' => 'h',
'info' => 'Show this help',
'flag' => true,
],
'dry-run' => [
'info' => 'Simulate, do not change anything',
'flag' => true,
],
'yes' => [
'short' => 'y',
'info' => 'Answer yes to every confirmation',
'flag' => true,
],
'verbose' => [
'info' => 'Show debug details (stack traces, full errors)',
'flag' => true,
],
'format' => [
'info' => 'How to print a table or a record: table or json',
'default' => 'table',
],
];
private array $commands = [];
private array $current_command = [];
private bool $show_help = false;
private string $boot_level = 'full';
public function boot()
{
// load all commands
$this->load_commands();
// get the current command
$this->current_command = $this->get_current_command();
// --help shortcut everything: no arg validation, no Piwigo boot
if ($this->help_requested())
{
$this->show_help = true;
$this->boot_level = 'none';
return;
}
// set the boot_level
$this->boot_level = $this->current_command['command']['spec']['boot'] ?? 'full';
// replace input args by parsed args
$this->current_command['args'] = $this->parse_args(
$this->current_command['args'],
$this->current_command['command']['spec']
);
// global flags feed the engine state, the callback only sees its own args
if (!empty($this->current_command['args']['yes']))
{
PwgCommand::assume_yes();
}
if (!empty($this->current_command['args']['verbose']))
{
PwgCommand::set_verbose();
}
if (!empty($this->current_command['args']['dry-run']))
{
PwgCommand::set_dry_run();
}
if (!PwgCommand::set_format($this->current_command['args']['format'] ?? 'table'))
{
PwgCommand::error('--format takes "table" or "json", not "'.$this->current_command['args']['format'].'"');
exit(PwgCommand::INVALID);
}
foreach (array_keys(self::GLOBAL_ARGS) as $global_arg)
{
unset($this->current_command['args'][$global_arg]);
}
}
public function init_minimal($verbose = true)
{
// define global $conf because
// config/database.inc.php set new $conf key
// global put these keys in the global scope
global $conf, $prefixeTable;
// define local dir and load database config
defined('PWG_LOCAL_DIR') or define('PWG_LOCAL_DIR', 'local/');
@include_once(PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'config/database.inc.php');
// if piwigo isn't installed, abort
if (!defined('PHPWG_INSTALLED'))
{
if ($verbose)
{
PwgCommand::error('Piwigo is not installed, this command needs a database');
}
return PwgCommand::ERROR;
}
// minimal boot gets the constants and the core functions here, the full boot gets them from common.inc.php
if ('full' !== $this->boot_level)
{
include_once(PHPWG_ROOT_PATH.'include/constants.php');
include_once(PHPWG_ROOT_PATH.'include/functions.inc.php');
}
return PwgCommand::SUCCESS;
}
public function init_db($verbose = true)
{
global $conf;
include_once(PHPWG_ROOT_PATH.'include/dblayer/functions_'.$conf['dblayer'].'.inc.php');
try
{
pwg_db_connect($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
return PwgCommand::SUCCESS;
}
catch (Exception $e)
{
if ($verbose)
{
PwgCommand::error('Unable to start a database connection:');
PwgCommand::error($e->getMessage());
}
return PwgCommand::ERROR;
}
}
public function init_piwigo($verbose = true)
{
global $conf;
// we need to fake this variable because we're not longer
// in HTTP context but in CLI context
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['HTTP_HOST'] = 'localhost';
// _data is the only directory the full boot itself writes to (Smarty
// compiles into _data/templates_c), probe it ignoring data_dir_checked
$data_dir = PHPWG_ROOT_PATH.$conf['data_location'];
$blocking = null;
if (!is_dir($data_dir) || !is_writable($data_dir))
{
$blocking = $conf['data_location'];
}
elseif (is_dir($data_dir.'templates_c') && !is_writable($data_dir.'templates_c'))
{
// created 755 by the web server user, the classic CLI trap
// (my first issue when i create thisd cli)
$blocking = $conf['data_location'].'templates_c';
}
if (null !== $blocking)
{
if ($verbose)
{
PwgCommand::error('"'.$blocking.'" is missing or not writable, this command needs to write in it');
$web_user = cli_web_user();
PwgCommand::errln('give write access ("chmod -R 777 '.$conf['data_location'].'") or run as the web server user'.(null === $web_user ? '' : ':'));
if (null !== $web_user)
{
PwgCommand::errln(' '.cli_run_as($web_user, 'php '.CLI_ROOT_PATH.'bin/pwg.php ...'));
}
}
return PwgCommand::ERROR;
}
return PwgCommand::SUCCESS;
}
public function prepare_cli_user()
{
include_once(PHPWG_ROOT_PATH.'include/functions_plugins.inc.php');
add_event_handler('user_init', 'cli_promote_user');
return PwgCommand::SUCCESS;
}
public function prepare_cli_logger()
{
include_once(PHPWG_ROOT_PATH.'include/functions_plugins.inc.php');
// "plugins_loaded" is the last event before the core writes its first log line
add_event_handler('plugins_loaded', 'cli_swap_logger');
return PwgCommand::SUCCESS;
}
public function run()
{
$command = $this->current_command['command'];
if ($this->show_help)
{
$this->command_help($command);
return PwgCommand::SUCCESS;
}
if (!is_callable($command['callback']) && !empty($command['file_to_include']))
{
include_once($command['file_to_include']);
}
if (!is_callable($command['callback']))
{
PwgCommand::error('Command "'.$command['name'].'" has no callable callback');
return PwgCommand::ERROR;
}
// a PHP warning during the command must fail it, never hide under an [OK]
set_error_handler([$this, 'handle_php_error']);
try
{
// a full boot command is an admin page: give it what admin.php gives
if ('full' === $this->boot_level)
{
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
}
$exit = call_user_func($command['callback'], $this->current_command['args']);
}
catch (\Throwable $th)
{
// catch all error to handle in CLI context
PwgCommand::error('An error occurred');
PwgCommand::errln($th->getMessage());
if (PwgCommand::is_verbose())
{
PwgCommand::errln([$th->getFile().':'.$th->getLine(), $th->getTraceAsString()]);
}
return PwgCommand::ERROR;
}
finally
{
restore_error_handler();
}
return is_int($exit) ? $exit : PwgCommand::SUCCESS;
}
// warnings become exceptions, notices and deprecations only show with --verbose
public function handle_php_error(int $errno, string $errstr, string $errfile, int $errline): bool
{
// the @ operator lowers error_reporting for that call, honor it like PHP does
if (!(error_reporting() & $errno))
{
return false;
}
if ($errno & (E_WARNING | E_USER_WARNING | E_USER_ERROR | E_RECOVERABLE_ERROR))
{
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
if (PwgCommand::is_verbose())
{
PwgCommand::errln('[NOTICE] '.$errstr.' ('.$errfile.':'.$errline.')');
}
return true;
}
// Ctrl+C: close an open progress bar, say so, leave with the Unix convention
public function trap_interrupt()
{
if (!function_exists('pcntl_async_signals'))
{
return;
}
pcntl_async_signals(true);
pcntl_signal(SIGINT, function () {
PwgCommand::progress_finish();
PwgCommand::errln('aborted');
exit(130);
});
}
private function load_commands()
{
global $conf;
$command_files = [
'system',
'album',
'photo',
'user',
'maintenance',
'purge',
'plugin',
'theme',
'import',
'update',
'backup',
];
// the test suite sets the env var, so fixtures stay invisible everywhere else
if (!empty($conf['cli_allow_test_commands']) || false !== getenv('PWG_CLI_TESTS'))
{
array_push($command_files, 'test');
}
foreach ($command_files as $file)
{
include_once(CLI_ROOT_PATH.'commands/cli.'.$file.'.php');
}
}
private function get_current_command()
{
$argv = $_SERVER['argv'];
$words = [];
for ($i = 1; $i < count($argv); $i++)
{
if (substr($argv[$i], 0, 1) === '-')
{
break; // an option closes the command name
}
$words[] = $argv[$i];
}
if (empty($words))
{
if (array_intersect(['--version', '-v'], $argv))
{
// read PHPWG_VERSION without executing constants.php, which would demand $conf and $prefixeTable
preg_match("/PHPWG_VERSION', '([^']+)'/", file_get_contents(PHPWG_ROOT_PATH.'include/constants.php'), $matches);
PwgCommand::writeln('Piwigo '.($matches[1] ?? 'unknown').', PHP '.PHP_VERSION);
exit(PwgCommand::SUCCESS);
}
// "pwg" and "pwg --help" both land here, only the former is a mistake
$this->general_help();
exit(in_array('--help', $argv) || in_array('-h', $argv) ? PwgCommand::SUCCESS : PwgCommand::INVALID);
}
for ($length = count($words); $length > 0; $length--)
{
$name = implode('.', array_slice($words, 0, $length));
if (isset($this->commands[$name]))
{
return [
'command' => $this->commands[$name],
'args' => array_slice($argv, $length + 1),
];
}
}
PwgCommand::error('Command "'.implode(' ', $words).'" not found, run "pwg list" to see available commands');
exit(PwgCommand::INVALID);
}
private function help_requested()
{
// -h and --help always mean help, global shorts cannot be claimed by a command
foreach ($this->current_command['args'] as $arg)
{
if ('--' === $arg)
{
break; // past the separator, "--help" is an operand like any other
}
if ('--help' === $arg || '-h' === $arg)
{
return true;
}
}
return false;
}
// to do:
// - parsing group args like "-ds" is in fact -d -s
// - type ( cast + validate to int or string)
// - choices (parse enum like this args accepts only: 'guest', 'admin', 'normal')
// - negative int need to be in "--value=-1" for value "-- -1" for operands
// we can have a better way: "pwg command -1"
private function parse_args(array $args, ?array $infos)
{
// the command's own declaration wins, so it can give dry-run a short letter
$spec = ($infos['args'] ?? []) + self::GLOBAL_ARGS;
$spec_operands = $infos['operands'] ?? [];
$options = [];
$operands = []; // positional, e.g. the files in "image add *.jpg"
// short letter => long name, e.g. n => name
$shorts = [];
foreach ($spec as $name => $arg_infos)
{
if (isset($arg_infos['short']))
{
$shorts[$arg_infos['short']] = $name;
}
}
// retrieves all args
$count = count($args);
for ($i = 0; $i < $count; $i++)
{
$arg = $args[$i];
if ('--' === $arg)
{
// everything after -- is an operand, even when it starts with a dash
$operands = array_merge($operands, array_slice($args, $i + 1));
break;
}
if (substr($arg, 0, 1) !== '-')
{
$operands[] = $arg;
continue;
}
$name = ltrim($arg, '-'); // -name and --name are the same option
// --name=value carries its value inline, the only way to pass a value
// that itself starts with a dash, e.g. --order=-1
$inline_value = null;
$equal = strpos($name, '=');
if (false !== $equal)
{
$inline_value = substr($name, $equal + 1);
$name = substr($name, 0, $equal);
$arg = explode('=', $arg, 2)[0]; // error messages show --name, not --name=value
}
// a long name wins over a short one, so an option named "n" stays reachable
if (!isset($spec[$name]) && isset($shorts[$name]))
{
$name = $shorts[$name];
}
if (!isset($spec[$name]))
{
PwgCommand::error('Unknown option "'.$arg.'"');
exit(PwgCommand::INVALID);
}
if (!empty($spec[$name]['flag']))
{
if (null !== $inline_value)
{
PwgCommand::error('Option "'.$arg.'" is a flag and takes no value');
exit(PwgCommand::INVALID);
}
$options[$name] = true; // a flag never takes a value
continue;
}
if (null !== $inline_value)
{
$options[$name] = $inline_value;
continue;
}
$value = $args[$i + 1] ?? null;
if (null === $value || substr($value, 0, 1) === '-')
{
PwgCommand::error('Option "'.$arg.'" needs a value');
exit(PwgCommand::INVALID);
}
$options[$name] = $value;
$i++; // the value has been consumed
}
// what the user did not write
foreach ($spec as $name => $arg_infos)
{
if (!array_key_exists($name, $options))
{
$options[$name] = !empty($arg_infos['flag'])
? false
: ($arg_infos['default'] ?? null);
}
}
// marries the positional values with their declared name, in order
$position = 0;
$variadic = false;
foreach ($spec_operands as $operand_name => $operand_infos)
{
if (!empty($operand_infos['multiple']))
{
$options[$operand_name] = array_slice($operands, $position);
$position = count($operands);
$variadic = true;
continue;
}
if (array_key_exists($position, $operands))
{
$options[$operand_name] = $operands[$position];
}
elseif (array_key_exists('default', $operand_infos))
{
$options[$operand_name] = $operand_infos['default'];
}
else
{
PwgCommand::error('Missing argument "'.$operand_name.'"');
exit(PwgCommand::INVALID);
}
$position++;
}
if (!$variadic && $position < count($operands))
{
PwgCommand::error('Unexpected argument "'.$operands[$position].'"');
exit(PwgCommand::INVALID);
}
return $options;
}
private function general_help()
{
$lines = [
'Usage:',
' pwg <command> [options] [arguments]',
' pwg --version, -v',
'',
];
$lines = array_merge($lines, ['Global options:'], $this->options_lines(self::GLOBAL_ARGS), ['']);
$lines[] = 'Available commands:';
PwgCommand::writeln($lines);
cli_list(['all' => false]); // one single rendering for the commands list
}
private function command_help(array $command)
{
$spec = $command['spec'] ?? [];
$lines = [];
if (!empty($spec['description']))
{
$lines = ['Description:', ' '.$spec['description']];
// "details" is only for the help: "description" must stay one line, pwg list shows it
foreach ((array) ($spec['details'] ?? []) as $paragraph)
{
$lines[] = '';
$lines = array_merge($lines, self::wrap($paragraph));
}
$lines[] = '';
}
$usage = ' pwg '.str_replace('.', ' ', $command['name']).' [options]';
foreach ($spec['operands'] ?? [] as $operand_name => $operand_infos)
{
$token = '<'.$operand_name.'>'.(!empty($operand_infos['multiple']) ? '...' : '');
// variadic or defaulted operands are optional
$usage .= !empty($operand_infos['multiple']) || array_key_exists('default', $operand_infos)
? ' ['.$token.']'
: ' '.$token;
}
$lines = array_merge($lines, ['Usage:', $usage]);
if (!empty($spec['operands']))
{
$lines[] = '';
$lines[] = 'Arguments:';
$width = max(array_map('strlen', array_keys($spec['operands'])));
foreach ($spec['operands'] as $operand_name => $operand_infos)
{
$lines[] = ' '.str_pad($operand_name, $width + 3).($operand_infos['info'] ?? '');
}
}
$lines[] = '';
$lines[] = 'Options:';
$lines = array_merge($lines, $this->options_lines(($spec['args'] ?? []) + self::GLOBAL_ARGS));
if (!empty($spec['examples']))
{
$lines[] = '';
$lines[] = 'Examples:';
foreach ((array) $spec['examples'] as $example)
{
$lines[] = ' '.$example;
}
}
PwgCommand::writeln($lines);
}
// help paragraphs are written as one long string, cut them to a readable width
private static function wrap(string $text, int $width = 76): array
{
return array_map(function ($line) { return ' '.$line; }, explode("\n", wordwrap(trim($text), $width)));
}
// " -d, --dry-run Simulate only" for each option, aligned
private function options_lines(array $spec)
{
$left = [];
foreach ($spec as $name => $arg_infos)
{
$left[$name] = (isset($arg_infos['short']) ? '-'.$arg_infos['short'].', ' : ' ').'--'.$name;
}
$width = max(array_map('strlen', $left));
$lines = [];
foreach ($spec as $name => $arg_infos)
{
$line = ' '.str_pad($left[$name], $width + 3).($arg_infos['info'] ?? '');
if (empty($arg_infos['flag']) && isset($arg_infos['default']))
{
$line .= ' [default: '.$arg_infos['default'].']';
}
$lines[] = $line;
}
return $lines;
}
/**
* @param callable|string|null $callback
*/
function add_command(string $name, $callback = null, array $spec = [], ?string $file_to_include = null)
{
// check if this command already exist
if (isset($this->commands[$name]))
{
PwgCommand::error('Command "'.$name.'" is already registered');
exit(PwgCommand::ERROR);
}
// injected before the checks below, so a command claiming "page" or "-l" is refused there
if (!empty($spec['pagination']))
{
foreach (self::PAGINATION_ARGS as $arg_name => $arg_infos)
{
if (isset($spec['args'][$arg_name]))
{
PwgCommand::error('Command "'.$name.'": arg "'.$arg_name.'" is reserved, the command declares "pagination"');
exit(PwgCommand::ERROR);
}
$spec['args'][$arg_name] = $arg_infos;
}
}
// global options are engine territory: neither their names nor their shorts can be taken
$reserved_shorts = [];
foreach (self::GLOBAL_ARGS as $global_name => $global_infos)
{
if (isset($global_infos['short']))
{
$reserved_shorts[$global_infos['short']] = $global_name;
}
}
$taken_shorts = [];
foreach ($spec['args'] ?? [] as $arg_name => $arg_infos)
{
if (isset(self::GLOBAL_ARGS[$arg_name]))
{
PwgCommand::error('Command "'.$name.'": arg "'.$arg_name.'" is reserved, it is a global option');
exit(PwgCommand::ERROR);
}
if (isset($arg_infos['short']))
{
// a short is one letter, "-do" would never match anything and nobody would know
if (1 !== strlen($arg_infos['short']))
{
PwgCommand::error('Command "'.$name.'": short "'.$arg_infos['short'].'" of "'.$arg_name.'" must be a single letter');
exit(PwgCommand::ERROR);
}
if (isset($reserved_shorts[$arg_infos['short']]))
{
PwgCommand::error('Command "'.$name.'": short "'.$arg_infos['short'].'" is reserved by the global option "'.$reserved_shorts[$arg_infos['short']].'"');
exit(PwgCommand::ERROR);
}
if (isset($taken_shorts[$arg_infos['short']]))
{
PwgCommand::error('Command "'.$name.'": short "'.$arg_infos['short'].'" is used by both "'.$taken_shorts[$arg_infos['short']].'" and "'.$arg_name.'"');
exit(PwgCommand::ERROR);
}
$taken_shorts[$arg_infos['short']] = $arg_name;
}
}
$new_command = [
'name' => $name,
'spec' => $spec,
'callback' => $callback,
'file_to_include' => $file_to_include,
];
if (null === $new_command['callback'])
{
PwgCommand::error('Command "'.$name.'" must have a callback');
exit(PwgCommand::ERROR);
}
// impossible operand declarations die here, at parse time the user could do nothing about them
$seen_optional = false;
$seen_multiple = false;
foreach ($spec['operands'] ?? [] as $operand_name => $operand_infos)
{
if ($seen_multiple)
{
PwgCommand::error('Command "'.$name.'": operand "'.$operand_name.'" is unreachable, the multiple operand must be the last one');
exit(PwgCommand::ERROR);
}
$seen_multiple = !empty($operand_infos['multiple']);
$optional = $seen_multiple || array_key_exists('default', $operand_infos);
if ($seen_optional && !$optional)
{
PwgCommand::error('Command "'.$name.'": mandatory operand "'.$operand_name.'" cannot follow an optional one');
exit(PwgCommand::ERROR);
}
$seen_optional = $optional;
}
$this->commands[$name] = $new_command;
}
public function boot_level()
{
return $this->boot_level;
}
public function all_commands()
{
return $this->commands;
}
}
// walk the PATH instead of calling "which": no shell_exec, which many hosts disable
function cli_has_program(string $program): bool
{
foreach (explode(PATH_SEPARATOR, (string) getenv('PATH')) as $directory)
{
if ('' !== $directory and is_executable(rtrim($directory, '/').'/'.$program))
{
return true;
}
}
return false;
}
// the user the web server runs PHP as, read off files only it writes: the compiled
// templates, then its log files. Null when the gallery has not written anything yet.
function cli_web_user(): ?string
{
global $conf;
if (!function_exists('posix_getpwuid'))
{
return null;
}
$data = PHPWG_ROOT_PATH.rtrim($conf['data_location'], '/').'/';
$written = glob($data.'templates_c/*.php') ?: [];
foreach (glob($data.trim($conf['log_dir'], '/').'/*.txt') ?: [] as $log)
{
// our own log files carry our own owner, they prove nothing about the web server
if (0 !== strpos(basename($log), 'log_cli_'))
{
$written[] = $log;
}
}
foreach ($written as $file)
{
$owner = posix_getpwuid(fileowner($file));
if (isset($owner['name']))
{
return $owner['name'];
}
}
return null;
}
// can that user write there, from owner, group and mode alone: ACLs are not read
function cli_user_can_write(string $user, string $path): bool
{
if (!function_exists('posix_getpwnam') or !file_exists($path))
{
return false;
}
$account = posix_getpwnam($user);
if (false === $account)
{
return false;
}
$mode = fileperms($path);
if ($mode & 0002)
{
return true;
}
if (fileowner($path) === $account['uid'])
{
return (bool) ($mode & 0200);
}
$group = posix_getgrgid(filegroup($path));
$in_group = filegroup($path) === $account['gid']
|| (false !== $group && in_array($user, $group['members'], true));
return $in_group && ($mode & 0020);
}
// what the CLI runs as right now, for the messages
function cli_process_user(): ?string
{
if (!function_exists('posix_geteuid'))
{
return null;
}
return posix_getpwuid(posix_geteuid())['name'] ?? (string) posix_geteuid();
}
// how to run something as another user, with what this system actually has
function cli_run_as(string $user, string $command): string
{
foreach (['sudo', 'doas'] as $elevator)
{
if (cli_has_program($elevator))
{
return $elevator.' -u '.$user.' '.$command;
}
}
if (is_file('/.dockerenv'))
{
return 'docker exec -u '.$user.' <container> '.$command;
}
return 'log in as '.$user.' and run: '.$command;
}
function cli_promote_user()
{
global $user, $conf;
$user = build_user($conf['webmaster_id'] ?? 1, false);
}
// the web server owns its log file, the CLI writes its own
function cli_swap_logger()
{
global $logger, $conf;
$logger = new Logger(array(
'directory' => PHPWG_ROOT_PATH.$conf['data_location'].$conf['log_dir'],
'severity' => $conf['log_level'],
// same hashed scheme as the core, the file must stay unreachable over HTTP
'filename' => 'log_cli_'.date('Y-m-d').'_'.sha1(date('Y-m-d').$conf['db_password']).'.txt',
// our own pattern, purging must never touch the web server files
'globPattern' => 'log_cli_*.txt',
'archiveDays' => $conf['log_archive_days'],
));
}