"Fossies" - the Fresh Open Source Software Archive

Member "Open-Web-Analytics-1.7.0/owa_coreAPI.php" (16 Sep 2020, 52286 Bytes) of package /linux/www/Open-Web-Analytics-1.7.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) PHP source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "owa_coreAPI.php" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 1.6.9_vs_1.7.0.

    1 <?php
    2 
    3 //
    4 // Open Web Analytics - An Open Source Web Analytics Framework
    5 //
    6 // Copyright 2006 Peter Adams. All rights reserved.
    7 //
    8 // Licensed under GPL v2.0 http://www.gnu.org/copyleft/gpl.html
    9 //
   10 // Unless required by applicable law or agreed to in writing, software
   11 // distributed under the License is distributed on an "AS IS" BASIS,
   12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   13 // See the License for the specific language governing permissions and
   14 // limitations under the License.
   15 //
   16 // $Id$
   17 //
   18 
   19 require_once(OWA_BASE_DIR.'/owa_lib.php');
   20 
   21 /**
   22  * OWA Core API
   23  * 
   24  * @author      Peter Adams <peter@openwebanalytics.com>
   25  * @copyright   Copyright &copy; 2006 Peter Adams <peter@openwebanalytics.com>
   26  * @license     http://www.gnu.org/copyleft/gpl.html GPL v2.0
   27  * @category    owa
   28  * @package     owa
   29  * @version        $Revision$
   30  * @since        owa 1.0.0
   31  */
   32 
   33 class owa_coreAPI {
   34 
   35 
   36     // @depricated
   37     // @todo remove
   38     public static function singleton($params = array()) {
   39 
   40         static $api;
   41 
   42         if(!isset($api)):
   43             $api = new owa_coreAPI();
   44         endif;
   45 
   46         if(!empty($params)):
   47             $api->params = $params;
   48         endif;
   49 
   50         return $api;
   51     }
   52 
   53     public static function setupStorageEngine($type) {
   54 
   55         if ( ! class_exists( 'owa_db' ) ) {
   56             
   57             require_once(OWA_BASE_CLASSES_DIR.'owa_db.php');
   58         }
   59         
   60         if ( $type ) {
   61             $connection_class = "owa_db_" . $type;
   62 
   63             if ( ! class_exists( $connection_class ) ) {
   64                 
   65                 $connection_class_path = OWA_PLUGIN_DIR.'db/' . $connection_class . ".php";
   66                 
   67                 if ( file_exists( $connection_class_path ) ) {
   68                     
   69                      if ( ! require_once( $connection_class_path ) ) {
   70                          
   71                          owa_coreAPI::error(sprintf('Cannot locate proper db class at %s.', $connection_class_path));
   72                          
   73                          return false;
   74                     }
   75                     
   76                 } else {
   77                     
   78                     owa_coreAPI::error("$type database connection class file not found.");
   79                 }
   80             }
   81 
   82         } else {
   83             
   84             owa_coreAPI::error("$type is not a supported database.");
   85         }
   86 
   87          return true;
   88 
   89     }
   90     /**
   91      * @return owa_db
   92      */
   93     public static function dbSingleton() {
   94 
   95         static $db;
   96 
   97         if (!isset($db)) {
   98 
   99             $db = owa_coreAPI::dbFactory();
  100         }
  101 
  102         return $db;
  103     }
  104 
  105     public static function dbFactory() {
  106 
  107         $db_type = owa_coreAPI::getSetting('base', 'db_type');
  108         $ret = owa_coreAPI::setupStorageEngine($db_type);
  109 
  110          if (!$ret) {
  111              owa_coreAPI::error(sprintf('Failed to intialise db of type %s. Exiting.', $db_type));
  112              return;
  113         } else {
  114             $connection_class = 'owa_db_'.$db_type;
  115             $db = new $connection_class(
  116                 owa_coreAPI::getSetting('base','db_host'),
  117                 owa_coreAPI::getSetting('base','db_port'),
  118                 owa_coreAPI::getSetting('base','db_name'),
  119                 owa_coreAPI::getSetting('base','db_user'),
  120                 owa_coreAPI::getSetting('base','db_password'),
  121                 owa_coreAPI::getSetting('base','db_force_new_connections'),
  122                 owa_coreAPI::getSetting('base','db_make_persistant_connections')
  123             );
  124 
  125             return $db;
  126         }
  127     }
  128 
  129     /**
  130      * @return owa_settings
  131      */
  132     public static function configSingleton() {
  133 
  134         static $config;
  135 
  136         if( ! isset( $config ) ) {
  137 
  138             if ( ! class_exists( 'owa_settings' ) ) {
  139                 require_once( OWA_BASE_CLASS_DIR.'settings.php' );
  140             }
  141 
  142             $config = owa_coreAPI::supportClassFactory( 'base', 'settings' );
  143         }
  144 
  145         return $config;
  146     }
  147 
  148     public static function errorSingleton() {
  149 
  150         static $e;
  151 
  152         if( ! $e ) {
  153 
  154             if ( ! class_exists( 'owa_error' ) ) {
  155                 require_once( OWA_BASE_CLASS_DIR.'error.php' );
  156             }
  157 
  158             $e = owa_coreAPI::supportClassFactory( 'base', 'error' );
  159 
  160         }
  161 
  162         return $e;
  163     }
  164 
  165     public static function getSetting($module, $name) {
  166 
  167         $s = owa_coreAPI::configSingleton();
  168         return $s->get($module, $name);
  169     }
  170 
  171     public static function setSetting($module, $name, $value, $persist = false) {
  172 
  173         $s = owa_coreAPI::configSingleton();
  174 
  175         if ($persist === true) {
  176             $s->persistSetting($module, $name, $value);
  177         } else {
  178             $s->setSetting($module, $name, $value);
  179         }
  180 
  181     }
  182 
  183     public static function persistSetting($module, $name, $value) {
  184 
  185         $s = owa_coreAPI::configSingleton();
  186         $s->persistSetting($module, $name, $value);
  187 
  188     }
  189 
  190     public static function getSiteSetting($site_id, $name) {
  191 
  192         $site = owa_coreAPI::entityFactory('base.site');
  193         $site->load( $site->generateId( $site_id ) );
  194 
  195         if ( $site->wasPersisted() ) {
  196 
  197             return $site->getSiteSetting($name);
  198         }
  199     }
  200 
  201     public static function getRegisteredDomain( $full_domain ) {
  202 
  203         static $psl;
  204 
  205         if ( ! $psl ) {
  206             $psl = owa_coreAPI::supportClassFactory( 'base', 'pslReader' );
  207         }
  208 
  209         return $psl->getRegisteredDomain( $full_domain );
  210     }
  211 
  212     public static function persistSiteSetting($site_id, $name, $value) {
  213 
  214         $site = owa_coreAPI::entityFactory('base.site');
  215         $site->load( $site->generateId( $site_id ) );
  216         if ( $site->wasPersisted() ) {
  217             $settings = $site->get('settings');
  218             if ( ! $settings ) {
  219                 $settings = array();
  220             }
  221             $settings[$name] = $value;
  222             $site->set('settings', $settings);
  223             $site->update();
  224         }
  225     }
  226 
  227     public static function getSiteSettings($site_id) {
  228 
  229         $site = owa_coreAPI::entityFactory('base.site');
  230         $site->load( $site->generateId( $site_id ) );
  231         if ( $site->wasPersisted() ) {
  232 
  233             $settings = $site->get('settings');
  234 
  235             if ( $settings ) {
  236                 return $settings;
  237             } else {
  238                 return array();
  239             }
  240         }
  241 
  242     }
  243 
  244     public static function getAllRoles() {
  245 
  246         $caps = owa_coreAPI::getSetting('base', 'capabilities');
  247         return array_keys($caps);
  248     }
  249 
  250     public static function getCapabilities($role) {
  251         $caps = owa_coreAPI::getSetting('base', 'capabilities');
  252         if (array_key_exists($role, $caps)) {
  253             return $caps[$role];
  254         } else {
  255             return array();
  256         }
  257     }
  258 
  259     /**
  260      * @return owa_serviceUser
  261      */
  262     public static function getCurrentUser() {
  263         $s = owa_coreAPI::serviceSingleton();
  264         return $s->getCurrentUser();
  265     }
  266 
  267     /**
  268      * check to see if the current user has a capability
  269      * always returns a bool
  270      * @return boolean
  271      */
  272     public static function isCurrentUserCapable($capability, $site_id = null) {
  273 
  274         $cu = owa_coreAPI::getCurrentUser();
  275         owa_coreAPI::debug("Current User Role: ".$cu->getRole());
  276         owa_coreAPI::debug("Current User Authentication: ".$cu->isAuthenticated());
  277         $ret = $cu->isCapable($capability, $site_id);
  278         owa_coreAPI::debug("Is current User capable: ".$ret);
  279         return $ret;
  280     }
  281 
  282     public static function isCurrentUserAuthenticated() {
  283 
  284         $cu = owa_coreAPI::getCurrentUser();
  285         return $cu->isAuthenticated();
  286     }
  287     /**
  288      * @return owa_service
  289      */
  290     public static function serviceSingleton() {
  291 
  292         static $s;
  293 
  294         if(empty($s)) {
  295 
  296             if (!class_exists('owa_service')) {
  297                 require_once(OWA_BASE_CLASS_DIR.'service.php');
  298             }
  299 
  300             $s = owa_coreAPI::supportClassFactory('base', 'service');
  301 
  302         }
  303 
  304         return $s;
  305     }
  306 
  307     public static function cacheSingleton($params = array()) {
  308 
  309         static $cache;
  310 
  311         if ( !isset ( $cache ) ) {
  312             $cache_type = owa_coreAPI::getSetting('base', 'cacheType');
  313 
  314             switch ($cache_type) {
  315 
  316                 case "memcached":
  317                     $implementation = array('owa_memcachedCache', OWA_BASE_CLASS_DIR.'memcachedCache.php');
  318                     break;
  319                 default:
  320                     $implementation = array('owa_fileCache', OWA_BASE_CLASS_DIR.'fileCache.php');
  321 
  322             }
  323 
  324             if ( ! class_exists( $implementation[0] ) ) {
  325                 require_once( $implementation[1] );
  326             }
  327             // make this plugable
  328             $cache = new $implementation[0];
  329         }
  330 
  331         return $cache;
  332     }
  333 
  334     public static function requestContainerSingleton() {
  335 
  336         static $request;
  337 
  338         if(!isset($request)):
  339 
  340             if (!class_exists('owa_requestContainer')):
  341                 require_once(OWA_DIR.'owa_requestContainer.php');
  342             endif;
  343 
  344             $request = owa_lib::factory(OWA_DIR, '', 'owa_requestContainer');
  345 
  346         endif;
  347 
  348         return $request;
  349 
  350     }
  351 
  352     public static function moduleRequireOnce($module, $class_dir, $file) {
  353 
  354         if (!empty($class_dir)) {
  355 
  356             $class_dir .= '/';
  357 
  358         }
  359 
  360         $full_file_path = OWA_BASE_DIR.'/modules/'.$module.'/'.$class_dir.$file.'.php';
  361 
  362         if (file_exists($full_file_path)) {
  363             return require_once($full_file_path);
  364         } else {
  365             owa_coreAPI::debug("moduleRequireOnce says no file found at: $full_file_path");
  366             return false;
  367         }
  368     }
  369 
  370     public static function moduleFactory($modulefile, $class_suffix = null, $params = '', $class_ns = 'owa_') {
  371         list($module, $file) = explode(".", $modulefile);
  372         $class = $class_ns.$file.$class_suffix;
  373         //print $class;
  374         // Require class file if class does not already exist
  375         if(!class_exists($class)):
  376             owa_coreAPI::moduleRequireOnce($module, '', $file);
  377         endif;
  378 
  379         $obj = owa_lib::factory(OWA_BASE_DIR.'/modules/'.$module, '', $class, $params);
  380 
  381         //if (isset($obj->module)):
  382             $obj->module = $module;
  383         //endif;
  384 
  385         return $obj;
  386     }
  387 
  388     public static function moduleGenericFactory($module, $sub_directory, $file, $class_suffix = null, $params = '', $class_ns = 'owa_') {
  389 
  390         $class = $class_ns.$file.$class_suffix;
  391 
  392         // Require class file if class does not already exist
  393         if(!class_exists($class)):
  394             owa_coreAPI::moduleRequireOnce($module, $sub_directory, $file);
  395         endif;
  396 
  397         $obj = owa_lib::factory(OWA_DIR.'modules'.'/'.$module.'/'.$sub_directory, '', $class, $params);
  398 
  399         return $obj;
  400     }
  401 
  402     /**
  403      * Produces Module Classes (module.php)
  404      *
  405      * @return Object module class object
  406      */
  407     public static function moduleClassFactory($module) {
  408 
  409         if (!class_exists('owa_module')):
  410             require_once(OWA_BASE_CLASSES_DIR.'owa_module.php');
  411         endif;
  412 
  413         require_once(OWA_BASE_DIR.'/modules/'.$module.'/module.php');
  414 
  415         return owa_lib::factory(OWA_BASE_CLASSES_DIR.$module, 'owa_', $module.'Module');
  416 
  417     }
  418 
  419 
  420     public static function updateFactory($module, $filename, $class_ns = 'owa_') {
  421 
  422         require_once(OWA_BASE_CLASS_DIR.'update.php');
  423 
  424         //$obj = owa_coreAPI::moduleGenericFactory($module, 'updates', $filename, '_update');
  425         $class = $class_ns.$module.'_'.$filename.'_update';
  426 
  427         // Require class file if class does not already exist
  428         if(!class_exists($class)):
  429             owa_coreAPI::moduleRequireOnce($module, 'updates', $filename);
  430         endif;
  431 
  432         $obj = owa_lib::factory(OWA_DIR.'modules'.'/'.$module.'/'.'updates', '', $class);
  433 
  434         $obj->module_name = $module;
  435         if (!$obj->schema_version) {
  436             $obj->schema_version = $filename;
  437         }
  438         return $obj;
  439     }
  440 
  441     public static function subViewFactory($subview, $params = array()) {
  442 
  443         list($module, $class) = explode(".", $subview);
  444         //print_r($module.' ' . $class);
  445         //owa_lib::moduleRequireOnce($module, $class);
  446 
  447         $subview =  owa_lib::moduleFactory($subview, 'View', $params);
  448         $subview->is_subview = true;
  449 
  450         return $subview;
  451     }
  452 
  453     public static function supportClassFactory($module, $class, $params = array(),$class_ns = 'owa_') {
  454 
  455         $obj = owa_lib::factory(OWA_BASE_DIR.'/'.'modules'.'/'.$module.'/'.'classes'.'/', $class_ns, $class, $params);
  456         $obj->module = $module;
  457 
  458         return $obj;
  459 
  460 
  461     }
  462 
  463     /**
  464      * Convienence method for generating entities
  465      *
  466      * @param unknown_type $entity_name
  467      * @return unknown
  468      */
  469     public static function entityFactory($entity_name) {
  470 
  471         /* SETUP STORAGE ENGINE */
  472 
  473         // Must be called before any entities are created
  474 
  475         if (!defined('OWA_DTD_INT')) {
  476             if (defined('OWA_DB_TYPE')) {
  477                 owa_coreAPI::setupStorageEngine(OWA_DB_TYPE);
  478             } else {
  479                 owa_coreAPI::setupStorageEngine('mysql');
  480             }
  481 
  482         }
  483 
  484 
  485 
  486         if (!class_exists('owa_entity')):
  487             require_once(OWA_BASE_CLASSES_DIR.'owa_entity.php');
  488         endif;
  489 
  490         $entity = owa_coreAPI::moduleSpecificFactory($entity_name, 'entities', '', '', false);
  491         $entity->name = $entity_name;
  492         return $entity;
  493         //return owa_coreAPI::supportClassFactory('base', 'entityManager', $entity_name);
  494 
  495     }
  496 
  497     /**
  498      * Convienence method for generating entities
  499      *
  500      * @param unknown_type $entity_name
  501      * @return unknown
  502      * @depricated
  503      * @todo REMOVE
  504      */
  505     public static function rawEntityFactory($entity_name) {
  506 
  507         return owa_coreAPI::entityFactory($entity_name);
  508 
  509     }
  510 
  511     /**
  512      * Factory for generating module specific classes
  513      *
  514      * @param string $modulefile
  515      * @param string $class_dir
  516      * @param string $class_suffix
  517      * @param array $params
  518      * @return unknown
  519      */
  520     public static function moduleSpecificFactory($modulefile, $class_dir, $class_suffix = null, $params = '', $add_module_name = true, $class_ns = 'owa_') {
  521 
  522         list($module, $file) = explode(".", $modulefile);
  523         $class = $class_ns.$file.$class_suffix;
  524 
  525         // Require class file if class does not already exist
  526         if(!class_exists($class)):
  527             owa_coreAPI::moduleRequireOnce($module, $class_dir, $file);
  528         endif;
  529 
  530         $obj = owa_lib::factory(OWA_BASE_DIR.'/'.'modules'.'/'.$class_dir.'/'.$module, '', $class, $params);
  531 
  532         if ($add_module_name == true):
  533             $obj->module = $module;
  534         endif;
  535 
  536         return $obj;
  537 
  538 
  539     }
  540 
  541     public static function executeApiCommand($map) {
  542         
  543         // carve out for REST API backwards compatability during migration
  544         if ( array_key_exists('version', $map) ) {
  545             
  546             $route = self::lookupRestRoute( $map['request_method'], $map['module'], $map['version'], $map['do']);
  547             
  548             if ( $route ) {
  549                 
  550                 //$params['rest_route'] = $route;
  551                 $controller = owa_lib::simpleFactory( $route['class_name'], $route['file'], $map );                 
  552                 $response = self::runController( $controller );
  553                 
  554                 $response = json_decode($response);
  555                 
  556                 return $response->data;
  557             }
  558         }
  559         
  560         if (!array_key_exists('do', $map)) {
  561             echo ("API Command missing from request.");
  562             owa_coreAPI::debug('API Command missing from request. Aborting.');
  563             exit;
  564         } else {
  565             // load service
  566             $s = owa_coreAPI::serviceSingleton();
  567             // lookup method class
  568             $do = $s->getApiMethodClass($map['do']);
  569 
  570         }
  571 
  572         // if exists, pass to OWA as a request
  573         if ($do) {
  574 
  575             if (array_key_exists('args', $do)) {
  576 
  577                 $passed_args = array();
  578 
  579                 foreach ($do['args'] as $arg) {
  580 
  581                     if (isset($map[$arg])) {
  582                         $passed_args[] = $map[$arg];
  583                     } else {
  584                         $passed_args[] = '';
  585                     }
  586                 }
  587 
  588                 if (!empty($do['file'])) {
  589 
  590                     if (!class_exists($do['callback'][0])) {
  591                         require_once($file);
  592                     }
  593                 }
  594 
  595                 $something = call_user_func_array($do['callback'], $passed_args);
  596             }
  597 
  598             return $something;
  599         } else {
  600             echo "No API Method Found.";
  601         }
  602 
  603     }
  604 
  605     /**
  606      * Convienence method for generating metrics
  607      *
  608      * @param unknown_type $entity_name
  609      * @return unknown
  610      */
  611     public static function metricFactory($metric_name, $params = array()) {
  612 
  613         if (!strpos($metric_name, '.')) {
  614             $s = owa_coreAPI::serviceSingleton();
  615             $metric_name = $s->getMetricClasses($metric_name);
  616         }
  617 
  618         if (!class_exists('owa_metric')) {
  619             require_once(OWA_BASE_CLASSES_DIR.'owa_metric.php');
  620         }
  621 
  622         return owa_coreAPI::moduleSpecificFactory($metric_name, 'metrics', '', $params, false);
  623     }
  624 
  625     /**
  626      * Returns a consolidated list of admin/options panels from all active modules
  627      *
  628      * @return array
  629      */
  630     public static function getAdminPanels() {
  631 
  632         $panels = array();
  633 
  634         $service = owa_coreAPI::serviceSingleton();
  635 
  636         foreach ($service->modules as $k => $v) {
  637             $v->registerAdminPanels();
  638             $module_panels = $v->getAdminPanels();
  639             if ($module_panels) {
  640                 foreach ($module_panels as $key => $value) {
  641 
  642                     $panels[$value['group']][] = $value;
  643                 }
  644             }
  645         }
  646 
  647         return $panels;
  648     }
  649 
  650     /**
  651      * Returns a consolidated list of nav links from all active modules for a particular view
  652      * and named navigation element.
  653      *
  654      * @param string nav_name the name of the navigation element that you want links for
  655      * @param string sortby the array value to sort the navigation array by
  656      * @return array
  657      */
  658     public static function getNavigation($view, $nav_name, $sortby ='order') {
  659 
  660         $links = array();
  661 
  662         $service = owa_coreAPI::serviceSingleton();
  663 
  664         foreach ($service->modules as $k => $v) {
  665 
  666             // If the module does not have nav links, register them. needed in case this function is called twice on
  667             // same view.
  668             if (empty($v->nav_links)):
  669                 $v->registerNavigation();
  670             endif;
  671 
  672             $module_nav = $v->getNavigationLinks();
  673 
  674 
  675             if (!empty($module_nav)) {
  676                 // assemble the navigation for a specific view's named navigation element'
  677                 foreach ($module_nav as $key => $value) {
  678 
  679                     $links[$value['view']][$value['nav_name']][] = $value;
  680                 }
  681             }
  682 
  683         }
  684 
  685         //print_r($links[$view][$nav_name]);
  686         if (!empty($links[$view][$nav_name])):
  687                // sort the array
  688                usort($links[$view][$nav_name], function($a, $b) use ($sortby) {
  689                 return strnatcmp($a[$sortby], $b[$sortby]);
  690             });
  691 
  692             return $links[$view][$nav_name];
  693         else:
  694             return false;
  695         endif;
  696 
  697     }
  698 
  699     public static function getGroupNavigation($group_name, $sortby ='order') {
  700 
  701         $links = array();
  702 
  703         $service = owa_coreAPI::serviceSingleton();
  704 
  705         foreach ($service->modules as $k => $v) {
  706 
  707             // If the module does not have nav links, register them. needed in case this function is called twice on
  708             // same view.
  709             if ( empty( $v->nav_links ) ) {
  710 
  711                 $v->registerNavigation();
  712             }
  713 
  714             $module_nav = $v->getNavigationLinks();
  715 
  716             if ( $module_nav ) {
  717 
  718                 //loop through returned nav array
  719                 foreach ( $module_nav as $group => $nav_links ) {
  720 
  721                     foreach ( $nav_links as $subgroup => $link ) {
  722 
  723                         // check to see if group exists
  724                         if ( array_key_exists( $group, $links ) ) {
  725 
  726                             // check to see if subgroup is already present in the main array
  727                             if ( array_key_exists( $subgroup, $links[ $group ] ) ) {
  728                                 // merge various elements?? not now.
  729 
  730                                 //check to see if there is an existing set of subgroup links
  731                                 if ( array_key_exists( 'subgroup', $links[ $group ][ $subgroup ] ) ) {
  732                                     // if so, merge the subgroups
  733                                     $links[ $group ][ $subgroup ][ 'subgroup' ] = array_merge( $links[ $group ][ $subgroup ][ 'subgroup' ], $link[ 'subgroup' ] );
  734                                 } else {
  735 
  736                                 }
  737                             } else {
  738                                 // else populate the link
  739                                 $links[$group][$subgroup] = $link;
  740                             }
  741 
  742                         } else {
  743                             $links[$group][$subgroup] = $link;
  744                         }
  745                     }
  746 
  747                 }
  748             }
  749         }
  750 
  751         if ( isset( $links[$group_name] ) ) {
  752 
  753             return $links[$group_name];
  754         }
  755     }
  756 
  757     /**
  758      * @Todo REMOVE
  759      */
  760     public static function getNavSort($a, $b) {
  761 
  762         return strnatcmp($a['order'], $b['order']);
  763     }
  764 
  765 
  766     public static function getActiveModules() {
  767 
  768         $c = owa_coreAPI::configSingleton();
  769 
  770         $config = $c->config->get('settings');
  771 
  772 
  773         $active_modules = array();
  774 
  775         foreach ($config as $k => $module) {
  776 
  777             if ( isset($module['is_active']) && $module['is_active'] == true) {
  778                 $active_modules[] = $k;
  779             }
  780         }
  781 
  782         return $active_modules;
  783 
  784     }
  785     
  786     public static function getPresentModules() {
  787         $path = OWA_DIR.'modules';
  788         // Check directory exists or not
  789         if( file_exists($path) && is_dir($path)) {
  790             // Scan the files in this directory
  791             $result = scandir($path);
  792         
  793             // Filter out the current (.) and parent (..) directories
  794             $files = array_diff($result, array('.', '..', 'index.php'));
  795             owa_coreAPI::debug('Modules present are: ');
  796             owa_coreAPI::debug( $files );
  797             
  798             return $files;
  799         }
  800     }
  801 
  802     public static function getModulesNeedingUpdates() {
  803 
  804         $service = owa_coreAPI::serviceSingleton();
  805 
  806         return $service->getModulesNeedingUpdates();
  807     }
  808 
  809     /**
  810      * Invokes controller to perform controller
  811      *
  812      * @param $action string
  813      *
  814      */
  815     public static function performAction( $action, $params = array() ) {
  816 
  817         $service = owa_coreAPI::serviceSingleton();
  818             
  819         // Load action controller from service map which uses the 'module.action' convention    
  820         $action_map = $service->getMapValue('actions', $action );
  821             
  822         // create the controller object
  823         if ( $action_map ) {
  824             
  825             $controller = owa_lib::simpleFactory( $action_map['class_name'], $action_map['file'], $params );
  826         
  827         } else {
  828         
  829             // attempt to use old style convention
  830             $controller = owa_coreAPI::moduleFactory($action, 'Controller', $params);
  831         }
  832         
  833         return owa_coreAPI::runController( $controller );        
  834     }
  835     
  836     public static function runController( $controller ) {
  837         
  838         if ( ! $controller || ! method_exists( $controller, 'doAction' ) ) {
  839 
  840             owa_coreAPI::debug("Class is not a controller. no doAction method found.");
  841             return;
  842         }
  843 
  844         // call the doAction method which is part of the abstract controller class
  845         // inherited by all other controller classes
  846         $data = $controller->doAction();
  847 
  848         // Display view if controller calls for one.
  849         if ( ! empty( $data['view'] ) || ! empty( $data['action'] ) ) {
  850 
  851             // Redirect to a view
  852             if ( $data['view_method'] == 'redirect' ) {
  853 
  854                 return owa_lib::redirectToView( $data );
  855 
  856             // return an image . Will output headers and binary data.
  857             } elseif ( $data['view_method'] == 'image' ) {
  858 
  859                 return owa_coreAPI::displayImage( $data );
  860 
  861             } else {
  862 
  863                 return owa_coreAPI::displayView( $data );
  864             }
  865 
  866         } elseif( ! empty( $data['do'] ) ) {
  867 
  868             return owa_lib::redirectToView( $data );
  869         }
  870     }
  871 
  872     /**
  873      * Logs an event to the event queue
  874      *
  875      * take an owa_event object as a message.
  876      *
  877      * @param string $event_type
  878      * @param object $message
  879      * @return boolean
  880      */
  881     public static function logEvent( $event_type, $message = '') {
  882 
  883         owa_coreAPI::debug("Logging new event $event_type");
  884         
  885         // Check to see if named users should be logged
  886         if (owa_coreAPI::getSetting('base', 'log_named_users') != true) {
  887             $cu = owa_coreAPI::getCurrentUser();
  888             $cu_user_id = $cu->getUserData('user_id');
  889 
  890             if( ! empty( $cu_user_id ) ) {
  891                 
  892                 return false;
  893             }
  894         }
  895 
  896         // backwads compatability with old style messages
  897         // @todo is this needed anymore?
  898         $class= 'owa_event';
  899         
  900         if ( ! ( $message instanceof $class ) ) {
  901             
  902             $event = owa_coreAPI::supportClassFactory( 'base', 'event' );
  903             $event->setProperties( $message );
  904             $event->setEventType( $event_type );
  905             
  906         } else {
  907             
  908             $event = $message;
  909         }
  910         
  911         $service = owa_coreAPI::serviceSingleton();
  912         
  913         // Tracking Event processing STAGE 1
  914         // sets any necessary environmental properties from SERVER global
  915         $teh = owa_coreAPI::getInstance( 'owa_trackingEventHelpers', OWA_BASE_CLASS_DIR.'trackingEventHelpers.php');
  916         $environmentals = $service->getMap( 'tracking_properties_environmental' );
  917         $teh->setTrackerProperties( $event, $environmentals );
  918         
  919         // do not log if the do not log property is set on the event.
  920         if ($event->get('do_not_log')) {
  921             return false;
  922         }
  923         
  924         // do not log if the request is robotic
  925         owa_coreAPI::debug("Testing to see if event was generated by a robot");
  926         owa_coreAPI::debug("User Agent: ". $message->get('HTTP_USER_AGENT') );
  927         
  928         $bcap = $service->getBrowscap( $message->get('HTTP_USER_AGENT') );
  929        
  930         if ( ! owa_coreAPI::getSetting('base', 'log_robots') ) {
  931 
  932             if ( $bcap->robotCheck() ) {
  933                 
  934                 owa_coreAPI::debug("ABORTING: request appears to be from a robot");
  935                 owa_coreAPI::setRequestParam('is_robot', true);
  936                 
  937                 return;
  938             }
  939         }
  940 
  941         // check to see if IP should be excluded
  942         if ( owa_coreAPI::isIpAddressExcluded( $event->get('ip_address') ) ) {
  943             
  944             owa_coreAPI::debug("Not logging event. IP address found in exclusion list.");
  945             
  946             return false;
  947         }
  948 
  949         // queue for later or process event straight away
  950         if ( owa_coreAPI::getSetting( 'base', 'queue_events' ) ||
  951              owa_coreAPI::getSetting( 'base', 'queue_incoming_tracking_events' ) ) {
  952 
  953             $q = owa_coreAPI::getEventQueue( 'incoming_tracking_events' );
  954             owa_coreAPI::debug('Queuing '.$event->getEventType().' event with properties: '.print_r($event->getProperties(), true ) );
  955             $q->sendMessage( $event );
  956 
  957         } else {
  958 
  959             // lookup which event processor to use to process this event type
  960             $processor_action = owa_coreAPI::getEventProcessor( $event->getEventType() );
  961            
  962             owa_coreAPI::debug('About to perform action: '.$processor_action);
  963             owa_coreAPI::debug($event);
  964             
  965             return owa_coreAPI::performAction( $processor_action, array( 'event' => $event ) );
  966         }
  967     }
  968 
  969     public static function getInstance( $class, $path ) {
  970 
  971         if ( ! class_exists( $class ) ) {
  972 
  973             require_once( $path );
  974         }
  975 
  976         return $class::getInstance();
  977     }
  978 
  979     public static function displayImage($data) {
  980 
  981         header('Content-type: image/gif');
  982         header('P3P: CP="'.owa_coreAPI::getSetting('base', 'p3p_policy').'"');
  983         header('Expires: Sat, 22 Apr 1978 02:19:00 GMT');
  984         header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  985         header('Cache-Control: no-store, no-cache, must-revalidate');
  986         header('Pragma: no-cache');
  987 
  988         echo owa_coreAPI::displayView($data);
  989     }
  990 
  991 
  992     /**
  993      * Displays a View without user authentication. Takes array of data as input
  994      *
  995      * @param array $data
  996      * @param string $viewfile a specific view file to use
  997      * @return string
  998      *
  999      */
 1000     public static function displayView($data, $viewfile = '') {
 1001 
 1002         if (empty($viewfile)):
 1003             $viewfile = $data['view'];
 1004         endif;
 1005 
 1006         $view = owa_coreAPI::moduleFactory($viewfile, 'View');
 1007       
 1008         $view->setData($data);
 1009         return $view->assembleView($data);
 1010 
 1011     }
 1012 
 1013     public static function displaySubView($data, $viewfile = '') {
 1014 
 1015         if (empty($viewfile)):
 1016             $viewfile = $data['view'];
 1017         endif;
 1018 
 1019         $view =  owa_coreAPI::subViewFactory($viewfile);
 1020 
 1021         return $view->assembleView($data);
 1022 
 1023     }
 1024 
 1025     /**
 1026      * Strip a URL of certain GET params
 1027      * @depricated
 1028      * @return string
 1029      * @todo REMOVE
 1030      */
 1031     function stripDocumentUrl($url) {
 1032 
 1033         if (owa_coreAPI::getSetting('base', 'clean_query_string')):
 1034 
 1035             if (owa_coreAPI::getSetting('base', 'query_string_filters')):
 1036                 $filters = str_replace(' ', '', owa_coreAPI::getSetting('base', 'query_string_filters'));
 1037                 $filters = explode(',', $filters);
 1038             else:
 1039                 $filters = array();
 1040             endif;
 1041 
 1042             // OWA specific params to filter
 1043             array_push($filters, owa_coreAPI::getSetting('base', 'source_param'));
 1044             array_push($filters, owa_coreAPI::getSetting('base', 'ns').owa_coreAPI::getSetting('base', 'feed_subscription_param'));
 1045 
 1046             //print_r($filters);
 1047 
 1048             foreach ($filters as $filter => $value) {
 1049 
 1050               $url = preg_replace(
 1051                 '#\?' .
 1052                 $value .
 1053                 '=.*$|&' .
 1054                 $value .
 1055                 '=.*$|' .
 1056                 $value .
 1057                 '=.*&#msiU',
 1058                 '',
 1059                 $url
 1060               );
 1061 
 1062             }
 1063 
 1064         endif;
 1065          //print $url;
 1066 
 1067          return $url;
 1068 
 1069     }
 1070 
 1071     public static function getRequestParam($name) {
 1072 
 1073         $service = owa_coreAPI::serviceSingleton();
 1074 
 1075         return $service->request->getParam($name);
 1076 
 1077     }
 1078 
 1079     public static function getRequest() {
 1080         $service = owa_coreAPI::serviceSingleton();
 1081         return $service->request;
 1082     }
 1083 
 1084     public static function setRequestParam($name, $value) {
 1085 
 1086         $service = owa_coreAPI::serviceSingleton();
 1087         return $service->request->setParam($name, $value);
 1088 
 1089     }
 1090 
 1091     public static function makeTimePeriod($time_period, $params = array()) {
 1092 
 1093         $period = owa_coreAPI::supportClassFactory('base', 'timePeriod');
 1094 
 1095         if ( ! array_key_exists('period', $params)) {
 1096             $params['period'] = $time_period;
 1097         }
 1098         $period->setFromMap( $params );
 1099         return $period;
 1100     }
 1101 
 1102     /**
 1103      * Factory method for producing validation objects
 1104      *
 1105      * @return Object
 1106      */
 1107     public static function validationFactory($class_file, $conf = array()) {
 1108 
 1109         if (!class_exists('owa_validation')):
 1110             require_once(OWA_BASE_CLASS_DIR.'validation.php');
 1111         endif;
 1112 
 1113         return owa_lib::factory(OWA_PLUGIN_DIR.'validations', 'owa_', $class_file, $conf, 'Validation');
 1114 
 1115     }
 1116 
 1117     public static function debug($msg) {
 1118 
 1119         $e = owa_coreAPI::errorSingleton();
 1120         $e->debug($msg);
 1121         return;
 1122     }
 1123 
 1124     public static function error($msg) {
 1125 
 1126         $e = owa_coreAPI::errorSingleton();
 1127         $e->err($msg);
 1128         return;
 1129     }
 1130 
 1131     public static function notice($msg) {
 1132 
 1133         $e = owa_coreAPI::errorSingleton();
 1134         $e->notice($msg);
 1135         return;
 1136     }
 1137 
 1138     public static function createCookie($cookie_name, $cookie_value, $expires = 0, $path = '/; samesite=Lax', $domain = '') {
 1139 
 1140         if ( $domain ) {
 1141             // sanitizes the domain
 1142             $domain = owa_lib::sanitizeCookieDomain( $domain );
 1143         } else {
 1144             $domain = owa_coreAPI::getSetting('base', 'cookie_domain');
 1145         }
 1146         if (is_array($cookie_value)) {
 1147 
 1148             $cookie_value = owa_lib::implode_assoc('=>', '|||', $cookie_value);
 1149         }
 1150 
 1151         // add namespace
 1152         $cookie_name = sprintf('%s%s', owa_coreAPI::getSetting('base', 'ns'), $cookie_name);
 1153 
 1154         // debug
 1155         owa_coreAPI::debug(sprintf('Setting cookie %s with values: %s under domain: %s', $cookie_name, $cookie_value, $domain));
 1156 
 1157         // makes cookie to session cookie only
 1158         if (!owa_coreAPI::getSetting('base', 'cookie_persistence')) {
 1159             $expires = 0;
 1160         }
 1161 
 1162         // set compact privacy header
 1163         header(sprintf('P3P: CP="%s"', owa_coreAPI::getSetting('base', 'p3p_policy')));
 1164         //owa_coreAPI::debug('time: '.$expires);
 1165         setcookie($cookie_name, $cookie_value, $expires, $path, $domain);
 1166         return;
 1167     }
 1168 
 1169     public static function deleteCookie($cookie_name, $path = '/', $domain = '') {
 1170 
 1171         return owa_coreAPI::createCookie($cookie_name, false, time()-3600*25, $path, $domain);
 1172     }
 1173 
 1174     public static function registerStateStore($name, $expiration, $length = '', $format = '', $type = 'cookie', $cdh_required = '') {
 1175 
 1176         $service = owa_coreAPI::serviceSingleton();
 1177         return $service->request->state->registerStore( $name, $expiration, $length, $format, $type, $cdh_required );
 1178     }
 1179 
 1180     public static function setState($store, $name = '', $value, $store_type = '', $is_perminent = '') {
 1181 
 1182         $service = owa_coreAPI::serviceSingleton();
 1183         return $service->request->state->set($store, $name, $value, $store_type, $is_perminent);
 1184     }
 1185 
 1186     public static function getState($store, $name = '') {
 1187 
 1188         $service = owa_coreAPI::serviceSingleton();
 1189         return $service->request->state->get($store, $name);
 1190     }
 1191 
 1192     // depricated
 1193     public static function getStateParam($store, $name = '') {
 1194 
 1195         return owa_coreAPI::getState($store, $name);
 1196     }
 1197 
 1198     public static function getServerParam($name = '') {
 1199 
 1200         $service = owa_coreAPI::serviceSingleton();
 1201         return $service->request->getServerParam($name);
 1202     }
 1203 
 1204     public static function clearState($store, $name = '') {
 1205 
 1206         $service = owa_coreAPI::serviceSingleton();
 1207         $service->request->state->clear($store, $name);
 1208 
 1209     }
 1210 
 1211     public static function getEventProcessor($event_type) {
 1212 
 1213         $service = owa_coreAPI::serviceSingleton();
 1214         $processor = $service->getMapValue('event_processors', $event_type);
 1215 
 1216         if (empty($processor)) {
 1217 
 1218             $processor = 'base.processEvent';
 1219         }
 1220 
 1221         return $processor;
 1222     }
 1223 
 1224     /**
 1225      * Retrieves any registered build packages
 1226      *
 1227      * @return array
 1228      */
 1229     public static function getBuildPackages() {
 1230 
 1231         $service = owa_coreAPI::serviceSingleton();
 1232         $map = $service->getMap('build_packages');
 1233 
 1234         if ( ! $map ) {
 1235             $map = array();
 1236         }
 1237 
 1238         return $map;
 1239     }
 1240 
 1241     /**
 1242      * Handles OWA internal page/action requests
 1243      *
 1244      * @return unknown
 1245      */
 1246     public static function handleRequest($caller_params = null, $action = '') {
 1247 
 1248         static $init;
 1249 
 1250         $service = owa_coreAPI::serviceSingleton();
 1251         // Override request parsms with those passed by caller
 1252         if (!empty($caller_params)) {
 1253             $service->request->mergeParams($caller_params);
 1254         };
 1255 
 1256         $params = $service->request->getAllOwaParams();
 1257 
 1258         if ($init != true) {
 1259             owa_coreAPI::debug('Handling request with params: '. print_r($params, true));
 1260         }
 1261 
 1262         // backwards compatability with old style view/controler scheme
 1263         // still needed??
 1264         if (array_key_exists('view', $params)) {
 1265             // its a view request so the only data is in whats in the params
 1266             $init = true;
 1267             return owa_coreAPI::displayView($params);
 1268         }
 1269 
 1270         if (empty($action)) {
 1271             $action = owa_coreAPI::getRequestParam('action');
 1272             if (empty($action)) {
 1273                 $action = owa_coreAPI::getRequestParam('do');
 1274 
 1275                 if (empty($action)) {
 1276                     $action = owa_coreAPI::getSetting('base', 'start_page');
 1277                     $params['do'] = $action;
 1278                 }
 1279             }
 1280         }
 1281         
 1282         
 1283         // REST API Requests
 1284         // Lookup controler for REST API route.
 1285         if ( owa_coreAPI::getSetting( 'base', 'request_mode' ) === 'rest_api' ) {
 1286             
 1287             // check for rewriten rest params and set module, version, and do params from that
 1288             $rest_params = self::getRequestParam('rest_params');
 1289             
 1290             if ( $rest_params ) {
 1291             
 1292                 $rest_params = explode('/', $rest_params); 
 1293                 self::debug( 'exploding raw REST params:');
 1294                 self::debug( $rest_params );
 1295             
 1296                 if ( count( $rest_params ) >= 3 ) {
 1297                     
 1298                     $params['module'] = $rest_params[0];
 1299                     $params['version'] = $rest_params[1];
 1300                     $params['do'] = $rest_params[2];
 1301                     $action = $params['do'];
 1302                 }               
 1303             }
 1304             
 1305             
 1306             owa_coreAPI::debug('Generating REST API route controller...');
 1307             
 1308             if ( owa_lib::keyExistsNotEmpty( 'module', $params ) && owa_lib::keyExistsNotEmpty( 'version', $params ) ) {
 1309             
 1310                 $request_method = $service->request->getRequestType();
 1311                 $route = self::lookupRestRoute( $request_method, $params['module'], $params['version'], $action );
 1312                 
 1313                 if ( $route ) {
 1314                     
 1315                     // set the remainer of the rewritten rest params
 1316                     
 1317                     if ( $rest_params ) {
 1318                         
 1319                         // slice off the first three params which have already been set
 1320                         $rest_params = array_slice($rest_params, 3); 
 1321                         
 1322                         foreach ( $rest_params as $k => $v) {
 1323                             
 1324                             $params[ $route['conf'][ 'params_order' ][$k] ] = $rest_params[ $k ];
 1325                         }
 1326                     }
 1327                     
 1328                     $params['rest_route'] = $route;
 1329                     $controller = owa_lib::simpleFactory( $route['class_name'], $route['file'], $params );                  
 1330                     return owa_coreAPI::runController( $controller );
 1331                 
 1332                 } else {
 1333                     
 1334                     owa_coreAPI::debug('No REST API route found');
 1335                     return; 
 1336                 }
 1337 
 1338             } else {
 1339                 
 1340                 owa_coreAPI::debug('Could not generate controller because no version param was on request.');
 1341                 return;
 1342             }
 1343             
 1344         } 
 1345         
 1346         
 1347         
 1348         $init = true;
 1349         owa_coreAPI::debug('About to perform action: '.$action);
 1350         return owa_coreAPI::performAction($action, $params);
 1351 
 1352     }
 1353     
 1354     public static function lookupRestRoute( $request_method, $module, $version, $do ) {
 1355         
 1356         if ( ! empty( $request_method ) 
 1357             && ! empty( $version )
 1358             && ! empty( $do )
 1359             && ! empty( $module ) 
 1360         ){
 1361             
 1362             $service = owa_coreAPI::serviceSingleton();
 1363             $route = $service->getRestApiRoute($module, $version, $do, $request_method );
 1364             owa_coreAPI::debug($route);
 1365             return $route;
 1366         }
 1367     }
 1368 
 1369     public static function isUpdateRequired() {
 1370 
 1371         $service = owa_coreAPI::serviceSingleton();
 1372         return $service->isUpdateRequired();
 1373     }
 1374 
 1375     /**
 1376      * @return array
 1377      */
 1378     public static function getSitesList() {
 1379         $db = owa_coreAPI::dbSingleton();
 1380         $db->selectFrom('owa_site');
 1381         $db->selectColumn('*');
 1382         $sites = $db->getAllRows();
 1383 
 1384         if ( ! $sites ) {
 1385             $sites = array();
 1386         }
 1387         return $sites;
 1388     }
 1389 
 1390     public static function profile($that = '', $function = '', $line = '', $msg = '') {
 1391 
 1392         if (defined('OWA_PROFILER')) {
 1393             if (OWA_PROFILER === true) {
 1394 
 1395                 static $profiler;
 1396 
 1397                 if (!class_exists('PhpQuickProfiler')) {
 1398                     require_once(OWA_INCLUDE_DIR.'pqp/classes/PhpQuickProfiler.php');
 1399                 }
 1400 
 1401                 if (empty($profiler)) {
 1402                     $profiler = new PhpQuickProfiler(PhpQuickProfiler::getMicroTime(), OWA_INCLUDE_DIR.'pqp/');
 1403                 }
 1404 
 1405                 $class = get_class($that);
 1406                 Console::logSpeed($class."::$function - Line: $line - Msg: $msg");
 1407                 Console::logMemory($that, $class. "::$function - Line: $line");
 1408 
 1409                 return $profiler;
 1410             }
 1411         }
 1412     }
 1413 
 1414     public static function profileDisplay() {
 1415         $p = owa_coreAPI::profile();
 1416         if ($p) {
 1417             $p->display();
 1418         }
 1419 
 1420     }
 1421 
 1422     public static function getEventDispatch() {
 1423 
 1424         if (! class_exists( 'owa_eventDispatch' ) ) {
 1425             require_once(OWA_BASE_CLASS_DIR.'eventDispatch.php');
 1426         }
 1427 
 1428         return owa_eventDispatch::get_instance();
 1429 
 1430     }
 1431 
 1432     public static function getEventQueue( $name ) {
 1433 
 1434         static $queues;
 1435 
 1436         // make queue if needed
 1437         if ( ! isset( $queues[ $name ] ) ) {
 1438 
 1439             // get queue config
 1440             $s = owa_coreAPI::serviceSingleton();
 1441             $map = $s->getMapValue('event_queues', $name);
 1442 
 1443             if ( $map ) {
 1444 
 1445                 $implementation = $s->getMapValue( 'event_queue_types', $map['queue_type'] );
 1446 
 1447                 if ( $implementation
 1448                      && isset( $implementation[0] )
 1449                      && isset( $implementation[1] )
 1450                 ) {
 1451                     owa_coreAPI::debug(print_r($implementation, true));
 1452                     $queues[ $name ] = owa_lib::simpleFactory( $implementation[0], $implementation[1], $map );
 1453 
 1454                 } else {
 1455 
 1456                     throw new Exception("No event queue by that type found.");
 1457                 }
 1458 
 1459             } else {
 1460 
 1461                 throw new Exception("No configuration found for event queue $name.");
 1462             }
 1463         }
 1464             // return queue
 1465         return $queues[ $name ];
 1466     }
 1467 
 1468     public static function getCliCommandClass($command) {
 1469 
 1470         $s = owa_coreAPI::serviceSingleton();
 1471         return $s->getCliCommandClass($command);
 1472     }
 1473 
 1474     public static function getGeolocationFromIpAddress($ip_address) {
 1475 
 1476         $s = owa_coreAPI::serviceSingleton();
 1477         $s->geolocation->getGeolocationFromIp($ip_address);
 1478         return $s->geolocation;
 1479     }
 1480 
 1481     public static function getNonceTimeInterval() {
 1482 
 1483         return  ceil( time() / owa_coreAPI::getSetting( 'base', 'nonce_expiration_period') );
 1484     }
 1485 
 1486     public static function createNonce($action) {
 1487 
 1488         $time = owa_coreAPI::getNonceTimeInterval();
 1489         $cu = owa_coreAPI::getCurrentUser();
 1490         $user_id = $cu->getUserData( 'user_id' );
 1491 
 1492         $full_nonce = $time . $action . $user_id . 'owa_nonce';
 1493 
 1494         $nonce = substr( owa_coreAPI::saltedHash($full_nonce, 'nonce'), -12, 10);
 1495 
 1496         return $nonce;
 1497     }
 1498 
 1499     public static function saltedHash( $data, $scheme, $hash_type = 'md5' ) {
 1500 
 1501         $salt = owa_coreAPI::getSalt( $scheme );
 1502         return owa_lib::hash( $hash_type, $data, $salt );
 1503     }
 1504 
 1505 
 1506 
 1507     public static function getSalt( $scheme ) {
 1508 
 1509         static $cached_salts;
 1510 
 1511         $scheme = strtoupper($scheme);
 1512 
 1513         if ( ! $cached_salts ) {
 1514 
 1515             $cached_salts = array();
 1516             $ns = strtoupper( owa_coreAPI::getSetting('base', 'ns') );
 1517 
 1518             foreach (array('NONCE', 'SECRET', 'AUTH') as $f ) {
 1519 
 1520                 foreach (array('KEY', 'SALT') as $s ) {
 1521 
 1522                     $const = sprintf("%s%s_%s", $ns, $f, $s);
 1523 
 1524                     if ( ! defined ( "$const" ) ) {
 1525                         continue;
 1526                     } else {
 1527 
 1528                         $cached_salts[ $f.'_'.$s ] = constant("$const");
 1529                     }
 1530                 }
 1531             }
 1532         }
 1533 
 1534 
 1535         $key = '';
 1536         $salt = '';
 1537 
 1538         if (array_key_exists( $scheme.'_KEY', $cached_salts ) ) {
 1539 
 1540             $key = $cached_salts[ $scheme.'_KEY' ];
 1541         }
 1542 
 1543         if (array_key_exists( $scheme.'_SALT', $cached_salts ) ) {
 1544 
 1545             $salt = $cached_salts[ $scheme.'_SALT' ];
 1546         }
 1547 
 1548         return $key . $salt;
 1549     }
 1550 
 1551     public static function secureRandomString( $length, $special_chars = true, $more_special_chars = true ) {
 1552 
 1553         $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
 1554         if ( $special_chars )
 1555             $chars .= '!@#$%^&*()';
 1556         if ( $more_special_chars )
 1557             $chars .= '-_ []{}<>~`+=,.;:/?|';
 1558 
 1559         $password = '';
 1560         for ( $i = 0; $i < $length; $i++ ) {
 1561             $password .= substr($chars, owa_coreAPI::random(0, strlen($chars) - 1), 1);
 1562         }
 1563 
 1564         return $password;
 1565     }
 1566 
 1567     public static function random($min, $max) {
 1568 
 1569         static $rnd_value;
 1570 
 1571         if ( strlen($rnd_value) < 8 ) {
 1572 
 1573             $notrandom = false;
 1574 
 1575             if ( function_exists( 'openssl_random_pseudo_bytes' ) ) {
 1576 
 1577                 $rnd_value = bin2hex(openssl_random_pseudo_bytes(32, $cstrong));
 1578 
 1579                 if ( ! $cstrong ) {
 1580 
 1581                     $notrandom = true;
 1582                 }
 1583 
 1584             } else {
 1585 
 1586                 $notrandom = true;
 1587             }
 1588 
 1589             if ( $notrandom ) {
 1590 
 1591                 $seed = microtime();
 1592                 $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
 1593                 $rnd_value .= sha1($rnd_value);
 1594                 $rnd_value .= sha1($rnd_value . $seed);
 1595 
 1596             }
 1597 
 1598             //$seed = md5($seed . $rnd_value);
 1599         }
 1600         // Take the first 8 digits for our value
 1601         $value = substr($rnd_value, 0, 8);
 1602 
 1603         // Strip the first eight, leaving the remainder for the next call to random.
 1604         $rnd_value = substr($rnd_value, 8);
 1605 
 1606         $value = abs(hexdec($value));
 1607 
 1608         // Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
 1609         $max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff
 1610 
 1611         // Reduce the value to be within the min - max range
 1612         if ( $max != 0 )
 1613             $value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 );
 1614 
 1615         return abs(intval($value));
 1616     }
 1617 
 1618     public static function summarize($map) {
 1619 
 1620         $entity = owa_coreAPI::entityFactory($map['entity']);
 1621         $db = owa_coreAPI::dbSingleton();
 1622         $db->selectFrom($entity->getTableName(), $entity->getTableAlias());
 1623 
 1624         foreach ($map['columns'] as $col => $action) {
 1625 
 1626             switch ($action) {
 1627 
 1628                 case 'sum':
 1629                     $col_def = sprintf("SUM(%s)", $col);
 1630                     $name = $col.'_sum';
 1631                     break;
 1632                 case 'count':
 1633                     $col_def = sprintf("COUNT(%s)", $col);
 1634                     $name = $col.'_count';
 1635                     break;
 1636                 case 'count_distinct':
 1637                     $col_def = sprintf("COUNT(distinct %s)", $col);
 1638                     $name = $col.'_dcount';
 1639                     break;
 1640                 case 'max':
 1641                     $col_def = sprintf("MAX(%s)", $col);
 1642                     $name = $col.'_max';
 1643                     break;
 1644             }
 1645 
 1646             $db->selectColumn($col_def, $name);
 1647         }
 1648 
 1649         foreach ($map['constraints'] as $con_col => $con_value) {
 1650 
 1651             if ( is_array( $con_value ) ) {
 1652                 $db->where($con_col, $con_value['value'], $con_value['operator']);
 1653             } else {
 1654                 $db->where($con_col, $con_value);
 1655             }
 1656         }
 1657 
 1658         $ret = $db->getOneRow();
 1659         return $ret;
 1660     }
 1661 
 1662     public static function getJsTrackerTag( $site_id, $options = array() ) {
 1663 
 1664         if ( ! class_exists( 'owa_template' ) ) {
 1665             require_once(OWA_BASE_CLASSES_DIR.'owa_template.php');
 1666         }
 1667 
 1668         $t = new owa_template();
 1669 
 1670         $t->set( 'site_id', $site_id );
 1671         $cmds = owa_coreAPI::filter( 'tracker_tag_cmds', array() );
 1672         $t->set( 'cmds', $cmds );
 1673         $t->set('options', $options);
 1674         $t->set_template('js_log_tag.tpl');
 1675         return $t->fetch();
 1676     }
 1677 
 1678     public static function activateModule( $module_name ) {
 1679 
 1680         if ( $module_name ) {
 1681 
 1682             $m = owa_coreAPI::moduleClassFactory($module_name);
 1683             return $m->activate();
 1684         }
 1685     }
 1686 
 1687     public static function deactivateModule( $module_name ) {
 1688 
 1689         if ( $module_name ) {
 1690 
 1691             $s = owa_coreAPI::serviceSingleton();
 1692             $m = $s->getModule($module_name);
 1693             return $m->deactivate();
 1694         }
 1695     }
 1696 
 1697     public static function installModule( $module_name ) {
 1698 
 1699         if ($module_name) {
 1700 
 1701             $m = owa_coreAPI::moduleClassFactory($module_name);
 1702             $status = $m->install();
 1703             return $status;
 1704         }
 1705     }
 1706 
 1707     public static function generateInstanceSpecificHash() {
 1708 
 1709         if ( defined( 'OWA_SECRET' ) ) {
 1710             $salt = OWA_SECRET;
 1711         } else {
 1712             $salt = '';
 1713         }
 1714 
 1715         if ( defined( 'OWA_DB_USER' ) ) {
 1716             $salt .= OWA_DB_USER;
 1717         }
 1718 
 1719         if ( defined( 'OWA_DB_PASSWORD' ) ) {
 1720             $salt .= OWA_DB_PASSWORD;
 1721         }
 1722 
 1723         return md5( $salt );
 1724     }
 1725 
 1726     public static function getAllDimensions() {
 1727 
 1728         $s = owa_coreAPI::serviceSingleton();
 1729 
 1730         $dims = $s->dimensions;
 1731 
 1732         foreach ( $s->denormalizedDimensions as $k => $entity_dims ) {
 1733             foreach ($entity_dims as $entity => $dedim) {
 1734                 $dims[$k] = $dedim;
 1735             }
 1736         }
 1737 
 1738         return $dims;
 1739     }
 1740 
 1741     public static function getAllMetrics() {
 1742 
 1743         $s = owa_coreAPI::serviceSingleton();
 1744         return $s->metrics;
 1745     }
 1746 
 1747     public static function getGoalManager( $siteId ) {
 1748 
 1749         static $gm;
 1750 
 1751         if ( ! $gm ) {
 1752 
 1753             $gm = array();
 1754         }
 1755 
 1756         if ( ! isset( $gm[$siteId] ) )  {
 1757             $gm[ $siteId ] = owa_coreAPI::supportClassFactory('base', 'goalManager', $siteId);
 1758         }
 1759 
 1760         return $gm[$siteId];
 1761     }
 1762 
 1763     public static function getRequestTimestamp() {
 1764 
 1765         $r = owa_coreAPI::requestContainerSingleton();
 1766         return $r->getTimestamp();
 1767     }
 1768 
 1769     public static function isEveryoneCapable( $capability ) {
 1770 
 1771         $caps = owa_coreAPI::getCapabilities('everyone');
 1772 
 1773         if ( in_array( $capability, $caps ) ) {
 1774             return true;
 1775         } else {
 1776             return false;
 1777         }
 1778     }
 1779 
 1780     public static function getCurrentUrl() {
 1781         $r = owa_coreAPI::requestContainerSingleton();
 1782         return $r->getCurrentUrl();
 1783     }
 1784 
 1785     public static function isIpAddressExcluded( $ip_address ) {
 1786 
 1787         // do not log if ip address is on the do not log list
 1788         $ips = owa_coreAPI::getSetting( 'base', 'excluded_ips' );
 1789         
 1790         if ( $ips ) {
 1791             
 1792             owa_coreAPI::debug('Excluded ip address list: '.$ips);
 1793 
 1794             $ips = trim( $ips );
 1795 
 1796             if ( strpos( $ips, ',' ) ) {
 1797                 $ips = explode( ',', $ips );
 1798             } else {
 1799                 $ips = array( $ips );
 1800             }
 1801 
 1802             foreach( $ips as $ip ) {
 1803                 $ip = trim( $ip );
 1804                 if ( $ip_address === $ip ) {
 1805                     owa_coreAPI::debug("Request is from excluded ip address: $ip.");
 1806                     return true;
 1807                 }
 1808             }
 1809         }
 1810     }
 1811 
 1812     /**
 1813      * Attaches an event handler to the event queue
 1814      *
 1815      * @param array $event_name
 1816      * @param string $handler_name
 1817      * @return boolean
 1818      */
 1819     public static function registerFilter( $filter_name, $callback, $priority = 10 ) {
 1820 
 1821         $ed = owa_coreAPI::getEventDispatch();
 1822         $ed->attachFilter($filter_name, $callback, $priority);
 1823     }
 1824 
 1825     public static function filter( $filter_name, $value ) {
 1826 
 1827         $ed = owa_coreAPI::getEventDispatch();
 1828         return $ed->filter( $filter_name, $value );
 1829     }
 1830     
 1831     public static function loadEntitiesFromArray( $items, $entity_name ) {
 1832         
 1833         $set = [];
 1834         
 1835         if ( $items ) {
 1836             
 1837             foreach ($items as $item ) {
 1838                 
 1839                 $entity = owa_coreAPI::entityFactory( $entity_name );
 1840                 $entity->setProperties( $item );
 1841                 $set[] = $entity;
 1842                 
 1843             }
 1844         }
 1845         
 1846         return $set;
 1847     }
 1848 
 1849 }
 1850 
 1851 ?>