-
Notifications
You must be signed in to change notification settings - Fork 3
/
system_objects.php
783 lines (706 loc) · 21.6 KB
/
system_objects.php
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
<?php
/**
* Scavix Web Development Framework
*
* Copyright (c) 2012-2019 Scavix Software Ltd. & Co. KG
* Copyright (c) since 2019 Scavix Software GmbH & Co. KG
*
* This library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation;
* either version 3 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>
*
* @author Scavix Software Ltd. & Co. KG https://www.scavix.com <[email protected]>
* @copyright 2012-2019 Scavix Software Ltd. & Co. KG
* @author Scavix Software GmbH & Co. KG https://www.scavix.com <[email protected]>
* @copyright since 2019 Scavix Software GmbH & Co. KG
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
*/
namespace ScavixWDF;
use Exception;
if( !defined('FRAMEWORK_LOADED') || FRAMEWORK_LOADED != 'uSI7hcKMQgPaPKAQDXg5' ) die('');
/**
* WDF internal replacement for $GLOBALS usage.
*/
class Wdf
{
public static $Logger = [];
public static $Timer = [];
public static $DataSources = [];
public static $Hooks = [];
public static $Modules = [];
public static $ClassAliases = [];
public static $Request;
public static $ClientIP;
public static $SessionHandler;
public static $ObjectStore;
public static $Translation;
private static $once_buffer = [];
/**
* Helper to easily check if something was already done.
*
* @param mixed $id An ID value
* @return bool True, if has already been called with $id, else false
*/
public static function Once($id)
{
if( isset(self::$once_buffer[$id]) )
return false;
self::$once_buffer[$id] = true;
return true;
}
protected static $buffers = [];
protected static $locks = false;
/**
* Checks if there's a buffer present.
*
* @param string $name Buffer identifier
* @return bool True if present, else false
*/
public static function HasBuffer($name)
{
return isset(self::$buffers[$name]);
}
/**
* Creates a buffer that can be used instead of $GLOBALS variable.
* Optionally, buffers can be mapped to a SESSION variable.
*
* @param string $name Buffer identifier
* @param array|callable $initial_data Array with initial data or callback returning this initial data
* @return \ScavixWDF\WdfBuffer
*/
public static function GetBuffer($name,$initial_data=[])
{
if( !isset(self::$buffers[$name]) )
self::$buffers[$name] = new WdfBuffer($initial_data);
return self::$buffers[$name];
}
/**
* Sets up a LOCK for a given name.
*
* On Linux system uses the /run/lock folder to create a lock file. If this
* succeeds returns true. If not and a timeout is given will try for that amount
* of seconds. If still fails trhows an exception if $exceptiononfailure is true or returns false.
* In all other OS see <system_get_lock>().
*
* @param string $name Lock name
* @param int $timeout Seconds to wait/retry (default 10)
* @param bool $exceptiononfailure If true will throw an exception if lock cannot be created (default: true)
* @return bool True on success, else false
*/
public static function GetLock($name,$timeout=10,$exceptiononfailure=true)
{
if( PHP_OS_FAMILY == "Linux" )
{
$lock = md5($name);
$dir = '/run/lock/wdf-'.md5(__SCAVIXWDF__);
$um = umask(0);
@mkdir($dir, 0777, true);
$end = time()+$timeout;
do
{
$fp = @fopen("$dir/$lock","x+");
if( !$fp )
{
if( $timeout > 0 )
usleep(100000);
continue;
}
fwrite($fp,getmypid());
fflush($fp);
fclose($fp);
if( self::$locks === false )
{
self::$locks = [];
register_shutdown_function(function()
{
foreach( Wdf::$locks as $lock=>$fp )
@unlink('/run/lock/wdf-'.md5(__SCAVIXWDF__).'/'.$lock);
});
}
self::$locks[$lock] = $fp;
umask($um);
return true;
}
while(time()<$end);
foreach( glob("$dir/???*") as $f )
{
if( !system_process_running(trim(@file_get_contents($f))) )
@unlink($f);
}
umask($um);
if( ($timeout <= 0) || !$exceptiononfailure )
return false;
else
WdfException::Raise("Timeout while awaiting the lock '$name'");
}
return system_get_lock($name,\ScavixWDF\Model\DataSource::Get(),$timeout);
}
/**
* Releases a LOCK.
*
* @param string|array $name The LOCK name as single string or array of lock names to release
* @return bool True if successful, else false
*/
public static function ReleaseLock($name)
{
$locks = array_filter(force_array($name));
$ret = false;
foreach ($locks as $lockname)
{
if (PHP_OS_FAMILY == "Linux")
{
$lock = md5($lockname);
if (isset(self::$locks[$lock]))
{
@unlink('/run/lock/wdf-'.md5(__SCAVIXWDF__).'/'.$lock);
unset(self::$locks[$lock]);
$ret = true;
}
}
elseif (system_release_lock($lockname, \ScavixWDF\Model\DataSource::Get()))
$ret = true;
}
return $ret;
}
}
/**
* Implements buffering methods.
*/
class WdfBuffer implements \Iterator, \JsonSerializable
{
protected $changed = false;
protected $data = [];
protected $session_name = false;
protected $position = 0;
function __construct($initial_data=[])
{
if( is_callable($initial_data) )
$this->data = $initial_data();
else
$this->data = is_array($initial_data)?$initial_data:[];
}
/**
* @internal see <JsonSerializable>
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->dump();
}
/**
* Maps this buffer to a $_SESSION variable.
*
* Mapping to the session means that from now on all data will be stored
* into $_SESSION[$name] and that getting data will transparently use that variable too.
*
* @param string $name Name of session variable
* @return \ScavixWDF\WdfBuffer
*/
function mapToSession($name=false)
{
if( !$this->session_name )
$this->session_name = $name;
return $this;
}
/**
* Returns all data as assiciative array.
*
* @return array
*/
function dump()
{
if( $this->session_name && isset($_SESSION[$this->session_name]) )
return array_merge($_SESSION[$this->session_name],$this->data);
return $this->data;
}
/**
* Returns true if some data has been changed.
*
* This is true, if <WdfBuffer::set> or <WdfBuffer::set> have been used
* and if they effectively did something.
*
* @return bool
*/
function hasChanged()
{
return $this->changed;
}
/**
* Returns an array of data keys.
*
* @return array
*/
function keys()
{
$keys = array_keys($this->data);
if( $this->session_name && isset($_SESSION[$this->session_name]) )
$keys = array_unique(array_merge($keys,array_keys($_SESSION[$this->session_name])));
return $keys;
}
/**
* Returns true, if there's data stored with the given name.
*
* @param string $name The key for the data
* @return bool
*/
function has($name)
{
return isset($this->data[$name])
|| ($this->session_name && isset($_SESSION[$this->session_name][$name]));
}
/**
* Stores data in the buffer.
*
* @param string $name The key for the data
* @param mixed $value The data to store
* @return mixed The value given
*/
function set($name, $value)
{
if( !$this->changed )
$prev = $this->get($name,null);
$this->data[$name] = $value;
if( $this->session_name )
$_SESSION[$this->session_name][$name] = $value;
if( !$this->changed )
$this->changed = ($prev !== $value);
return $value;
}
/**
* Removes data from the buffer.
*
* @param string $name The key for the data
* @return mixed The removed value if present, else null
*/
function del($name)
{
if( isset($this->data[$name]) )
{
$r = $this->data[$name];
unset($this->data[$name]);
$this->changed = true;
}
if( $this->session_name && isset($_SESSION[$this->session_name][$name]) )
{
unset($_SESSION[$this->session_name][$name]);
$this->changed = true;
}
return isset($r)?$r:null;
}
/**
* Removes all data from the buffer.
*
* @return void
*/
function clear()
{
$this->changed = count($this->data)>0;
$this->data = [];
if( $this->session_name && isset($_SESSION[$this->session_name]) )
{
$this->changed |= count($_SESSION[$this->session_name])>0;
$_SESSION[$this->session_name] = [];
}
}
/**
* Returns data from the buffer.
*
* @param string $name The key for the data
* @param mixed $default A default value, can be a callable too that will get the name and must return the value;
* @return mixed The removed value if present, else null
*/
function get($name, $default=null)
{
if( !isset($this->data[$name]) && $this->session_name && isset($_SESSION[$this->session_name][$name]) )
$this->data[$name] = $_SESSION[$this->session_name][$name];
if( isset($this->data[$name]) )
return $this->data[$name];
if( is_callable($default) )
return $this->set($name,$default($name));
return $default;
}
/**
* @implements <Iterator::rewind>
*/
public function rewind():void
{
$this->position = 0;
}
/**
* @implements <Iterator::current>
*/
#[\ReturnTypeWillChange]
public function current():mixed
{
return $this->get($this->key());
}
/**
* @implements <Iterator::key>
*/
#[\ReturnTypeWillChange]
public function key():mixed
{
return $this->keys()[$this->position];
}
/**
* @implements <Iterator::next>
*/
public function next():void
{
$this->position++;
}
/**
* @implements <Iterator::valid>
*/
public function valid():bool
{
return isset($this->keys()[$this->position]);
}
}
/**
* We use this to test access to controllers.
* All controllers must implement this interface
*/
interface ICallable {}
/**
* Defines an objects that handles log-string creation itself.
*/
interface ILogWritable
{
public function __toLogString(): string;
}
/**
* Transparently wraps Exceptions thus providing a way to catch them easily while still having the original
* Exception information.
*
* Using static <WdfException::Raise>() method you can pass in multiple arguments. ScavixWDF will try to detect
* if there's an exception object given and use it (the first one detected) as inner exception object.
* <code php>
* WdfException::Raise('My simple test');
* WdfException::Raise('My simple test2',$obj_to_debug_1,'and',$obj_to_debug_2);
* try{ $i=42/0; }catch(Exception $ex){ WdfException::Raise('That was stupid!',$ex); }
* <code>
*/
class WdfException extends Exception
{
use WdfThrowable;
}
trait WdfThrowable
{
public $details = '';
private function ex()
{
$inner = $this->getPrevious();
return $inner?$inner:$this;
}
/**
* Use this to throw exceptions the easy way.
*
* Can be used from derivered classes too like this:
* <code php>
* ToDoException::Raise('implement myclass->mymethod()');
* </code>
* @param mixed ...$args Messages to be concatenated
* @return void
* @suppress PHP1402
*/
public static function Raise(...$args)
{
[$message, $msgs, $inner_exception] = self::_prepareArgs(...$args);
/**
* @var WdfException $classname
*/
$classname = get_called_class();
if( $inner_exception )
$ex = new $classname($message,$inner_exception->getCode(),$inner_exception);
else
$ex = new $classname($message);
$ex->details = implode("\t",$msgs);
throw $ex;
}
protected static function _prepareArgs(...$args)
{
$msgs = [];
$inner_exception = false;
foreach( $args as $m )
{
if( !$inner_exception && ($m instanceof Exception) )
$inner_exception = $m;
else
$msgs[] = logging_render_var($m);
}
$message = array_shift($msgs);
return [$message, $msgs, $inner_exception];
}
/**
* Use this to easily log an exception the nice way.
*
* Ensures that all your exceptions are logged the same way, so they are easily readable.
* sample:
* <code php>
* try{
* some code
* }catch(Exception $ex){ WdfException::Log("Weird:",$ex); }
* </code>
* Note that Raise method will log automatically, so this is mainly useful when silently catching exceptions.
* @param mixed ...$args Messages to be concatenated
* @return void
*/
public static function Log(...$args)
{
call_user_func_array('log_error', $args);
}
/**
* Returns exception message.
*
* Check if there's an inner exception and combines this and that messages into one if so.
* @return string Combined message
*/
public function getMessageEx()
{
$inner = $this->getPrevious();
return $this->getMessage().($inner?"\nOriginal message: ".$inner->getMessage():'');
}
/**
* Calls this or the inner exceptions getFile() method.
*
* See http://www.php.net/manual/en/exception.getfile.php
* @return string Returns the filename in which the exception was created
*/
public function getFileEx(){ return $this->ex()->getFile(); }
/**
* Calls this or the inner exceptions getCode() method.
*
* See http://www.php.net/manual/en/exception.getcode.php
* @return string Returns the exception code as integer
*/
public function getCodeEx(){ return $this->ex()->getCode(); }
/**
* Calls this or the inner exceptions getLine() method.
*
* See http://www.php.net/manual/en/exception.getline.php
* @return string Returns the line number where the exception was created
*/
public function getLineEx(){ return $this->ex()->getLine(); }
/**
* Calls this or the inner exceptions getTrace() method.
*
* See http://www.php.net/manual/en/exception.gettrace.php
* @return array Returns the Exception stack trace as an array
*/
public function getTraceEx(){ return $this->ex()->getTrace(); }
}
/**
* Thrown when something still needs investigation
*
* We use this like this: `ToDoException::Raise('Not yet implemented')`
*/
class ToDoException extends WdfException {}
/**
* Thrown from all database related system parts
*
* All code in the model essential (essentials/model.php + essentials/model/*) use this instead of WdfException.
* Just to have everyting nicely wrapped.
*/
class WdfDbException extends WdfException
{
public static $DISABLE_LOGGING = false;
private $statement;
private static function _prepare(string $message, ?Model\ResultSet $statement = null)
{
if( isDev() )
$msg = "SQL Error: $message";
else
$msg = "SQL Error occured";
if( $statement )
{
$trim_sql = function($s)
{
$lines = explode("\n",$s);
foreach( ["\t"," "] as $ws )
{
$pre = [];
foreach( $lines as $l )
$pre[] = strspn($l,$ws)?:999;
$min = min($pre);
if( $min == 999 )
continue;
foreach( $lines as $i=>&$l )
$l = preg_replace("/^{$ws}{{$min}}/","",$l);
break;
}
return implode("\n",$lines);
};
$sql = $trim_sql($statement->GetSql());
$args = $statement->GetArgs();
$msql = $trim_sql($statement->GetMergedSql());
$details = "Message: $message\nSQL: $sql";
if( $args && count($args) )
$details .= "\nArguments: ".json_encode($args);
if( $msql != $sql )
$details .= "\nMerged: $msql";
return [$msg, $details];
}
return [$msg, ''];
}
/**
* @internal Wraps a \PDOException, optionally with the triggering statement
*/
public static function RaisePdoEx(\PDOException $ex, ?Model\ResultSet $statement = null)
{
list($msg, $details) = self::_prepare($ex->getMessage(),$statement);
$res = new WdfDbException($msg);
$res->details = $details;
$res->statement = $statement;
throw $res;
}
/**
* @internal Raises an Exception for a failed DB Statement.
*/
public static function RaiseStatement($statement)
{
if(!($statement instanceof Model\ResultSet))
$statement = new Model\ResultSet($statement->_ds, $statement);
list($msg, $details) = self::_prepare(json_encode($statement->ErrorInfo()),$statement);
$ex = new WdfDbException($msg);
$ex->details = $details;
$ex->statement = $statement;
throw $ex;
}
/**
* Returns the SQL string used
*
* @return string SQL
*/
function getSql()
{
if( $this->statement )
return $this->statement->GetSql();
return '(undefined)';
}
/**
* Returns the arguments used
*
* @return array The arguments
*/
function getArguments()
{
if( $this->statement )
return $this->statement->GetArgs();
return [];
}
/**
* Returns a string merged from the SQL statement and the arguments
*
* @return string Merged SQL statement
*/
function getMergedSql()
{
if( $this->statement )
return $this->statement->GetMergedSql();
return '(undefined)';
}
/**
* Returns an array with error information
*
* @return array
*/
function getErrorInfo()
{
if( $this->statement )
return $this->statement->ErrorInfo();
return ['','',"Error preparing the SQL statement. Most likely there's an error in the SQL syntax."];
}
/**
* @internal Helper method to detect if this represents an Exception indicating a duplicate key
*/
function isDuplicateKeyException($key = false)
{
list($c1,$c2,$msg) = $this->getErrorInfo();
$regex = "/Duplicate entry '.*' for key".($key ? " '".$key."'" : '')."/i";
return (preg_match($regex, $msg, $dummy) != false);
}
/**
* @internal Helper method to detect if this represents an Exception indicating a missing table.
*/
function isTableNotExistException($table = false)
{
list($c1,$c2,$msg) = $this->getErrorInfo();
$regex = "/Table '.*".($table ? $table : '')."' doesn't exist/i";
return (preg_match($regex, $msg, $dummy) != false);
}
}
/**
* Thrown when some process reached a state where graceful but immidiate termination is required.
*
* We use this like this: `TerminationException::WithCode('HTTP_500','Server responded with 500, cannot do that now')`
*/
class TerminationException extends \Error
{
use WdfThrowable;
private $verbose, $reason;
private static function _make(string $reason, bool $verbose, ...$args)
{
[$message, $msgs, $inner_exception] = self::_prepareArgs(...$args);
$message = $message?"$reason: $message":$reason;
if( $inner_exception )
$ex = new TerminationException($message,$inner_exception->getCode(),$inner_exception);
else
$ex = new TerminationException($message);
$ex->details = implode("\t",$msgs);
$ex->verbose = $verbose;
$ex->reason = $reason;
return $ex;
}
/**
* Raises a silent TerminationException.
*
* @param string $reason The reason for the Exception
* @param array $args Additional arguments to be logged.
* @return void
*/
static function Silent(string $reason, ...$args)
{
throw self::_make($reason, isDev(), ...$args);
}
/**
* Raises a verbose TerminationException.
*
* @param string $reason The reason for the Exception
* @param array $args Additional arguments to be logged.
* @return void
*/
static function Verbose(string $reason, ...$args)
{
throw self::_make($reason, true, ...$args);
}
/**
* Returns the reason string.
*
* @return string The reason this exception was thrown of.
*/
public function getReason()
{
return $this->reason;
}
/**
* Writes the exception to the log if it is verbose.
* @return void
*/
public function writeLog()
{
if (!$this->verbose)
return;
log_debug($this->getMessageEx());
}
}