forked from Daniel-KM/Noid4Php
-
Notifications
You must be signed in to change notification settings - Fork 1
/
noid
executable file
·2661 lines (2525 loc) · 94.7 KB
/
noid
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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/php
<?php
/**
* noid - a php script that mints and binds nice opaque identifiers
* using the Noid.php class. This script can be invoked additionally
* via a URL interface as "noidu…", which formats output for the web.
*
* Author: John A. Kunze, jak@ucop.edu, California Digital Library
* Orginally created Nov. 2002 at UCSF Center for Knowledge Management
* Ported to PHP by Daniel Berthereau for Mines ParisTech
*
* ---------
* Copyright (c) 2002-2006 UC Regents
* Copyright (c) 2016 Daniel Berthereau
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names
* of the UC Regents and the University of California are not used in any
* advertising or publicity relating to the software without the specific,
* prior written permission of the University of California.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY
* THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOFTWARE.
* ---------
*
* XXX change 'NOID' as database name to 'dbnoid' (for case insensitive filesys)
* XXX fix To Do alphabets
* XXX document an example of how to set up a rewrite rule that responds
* to the ? and ?? at the end of an id, and convert to a CGI string
* XXX add java interface
* XXX fix env test to suggest that NFS and AFS filesystems not be used
* XXX why does dbopen fail when doing dbinfo from an account that can't
* write the file -- should be doing readonly open
* XXX record literal noid dbcreate (re)creation command used into README
*/
/**
* Notes
*
* Command line is strict posix: options must be set before arguments, with or
* without the "--" separator. Perl script allows any order.
*/
/**
* added by xQ, 2018-12-25 07:24
*
* read all the database interfaces.
*
* lib/GlobalValues.php
* includes the array of 'db_type' => 'database class/file name'.
*/
namespace Noid;
use \Exception;
use Noid\Lib\Noid;
use Noid\Lib\Globals;
use Noid\Lib\Db;
use Noid\Lib\Log;
use Noid\Lib\Storage\DatabaseInterface;
require_once 'Lib/Noid.php';
require_once 'Lib/Globals.php';
require_once 'Lib/Db.php';
require_once 'Lib/Log.php';
require_once 'Lib/Storage/DatabaseInterface.php';
// Not used.
// $template = NULL;
// $snaa = NULL;
// $total = NULL;
// yyy make a noidmail (email robot interface?)
// yyy location field for redirect should include a discriminant
// eg, ^c for client choice, ^i for ipaddr, ^f format, ^l language
// and ^b for browser type, ^xyz for any http header??
// yyy add "file" command, like bind, but stores a file, either as file or
// in a big concatenation stream (binding offset, length, checksum)?
// yyy figure out whether validate needs to open the database, and if not,
// what that means
// yyy for locking and transactions: (1) ask Paul Marquess about what
// Perl interface support for txn and locking really is (2) check into
// lock and/or transaction timeout, (3) if I use cursors exclusively for
// storage, that may solve everything(?) (eg, no more simple tied assignments,
// which are db_put's in disguise, (4) make sure Noid.pm exit block releases
// locks, aborts transactions, etc.
if(!class_exists('NoidApp')){
/**
* Main class - NoidApp
*
* @attention function run()
*/
class NoidApp{
/**
* List of possible long options according to short ones.
*
* @const array OPTS
*/
private const OPTS = [
'd' => 'debug', // flag
'l:' => 'locktest:', // flag
'f:' => 'fdbdir:', // filesystem directory name
't:' => 'type:', // db type - bdb, mysql, xml, json, ...
'v' => 'version', // flag
'h' => 'help', // flag
];
/**
* List of valid noid commands.
*
* @const array VALID_COMMANDS
*/
private const VALID_COMMANDS = [
'bind', 'dbinfo', 'dbcreate', 'dbimport', 'fetch', 'get',
'hello', 'help', 'hold', 'mint', 'note', 'peppermint',
'queue', 'validate',
];
/**
* List of valid help topics.
*
* The valid commands are added when needed.
*
* @var array
*/
private $_valid_help_topics = [
'intro', 'all', 'templates',
];
/**
* Content of help topics.
*
* @internal purposely empty for now: filled only when needed (usage).
*
* @var array $_info
*/
private $_info;
/**
* @var string $dbdir where bdb/log files are placed.
* though mysql mode, it is used for logging.
*/
private $dbdir;
/**
* @var resource $stderr Redirect errors for web (redirect stderr to standard output).
*/
private $stderr;
/**
* @var string $contact
*/
private $contact;
/**
* @var bool $is_web Is web context?
*/
private $is_web;
/**
* Main function in main class
*
* @param array $argv arguments array
*
* @return bool TRUE - successful execution, FALSE - error
*/
public function run($argv)
{
// this setting is just for the function strftime() in Helper::getTemper().
date_default_timezone_set('UTC');
$this->is_web = FALSE;
/**
* when initialized 1st, bulk-command mode is off.
*
* @var bool $bulk_mode
*/
$bulk_mode = FALSE;
$this->stderr = STDERR;
// If called with the URL interface.
if(preg_match('|noidu[^/]*$|', $argv[0])){
if(PHP_SAPI === 'cli' || empty($_SERVER['REMOTE_ADDR'])){
print 'Not called via http.' . PHP_EOL;
return FALSE;
}
$this->is_web = TRUE; // orient output for HTTP
print 'Content-Type: text/plain' . PHP_EOL . PHP_EOL;
// Seems not possible directly in php.
// if (fopen(STDERR, ">&STDOUT") === false) {
// $error = error_get_last();
// die("Can't combine stderr and stdout: " . $error['message'] . PHP_EOL);
// }
$this->stderr = STDOUT;
if(empty($_REQUEST)){
print 'No QUERY_STRING (hence no command) defined.' . PHP_EOL;
return FALSE;
}
/**
* List of arguments from command line ($argv) or web request ($_REQUEST).
*
* @var array $args
*/
$args = $_REQUEST;
// print "ARGV: " . join('|', $argv) . PHP_EOL;
}
// If called for RewriteMap resolving.
// See Apache Rewrite mod documentation.
// TODO Check "noidr" for RewriteMap via Apache.
else if(preg_match('|noidr[^/]*$|', $argv[0])){
flush(); // very important to empty the output buffer.
$bulk_mode = TRUE;
// yyy should we set a timeout to prevent hanging the server?
/**
* List of arguments from command line ($argv) or web request ($_REQUEST).
*
* @var array $args
*/
$args = $argv;
}
else{
/**
* List of arguments from command line ($argv) or web request ($_REQUEST).
*
* @var array $args
*/
$args = $argv;
}
$this->contact = $this->who_are_you($this->is_web);
if(empty($this->contact)){
$error = error_get_last();
fwrite($this->stderr, "Can't tell who you are: " . $error['message'] . PHP_EOL);
return FALSE;
}
$options = $this->getoptreq();
if($options === FALSE){
print 'error: GetOptions' . PHP_EOL;
$this->usage(1, 1, 'intro');
return FALSE;
}
$args = $this->getOnlyArguments($args, $options);
$options = $this->unifyOptionsAsLong($options);
if(isset($options['locktest'])){
$locktest = (int)$options['locktest'];
if($locktest < 0){
print 'error: locktest value must be a positive number of seconds to sleep' . PHP_EOL;
// NOTE Why exit 0 for an error in Perl script (and somewhere else)?
return FALSE;
}
$this->command(array_combine(array('locktest'), array($locktest)));
}
if($this->is_web && !empty($options['debug'])){
print "contact={$this->contact}, pwd=" . getcwd();
}
// Handle -v or -h, and exit early.
if(isset($options['version'])){
// We take our version number from the Noid module version.
printf('This is "noid" version %s.' . PHP_EOL, Globals::VERSION);
return TRUE;
}
if(isset($options['help'])){
// yyy should we encode help output? print 'help:' . PHP_EOL;
$this->usage(0, 0, 'intro');
return TRUE;
}
// NOTE Not clear why checked later in Perl script.
if($this->is_web && isset($options['fdbdir'])){
print '-f option not allowed in URL interface.' . PHP_EOL;
return FALSE;
}
$this->dbdir = isset($options['fdbdir']) ? $options['fdbdir'] : NULL;
// Now try to find a database directory string.
// In the special case of dbcreate, we may create
// and name the directory on behalf of the user.
if(empty($this->dbdir)){
if(getenv('NOID')){ // is NOID env variable defined?
$this->dbdir = getenv('NOID');
}
// Executable link reveals dbdir?
else if(preg_match('|_([^/]+)$|', $args[0], $matches)){
$this->dbdir = $matches[1];
}
// Else try current directory.
else{
$this->dbdir = getcwd();
}
$this->dbdir = trim($this->dbdir);
if(empty($this->dbdir)){
print 'error: no DbDir' . PHP_EOL;
$this->usage(1, 1, 'intro');
return FALSE;
}
}
// Now check the validity of $this->dbdir. yyy we can do better?
if(preg_match('|^(.*)$|', $this->dbdir, $matches)){
$this->dbdir = $matches[1];
}
else{
print('error: bad DbDir' . PHP_EOL);
$this->usage(1, 1, 'intro');
return FALSE;
}
// get the option "-t/--type" (database type)
// default - bdb (BerkeleyDB)
$db_type_option = isset($options['type']) ? $options['type'] : 'bdb';
if(empty($db_type_option)){
$db_type_option = 'bdb';
}
else if(!in_array($db_type_option, array_keys(Globals::DB_TYPES))){
print 'error: invalid DbType (database type).' . PHP_EOL;
$this->usage(1, 1, 'intro');
return FALSE;
}
Globals::$db_type = $db_type_option;
// Bulk command mode is signified by a single final argument of "-".
// If we're _not_ in bulk command mode, expect a single command
// represented by the remaining arguments; do it and exit.
$bulk_mode = $bulk_mode || (count($args) == 2 && $args[1] == '-');
/* normal execution */
if(!$bulk_mode){
// Remove the command itself.
unset($args[0]);
$this->command($args);
}
/* bulk("endless") command by while-loop */
else{
// If we get here, we're in bulk command mode. Read, tokenize,
// and execute commands from the standard input. Test with
// curl --data-binary @cmd_file http://dot.ucop.edu/nd/noidu_kt5\?-
// where cmd_file contains newline-separated commands.
// XXX make sure to %-decode web QUERY_STRING, so we don't have
// to always put +'s for spaces
//
// NOTE The delimiter is the '"', even missing, but command line allows "'" too.
while($args = fgetcsv(STDIN, ' ', '"')){
$this->command($args);
}
}
return TRUE;
}
/**
* @param array $args
*
* @return int|mixed
*/
public function command($args = array())
{
// Any remaining args should form a noid command.
// Look at the command part (if any) now, and complain about
// a non-existent database unless the command is "dbcreate".
$command = array_shift($args);
$command = trim($command);
if(empty($command)){ // if no command arg
$this->usage(1, 1, 'intro');
return 0;
}
if(!is_dir($this->dbdir)
&& $command != 'dbcreate'
&& $command != 'help'
){
// if the database doesn't exist when it needs to
fwrite($this->stderr, sprintf('error: no storage path (%s) -- use dbcreate?', $this->dbdir) . PHP_EOL . PHP_EOL);
$this->usage(1, 1, 'intro');
return 0;
}
if(!in_array($command, self::VALID_COMMANDS)){
printf('error: no such command: %s (%s).' . PHP_EOL,
$command, implode(' ', $args));
$this->usage(1, 1, 'intro');
return 0;
}
// Perform extra checks in $this->is_web case.
if($this->is_web && $command == 'dbcreate'){
printf('error: command "%s" not allowed in URL interface.' . PHP_EOL, $command);
$this->usage(1, 1, 'intro');
return 0;
}
return call_user_func_array(array($this, $command), $args);
}
/* --- begin almost alphabetic listing of functions --- */
/**
* Returns number of elements successfully bound.
*
* yyy what is the sensible thing to do if (a) no element given,
* (b) if no value, or (c) if there are multiple values?
* yyy vbind(…, template, …)? nvbind()?
*
* yyy what about append at the list vs the string level?
*
* @param string $how
* @param string $id
* @param string $elem
* @param string $value
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function bind($how = NULL, $id = NULL, $elem = NULL, $value = NULL)
{
$validate = 1;
$noid = Db::dbopen($this->dbdir, DatabaseInterface::DB_WRITE);
if(!$noid){
fwrite($this->stderr, Log::errmsg($noid));
return 0;
}
$report = NULL;
if(is_null($elem)){
$elem = '';
}
if($elem === ':'){ // expect name/value pairs up to blank line
if(strlen($value)){
fwrite($this->stderr, sprintf('Why give a value (%s) with an element "%s"?',
$value, $elem) . PHP_EOL);
Db::dbclose($noid);
return 0;
}
// Slurp a paragraph (double end of line).
// Multi lines input from command line: loop until two end of lines.
$input = '';
$eol = 0;
do{
$line = fgets(STDIN); // reads one line from STDIN
// Check if this is a double end of line (without white spaces).
$line == PHP_EOL ? $eol++ : $eol = 0;
$input .= $line;
}while($eol < 1); // Means paragraph mode.
$para = trim($input);
// Only the first comment is removed.
$para = preg_replace('/^#.*\R/', '', $para); // remove comment lines
$para = preg_replace('/\R\s+/', ' ', $para); // merge continuation lines
// Keep only lines with at least one ":".
$elemvals = preg_split('/^([^:]+)\s*:\s*/m', $para, -1, PREG_SPLIT_DELIM_CAPTURE);
array_shift($elemvals); // throw away first null
$bound = 0;
$total = 0;
while(TRUE){
$elem = trim(array_shift($elemvals));
$value = trim(array_shift($elemvals));
if(strlen($elem) == 0 && strlen($value) == 0){
break;
}
$total++;
if(strlen($elem) == 0){
Log::addmsg($noid,
sprintf('error: %s: bad element associated with value "%s".', $id, $value));
break;
}
$report = Noid::bind($noid, $this->contact, $validate,
$how, $id, $elem, $value);
if(is_null($report)){
fwrite($this->stderr, $report . PHP_EOL);
$this->usage(1, 1, 'bind');
// yyy how/who should log failures in "hard" case
}
else{
$bound++;
print $report . PHP_EOL;
}
}
// yyy summarize for log $total and $bound
Db::dbclose($noid);
return is_null($report) ? 1 : 0;
}
else if($elem == ':-'){ // expect name/value to be rest of file
if(strlen($value)){
fwrite($this->stderr, sprintf('Why give a value (%s) with an element "%s"?',
$value, $elem) . PHP_EOL);
Db::dbclose($noid);
return 0;
}
// Read all of STDIN into array "@input_lines".
// And remove all newlines.
$input_lines = file_get_contents('php://stdin', 'r');
$input_lines = explode(PHP_EOL, trim($input_lines));
$input_lines = array_map('trim', $input_lines);
// Ignore any leading lines that start with a pound sign
// or contain nothing but white space.
while(count($input_lines) > 0){
if(substr($input_lines[0], 0, 1) == '#'
|| trim($input_lines[0]) == ''
){
array_shift($input_lines);
continue;
}
break;
}
// If we don't have any lines, there's a problem.
if(count($input_lines) == 0){
fwrite($this->stderr, 'error: no non-blank, non-comment input.' . PHP_EOL);
Db::dbclose($noid);
return 0;
}
// There must be an element and a colon on the first line.
if(!preg_match('/^\s*(\w+)\s*:\s*(.*)$/', $input_lines[0], $matches)){
fwrite($this->stderr, 'error: missing element or colon on first non-blank, non-comment line.' . PHP_EOL);
Db::dbclose($noid);
return 0;
}
// Save the element, and any part of the value that there
// might be on the first line.
$elem = $matches[1];
$value = $matches[2];
// Remove the first line from the array.
array_shift($input_lines);
// Append any additional lines to the value.
foreach($input_lines as $v){
$value .= PHP_EOL . $v;
}
// Put on the final newline.
$value .= PHP_EOL;
// Now drop through to end of if-elseif clause to real binding.
}
// yyy eg, :fragment:Offset:Length:Path
// yyy eg, :fragment:Offset:Length:Path
// yyy eg, :file:Path
// yyy eg, ":xml",
else if(strpos($elem, ':') === 0){
fwrite($this->stderr, sprintf('Binding to element syntax "%s" not supported.', $elem) . PHP_EOL);
Db::dbclose($noid);
return 0;
}
$report = Noid::bind($noid, $this->contact, $validate, $how, $id, $elem, $value);
if(empty($report)){
fwrite($this->stderr, Log::errmsg($noid));
$this->usage(0, 1, 'bind');
}
else{
print $report . PHP_EOL;
}
// yyy make sure return(0)'s do dbclose…
Db::dbclose($noid);
return empty($report) ? 1 : 0;
}
/**
* This routine may not make sense in the URL interface.
*
* @param string $template
* @param string $policy
* @param string $naan
* @param string $naa
* @param string $subnaa
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function dbcreate($template = NULL, $policy = NULL, $naan = NULL, $naa = NULL, $subnaa = NULL)
{
$dbreport = Db::dbcreate($this->dbdir, $this->contact, $template, $policy,
$naan, $naa, $subnaa);
if(!$dbreport){
print Log::errmsg() . PHP_EOL;
return 0;
}
print $dbreport . PHP_EOL;
return 1;
}
/**
* @param string $src_type
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function dbimport($src_type)
{
if(!isset($src_type)){
print "Missing argument for dbimport. (xml/bdb/mysql)" . PHP_EOL;
return 0;
}
if(!strcmp(Globals::$db_type, strtolower($src_type))){
print "The source db type must differ to the destination(" . Globals::$db_type . ")." . PHP_EOL;
return 0;
}
print "Importing from {$src_type} to " . Globals::$db_type . "... ";
if(!Db::dbimport($this->dbdir, $src_type)){
print "[failed]" . PHP_EOL;
return 0;
}
print "[OK]" . PHP_EOL;
return 1;
}
/**
* Return info about database.
*
* @param string $level
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function dbinfo($level = NULL)
{
if(empty($level)){
$level = 'brief';
}
$noid = Db::dbopen($this->dbdir, DatabaseInterface::DB_RDONLY);
if(!$noid){
print Log::errmsg($noid);
return 0;
}
Db::dbinfo($noid, $level);
Db::dbclose($noid);
return 1;
}
/**
* Fetch elements.
*
* @param string $id
* @param array|string $elems All arguments will be fetched if not an array.
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function fetch($id = NULL, $elems = array())
{
if(!is_array($elems)){
$elems = func_get_args();
array_shift($elems);
}
return $this->_getfetch(1, $id, $elems);
}
/**
* Get elements.
*
* @param string $id
* @param array|string $elems All arguments will be gotten if not an array.
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function get($id = NULL, $elems = array())
{
if(!is_array($elems)){
$elems = func_get_args();
array_shift($elems);
}
return $this->_getfetch(0, $id, $elems);
}
/**
* Helper to get/fetch elements.
*
* @param int $verbose
* @param string $id
* @param array $elems
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
private function _getfetch($verbose, $id, $elems)
{
$noid = Db::dbopen($this->dbdir, DatabaseInterface::DB_RDONLY);
if(!$noid){
fwrite($this->stderr, Log::errmsg($noid));
return 0;
}
$fetched = Noid::fetch($noid, $verbose, $id, $elems);
if(is_null($fetched)){
fwrite($this->stderr, Log::errmsg($noid));
}
else{
print($fetched);
if($verbose){
print PHP_EOL;
}
}
Db::dbclose($noid);
return 1;
}
/**
* Get a user note from a key.
*
* @param string $key
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function get_note($key)
{
$noid = Db::dbopen($this->dbdir, DatabaseInterface::DB_RDONLY);
if(!$noid){
fwrite($this->stderr, Log::errmsg($noid));
return 0;
}
$note = Log::get_note($noid, $key);
if(is_null($note)){
fwrite($this->stderr, Log::errmsg($noid));
}
else{
print($note);
}
Db::dbclose($noid);
return 1;
}
/**
* A useless function to check the module.
*
* @return void
*/
public function hello()
{
print 'Hello.' . PHP_EOL;
}
/**
* Return help about a command.
*
* @param string $topic
*
* @return int 1 (success)
*/
public function help($topic = '')
{
$in_error = 0;
$brief = 0;
return $this->usage($in_error, $brief, $topic);
}
// yyy what about a "winnow" routine that is either started
// from cron or is started when an exiting noid call notices
// that there's some harvesting/garbage collecting to do and
// schedules it for, say, 10 minutes hence (by not exiting,
// but sleeping for 10 minutes and then harvesting)?
/**
* Hold ids.
*
* @param string $on_off "hold" or "release"
* @param array|string $ids All arguments will be processed if not an array.
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function hold($on_off = NULL, $ids = array())
{
if(!is_array($ids)){
$ids = func_get_args();
array_shift($ids);
}
$noid = Db::dbopen($this->dbdir, DatabaseInterface::DB_WRITE);
if(!$noid){
fwrite($this->stderr, Log::errmsg($noid));
return 0;
}
if(!Noid::hold($noid, $this->contact, $on_off, $ids)){
fwrite($this->stderr, Log::errmsg($noid));
$this->usage(1, 1, 'hold');
Db::dbclose($noid);
return 0;
}
print(Log::errmsg($noid) . PHP_EOL); // no error message at all
Db::dbclose($noid);
return 1;
}
/**
* Peppermint a noid.
*
* @param int $n
* @param string $elem
* @param string $value
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function peppermint($n = 0, $elem = NULL, $value = NULL)
{
return $this->mint($n, $elem, $value, TRUE);
}
/**
* Mint a noid.
*
* @param int $n
* @param string $elem
* @param string $value
* @param bool $pepper
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function mint($n = NULL, $elem = NULL, $value = NULL, $pepper = FALSE)
{
if($pepper){
fwrite($this->stderr,
'The peppermint command is not implemented yet.' . PHP_EOL);
return 0;
}
if(is_null($n) || !is_numeric($n)){
fwrite($this->stderr, sprintf('Argument error: expected positive integer, got %s',
!is_null($n) ? $n : 'nothing') . PHP_EOL);
$this->usage(1, 1, 'mint');
return 0;
}
$noid = Db::dbopen($this->dbdir, DatabaseInterface::DB_WRITE);
if(!$noid){
print Log::errmsg($noid);
return 0;
}
while($n--){
$id = Noid::mint($noid, $this->contact, $pepper);
if(is_null($id)){
fwrite($this->stderr, Log::errmsg($noid));
Db::dbclose($noid);
return 0;
}
print "id: $id" . PHP_EOL;
}
Db::dbclose($noid);
print PHP_EOL;
return 1;
}
/**
* Add a note.
*
* @param string $key
* @param string $value
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function note($key = '', $value = '')
{
if(!strlen($key) || !strlen($value)){
fwrite($this->stderr,
'You must supply a key and a value.' . PHP_EOL);
$this->usage(1, 1, 'note');
return 0;
}
$noid = Db::dbopen($this->dbdir, DatabaseInterface::DB_WRITE);
if(!Log::note($noid, $this->contact, $key, $value)){
print Log::errmsg($noid);
}
Db::dbclose($noid);
return 1;
}
/**
* Queue.
*
* @param string $when
* @param array|string $ids All arguments will be queued if not an array.
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function queue($when = NULL, $ids = array())
{
if(!is_array($ids)){
$ids = func_get_args();
array_shift($ids);
}
$noid = Db::dbopen($this->dbdir, DatabaseInterface::DB_WRITE);
if(!$noid){
fwrite($this->stderr, Log::errmsg($noid));
return 0;
}
$queued = Noid::queue($noid, $this->contact, $when, $ids);
if(empty($queued)){
$retval = 0;
fwrite($this->stderr, Log::errmsg($noid) . PHP_EOL);
}
else{
$retval = 1;
print(join(PHP_EOL, $queued) . PHP_EOL);
}
$n = array_filter($queued, function($v){
return strpos($v, 'error:') !== 0;
});
$n = count($n);
printf('note: %d %s queued' . PHP_EOL, $n, $n == 1 ? 'identifier' : 'identifiers');
Db::dbclose($noid);
return $retval;
}
/**
* Returns the number of valid ids.
*
* @param string $template
* @param array|string $ids All arguments will be validated if not an array.
*
* @return int 0 (error) or 1 (success)
* @throws Exception
*/
public function validate($template = NULL, $ids = array())
{
if(!is_array($ids)){
$ids = func_get_args();
array_shift($ids);
}
$noid = Db::dbopen($this->dbdir, DatabaseInterface::DB_RDONLY);
if(!$noid){
print Log::errmsg($noid);
return 0;
}
$valids = Noid::validate($noid, $template, $ids);
if(empty($valids)){
fwrite($this->stderr, Log::errmsg($noid));
Db::dbclose($noid);
$this->usage(1, 1, 'validate');
return 0;
}
$iderrs = array_filter($valids, function($v){
return strpos($v, 'error:') === 0;
});
foreach($valids as $valid){
print($valid . PHP_EOL);
}
Db::dbclose($noid);
return count($ids) - count($iderrs);
}
/**
* Print a blank (space) in front of every newline.
* First arg must be a filehandle.
*
* @param resource $out
* @param string|array $args
*
* @return bool|int
*/
private function _bprint($out, $args)
{
$string = is_array($args) ? implode('', $args) : $args;
$string = str_replace(PHP_EOL, PHP_EOL . ' ', $string);
return fwrite($out, $string);
}
/**
* Print a message about a topic.
*
* @param int $in_error
* @param int $brief
* @param string $topic
*
* @return int Always returns 1 so it can be used in boolean blocks.
*/
private function usage($in_error = NULL, $brief = NULL, $topic = NULL)
{
$info = &$this->_info;
if(is_null($in_error)){
$in_error = 1; // default is to treat as error