Add analytics
[bus.git] / busui / owa / owa_coreAPI.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
<?php
 
//
// Open Web Analytics - An Open Source Web Analytics Framework
//
// Copyright 2006 Peter Adams. All rights reserved.
//
// Licensed under GPL v2.0 http://www.gnu.org/copyleft/gpl.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// $Id$
//
 
require_once(OWA_BASE_DIR.'/owa_lib.php');
 
/**
 * OWA Core API
 * 
 * @author      Peter Adams <peter@openwebanalytics.com>
 * @copyright   Copyright &copy; 2006 Peter Adams <peter@openwebanalytics.com>
 * @license     http://www.gnu.org/copyleft/gpl.html GPL v2.0
 * @category    owa
 * @package     owa
 * @version             $Revision$            
 * @since               owa 1.0.0
 */
 
class owa_coreAPI {
                
        public static function &singleton($params = array()) {
                
                static $api;
                
                if(!isset($api)):
                        $api = new owa_coreAPI();
                endif;
                
                if(!empty($params)):
                        $api->params = $params;
                endif;
                
                return $api;
        }
        
        public static function setupStorageEngine($type) {
        
                if (!class_exists('owa_db')) {
                        require_once(OWA_BASE_CLASSES_DIR.'owa_db.php');
                }
                
                if ($type) {
                        
                $connection_class = "owa_db_" . $type;
                
                        if (!class_exists($connection_class)) {
                                $connection_class_path = OWA_PLUGINS_DIR.'/db/' . $connection_class . ".php";
                
                                if (!require_once($connection_class_path)) {
                                        owa_coreAPI::error(sprintf('Cannot locate proper db class at %s.', $connection_class_path));
                                        return false;
                                }
                        }
                
                }
                
                return true;
 
        }
        
        public static function &dbSingleton() {
                
                static $db;
        
                if (!isset($db)) {
                        
                        $db_type = owa_coreAPI::getSetting('base', 'db_type');
                        $ret = owa_coreAPI::setupStorageEngine($db_type);
        
                        if (!$ret) {
                                owa_coreAPI::error(sprintf('Cannot locate proper db class at %s. Exiting.', $connection_class_path));
                                return;
                        } else {        
                                $connection_class = 'owa_db_'.$db_type;
                                $db = new $connection_class(
                                        owa_coreAPI::getSetting('base','db_host'), 
                                        owa_coreAPI::getSetting('base','db_name'),
                                        owa_coreAPI::getSetting('base','db_user'),
                                        owa_coreAPI::getSetting('base','db_password'),
                                        owa_coreAPI::getSetting('base','db_force_new_connections'),
                                        owa_coreAPI::getSetting('base','db_make_persistant_connections')
                                );      
                        }
                }
                
                return $db;
        }
                
        public static function &configSingleton($params = array()) {
                
                static $config;
                
                if(!isset($config)):
                        
                        if (!class_exists('owa_settings')):
                                require_once(OWA_BASE_CLASS_DIR.'settings.php');
                        endif;
                        
                        $config = owa_coreAPI::supportClassFactory('base', 'settings');
                        
                endif;
                
                return $config;
        }
        
        public static function &errorSingleton() {
                
                static $e;
                
                if(!$e) {
                        
                        if (!class_exists('owa_error')):
                                require_once(OWA_BASE_CLASS_DIR.'error.php');
                        endif;
                        
                        $e = owa_coreAPI::supportClassFactory('base', 'error');
                        
                }
                
                return $e;
        }
        
        public static function getSetting($module, $name) {
                
                $s = &owa_coreAPI::configSingleton();
                return $s->get($module, $name);
        }
        
        public static function setSetting($module, $name, $value, $persist = false) {
                
                $s = &owa_coreAPI::configSingleton();
                
                if ($persist === true) {
                        $s->persistSetting($module, $name, $value);
                } else {
                        $s->setSetting($module, $name, $value);
                }
                
        }
        
        public static function persistSetting($module, $name, $value) {
                
                $s = &owa_coreAPI::configSingleton();
                $s->persistSetting($module, $name, $value);
                
        }
        
        public static function getSiteSetting($site_id, $name) {
                
                $site = owa_coreAPI::entityFactory('base.site');
                $site->load( $site->generateId( $site_id ) );
                if ( $site->wasPersisted() ) {
                
                        $settings = $site->get('settings');
                        if (!empty($settings)) {
                                if ( array_key_exists($name, $settings) ) {
                                        return $settings[$name];
                                }
                        }                       
                }
        }
        
