forked from Open-Web-Analytics/Open-Web-Analytics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
owa_lib.php
1418 lines (1051 loc) · 36.8 KB
/
owa_lib.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
//
// Open Web Analytics - An Open Source Web Analytics Framework
//
// Copyright Peter Adams. All rights reserved.
//
// Licensed under GPL v2.0 http://www.gnu.org/copyleft/gpl.html
/**
* Utility Functions
*
*/
class owa_lib {
/**
* Convert Associative Array to String
*
* @param string $inner_glue
* @param string $outer_glue
* @param array $array
* @return string
*/
public static function implode_assoc($inner_glue, $outer_glue, $array) {
$output = array();
foreach( $array as $key => $item ) {
$output[] = $key . $inner_glue . $item;
}
return implode($outer_glue, $output);
}
/**
* Deconstruct Associative Array
*
* For example this takes array([1] => array(a => dog, b => cat), [2] => array(a => sheep, b => goat))
* and tunrs it into array([a] => array(dog, sheep), [b] => array(cat, goat))
*
* @param array $a_array
* @return array $data_arrays
* @access public
*/
public static function deconstruct_assoc($a_array) {
if (!empty($a_array)):
$data_arrays = array();
if(!empty($a_array[1])) :
foreach ($a_array as $key => $value) {
foreach ($value as $k => $v) {
$data_arrays[$k][] = $v;
}
}
else:
//print_r($a_array[0]);
foreach ($a_array[0] as $key => $value) {
$data_arrays[$key][] = $value;
}
endif;
return $data_arrays;
else:
return array();
endif;
}
public static function decon_assoc($a_array) {
$data_arrays = array();
foreach ($a_array as $key => $value) {
//foreach ($value as $k => $v) {
$data_arrays[$key][] = $value;
//}
}
return $data_arrays;
}
// php 4 compatible function
public static function array_intersect_key() {
$arrs = func_get_args();
$result = array_shift($arrs);
foreach ($arrs as $array) {
foreach ($result as $key => $v) {
if (!array_key_exists($key, $array)) {
unset($result[$key]);
}
}
}
return $result;
}
// php4 compatible function
public static function array_walk_recursive(&$input, $funcname, $userdata = "")
{
if (!is_callable($funcname))
{
return false;
}
if (!is_array($input))
{
return false;
}
if (is_array($funcname))
{
$funcname = $funcname[0].'::'.$funcname[1];
}
foreach ($input AS $key => $value)
{
if (is_array($input[$key]))
{
array_walk_recursive($input[$key], $funcname, $userdata);
}
else
{
$saved_value = $value;
if (!empty($userdata))
{
$funcname($value, $key, $userdata);
}
else
{
$funcname($value, $key);
}
if ($value != $saved_value)
{
$input[$key] = $value;
}
}
}
return true;
}
/**
* Array of Current Time
*
* @return array
* @access public
*/
public static function time_now() {
$timestamp = time();
return array(
'year' => date("Y", $timestamp),
'month' => date("n", $timestamp),
'day' => date("d", $timestamp),
'dayofweek' => date("w", $timestamp),
'dayofyear' => date("z", $timestamp),
'weekofyear' => date("W", $timestamp),
'hour' => date("G", $timestamp),
'minute' => date("i", $timestamp),
'second' => date("s", $timestamp),
'timestamp' => $timestamp
);
}
/**
* Information array for Months in the year.
*
* @return array
*/
public static function months() {
return array(
1 => array('label' => 'January'),
2 => array('label' => 'February'),
3 => array('label' => 'March'),
4 => array('label' => 'April'),
5 => array('label' => 'May'),
6 => array('label' => 'June'),
7 => array('label' => 'July'),
8 => array('label' => 'August'),
9 => array('label' => 'September'),
10 => array('label' => 'October'),
11 => array('label' => 'November'),
12 => array('label' => 'December')
);
}
public static function days() {
return array(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);
}
public static function years() {
static $years;
if (empty($years)):
$start_year = 2005;
$years = array($start_year);
$num_years = date("Y", time()) - $start_year;
for($i=1; $i<=$num_years; $i++) {
$years[] = $start_year + $i;
}
$years = array_reverse($years);
endif;
return $years;
}
/**
* Returns a label from an array of months
*
* @param int $month
* @return string
*/
public static function get_month_label($month) {
static $months;
if (empty($months)):
$months = owa_lib::months();
endif;
return $months[$month]['label'];
}
/**
* Sets the suffix for Days used in Date labels
* @depricated
* @param string $day
* @return string
*/
public static function setDaySuffix($day) {
switch ($day) {
case "1":
$day_suffix = 'st';
break;
case "2":
$day_suffix = 'nd';
break;
case "3":
$day_suffix = 'rd';
break;
default:
$day_suffix = 'th';
}
return $day_suffix;
}
/**
* Generates the label for a date
* @depricated
* @param array $params
* @return string
*/
public static function getDatelabel($params) {
switch ($params['period']) {
case "day":
return sprintf("%s, %d%s %s",
owa_lib::get_month_label($params['month']),
$params['day'],
owa_lib::setDaySuffix($params['day']),
$params['year']
);
break;
case "month":
return sprintf("%s %s",
owa_lib::get_month_label($params['month']),
$params['year']
);
break;
case "year":
return sprintf("%s",
$params['year']
);
break;
case "date_range":
return sprintf("%s, %d%s %s - %s, %d%s %s",
owa_lib::get_month_label($params['month']),
$params['day'],
owa_lib::setDaySuffix($params['day']),
$params['year'],
owa_lib::get_month_label($params['month2']),
$params['day2'],
owa_lib::setDaySuffix($params['day2']),
$params['year2']
);
break;
}
return false;
}
/**
* Array of Reporting Periods
* @depricated
* @return array
*/
public static function reporting_periods() {
return array(
'today' => array('label' => 'Today'),
'yesterday' => array('label' => 'Yesterday'),
'this_week' => array('label' => 'This Week'),
'this_month' => array('label' => 'This Month'),
'this_year' => array('label' => 'This Year'),
'last_week' => array('label' => 'Last Week'),
'last_month' => array('label' => 'Last Month'),
'last_year' => array('label' => 'Last Year'),
'last_half_hour' => array('label' => 'The Last 30 Minutes'),
'last_hour' => array('label' => 'Last Hour'),
'last_24_hours' => array('label' => 'The Last 24 Hours'),
'last_seven_days' => array('label' => 'The Last Seven Days'),
'last_thirty_days' => array('label' => 'The Last Thirty Days'),
'same_day_last_week' => array('label' => 'Same Day last Week'),
'same_week_last_year' => array('label' => 'Same Week Last Year'),
'same_month_last_year' => array('label' => 'Same Month Last Year'),
'date_range' => array('label' => 'Date Range')
);
}
/**
* Array of Date specific Reporting Periods
* @depricated
* @return array
*/
public static function date_reporting_periods() {
return array(
'day' => array('label' => 'Day'),
'month' => array('label' => 'Month'),
'year' => array('label' => 'Year'),
'date_range' => array('label' => 'Date Range')
);
}
/**
* Gets label for a particular reporting period
*
* @param unknown_type $period
* @return unknown
*/
public static function get_period_label($period) {
$periods = owa_lib::reporting_periods();
return $periods[$period]['label'];
}
public static function isHttps() {
// check for https
if(
( isset( $_SERVER['HTTPS'] ) && strtolower( $_SERVER['HTTPS'] ) == 'on' )
|| ( ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) )
|| ( ( isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) && $_SERVER['HTTP_X_FORWARDED_PORT'] == 443 ) )
|| ( ( isset( $_SERVER['SERVER_PORT'] ) && $_SERVER['SERVER_PORT'] == 443 ) )
|| ( ( isset( $_SERVER['HTTP_ORIGIN'] ) && substr( $_SERVER['HTTP_ORIGIN'], 0, 5 ) === 'https' ) )
|| ( ( isset( $_SERVER['HTTP_REFERER'] ) && substr( $_SERVER['HTTP_REFERER'], 0, 5 ) === 'https' ) )
) {
return true;
}
}
/**
* Assembles the current URL from request params
*
* @return string
*/
public static function get_current_url() {
if ( self::isHttps() ) {
$url = 'https';
} else {
$url = 'http';
}
if ( isset( $_SERVER['HTTP_HOST'] ) ) {
// contains port number
$domain = $_SERVER['HTTP_HOST'];
} else {
// does not contain port number.
$domain = $_SERVER['SERVER_NAME'];
if( $_SERVER['SERVER_PORT'] != 80 ) {
$domain .= ':' . $_SERVER['SERVER_PORT'];
}
}
$url .= '://'.$domain;
$url .= $_SERVER['REQUEST_URI'];
return $url;
}
public static function inputFilter($input, $options = array() ) {
return owa_sanitize::cleanInput( $input, $options );
}
public static function fileInclusionFilter($str) {
$str = str_replace("http://", "", $str);
$str = str_replace("/", "", $str);
$str = str_replace("\\", "", $str);
$str = str_replace("../", "", $str);
$str = str_replace("..", "", $str);
$str = str_replace("?", "", $str);
$str = str_replace("%00", "", $str);
if (strpos($str, '%00')) {
$str = '';
}
if ($str == null) {
$str = '';
}
return $str;
}
/**
* Generic Factory method
*
* @param string $class_dir
* @param string $class_prefix
* @param string $class_name
* @param array $constructorArguments
* @return object
*/
public static function factory($class_dir, $class_prefix, $class_name, $constructorArguments = array(), $class_suffix = '') {
$class_dir = $class_dir.'/';
$classfile = $class_dir . $class_name . '.php';
$class = $class_prefix . $class_name . $class_suffix;
/*
* Attempt to include a version of the named class, but don't treat
* a failure as fatal. The caller may have already included their own
* version of the named class.
*/
if (!class_exists($class)) {
if (!file_exists($classfile)) {
throw new Exception('Class File '.$classfile.' not existend!');
}
require_once ($classfile);
}
if (!class_exists($class)) {
throw new Exception('Class '.$class.' does not exist!');
}
return new $class($constructorArguments);
}
public static function simpleFactory( $class_name, $file_path = '', $args = '' ) {
if ( ! class_exists( $class_name ) ) {
if ( ! file_exists( $file_path ) ) {
throw new Exception("Factory cannot make $class_name because $file_path does not exist!");
} else {
require_once( $file_path );
}
}
if ( ! class_exists( $class_name ) ) {
throw new Exception("Class $class_name still does not exist!");
}
return new $class_name( $args );
}
/**
* Generic Object Singleton
*
* @param string $class_dir
* @param string $class_prefix
* @param string $class_name
* @param array $conf
* @return object
*/
public static function singleton($class_dir, $class_prefix, $class_name, $conf = array()) {
static $instance;
if (!isset($instance)) {
// below missing a reference becasue the static vriable can not handle a reference
$instance = owa_lib::factory($class_dir, $class_prefix, $class_name, $conf);
}
return $instance;
}
/**
* 302 HTTP redirect the user to a new url
*
* @param string $url
*/
public static function redirectBrowser($url) {
//print ($url); exit;
// 302 redirect to URL
header ('Location: '.$url);
header ('HTTP/1.0 302 Found');
}
public static function makeLinkQueryString($query_params) {
$new_query_params = array();
//Load params passed by caller
if (!empty($this->caller_params)):
foreach ($this->caller_params as $name => $value) {
if (!empty($value)):
$new_query_params[$name] = $value;
endif;
}
endif;
// Load overrides
if (!empty($query_params)):
foreach ($query_params as $name => $value) {
if (!empty($value)):
$new_query_params[$name] = $value;
endif;
}
endif;
// Construct GET request
if (!empty($new_query_params)):
foreach ($new_query_params as $name => $value) {
if (!empty($value)):
$get .= $name . "=" . $value . "&";
endif;
}
endif;
return $get;
}
public static function getRequestParams() {
$params = array();
if (!empty($_POST)) {
$params = $_POST;
} else {
$params = $_GET;
}
if (!empty($_COOKIE)) {
$params = array_merge($params, $_COOKIE);
}
return $params;
}
public static function rekeyArray($array, $new_keys) {
$new_keys = $new_keys;
$new_array = array();
foreach ($array as $k => $v) {
if (array_key_exists($k, $new_keys)) {
$k = $new_keys[$k];
}
$new_array[$k] = $v;
}
return $new_array;
}
public static function stripParams($params, $ns = '') {
$striped_params = array();
if (!empty($ns)) {
$len = strlen($ns);
foreach ($params as $n => $v) {
// if namespace is present in param
if (strstr($n, $ns)) {
// strip the namespace value
$striped_n = substr($n, $len);
//add to striped array
$striped_params[$striped_n] = $v;
}
}
return $striped_params;
} else {
return $params;
}
}
/**
* module specific require method
*
* @param unknown_type $module
* @param unknown_type $file
* @return unknown
* @deprecated
*/
public static function moduleRequireOnce($module, $file) {
return require_once(OWA_BASE_DIR.'/modules/'.$module.'/'.$file.'.php');
}
/**
* module specific factory
*
* @param unknown_type $modulefile
* @param unknown_type $class_suffix
* @param unknown_type $params
* @return unknown
* @deprecated
*/
public static function moduleFactory($modulefile, $class_suffix = null, $params = '') {
list($module, $file) = explode(".", $modulefile);
$class = 'owa_'.$file.$class_suffix;
// Require class file if class does not already exist
if(!class_exists($class)):
owa_lib::moduleRequireOnce($module, $file);
endif;
$obj = owa_lib::factory(OWA_BASE_DIR.'/modules/'.$module, '', $class, $params);
$obj->module = $module;
return $obj;
}
/**
* redirects borwser to a particular view
*
* @param unknown_type $data
*/
public static function redirectToView($data) {
//print_r($data);
$c = owa_coreAPI::configSingleton();
$config = $c->fetch('base');
$control_params = array('view_method', 'auth_status');
$get = '';
foreach ($data as $n => $v) {
if (!in_array($n, $control_params)) {
$get .= $config['ns'].$n.'='.$v.'&';
}
}
$new_url = sprintf($config['link_template'], $config['main_url'], $get);
owa_lib::redirectBrowser($new_url);
}
/**
* Displays a View without user authentication. Takes array of data as input
*
* @param array $data
* @deprecated
*/
public static function displayView($data, $params = array()) {
$view = owa_lib::moduleFactory($data['view'], 'View', $params);
return $view->assembleView($data);
}
/**
* Create guid from string
*
* @param string $string
* @return integer
* @access private
*/
public static function setStringGuid($string) {
if ( $string ) {
if ( owa_coreAPI::getSetting('base', 'use_64bit_hash') && PHP_INT_MAX == '9223372036854775807') {
// make 64 bit ID from partial sha1
return (string) (int) hexdec( substr( sha1( strtolower( $string ) ), 0, 16 ) );
} else {
// make 32 bit ID from crc32
return crc32( strtolower( $string ) );
}
}
}
/**
* Add constraints into SQL where clause
*
* @param array $constraints
* @return string $where
* @access public
* @depricated
* @todo remove
*/
function addConstraints($constraints) {
if (!empty($constraints)):
$count = count($constraints);
$i = 0;
$where = '';
foreach ($constraints as $key => $value) {
if (empty($value)):
$i++;
else:
if (!is_array($value)):
$where .= $key . ' = ' . "'$value'";
else:
switch ($value['operator']) {
case 'BETWEEN':
$where .= sprintf("%s BETWEEN '%s' AND '%s'", $key, $value['start'], $value['end']);
break;
default:
$where .= sprintf("%s %s '%s'", $key, $value['operator'], $value['value']);
break;
}
endif;
if ($i < $count - 1):
$where .= " AND ";
endif;
$i++;
endif;
}
// needed in case all values in the array are empty
if (!empty($where)):
return $where;
else:
return;
endif;
else:
return;
endif;
}
public static function assocFromString($string_state, $inner = '=>', $outer = '|||') {
if (!empty($string_state)):
if (strpos($string_state, $outer) === false):
return $string_state;
else:
$array = explode($outer, $string_state);
$state = array();
foreach ($array as $key => $value) {
list($realkey, $realvalue) = explode($inner, $value);
$state[$realkey] = $realvalue;
}
endif;
endif;
return $state;
}
/**
* Simple function to replicate PHP 5 behaviour
*/
public static function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
/**
* Lists all files in a Directory
*
*/
public static function listDir($start_dir='.', $recursive = true) {
$files = array();
if (is_dir($start_dir)):
$fh = opendir($start_dir);
while (($file = readdir($fh)) !== false) {
// loop through the files, skipping . and .., and recursing if necessary
if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue;
$filepath = $start_dir . '/' . $file;
if (is_dir($filepath)):
if ($recursive === true):
$files = array_merge($files, owa_lib::listDir($filepath));
endif;
else:
array_push($files, array('name' => $file, 'path' => $filepath));
endif;
}
closedir($fh);
else:
// false if the function was called with an invalid non-directory argument
$files = false;
endif;
return $files;
}
public static function makeDateArray($result, $format) {
if (!empty($result)) {
$timestamps = array();
foreach ($result as $row) {
$timestamps[]= mktime(0,0,0,$row['month'],$row['day'],$row['year']);
}
return owa_lib::makeDates($timestamps, $format);
} else {
return array();
}
}
public static function makeDates($timestamps, $format) {
sort($timestamps);
$new_dates = array();
foreach ($timestamps as $timestamp) {
$new_dates[] = date($format, $timestamp);
}
return $new_dates;
}
public static function html2txt($document){
$search = array('@<script[^>]*?>.*?</script>@si', // Strip out javascript
'@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments including CDATA
);
$text = preg_replace($search, '', $document);
return $text;
}
public static function escapeNonAsciiChars($string) {
return preg_replace('/[^(\x20-\x7F)]*/','', $string);
}
/**
* Truncate string
*
* @param string $str
* @param integer $length
* @param string $trailing
* @return string
*/
public static function truncate ($str, $length=10, $trailing='...') {
// take off chars for the trailing
$length-=strlen($trailing);
if (strlen($str) > $length):
// string exceeded length, truncate and add trailing dots
return substr($str,0,$length).$trailing;
else:
// string was already short enough, return the string
$res = $str;
endif;
return $res;
}
/**
* Simple Password Encryption
*
* @param string $password
* @return string
*/
public static function encryptOldPassword($password) {
return md5(strtolower($password).strlen($password));
//return owa_coreAPI::saltedHash( $password, 'auth');
}
public static function encryptPassword($password) {
// check function exists to support older PHP
if ( function_exists('password_hash') ) {
return password_hash( $password, PASSWORD_DEFAULT );
} else {
return self::encryptOldPassword($password);
}
}
public static function hash( $hash_type, $data, $salt = '' ) {
if ( ! $hash_type ) {
$hash_type = 'md5';
}
return hash_hmac( $hash_type, $data, $salt );