-
Notifications
You must be signed in to change notification settings - Fork 214
/
fogbase.class.php
2268 lines (2213 loc) · 61.7 KB
/
fogbase.class.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
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
<?php
/**
* FOGBase, the base class for pretty much all of fog.
*
* PHP version 5
*
* This gives all the rest of the classes a common frame to work from.
*
* @category FOGBase
* @package FOGProject
* @author Tom Elliott <tommygunsster@gmail.com>
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link https://fogproject.org
*/
/**
* FOGBase, the base class for pretty much all of fog.
*
* @category FOGBase
* @package FOGProject
* @author Tom Elliott <tommygunsster@gmail.com>
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link https://fogproject.org
*/
abstract class FOGBase
{
/**
* Language variables brought in from text.php.
*
* @var array
*/
public static $foglang;
/**
* Sets if the requesting call is ajax requested.
*
* @var bool
*/
public static $ajax = false;
/**
* Sets if this is a form submit.
*
* @var bool
*/
public static $post = false;
/**
* Tells whether or not its a fog/service request.
*
* @var bool
*/
public static $service = false;
/**
* Tells if we are json or not
*
* @var bool
*/
public static $json = false;
/**
* Tells if we are new service or not
*
* @var bool
*/
public static $newService = false;
/**
* Tests/sets if a given key is loaded already.
*
* @var array
*/
protected $isLoaded = array();
/**
* The length of a given string item.
*
* @var int
*/
protected static $strlen;
/**
* Display debug information.
*
* @var bool
*/
protected static $debug = false;
/**
* Display extra information about items.
*
* @var bool
*/
protected static $info = false;
/**
* Select box creator function stored in variable.
*
* @var callable
*/
protected static $buildSelectBox;
/**
* Sets what's selected for the select box.
*
* @var bool|int
*/
protected static $selected;
/**
* The database handler.
*
* @var object
*/
protected static $DB;
/**
* FTP Handler.
*
* @var object
*/
protected static $FOGFTP;
/**
* Core usage elements as FOGBase is abstract.
*
* @var object
*/
protected static $FOGCore;
/**
* Event handling.
*
* @var object
*/
protected static $EventManager;
/**
* Hook handling.
*
* @var object
*/
protected static $HookManager;
/**
* The default timezone for all of fog to use.
*
* @var object
*/
protected static $TimeZone;
/**
* The logged in user.
*
* @var object
*/
protected static $FOGUser;
/**
* View/Page Controller-Manager.
*
* @var object
*/
protected static $FOGPageManager;
/**
* URL Manager | mainly for ajax, and externel getters.
*
* @var object
*/
protected static $FOGURLRequests;
/**
* Side/Sub menu manager.
*
* @var object
*/
protected static $FOGSubMenu;
/**
* Current requests script name.
*
* @var string
*/
protected static $scriptname;
/**
* Current requests query string.
*
* @var string
*/
protected static $querystring;
/**
* Current requests http requested with string.
*
* @var string
*/
protected static $httpreqwith;
/**
* Current request method.
*
* @var string
*/
protected static $reqmethod;
/**
* Is this a mobile request?
*
* @var int|bool
*/
protected static $isMobile;
/**
* The current server's IP information.
*
* @var array
*/
protected static $ips = array();
/**
* The current server's Interface information.
*
* @var array
*/
protected static $interface = array();
/**
* The current base pages requiring search functionality.
*
* @var array
*/
protected static $searchPages = array(
'user',
'host',
'group',
'image',
'storage',
'snapin',
'printer',
'task',
);
/**
* Is our current element already initialized?
*
* @var bool
*/
private static $_initialized = false;
/**
* The current running schema information.
*
* @var int
*/
public static $mySchema = 0;
/**
* Initializes the FOG System if needed.
*
* @return void
*/
private static function _init()
{
if (self::$_initialized === true) {
return;
}
global $foglang;
global $FOGFTP;
global $FOGCore;
global $DB;
global $currentUser;
global $EventManager;
global $HookManager;
global $FOGURLRequests;
global $FOGPageManager;
global $TimeZone;
self::$foglang = &$foglang;
self::$FOGFTP = &$FOGFTP;
self::$FOGCore = &$FOGCore;
self::$DB = &$DB;
self::$EventManager = &$EventManager;
self::$HookManager = &$HookManager;
self::$FOGUser = &$currentUser;
$scriptPattern = '#/service/#i';
$queryPattern = '#sub=requestClientInfo#i';
self::$querystring = $_SERVER['QUERY_STRING'];
if (isset($_SERVER['SCRIPT_NAME'])) {
self::$scriptname = htmlentities(
$_SERVER['SCRIPT_NAME'],
ENT_QUOTES,
'utf-8'
);
}
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
self::$httpreqwith = htmlentities(
$_SERVER['HTTP_X_REQUESTED_WITH'],
ENT_QUOTES,
'utf-8'
);
}
if (isset($_SERVER['REQUEST_METHOD'])) {
self::$reqmethod = htmlentities(
$_SERVER['REQUEST_METHOD'],
ENT_QUOTES,
'utf-8'
);
}
if (preg_match('#/mobile/#i', self::$scriptname)) {
self::$isMobile = true;
}
if (preg_match($scriptPattern, self::$scriptname)) {
self::$service = true;
} elseif (preg_match($queryPattern, self::$querystring)) {
self::$service = true;
}
self::$ajax = preg_match('#^xmlhttprequest$#i', self::$httpreqwith);
self::$post = preg_match('#^post$#i', self::$reqmethod);
self::$newService = isset($_REQUEST['newService'])
|| $_REQUEST['sub'] == 'requestClientInfo';
self::$json = isset($_REQUEST['json'])
|| self::$newService
|| $_REQUEST['sub'] == 'requestClientInfo';
self::$FOGURLRequests = &$FOGURLRequests;
self::$FOGPageManager = &$FOGPageManager;
self::$TimeZone = &$TimeZone;
/*
* Lambda function to allow building of select boxes.
*
* @param string $option the option to iterate
* @param bool|int $index the index to operate on if needed.
*
* @return void
*/
self::$buildSelectBox = function ($option, $index = false) {
$value = $option;
if ($index) {
$value = $index;
}
printf(
'<option value="%s"%s>%s</option>',
$value,
(self::$selected == $value ? ' selected' : ''),
$option
);
};
self::$_initialized = true;
}
/**
* Initiates the base class for FOG.
*
* @return this
*/
public function __construct()
{
self::_init();
return $this;
}
/**
* Defines string as class name.
*
* @return string
*/
public function __toString()
{
return get_class($this);
}
/**
* Returns the class after verifying reflection of the class.
*
* @param string $class the name of the class to load
* @param mixed $data the data to load into the class
* @param bool $props return just properties or full object
*
* @throws Exception
*
* @return class Returns the instantiated class
*/
public static function getClass($class, $data = '', $props = false)
{
if (!is_string($class)) {
throw new Exception(_('Class name must be a string'));
}
// Get all args, even unnamed args.
$args = func_get_args();
array_shift($args);
// Trim the class var
$class = trim($class);
// Test what the class is and return if it is Reflection.
$lClass = strtolower($class);
if ($lClass === 'reflectionclass') {
return new ReflectionClass(count($args) === 1 ? $args[0] : $args);
}
global $sub;
// If class is Storage, test if sub is group or node.
if ($class === 'Storage') {
$class = 'StorageNode';
if (preg_match('#storage[-|_]group#i', $sub)) {
$class = 'StorageGroup';
}
}
// Initiate Reflection item.
$obj = new ReflectionClass($class);
// If props is set to true return the properties of the class.
if ($props === true) {
return $obj->getDefaultProperties();
}
// Return the main object
if ($obj->getConstructor()) {
// If there's only one argument return the instance using it.
// Otherwise return with full call.
if (count($args) === 1) {
$class = $obj->newInstance($args[0]);
} else {
$class = $obj->newInstanceArgs($args);
}
} else {
$class = $obj->newInstanceWithoutConstructor();
}
return $class;
}
/**
* Get's the relevant host item.
*
* @param bool $service Is this a service request
* @param bool $encoded Is this data encoded
* @param bool $hostnotrequired Is the host return needed
* @param bool $returnmacs Only return macs?
* @param bool $override Perform an override of the items?
*
* @throws Exception
*
* @return array|object Returns either th macs or the host
*/
public static function getHostItem(
$service = true,
$encoded = false,
$hostnotrequired = false,
$returnmacs = false,
$override = false
) {
// Store the mac
$mac = $_REQUEST['mac'];
// If encoded decode and store value
if ($encoded === true) {
$mac = base64_decode($mac);
}
// Trim the mac list.
$mac = trim($mac);
// Parsing the macs
$MACs = self::parseMacList($mac, !$service, $service);
foreach ((array) $MACs as &$mac) {
if (!$mac->isValid()) {
continue;
}
$macs[] = $mac->__toString();
unset($mac);
}
// If no macs are returned and the host is not required,
// throw message that it's an invalid mac.
if (count($macs) < 1 && $hostnotrequired === false) {
if ($service) {
$msg = '#!im';
} else {
$msg = sprintf('%s %s', self::$foglang, $_REQUEST['mac']);
}
throw new Exception($msg);
}
// If returnmacs parameter is true, return the macs as an array
if ($returnmacs) {
if (!is_array($macs)) {
$macs = (array) $macs;
}
return $macs;
}
// Get the host element based on the mac address
$Host = self::getClass('HostManager')->getHostByMacAddresses($macs);
if ($hostnotrequired === false && $override === false) {
if ($Host->get('pending')) {
$Host = new Host(0);
}
if (!($Host->isValid())) {
if ($service) {
$msg = '#!ih';
} else {
$msg = _('Invalid Host');
}
throw new Exception($msg);
}
}
return $Host;
}
/**
* Get's blamed nodes for failures.
*
* @return array
*/
public function getAllBlamedNodes()
{
$DateInterval = self::niceDate()->modify('-5 minutes');
/**
* Returns the node id if still accurate
* or will clean up past time nodes.
*
* @param object $NodeFailure the node that is in failed state
*
* @return int|bool
*/
$nodeFail = function ($NodeFailure) use ($DateInterval) {
if ($NodeFailure->isValid()) {
return false;
}
$DateTime = self::niceDate($NodeFailure->get('failureTime'));
if ($DateTime < $DateInterval) {
$NodeFailure->destroy();
return false;
}
return $NodeFailure->get('id');
};
$find = array(
'taskID' => $this->Host->get('task')->get('id'),
'hostID' => $this->Host->get('id'),
);
$nodeRet = array_map(
$nodeFail,
(array)self::getClass('NodeFailureManager')->find($find)
);
$nodeRet = array_filter($nodeRet);
$nodeRet = array_unique($nodeRet);
$nodeRet = array_values($nodeRet);
return $nodeRet;
}
/**
* Returns array of plugins installed.
*
* @return array
*/
protected static function getActivePlugins()
{
$plugins = self::getSubObjectIDs(
'Plugin',
array(
'installed' => 1,
'state' => 1,
),
'name'
);
return array_map('strtolower', (array) $plugins);
}
/**
* Converts our string if needed.
*
* @param string $txt the string to use
* @param array $data the data if txt is formatted string
*
* @return string
*/
private static function _setString($txt, $data = array())
{
if (count($data)) {
$data = vsprintf($txt, $data);
} else {
$data = $txt;
}
return $data;
}
/**
* Prints fatal errors.
*
* @param string $txt the string to use
* @param array $data the data if txt is formatted string
*
* @return void
*/
protected function fatalError($txt, $data = array())
{
if (self::$service || self::$ajax) {
return;
}
$data = self::_setString($txt, $data);
$string = sprintf(
'FOG FATAL ERROR: %s: %s',
get_class($this),
$data
);
printf('<div class="debug-error">%s</div>', $string);
}
/**
* Prints error.
*
* @param string $txt the string to use
* @param array $data the data if txt is formatted string
*
* @return void
*/
protected function error($txt, $data = array())
{
if ((self::$service || self::$ajax) || !self::$debug) {
return;
}
$data = self::_setString($txt, $data);
$string = sprintf(
'FOG ERROR: %s: %s',
get_class($this),
$data
);
printf('<div class="debug-error">%s</div>', $string);
}
/**
* Prints debug.
*
* @param string $txt the string to use
* @param array $data the data if txt is formatted string
*
* @return void
*/
protected function debug($txt, $data = array())
{
if ((self::$service || self::$ajax) || !self::$debug) {
return;
}
$data = self::_setString($txt, $data);
$string = sprintf(
'FOG DEBUG: %s: %s',
get_class($this),
$data
);
printf('<div class="debug-error">%s</div>', $string);
}
/**
* Prints info.
*
* @param string $txt the string to use
* @param array $data the data if txt is formatted string
*
* @return void
*/
protected function info($txt, $data = array())
{
if (!self::$info || self::$service || self::$ajax) {
return;
}
$data = self::_setString($txt, $data);
$string = sprintf(
'FOG INFO: %s: %s',
get_class($this),
$data
);
printf('<div class="debug-info">%s</div>', $string);
}
/**
* Sets message banner at top of pages.
*
* @param string $txt the string to use
* @param array $data the data if txt is formatted string
*
* @return void
*/
protected function setMessage($txt, $data = array())
{
$_SESSION['FOG_MESSAGES'] = self::_setString($txt, $data);
}
/**
* Gets message banner and prepares to display it.
*
* @return string
*/
protected function getMessages()
{
if (!isset($_SESSION['FOG_MESSAGES'])) {
$_SESSION['FOG_MESSAGES'] = array();
}
$messages = (array) $_SESSION['FOG_MESSAGES'];
unset($_SESSION['FOG_MESSAGES']);
// Create a hook in for messages
if (self::$HookManager instanceof HookManager) {
self::$HookManager->processEvent(
'MessageBox',
array('data' => &$messages)
);
}
/**
* Lambda that simply prints the messages as passed.
*
* @param string $message the message to print
*/
$print_messages = function ($message) {
printf('<div class="fog-message-box">%s</div>', $message);
};
// Print the messages
array_map($print_messages, $messages);
unset($messages);
}
/**
* Redirect pages where/when necessary.
*
* @param string $url The url to redirect to
*
* @return void
*/
protected function redirect($url = '')
{
if (self::$service) {
return;
}
header('Strict-Transport-Security: "max-age=15768000"');
header('X-Content-Type-Options: nosniff');
header('X-XSS-Protection: 1; mode=block');
header('X-Robots-Tag: none');
header('X-Frame-Options: SAMEORIGIN');
header("Location: $url");
exit;
}
/**
* Insert before key in array.
*
* @param string $key the key to insert before
* @param array $array the array to modify
* @param string $new_key the new key to insert
* @param mixed $new_value the value to insert
*
* @throws Exception
* @return void
*/
protected function arrayInsertBefore($key, array &$array, $new_key, $new_value)
{
if (!is_string($key)) {
throw new Exception(_('Key must be a string or index'));
}
$new = array();
foreach ($array as $k => &$value) {
if ($k === $key) {
$new[$new_key] = $new_value;
}
$new[$k] = $value;
unset($k, $value);
}
$array = $new;
}
/**
* Insert after key in array.
*
* @param string $key the key to insert after
* @param array $array the array to modify
* @param string $new_key the new key to insert
* @param mixed $new_value the value to insert
*
* @throws Exception
* @return void
*/
protected function arrayInsertAfter($key, array &$array, $new_key, $new_value)
{
if (!is_string($key) && !is_numeric($key)) {
throw new Exception(_('Key must be a string or index'));
}
$new = array();
foreach ($array as $k => &$value) {
$new[$k] = $value;
if ($k === $key) {
$new[$new_key] = $new_value;
}
unset($k, $value);
}
$array = $new;
}
/**
* Remove value based on the key from array.
*
* @param string|array $key the key to remove
* @param array $array the array to work with
*
* @throws Exception
* @return void
*/
protected function arrayRemove($key, array &$array)
{
if (!(is_string($key) || is_array($key))) {
throw new Exception(_('Key must be an array of keys or a string.'));
}
if (is_array($key)) {
foreach ($key as &$k) {
$this->arrayRemove($k, $array);
unset($k);
}
} else {
foreach ($array as &$value) {
if (is_array($value)) {
$this->arrayRemove($key, $value);
} else {
unset($array[$key]);
}
unset($value);
}
}
}
/**
* Find the key of a needle within the haystack that is an array.
*
* @param mixed $needle the needle to find
* @param array $haystack the array to search in
* @param bool|mixed $ignorecase whether to care about case
*
* @return key or false
*/
protected function arrayFind(
$needle,
array $haystack,
$ignorecase = false
) {
$cmd = $ignorecase !== false ? 'stripos' : 'strpos';
foreach ($haystack as $key => &$value) {
if (false !== $cmd($value, $needle)) {
return $key;
}
unset($value);
}
return false;
}
/**
* Check if isLoaded.
*
* @param string|int $key the key to see if loaded
*
* @return bool|string
*/
protected function isLoaded($key)
{
$key = $this->key($key);
$result = isset($this->isLoaded[$key]) ? $this->isLoaded[$key] : 0;
++$this->isLoaded[$key];
return $result ? $result : false;
}
/**
* Reset request variables.
*
* @return void
*/
protected function resetRequest()
{
if (!isset($_SESSION['post_request_vals'])) {
$_SESSION['post_request_vals'] = array();
}
$sesVars = $_SESSION['post_request_vals'];
$setReq = function (&$val, &$key) {
$_REQUEST[$key] = $val;
unset($val, $key);
};
array_walk($sesVars, $setReq);
unset($_SESSION['post_request_vals'], $sesVars, $reqVars);
}
/**
* Set request vars particularly for post failures really.
*
* @return void
*/
protected function setRequest()
{
if (!isset($_SESSION['post_request_vals'])) {
$_SESSION['post_request_vals'] = array();
}
if (!$_SESSION['post_request_vals'] && self::$post) {
$_SESSION['post_request_vals'] = $_POST;
}
}
/**
* Return nicely formatted byte sizes.
*
* @param int|float $size the size to convert
*
* @return float
*/
protected function formatByteSize($size)
{
$units = array('iB', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');
$factor = floor((strlen($size) - 1) / 3);
return sprintf('%3.2f %s', $size / pow(1024, $factor), $units[$factor]);
}
/**
* Gets the global module status.
*
* Can return just the shortnames or the long.
*
* @param bool $names if set will return the services as set
* @param bool $keys will return just the shortnames if set
*
* @return array
*/
protected function getGlobalModuleStatus($names = false, $keys = false)
{
// The shortnames are on the left, the long names are on the right
// If the right is true it means the short is accurate.
// If the left is not the right caller in form of:
// FOG_CLIENT_<name>_ENABLED in lowercase.
$services = array(
'autologout' => 'autologoff',
'clientupdater' => true,
'dircleanup' => 'directorycleaner',
'displaymanager' => true,
'greenfog' => true,
'hostnamechanger' => true,
'hostregister' => true,
'powermanagement' => true,
'printermanager' => true,
'snapinclient' => 'snapin',
'taskreboot' => true,
'usercleanup' => true,
'usertracker' => true,
);
// If keys is set, return just the keys.
if ($keys) {
$keys = array_keys($services);
$keys = array_filter($keys);
$keys = array_unique($keys);
return array_values($keys);
}
// Change the keys values
foreach ($services as $short => &$value) {
$tmp = $value === true ? $short : $value;
$value = sprintf('FOG_CLIENT_%s_ENABLED', strtoupper($tmp));
unset($value);
}
// If names is set, send back the short and long names together.
if ($names) {
return $services;
}
// Now lets get their status'
$serviceEn = self::getSubObjectIDs(
'Service',
array(
'name' => array_values($services),
),
'value',
false,
'AND',
'name',
false,
false
);
return array_combine(array_keys($services), $serviceEn);
}
/**
* Sets the date.
*
* @param mixed $date The date stamp, defaults to now if not set
* @param bool $utc Whether to use utc timezone or not
*
* @return DateTime
*/
public static function niceDate($date = 'now', $utc = false)
{
if ($utc || empty(self::$TimeZone)) {
$tz = new DateTimeZone('UTC');
} else {
$tz = new DateTimeZone(self::$TimeZone);
}
return new DateTime($date, $tz);
}
/**
* Do formatting things.
*
* @param mixed $time The time to work from
* @param mixed $format Specified format to return
* @param bool $utc Use UTC Timezone?
*
* @return mixed
*/
public static function formatTime($time, $format = false, $utc = false)
{
if (!$time instanceof DateTime) {
$time = self::niceDate($time, $utc);
}
if ($format) {
if (!self::validDate($time)) {
return _('No Data');
}
return $time->format($format);
}
$now = self::niceDate('now', $utc);
// Get difference of the current to supplied.
$diff = $now->format('U') - $time->format('U');
$absolute = abs($diff);
if (is_nan($diff)) {
return _('Not a number');
}
if (!self::validDate($time)) {
return _('No Data');
}
$date = $time->format('Y/m/d');
if ($now->format('Y/m/d') == $date) {
if (0 <= $diff && $absolute < 60) {
return 'Moments ago';
} elseif ($diff < 0 && $absolute < 60) {
return 'Seconds from now';
} elseif ($absolute < 3600) {
return self::humanify($diff / 60, 'minute');
} else {
return self::humanify($diff / 3600, 'hour');
}
}
$dayAgo = clone $now;
$dayAgo->modify('-1 day');
$dayAhead = clone $now;