        public static function persistSiteSetting($site_id, $name, $value) {
                
                $site = owa_coreAPI::entityFactory('base.site');
                $site->load( $site->generateId( $site_id ) );
                if ( $site->wasPersisted() ) {
                        $settings = $site->get('settings');
                        if ( ! $settings ) {
                                $settings = array();
                        }
                        $settings[$name] = $value;
                        $site->set('settings', $settings);      
                        $site->update();
                }
        }
        
        public static function getSiteSettings($site_id) {
                
                $site = owa_coreAPI::entityFactory('base.site');
                $site->load( $site->generateId( $site_id ) );
                if ( $site->wasPersisted() ) {
                
                        $settings = $site->get('settings');
                        
                        if ( $settings ) {
                                return $settings;
                        } else {
                                return array();
                        }
                }
                
        }
        
        public static function getAllRoles() {
                
                $caps = owa_coreAPI::getSetting('base', 'capabilities');
                return array_keys($caps);
        }
        
        public static function &getCurrentUser() {
                
                $s = &owa_coreAPI::serviceSingleton();
                return $s->getCurrentUser();
        }
        
        /**
         * check to see if the current user has a capability
         * always returns a bool
         */
        public static function isCurrentUserCapable($capability) {
                
                $cu = &owa_coreAPI::getCurrentUser();
                owa_coreAPI::debug("Current User Role: ".$cu->getRole());
                owa_coreAPI::debug("Current User Authentication: ".$cu->isAuthenticated());
                $ret = $cu->isCapable($capability);
                owa_coreAPI::debug("Is current User capable: ".$ret);
                return $ret;
        }
        
        public static function isCurrentUserAuthenticated() {
                
                $cu = &owa_coreAPI::getCurrentUser();
                return $cu->isAuthenticated();
        }
        
        public static function &serviceSingleton() {
                
                static $s;
                
                if(empty($s)) {
                        
                        if (!class_exists('owa_service')) {
                                require_once(OWA_BASE_CLASS_DIR.'service.php');
                        }
                        
                        $s = owa_coreAPI::supportClassFactory('base', 'service');
                        
                }
                
                return $s;
        }
        
        public static function &cacheSingleton($params = array()) {
                
                static $cache;
                
                if ( !isset ( $cache ) ) {
                        $cache_type = owa_coreAPI::getSetting('base', 'cacheType');
                        
                        switch ($cache_type) {
                                
                                case "memcached":
                                        $implementation = array('owa_memcachedCache', OWA_BASE_CLASS_DIR.'memcachedCache.php');
                                        break;
                                default:
                                        $implementation = array('owa_fileCache', OWA_BASE_CLASS_DIR.'fileCache.php');
                                        
                        }
                        
                        if ( ! class_exists( $implementation[0] ) ) {
                                require_once( $implementation[1] );
                        }
                        // make this plugable
                        $cache = new $implementation[0];                
                }
                
                return $cache;
        }
        
        public static function requestContainerSingleton() {
        
                static $request;
                
                if(!isset($request)):
                        
                        if (!class_exists('owa_requestContainer')):
                                require_once(OWA_DIR.'owa_requestContainer.php');
                        endif;
                        
                        $request = owa_lib::factory(OWA_DIR, '', 'owa_requestContainer');
                        
                endif;
                
                return $request;
        
        }
                
        public static function moduleRequireOnce($module, $class_dir, $file) {
                
                if (!empty($class_dir)) {
                
                        $class_dir .= DIRECTORY_SEPARATOR;
                        
                }
                
                $full_file_path = OWA_BASE_DIR.'/modules/'.$module.DIRECTORY_SEPARATOR.$class_dir.$file.'.php';
                
                if (file_exists($full_file_path)) {
                        return require_once($full_file_path);
                } else {
                        owa_coreAPI::debug("moduleRequireOnce says no file found at: $full_file_path");
                        return false;
                }
        }
        
        public static function moduleFactory($modulefile, $class_suffix = null, $params = '', $class_ns = 'owa_') {
                
                list($module, $file) = explode(".", $modulefile);
                $class = $class_ns.$file.$class_suffix;
                //print $class;
                // Require class file if class does not already exist
                if(!class_exists($class)):      
                        owa_coreAPI::moduleRequireOnce($module, '', $file);
                endif;
                        
                $obj = owa_lib::factory(OWA_BASE_DIR.'/modules/'.$module, '', $class, $params);
                
                //if (isset($obj->module)):
                        $obj->module = $module;
                //endif;
                
                return $obj;
        }
        
        public static function moduleGenericFactory($module, $sub_directory, $file, $class_suffix = null, $params = '', $class_ns = 'owa_') {
                
                $class = $class_ns.$file.$class_suffix;
        
                // Require class file if class does not already exist
                if(!class_exists($class)):      
                        owa_coreAPI::moduleRequireOnce($module, $sub_directory, $file);
                endif;
                        
                $obj = owa_lib::factory(OWA_DIR.'modules'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$sub_directory, '', $class, $params);
                
                return $obj;
        }
        
        /**
         * Produces Module Classes (module.php)
         *  
         * @return Object module class object
         */
        public static function moduleClassFactory($module) {
                
                if (!class_exists('owa_module')):
                        require_once(OWA_BASE_CLASSES_DIR.'owa_module.php');
                endif;
                        
                require_once(OWA_BASE_DIR.'/modules/'.$module.'/module.php');
                        
                return owa_lib::factory(OWA_BASE_CLASSES_DIR.$module, 'owa_', $module.'Module');
                
        }
 
        
        public static function updateFactory($module, $filename, $class_ns = 'owa_') {
        
                require_once(OWA_BASE_CLASS_DIR.'update.php');
                
                //$obj = owa_coreAPI::moduleGenericFactory($module, 'updates', $filename, '_update');
                $class = $class_ns.$module.'_'.$filename.'_update';
        
                // Require class file if class does not already exist
                if(!class_exists($class)):      
                        owa_coreAPI::moduleRequireOnce($module, 'updates', $filename);
                endif;
                        
                $obj = owa_lib::factory(OWA_DIR.'modules'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.'updates', '', $class);
 
                $obj->module_name = $module;
                if (!$obj->schema_version) {
                        $obj->schema_version = $filename;
                }
                return $obj;
        }
                
        public static function subViewFactory($subview, $params = array()) {
                
                list($module, $class) = explode(".", $subview);
                //print_r($module.' ' . $class);
                //owa_lib::moduleRequireOnce($module, $class);
        
                $subview =  owa_lib::moduleFactory($subview, 'View', $params);
                $subview->is_subview = true;
                
                return $subview;
        }
        
        public static function &supportClassFactory($module, $class, $params = array(),$class_ns = 'owa_') {
                
                $obj = &owa_lib::factory(OWA_BASE_DIR.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR, $class_ns, $class, $params);
                $obj->module = $module;
                
                return $obj;
                
                
        }
        
        /**
         * Convienence method for generating entities
         *
         * @param unknown_type $entity_name
         * @return unknown
         */
        public static function entityFactory($entity_name) {
                
                /* SETUP STORAGE ENGINE */
                
                // Must be called before any entities are created
                
                if (!defined('OWA_DTD_INT')) {
                        if (defined('OWA_DB_TYPE')) {
                                owa_coreAPI::setupStorageEngine(OWA_DB_TYPE);
                        } else {
                                owa_coreAPI::setupStorageEngine('mysql');
                        }
                                
                }
                
                
                        
                if (!class_exists('owa_entity')):
                        require_once(OWA_BASE_CLASSES_DIR.'owa_entity.php');    
                endif;
                        
                $entity = owa_coreAPI::moduleSpecificFactory($entity_name, 'entities', '', '', false);
                $entity->name = $entity_name;
                return $entity;
                //return owa_coreAPI::supportClassFactory('base', 'entityManager', $entity_name);
                
        }
        
        /**
         * Convienence method for generating entities
         *
         * @param unknown_type $entity_name
         * @return unknown
         * @depricated
         * @todo REMOVE
         */
        public static function rawEntityFactory($entity_name) {
                        
                return owa_coreAPI::entityFactory($entity_name);
                                
        }
        
        /**
         * Factory for generating module specific classes
         *
         * @param string $modulefile
         * @param string $class_dir
         * @param string $class_suffix
         * @param array $params
         * @return unknown
         */
        public static function moduleSpecificFactory($modulefile, $class_dir, $class_suffix = null, $params = '', $add_module_name = true, $class_ns = 'owa_') {
                
                list($module, $file) = explode(".", $modulefile);
                $class = $class_ns.$file.$class_suffix;
                
                // Require class file if class does not already exist
                if(!class_exists($class)):      
                        owa_coreAPI::moduleRequireOnce($module, $class_dir, $file);
                endif;
                        
                $obj = owa_lib::factory(OWA_BASE_DIR.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.$class_dir.DIRECTORY_SEPARATOR.$module, '', $class, $params);
                
                if ($add_module_name == true):
                        $obj->module = $module;
                endif;
                
                return $obj;
                
                
        }
        
        public static function executeApiCommand($map) {
                
                if (!array_key_exists('do', $map)) {
                        echo ("API Command missing from request.");
                        owa_coreAPI::debug('API Command missing from request. Aborting.');
                        exit;
                } else {
                        // load service
                        $s = owa_coreAPI::serviceSingleton();
                        // lookup method class
                        $do = $s->getApiMethodClass($map['do']);
                                
                }
                
                // if exists, pass to OWA as a request
                if ($do) {
                                
                        if (array_key_exists('args', $do)) {
                                
                                $passed_args = array();
                                
                                foreach ($do['args'] as $arg) {
                                        
                                        if (isset($map[$arg])) {
                                                $passed_args[] = $map[$arg];
                                        } else {
                                                $passed_args[] = '';
                                        }
                                }
                                
                                if (!empty($do['file'])) {
                                        
                                        if (!class_exists($do['callback'][0])) {
                                                require_once($file);
                                        }
                                }
                                
                                $something = call_user_func_array($do['callback'], $passed_args);
                        }       
                        
                        return $something;
                } else {
                        echo "No API Method Found.";
                }
 
        }
        
        /**
         * Convienence method for generating metrics
         *
         * @param unknown_type $entity_name
         * @return unknown
         */
        public static function metricFactory($metric_name, $params = array()) {
                
                if (!strpos($metric_name, '.')) {
                        $s = owa_coreAPI::serviceSingleton();
                        $metric_name = $s->getMetricClasses($metric_name);
                }
                
                if (!class_exists('owa_metric')) {
                        require_once(OWA_BASE_CLASSES_DIR.'owa_metric.php');    
                }
                
                return owa_coreAPI::moduleSpecificFactory($metric_name, 'metrics', '', $params, false);
        }
        
        /**
         * Returns a consolidated list of admin/options panels from all active modules 
         *
         * @return array
         */
        public static function getAdminPanels() {
                
                $panels = array();
                
                $service = owa_coreAPI::serviceSingleton();
                
                foreach ($service->modules as $k => $v) {
                        $v->registerAdminPanels();
                        $module_panels = $v->getAdminPanels();
                        if ($module_panels) {
                                foreach ($module_panels as $key => $value) {
                                        
                                        $panels[$value['group']][] = $value;
                                }
                        }                       
                }
                
                return $panels;
        }
        
        /**
         * Returns a consolidated list of nav links from all active modules for a particular view
         * and named navigation element.
         *
         * @param string nav_name the name of the navigation element that you want links for
         * @param string sortby the array value to sort the navigation array by
         * @return array
         */
        public static function getNavigation($view, $nav_name, $sortby ='order') {
                
                $links = array();
                
                $service = owa_coreAPI::serviceSingleton();
                
                foreach ($service->modules as $k => $v) {
                        
                        // If the module does not have nav links, register them. needed in case this function is called twice on
                        // same view.
                        if (empty($v->nav_links)):
                                $v->registerNavigation();
                        endif;          
                        
                        $module_nav = $v->getNavigationLinks();
                        
        
                        if (!empty($module_nav)) {
                                // assemble the navigation for a specific view's named navigation element'      
                                foreach ($module_nav as $key => $value) {
                                        
                                        $links[$value['view']][$value['nav_name']][] = $value;
                                }
                        }
                        
                }
                
                //print_r($links[$view][$nav_name]);
                if (!empty($links[$view][$nav_name])):
                        // anonymous sorting function, takes sort by variable.
                        $code = "return strnatcmp(\$a['$sortby'], \$b['$sortby']);";
                        
                        // sort the array
                        $ret = usort($links[$view][$nav_name], create_function('$a,$b', $code));
                        
                        return $links[$view][$nav_name];
                else: 
                        return false;
                endif;
                 
        }
        
        public static function getGroupNavigation($group, $sortby ='order') {
        
                $links = array();
                
                $service = owa_coreAPI::serviceSingleton();
                
                foreach ($service->modules as $k => $v) {
                        
                        // If the module does not have nav links, register them. needed in case this function is called twice on
                        // same view.
                        if (empty($v->nav_links)):
                                $v->registerNavigation();
                        endif;          
                        
                        $module_nav = $v->getNavigationLinks();
                        
                        if (!empty($module_nav)):
                                //loop through returned nav array
                                foreach ($module_nav as $group => $nav_links) {
                                        
                                        foreach ($nav_links as $link) { 
                                                                        
                                                if (array_key_exists($group, $links)):
                                                        
                                                        // check to see if link is already present in the main array
                                                        if (array_key_exists($link['anchortext'], $links[$group])):
                                                                // merge various elements?? not now.
                                                                //check to see if there is an existing subgroup
                                                                
                                                                if (array_key_exists('subgroup', $links[$group][$link['anchortext']])):
                                                                        // if so, merge the subgroups
                                                                        $links[$group][$link['anchortext']]['subgroup'] = array_merge($links[$group][$link['anchortext']]['subgroup'], $link['subgroup']);
                                                                endif;  
                                                        else:
                                                                // else populate the link
                                                                $links[$group][$link['anchortext']] = $link;    
                                                        endif;
                                                        
                                                else:
                                                        $links[$group][$link['anchortext']] = $link;
                                                endif;
                                        }                                       
                                        
                                }
                        endif;
                        
                }
                
                return $links[$group];  
        }
        
        /**
         * @Todo REMOVE
         */
        public static function getNavSort($a, $b) {
                
                return strnatcmp($a['order'], $b['order']);
        }
        
                
        public static function getActiveModules() {
        
                $c = owa_coreAPI::configSingleton();
                $config = $c->config->get('settings');
                
                //print_r($config);
                $active_modules = array();
                
                foreach ($config as $k => $module) {
                        
                        if ($module['is_active'] == true):
                                $active_modules[] = $k;
                        endif;
                }
 
                return $active_modules;
        
        }
        
        public static function getModulesNeedingUpdates() {
        
                $service = owa_coreAPI::serviceSingleton();
                
                return $service->getModulesNeedingUpdates();
        }
        
        /**
         * Invokes controller to perform controller
         *
         * @param $action string
         * 
         */
        public static function performAction($action, $params = array()) {
                
                // Load 
                $controller = owa_coreAPI::moduleFactory($action, 'Controller', $params);
                
                if (!$controller || !method_exists($controller, 'doAction')) {
                        owa_coreAPI::debug("No controller is associated with $action.");
                        return;
                }
                
                $data = $controller->doAction();
                                                
                // Display view if controller calls for one.
                if (!empty($data['view']) || !empty($data['action'])):
                
                        // 
                        if ($data['view_method'] == 'delegate'):
                                return owa_coreAPI::displayView($data);
                        
                        // Redirect to a view   
                        elseif ($data['view_method'] == 'redirect'):
                                owa_lib::redirectToView($data);
                                return;
                                
                        // return an image . Will output headers and binary data.
                        elseif ($data['view_method'] == 'image'):
                                return owa_coreAPI::displayImage($data);
                        
                        else:
                                return owa_coreAPI::displayView($data);
                                
                        endif;
                
                elseif(!empty($data['do'])):
                        //print_r($data);
                        owa_lib::redirectToView($data);
                        return;
                        
                endif;
        }
        
        /**
         * Logs an event to the event queue
         *
         * take an owa_event object as a message.
         *
         * @param string $event_type
         * @param object $message
         * @return boolean
         */
        public static function logEvent($event_type, $message = '') {
                
                // debug
                owa_coreAPI::debug("logging event $event_type");
                
                if (owa_coreAPI::getSetting('base', 'error_log_level') > 9) {
                        owa_coreAPI::debug("PHP Server Global: ".print_r($_SERVER, true));
                }
                        
                // Check to see if named users should be logged         
                if (owa_coreAPI::getSetting('base', 'log_named_users') != true) {
                        $cu = owa_coreAPI::getCurrentUser();    
                        $cu_user_id = $cu->getUserData('user_id');
                        
                        if(!empty($cu_user_id)) {
                                return false;
                        }
                }
                
                // do not log if the request is robotic
                $service = &owa_coreAPI::serviceSingleton();
                $bcap = $service->getBrowscap();
                owa_coreAPI::profile(__CLASS__, __FUNCTION__, __LINE__);
                if (!owa_coreAPI::getSetting('base', 'log_robots')) {
                        
                        if ($bcap->robotCheck()) {
                                owa_coreAPI::debug("ABORTING: request appears to be from a robot");
                                owa_coreAPI::setRequestParam('is_robot', true);
                                return;
                        }
                        owa_coreAPI::profile(__CLASS__, __FUNCTION__, __LINE__);
                }
                
                $service->setBrowscap($bcap);
                
                // form event if one was not passed
                $class= 'owa_event';
                if (!($message instanceof $class)) {
                        $event = owa_coreAPI::supportClassFactory('base', 'event');
                        $event->setProperties($message);
                        $event->setEventType($event_type);
                } else {
                        $event = $message;
                }
                                                                
                // Filter XSS exploits from event properties
                $event->cleanProperties();
                
                // do not log if the do not log property is set on the event.
                if ($event->get('do_not_log')) {
                        return false;
                }
                
                // lookup which event processor to use to process this event type
                $processor_action = owa_coreAPI::getEventProcessor($event->getEventType());
                
                return owa_coreAPI::handleRequest(array('event' => $event), $processor_action);
        }
 
        
        public static function displayImage($data) {
                
                header('Content-type: image/gif');
                header('P3P: CP="'.owa_coreAPI::getSetting('base', 'p3p_policy').'"');
                header('Expires: Sat, 22 Apr 1978 02:19:00 GMT');
                header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
                header('Cache-Control: no-store, no-cache, must-revalidate');
                header('Cache-Control: post-check=0, pre-check=0', false);
                header('Pragma: no-cache');
                
                echo owa_coreAPI::displayView($data);           
        }
        
        
        /**
         * Displays a View without user authentication. Takes array of data as input
         *
         * @param array $data
         * @param string $viewfile a specific view file to use
         * @return string
         * 
         */
        public static function displayView($data, $viewfile = '') {
                
                if (empty($viewfile)):
                        $viewfile = $data['view'];
                endif;
                
                $view = owa_coreAPI::moduleFactory($viewfile, 'View');
                $view->setData($data);
                return $view->assembleView($data);
                
        }
        
        public static function displaySubView($data, $viewfile = '') {
                
                if (empty($viewfile)):
                        $viewfile = $data['view'];
                endif;
                
                $view =  owa_coreAPI::subViewFactory($viewfile);
                
                return $view->assembleView($data);
                
        }
        
        /**
         * Strip a URL of certain GET params
         * @depricated
         * @return string
         * @todo REMOVE
         */
        function stripDocumentUrl($url) {
                
                if (owa_coreAPI::getSetting('base', 'clean_query_string')):
                
                        if (owa_coreAPI::getSetting('base', 'query_string_filters')):
                                $filters = str_replace(' ', '', owa_coreAPI::getSetting('base', 'query_string_filters'));
                                $filters = explode(',', $filters);
                        else:
                                $filters = array();
                        endif;
                        
                        // OWA specific params to filter
                        array_push($filters, owa_coreAPI::getSetting('base', 'source_param'));
                        array_push($filters, owa_coreAPI::getSetting('base', 'ns').owa_coreAPI::getSetting('base', 'feed_subscription_param'));
                        
                        //print_r($filters);
                        
                        foreach ($filters as $filter => $value) {
                                
                  $url = preg_replace(
                    '#\?' .
                    $value .
                    '=.*$|&' .
                    $value .
                    '=.*$|' .
                    $value .
                    '=.*&#msiU',
                    '',
                    $url
                  );
                  
                }
                
            endif;
        //print $url;
        
        return $url;
                
        }
        
        public static function getRequestParam($name) {
                
                $service = &owa_coreAPI::serviceSingleton();
                return $service->request->getParam($name);
                
        }
        
        public static function getRequest() {
                $service = &owa_coreAPI::serviceSingleton();
                return $service->request;
        }
        
        public static function setRequestParam($name, $value) {
                
                $service = &owa_coreAPI::serviceSingleton();
                return $service->request->setParam($name, $value);
                
        }
        
        public static function makeTimePeriod($time_period, $params = array()) {
                
                $period = owa_coreAPI::supportClassFactory('base', 'timePeriod');
                $map = array();
                
                if (array_key_exists('startDate', $params)) {
                        $map['startDate'] = $params['startDate'];                       
                }
                
                if (array_key_exists('endDate', $params)) {
                        $map['endDate'] = $params['endDate'];
                }
                
                if (array_key_exists('startTime', $params)) {
                        $map['startTime'] = $params['startTime'];                       
                }
                
                if (array_key_exists('endTime', $params)) {
                        $map['endTime'] = $params['endTime'];
                }
                
                $period->set($time_period, $map);
                
                return $period;
        }
 
        /**
         * Factory method for producing validation objects
         * 
         * @return Object
         */
        public static function validationFactory($class_file) {
                
                if (!class_exists('owa_validation')):
                        require_once(OWA_BASE_CLASS_DIR.'validation.php');
                endif;
                
                return owa_lib::factory(OWA_PLUGINS_DIR.'/validations', 'owa_', $class_file, array(), 'Validation');
                
        }
        
        public static function debug($msg) {
                
                $e = owa_coreAPI::errorSingleton();
                $e->debug($msg);
                return;
        }
        
        public static function error($msg) {
                
                $e = owa_coreAPI::errorSingleton();
                $e->err($msg);
                return;
        }
        
        public static function notice($msg) {
                
                $e = owa_coreAPI::errorSingleton();
                $e->notice($msg);
                return;
        }
        
        public static function createCookie($cookie_name, $cookie_value, $expires = 0, $path = '/', $domain = '') {
                
                if ( $domain ) {
                        // sanitizes the domain
                        $domain = owa_lib::sanitizeCookieDomain( $domain );
                } else {
                        $domain = owa_coreAPI::getSetting('base', 'cookie_domain');
                }       
                if (is_array($cookie_value)) {
                        
                        $cookie_value = owa_lib::implode_assoc('=>', '|||', $cookie_value);
                }
                
                // add namespace
                $cookie_name = sprintf('%s%s', owa_coreAPI::getSetting('base', 'ns'), $cookie_name);
                
                // debug
                owa_coreAPI::debug(sprintf('Setting cookie %s with values: %s under domain: %s', $cookie_name, $cookie_value, $domain));
                
                // set compact privacy header
                header(sprintf('P3P: CP="%s"', owa_coreAPI::getSetting('base', 'p3p_policy')));
                //owa_coreAPI::debug('time: '.$expires);
                setcookie($cookie_name, $cookie_value, $expires, $path, $domain);
                return;
        }
        
        public static function deleteCookie($cookie_name, $path = '/', $domain = '') {
        
                return owa_coreAPI::createCookie($cookie_name, false, time()-3600*25, $path, $domain);
        }
        
        public static function setState($store, $name = '', $value, $store_type = '', $is_perminent = '') {
                
                $service = &owa_coreAPI::serviceSingleton();
                return $service->request->state->set($store, $name, $value, $store_type, $is_perminent);
        }
        
        public static function getStateParam($store, $name = '') {
                
                $service = &owa_coreAPI::serviceSingleton();
                return $service->request->state->get($store, $name);    
        }
        
        public static function getServerParam($name = '') {
                
                $service = &owa_coreAPI::serviceSingleton();
                return $service->request->getServerParam($name);        
        }
        
        public static function clearState($store) {
                
                $service = &owa_coreAPI::serviceSingleton();
                $service->request->state->clear($store); 
                                
        }
        
        public static function getEventProcessor($event_type) {
                
                $service = &owa_coreAPI::serviceSingleton();
                $processor = $service->getMapValue('event_processors', $event_type);
                
                if (empty($processor)) {
                
                        $processor = 'base.processEvent';
                }
                
                return $processor;
        }
        
        /**
         * Handles OWA internal page/action requests
         *
         * @return unknown
         */
        public static function handleRequest($caller_params = null, $action = '') {
                
                static $init;
                
                $service = &owa_coreAPI::serviceSingleton();
                // Override request parsms with those passed by caller
                if (!empty($caller_params)) {
                        $service->request->mergeParams($caller_params);
                };
                
                $params = $service->request->getAllOwaParams();
                
                if ($init != true) {
                        owa_coreAPI::debug('Handling request with params: '. print_r($params, true));
                }
                
                // backwards compatability with old style view/controler scheme
                // still needed??
                if (array_key_exists('view', $params)) {
                        // its a view request so the only data is in whats in the params
                        $init = true;
                        return owa_coreAPI::displayView($params);
                } 
        
                if (empty($action)) {
                        $action = owa_coreAPI::getRequestParam('action');
                        if (empty($action)) {
                                $action = owa_coreAPI::getRequestParam('do');
                                
                                if (empty($action)) {
                                        $action = owa_coreAPI::getSetting('base', 'start_page');
                                }       
                        }
                }
                
                $init = true;
                owa_coreAPI::debug('About to perform action: '.$action);
                return owa_coreAPI::performAction($action, $params);
                                                
        }
        
        public static function isUpdateRequired() {
                
                $service = &owa_coreAPI::serviceSingleton();
                return $service->isUpdateRequired();
        }
        
        public static function getSitesList() {
                
                //$s = owa_coreAPI::entityFactory('base.site');
                $db = owa_coreAPI::dbSingleton();
                $db->selectFrom('owa_site');
                $db->selectColumn('*');
                return $db->getAllRows();
                
        }
        
        public static function profile($that = '', $function = '', $line = '', $msg = '') {
        
                if (defined('OWA_PROFILER')) {
                        if (OWA_PROFILER === true) {
                        
                                static $profiler;
                                                
                                if (!class_exists('PhpQuickProfiler')) {
                                        require_once(OWA_INCLUDE_DIR.'pqp/classes/PhpQuickProfiler.php');
                                }
                                
                                if (empty($profiler)) {
                                        $profiler = new PhpQuickProfiler(PhpQuickProfiler::getMicroTime(), OWA_INCLUDE_DIR.'pqp/');
                                }
                                
                                $class = get_class($that);
                                Console::logSpeed($class."::$function - Line: $line - Msg: $msg");
                                Console::logMemory($that, $class. "::$function - Line: $line");
                                
                                return $profiler;
                        }
                }
        }
        
        public static function profileDisplay() {
                $p = owa_coreAPI::profile();
                if ($p) {
                        $p->display();
                }
                
        }
        
        public static function getEventDispatch() {
                
                if (!class_exists('eventQueue')) {
                        require_once(OWA_DIR.'/eventQueue.php');
                }
 
                $eq = &eventQueue::get_instance();
                return $eq;
        }
        
        public static function getCliCommandClass($command) {
                
                $s = owa_coreAPI::serviceSingleton();
                return $s->getCliCommandClass($command);
        }
        
        public static function getGeolocationFromIpAddress($ip_address) {
                
                $s = &owa_coreAPI::serviceSingleton();
                $s->geolocation->getGeolocationFromIp($ip_address);
                return $s->geolocation;
        }
        
        public static function getNonceTimeInterval() {
                
                return  ceil( time() / owa_coreAPI::getSetting( 'base', 'nonce_expiration_period') );
        }
        
        public static function createNonce($action) {
                
                $time = owa_coreAPI::getNonceTimeInterval();
                $cu = owa_coreAPI::getCurrentUser();
                $user_id = $cu->getUserData( 'user_id' );
                $full_nonce = $time . $action . $user_id . 'owa_nonce';
                $nonce = substr(md5($full_nonce), -12, 10);
                
                return $nonce;
        }
        
        public static function summarize($map) {
                
                $entity = owa_coreAPI::entityFactory($map['entity']);
                $db = owa_coreAPI::dbSingleton();
                $db->selectFrom($entity->getTableName(), $entity->getTableAlias());
                
                foreach ($map['columns'] as $col => $action) {
                        
                        switch ($action) {
                                
                                case 'sum':
                                        $col_def = sprintf("SUM(%s)", $col);
                                        $name = $col.'_sum';
                                        break;
                                case 'count':
                                        $col_def = sprintf("COUNT(%s)", $col);
                                        $name = $col.'_count';
                                        break;
                                case 'count_distinct':
                                        $col_def = sprintf("COUNT(distinct %s)", $col);
                                        $name = $col.'_dcount';
                                        break;
                        }
                        
                        $db->selectColumn($col_def, $name);
                }
                
                foreach ($map['constraints'] as $con_col => $con_value) {
                        
                        if ( is_array( $con_value ) ) {
                                $db->where($con_col, $con_value['value'], $con_value['operator']);
                        } else {
                                $db->where($con_col, $con_value);
                        }
                }
                
                $ret = $db->getOneRow();
                return $ret;
        }
        
        public static function getJsTrackerTag( $site_id, $options = array() ) {
                
                if ( ! class_exists( 'owa_template' ) ) {
                        require_once(OWA_BASE_CLASSES_DIR.'owa_template.php');
                }
                
                $t = new owa_template();
                
                // check to see if first hit tag is needed
                if (owa_coreAPI::getSetting('base', 'delay_first_hit')) {
                
                        $service = &owa_coreAPI::serviceSingleton();
                        //check for persistant cookie
                        $v = $service->request->getOwaCookie('v');
                        
                        if (empty($v)) {
                                
                                $options['first_hit_tag'] = true;
                        }               
                }
                
                //check to see if we shuld log clicks.
                if ( ! owa_coreAPI::getSetting( 'base', 'log_dom_clicks' ) ) {
                        $options['do_not_log_clicks'] = true;
                }
 
                if ( ! owa_coreAPI::getSetting( 'base', 'log_dom_streams' ) ) {
                        $options['do_not_log_domstream'] = true;
                }
                
                if (owa_coreAPI::getSetting('base', 'is_embedded')) {
                        
                        // needed to override the endpoint used by the js tracker
                        $options['apiEndpoint'] = owa_coreAPI::getSetting('base', 'api_url');
                }
                                
                $t->set( 'site_id', $site_id );
                $t->set( 'options', $options);
                
                $t->set_template('js_helper_tags.tpl');
                return $t->fetch();
        }
        
        public static function activateModule( $module_name ) {
                
                if ( $module_name ) {
                
                        $m = owa_coreAPI::moduleClassFactory($module_name);
                        return $m->activate();
                }
        }
        
        public static function deactivateModule( $module_name ) {
                
                if ( $module_name ) {
                
                        $s = owa_coreAPI::serviceSingleton();
                        $m = $s->getModule($module_name);
                        return $m->deactivate();
                }
        }
        
        public static function installModule( $module_name ) {
                
                if ($module_name) {
                
                        $m = owa_coreAPI::moduleClassFactory($module_name);
                        $status = $m->install();
                        return $status;
                }
        }
        
        public static function generateInstanceSpecificHash() {
                
                if ( defined( 'OWA_SECRET' ) ) {
                        $salt = OWA_SECRET;
                } else {
                        $salt = '';
                }
                
                if ( defined( 'OWA_DB_USER' ) ) { 
                        $salt .= OWA_DB_USER; 
                } 
                
                if ( defined( 'OWA_DB_PASSWORD' ) ) { 
                        $salt .= OWA_DB_PASSWORD; 
                }                        
                
                return md5( $salt ); 
        }
}
 
?>