"Fossies" - the Fresh Open Source Software Archive

Member "Open-Web-Analytics-1.7.0/modules/base/classes/settings.php" (16 Sep 2020, 38260 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 "settings.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 /**
   20  * Settings Class
   21  * 
   22  * @author      Peter Adams <peter@openwebanalytics.com>
   23  * @copyright   Copyright &copy; 2006 Peter Adams <peter@openwebanalytics.com>
   24  * @license     http://www.gnu.org/copyleft/gpl.html GPL v2.0
   25  * @category    owa
   26  * @package     owa
   27  * @version        $Revision$
   28  * @since        owa 1.0.0
   29  */
   30  
   31  class owa_settings {
   32 
   33      /**
   34       * Configuration Entity
   35       *
   36       * @var owa_configuration
   37       */
   38      var $config;
   39 
   40      var $default_config;
   41 
   42      var $db_settings = array();
   43 
   44      var $fetched_from_db;
   45 
   46      var $is_dirty;
   47 
   48      var $config_id;
   49 
   50      var $config_from_db;
   51 
   52      /**
   53       * Constructor
   54       *
   55       * @param string id the id of the configuration array to load
   56       */
   57      function __construct() {
   58 
   59          // create configuration object
   60          $this->config = owa_coreAPI::entityFactory('base.configuration');
   61          // load the default settings
   62          $this->config->set('settings', $this->getDefaultSettingsArray());
   63 
   64          // include/load config file
   65          $this->loadConfigFile();
   66          // apply config constants
   67          $this->applyConfigConstants();
   68          // setup directory paths
   69          $this->setupPaths();
   70 
   71          // Todo: must remove config object dependancy from all classes generated by $this->load
   72          // before we can uncomment this and remove it from owa_caller constructor or else there
   73          // is a race condition.
   74 
   75          //if ($this->isConfigFilePresent()) {
   76          //    $this->load($this->get('base', 'configuration_id'));
   77          //}
   78 
   79          // include storage engine class so that DTD constants get loaded
   80          owa_coreAPI::setupStorageEngine($this->get('base','db_type'));
   81 
   82      }
   83 
   84      public function setTimezone() {
   85 
   86          // set default timezone while surpressing any warning
   87         if ( function_exists( 'date_default_timezone_set' ) ) {
   88             $level = error_reporting( 0 );
   89             date_default_timezone_set( $this->get( 'base', 'timezone' ) );
   90             error_reporting( $level );
   91         }
   92      }
   93 
   94      /**
   95       * @return boolean
   96       */
   97      public function isConfigFilePresent() {
   98 
   99         $file = OWA_DIR.'owa-config.php';
  100         $oldfile = OWA_BASE_DIR.'/conf/owa-config.php';
  101 
  102         if (file_exists($file)) {
  103             return true;
  104         } elseif (file_exists($oldfile)) {
  105             return true;
  106         } else {
  107             return false;
  108         }
  109      }
  110 
  111      private function loadConfigFile() {
  112 
  113          /* LOAD CONFIG FILE */
  114         $file = OWA_DIR.'owa-config.php';
  115         $oldfile = OWA_BASE_DIR.'/conf/owa-config.php';
  116 
  117         if (file_exists($file)) {
  118             include_once($file);
  119             $config_file_exists = true;
  120         } elseif (file_exists($oldfile)) {
  121             include_once($oldfile);
  122             $config_file_exists = true;
  123         } else {
  124             $config_file_exists = false;
  125         }
  126      }
  127 
  128      function applyConfigConstants() {
  129 
  130          if(!defined('OWA_DATA_DIR')){
  131             define('OWA_DATA_DIR', OWA_DIR.'owa-data/');
  132 
  133         }
  134 
  135         if (defined('OWA_DATA_DIR')) {
  136             $this->set('base', 'data_dir', OWA_DATA_DIR);
  137         }
  138 
  139         if(!defined('OWA_CACHE_DIR')){
  140             define('OWA_CACHE_DIR', OWA_DATA_DIR.'caches/');
  141          }
  142 
  143          if (defined('OWA_CACHE_DIR')) {
  144             $this->set('base', 'cache_dir', OWA_CACHE_DIR);
  145         }
  146 
  147          // Looks for log level constant
  148         if (defined('OWA_ERROR_LOG_LEVEL')) {
  149             $this->set('base', 'error_log_level', OWA_ERROR_LOG_LEVEL);
  150         }
  151 
  152         /* CONFIGURATION ID */
  153 
  154         if (defined('OWA_CONFIGURATION_ID')) {
  155             $this->set('base', 'configuration_id', OWA_CONFIGURATION_ID);
  156         }
  157 
  158         /* OBJECT CACHING */
  159 
  160         // Looks for object cache config constant
  161         // must comebefore user db values are fetched from db
  162         if (defined('OWA_CACHE_OBJECTS')) {
  163             $this->set('base', 'cache_objects', OWA_CACHE_OBJECTS);
  164         }
  165 
  166         /* DATABASE CONFIGURATION */
  167 
  168         // This needs to come before the fetch of user overrides from the DB
  169         // Constants defined in the config file have the final word
  170         // values passed from calling application must be applied prior
  171         // to the rest of the caller's overrides
  172 
  173         if (defined('OWA_DB_TYPE')) {
  174             $this->set('base', 'db_type', OWA_DB_TYPE);
  175         }
  176 
  177         if (defined('OWA_DB_NAME')) {
  178             $this->set('base', 'db_name', OWA_DB_NAME);
  179         }
  180 
  181         if (defined('OWA_DB_HOST')) {
  182             $this->set('base', 'db_host', OWA_DB_HOST);
  183         }
  184 
  185         if (defined('OWA_DB_PORT')) {
  186             $this->set('base', 'db_port', OWA_DB_PORT);
  187         }
  188 
  189         if (defined('OWA_DB_USER')) {
  190             $this->set('base', 'db_user', OWA_DB_USER);
  191         }
  192 
  193         if (defined('OWA_DB_PASSWORD')) {
  194             $this->set('base', 'db_password', OWA_DB_PASSWORD);
  195         }
  196 
  197         /* SET ERROR HANDLER */
  198         if (defined('OWA_ERROR_HANDLER')) {
  199             $this->set('base', 'error_handler', OWA_ERROR_HANDLER);
  200         }
  201 
  202         if (defined('OWA_CONFIG_DO_NOT_FETCH_FROM_DB')) {
  203             $this->set('base', 'do_not_fetch_config_from_db', OWA_CONFIG_DO_NOT_FETCH_FROM_DB);
  204         }
  205 
  206         if (defined('OWA_PUBLIC_URL')) {
  207             $this->set('base', 'public_url', OWA_PUBLIC_URL);
  208         }
  209 
  210         if (defined('OWA_PUBLIC_PATH')) {
  211             $this->set('base', 'public_path', OWA_PUBLIC_PATH);
  212         }
  213 
  214         if (defined('OWA_QUEUE_EVENTS')) {
  215             $this->set('base', 'queue_events', OWA_QUEUE_EVENTS);
  216         }
  217 
  218         if (defined('OWA_EVENT_QUEUE_TYPE')) {
  219             $this->set('base', 'event_queue_type', OWA_EVENT_QUEUE_TYPE);
  220         }
  221 
  222         if (defined('OWA_EVENT_SECONDARY_QUEUE_TYPE')) {
  223             $this->set('base', 'event_secondary_queue_type', OWA_EVENT_SECONDARY_QUEUE_TYPE);
  224         }
  225 
  226         if (defined('OWA_USE_REMOTE_EVENT_QUEUE')) {
  227             $this->set('base', 'use_remote_event_queue', OWA_USE_REMOTE_EVENT_QUEUE);
  228         }
  229 
  230         if (defined('OWA_REMOTE_EVENT_QUEUE_TYPE')) {
  231             $this->set('base', 'remote_event_queue_type', OWA_REMOTE_EVENT_QUEUE_TYPE);
  232         }
  233 
  234         if (defined('OWA_REMOTE_EVENT_QUEUE_ENDPOINT')) {
  235             $this->set('base', 'remote_event_queue_endpoint', OWA_REMOTE_EVENT_QUEUE_ENDPOINT);
  236         }
  237 
  238      }
  239      /**
  240       * Ovverrides settings - used in some controllers (@see owa_caller )
  241       * @param string $module
  242       * @param array $config
  243       */
  244      public function applyModuleOverrides($module, $config) {
  245 
  246          // merge default config with overrides
  247 
  248          if (!empty($config)) {
  249 
  250              $in_place_config = $this->config->get('settings');
  251 
  252              $old_array = $in_place_config[$module];
  253 
  254              $new_array = array_merge($old_array, $config);
  255 
  256             $in_place_config[$module] = $new_array;
  257 
  258              $this->config->set('settings', $in_place_config);
  259 
  260              //print_r($this->config->get('settings'));
  261 
  262          }
  263      }
  264 
  265      /**
  266       * Loads configuration from data store
  267       *
  268       * @param string id  the id of the configuration array to load
  269       */
  270      function load($id = 1) {
  271 
  272             $this->config_id = $id;
  273  
  274             $db_config = owa_coreAPI::entityFactory('base.configuration');
  275             $db_config->getByPk('id', $id);
  276             $db_settings = unserialize($db_config->get('settings'));
  277 
  278             //print $db_settings;
  279             // store copy of config for use with updates and set a flag
  280             if (!empty($db_settings)):
  281 
  282                 // needed to get rid of legacy setting that used to be stored in the DB.
  283                 if (array_key_exists('error_handler', $db_settings['base'])) {
  284                     unset($db_settings['base']['error_handler']);
  285                 }
  286 
  287                 $this->db_settings = $db_settings;
  288                 $this->config_from_db = true;
  289             endif;
  290 
  291             if (!empty($db_settings)):
  292                 //print_r($db_settings);
  293                 //$db_settings = unserialize($db_settings);
  294 
  295                 $default = $this->config->get('settings');
  296 
  297                 // merge default config with overrides fetched from data store
  298 
  299                 $new_config = array();
  300 
  301                 foreach ($db_settings as $k => $v) {
  302 
  303                     if (isset($default[$k]) && is_array($default[$k])):
  304                         $new_config[$k] = array_merge($default[$k], $db_settings[$k]);
  305                     else:
  306                         $new_config[$k] = $db_settings[$k];
  307                     endif;
  308                 }
  309 
  310                 $this->config->set('settings', $new_config);
  311 
  312 
  313             endif;
  314 
  315             $db_id = $db_config->get('id');
  316             $this->config->set('id', $db_id);
  317 
  318          return;
  319 
  320      }
  321 
  322      /**
  323       * Fetches a modules entire configuration array
  324       *
  325       * @param string $module The name of module whose configuration values you want to fetch
  326       * @return array Config values
  327       */
  328      function fetch($module = '') {
  329          $v = $this->config->get('settings');
  330 
  331          if (!empty($module)):
  332 
  333              return $v[$module];
  334         else:
  335             return $v['base'];
  336         endif;
  337      }
  338 
  339      /**
  340       * updates or creates configuration values
  341       *
  342       * @return boolean
  343       */
  344      function save() {
  345 
  346          // serialize array of values prior to update
  347 
  348         $config = owa_coreAPI::entityFactory('base.configuration');
  349 
  350         // if fetch from db flag is not true, try to fetch the config just in
  351         // case if was cached or something wen wrong.
  352         // Then merge the new values into it.
  353         if ($this->config_from_db != true):
  354 
  355             $config->getByPk('id', $this->get('base', 'configuration_id'));
  356 
  357             $settings = $config->get('settings');
  358 
  359             if (!empty($settings)):
  360 
  361                 $settings = unserialize($settings);
  362 
  363                 $new_config = array();
  364 
  365                 foreach ($this->db_settings as $k => $v) {
  366 
  367                     if (!is_array($settings[$k])):
  368                         $settings[$k] = array();
  369                     endif;
  370 
  371                     $new_config[$k] = array_merge($settings[$k], $this->db_settings[$k]);
  372 
  373                 }
  374 
  375                 $config->set('settings', serialize($new_config));
  376 
  377                 //$config->set('settings', serialize(array_merge($settings, $this->db_settings)));
  378             else:
  379                 $config->set('settings', serialize($this->db_settings));
  380             endif;
  381 
  382             // test to see if object exists
  383             $id = $config->get('id');
  384 
  385             // if it does just update
  386             if (!empty($id)):
  387                 $status = $config->update();
  388 
  389             // else create the object
  390             else:
  391                 $config->set('id', $this->get('base', 'configuration_id'));
  392                 $status = $config->create();
  393             endif;
  394 
  395         // update the config
  396         else:
  397             $config->set('settings', serialize($this->db_settings));
  398             $config->set('id', $this->get('base', 'configuration_id'));
  399             $status = $config->update();
  400         endif;
  401 
  402         $this->is_dirty = false;
  403 
  404          return $status;
  405 
  406      }
  407 
  408      /**
  409       * Accessor Method
  410       *
  411       * @param string $module the name of the module
  412       * @param string $key the configuration key
  413       * @return unknown
  414       */
  415      function get($module, $key) {
  416 
  417          $values = $this->config->get('settings');
  418 
  419          if ( isset( $values[$module] ) && array_key_exists($key, $values[$module])) {
  420              return $values[$module][$key];
  421          } else {
  422              return false;
  423          }
  424 
  425      }
  426 
  427      /**
  428       * Sets configuration value. will not be persisted.
  429       *
  430       * @param string $module the name of the module
  431       * @param string $key the configuration key
  432       * @param string $value the configuration value
  433       * @return boolean
  434       */
  435      function set($module, $key, $value) {
  436 
  437          $values = $this->config->get('settings');
  438 
  439          $values[$module][$key] = $value;
  440 
  441          $this->config->set('settings', $values);
  442      }
  443 
  444 
  445      /**
  446       * Adds Setting value to be configuration and persistant data store
  447       * same as $this->set
  448       *
  449       * @param string $module the name of the module
  450       * @param string $key the configuration key
  451       * @param string $value the configuration value
  452       * @depricated
  453       */
  454      function setSetting($module, $key, $value) {
  455          return $this->set($module, $key, $value);
  456      }
  457 
  458      /**
  459       * Adds Setting value to be configuration and persistant data store
  460       *
  461       * @param string $module the name of the module
  462       * @param string $key the configuration key
  463       * @param string $value the configuration value
  464       * @return
  465       */
  466      public function persistSetting($module, $key, $value) {
  467 
  468          $this->set($module, $key, $value);
  469          $this->db_settings[$module][$key] = $value;
  470          $this->is_dirty = true;
  471      }
  472 
  473      /**
  474       * SEEMS unused - To be removed later
  475       *
  476       *
  477          function defaultSetting($module, $key) {
  478              $defaults = $this->getDefaultSettingsArray();
  479 
  480              if ( array_key_exists($module, $defaults) && array_key_exists($key, $defaults[$module]) ) {
  481                  $this->set($module, $key, $defaults[$module][$key]);
  482 
  483                  if ( array_key_exists($module, $this->db_settings) && array_key_exists($key, $this->db_settings[$module]) ) {
  484                      unset($this->db_settings[$module][$key]);
  485                      $this->is_dirty = true;
  486                  }
  487              }
  488          }
  489  
  490          //Adds Setting value to be configuration but DOES NOT add to persistant data store
  491          function setSettingTemporary($module, $key, $value) {
  492 
  493              $this->set($module, $key, $value);
  494 
  495              return;
  496 
  497          }
  498     */
  499 
  500      /**
  501       * Replaces all values of a particular module's configuration
  502       * @todo: search to see where else this is used. If unused then make it for use in persist only.
  503       */
  504      private function replace($module, $values, $persist = false) {
  505 
  506          if ($persist) {
  507              $this->db_settings[$module] = $values;
  508              return;
  509          }
  510 
  511          $settings = $this->config->get('settings');
  512 
  513          $settings[$module] = $values;
  514 
  515          $this->config->set('settings', $settings);
  516      }
  517 
  518      /**
  519       * Alternate Constructor for base module settings
  520       * Needed for backwards compatability with older classes
  521       *
  522       */
  523      function &get_settings($id = 1) {
  524 
  525          static $config2;
  526 
  527          if (!isset($config2)):
  528              //print 'hello from alt constructor';
  529              $config2 = owa_coreAPI::configSingleton();
  530          endif;
  531 
  532          return $config2->fetch('base');
  533 
  534      }
  535 
  536 
  537      /**
  538       * @return array
  539       */
  540      private function getDefaultSettingsArray() {
  541          
  542          if (isset($_SERVER['SERVER_NAME'])) {
  543              
  544              $mailer_domain = $_SERVER['SERVER_NAME'];
  545          } else {
  546              
  547              if ( defined( 'PUBLIC_URL' ) ) {
  548                  
  549                  $parts = parse_url( PUBLIC_URL );
  550                  $mailer_domain = $parts['host'];
  551              }
  552          }
  553          
  554          return array(
  555              'base' => array(
  556                 'ns'                                => 'owa_',
  557                 'visitor_param'                        => 'v',
  558                 'session_param'                        => 's',
  559                 'site_session_param'                => 'ss', //sdk
  560                 'last_request_param'                => 'last_req',
  561                 'feed_subscription_param'            => 'sid',
  562                 'source_param'                        => 'source',
  563                 'graph_param'                        => 'graph',
  564                 'period_param'                        => 'period',
  565                 'document_param'                    => 'document',
  566                 'referer_param'                        => 'referer',
  567                 'site_id'                            => '',
  568                 'configuration_id'                    => '1',
  569                 'session_length'                    => 1800, //sdk
  570                 'requests_table'                    => 'request',
  571                 'sessions_table'                    => 'session',
  572                 'referers_table'                    => 'referer',
  573                 'ua_table'                            => 'ua',
  574                 'os_table'                            => 'os',
  575                 'documents_table'                    => 'document',
  576                 'sites_table'                        => 'site',
  577                 'hosts_table'                        => 'host',
  578                 'config_table'                        => 'configuration',
  579                 'version_table'                        => 'version',
  580                 'feed_requests_table'                => 'feed_request',
  581                 'visitors_table'                    => 'visitor',
  582                 'impressions_table'                    => 'impression',
  583                 'clicks_table'                        => 'click',
  584                 'exits_table'                        => 'exit',
  585                 'users_table'                        => 'user',
  586                 'db_type'                            => '',
  587                 'db_name'                            => '',
  588                 'db_host'                            => '',
  589                 'db_port'                            => 3306,
  590                 'db_user'                            => '',
  591                 'db_password'                        => '',
  592                 'db_force_new_connections'            => true,
  593                 'db_make_persistant_connections'    => false,
  594                 'resolve_hosts'                        => true,
  595                 'log_feedreaders'                    => true,
  596                 'log_robots'                        => false,
  597                 'log_sessions'                        => true,
  598                 'log_dom_clicks'                    => true,
  599                 'async_db'                            => false,
  600                 'clean_query_string'                => true,
  601                 'fetch_refering_page_info'            => true,
  602                 'query_string_filters'                => '', // move to site settings
  603                 'async_log_dir'                        => '', //OWA_DATA_DIR . 'logs/',
  604                 'async_log_file'                    => 'events.txt',
  605                 'async_lock_file'                    => 'owa.lock',
  606                 'async_error_log_file'                => 'events_error.txt',
  607                 'notice_email'                        => '',
  608                 'log_php_errors'                    => false,
  609                 'error_handler'                        => 'production',
  610                 'error_log_level'                    => 0,
  611                 'error_log_file'                    => '', //OWA_DATA_DIR . 'logs/errors.txt',
  612                 'ua-regexes'                        => '',
  613                 'search_engines.ini'                => OWA_BASE_DIR . '/conf/search_engines.ini',
  614                 'query_strings.ini'                    => OWA_BASE_DIR . '/conf/query_strings.ini',
  615                 'db_class_dir'                        => OWA_BASE_DIR . '/plugins/db/',
  616                 'templates_dir'                        => OWA_BASE_DIR . '/templates/',
  617                 'plugin_dir'                        => OWA_BASE_DIR . '/plugins/',
  618                 'module_dir'                        => OWA_BASE_DIR . '/modules',
  619                 'public_path'                        => '',
  620                 'geolocation_lookup'                => true,
  621                 'geolocation_service'                => '',
  622                 'report_wrapper'                    => 'wrapper_default.tpl',
  623                 'do_not_fetch_config_from_db'        => false,
  624                 'announce_visitors'                    => false,
  625                 'public_url'                        => '',
  626                 'base_url'                            => '',
  627                 'action_url'                        => '',
  628                 'images_url'                        => '',
  629                 'reporting_url'                        => '',
  630                 'p3p_policy'                        => 'NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM',
  631                 'graph_link_template'                => '%s?owa_action=graph&name=%s&%s', //action_url?...
  632                 'link_template'                        => '%s?%s', // main_url?key=value....
  633                 'owa_user_agent'                    => 'Open Web Analytics Bot '.OWA_VERSION,
  634                 'fetch_owa_news'                    => true,
  635                 'owa_news_url'                        => 'https://api.github.com/repositories/3891123/releases?page=1&per_page=5',
  636                 'use_summary_tables'                => false,
  637                 'summary_framework'                    => '',
  638                 'click_drawing_mode'                => 'center_on_page', // remove
  639                 'log_clicks'                        => true,
  640                 'timezone'                            => 'America/Los_Angeles',
  641                 'log_dom_stream_percentage'            => 50,
  642                 'owa_wiki_link_template'            => 'http://wiki.openwebanalytics.com/index.php?title=%s',
  643                 'wiki_url'                            => 'https://github.com/Open-Web-Analytics/Open-Web-Analytics/wiki',
  644                 'password_length'                    => 4,
  645                 'modules'                            => array('base'),
  646                 'mailer-from'                        => 'owa@' . $mailer_domain, // Set default address, because sending from root@localhost wont work
  647                 'mailer-fromName'                    => 'OWA Mailer',
  648                 'mailer-host'                        => '',
  649                 'mailer-port'                        => '',
  650                 'mailer-use-smtp'                    => false,
  651                 'mailer-smtpAuth'                    => false,
  652                 'mailer-username'                    => '',
  653                 'mailer-password'                    => '',
  654                 'queue_events'                        => false,
  655                 'event_queue_type'                    => 'file',
  656                 'event_secondary_queue_type'        => '',
  657                 'use_remote_event_queue'            => true,
  658                 'remote_event_queue_type'            => 'http',
  659                 'remote_event_queue_endpoint'        => '',
  660                 'cookie_domain'                        => false,
  661                 'cookie_persistence'                => true,  // Controls persistence of cookies, only for use in europe needed
  662                 'ws_timeout'                        => 10,
  663                 'is_active'                            => true,
  664                 'per_site_visitors'                    => false, // remove
  665                 'cache_objects'                        => true,
  666                 'log_named_users'                    => true,
  667                 'log_visitor_pii'                    => true,
  668                 'excluded_ips'                        => '',
  669                 'anonymize_ips'                        => false,
  670                 'track_feed_links'                    => true,
  671                 'theme'                                => '',
  672                 'reserved_words'                    => array('do' => 'action'),
  673                 'login_view'                        => 'base.login',
  674                 'not_capable_view'                    => 'base.error',
  675                 'start_page'                        => 'base.sites',
  676                 'default_action'                    => 'base.loginForm',
  677                 'default_page'                        => '', // move to site settings
  678                 'default_cache_expiration_period'    => 604800,
  679                 'nonce_expiration_period'            => 7200,
  680                 'max_prior_campaigns'                => 5, //sdk
  681                 'default_reporting_period'            => 'last_seven_days',
  682                 'campaign_params'                    => array(
  683                         'campaign'        => 'owa_campaign',
  684                         'medium'        => 'owa_medium',
  685                         'source'        => 'owa_source',
  686                         'search_terms'    => 'owa_search_terms',
  687                         'ad'            => 'owa_ad',
  688                         'ad_type'        => 'owa_ad_type'),
  689                 'trafficAttributionMode'            => 'direct', //sdk
  690                 'campaignAttributionWindow'            => 60, //sdk
  691                  //list of capabilities that require access to the site
  692                  'capabilitiesThatRequireSiteAccess' => array(
  693                      'view_reports',
  694                      'view_reports_ecommerce',
  695                      'edit_sites',
  696                  ),
  697                  // role to capabilities configuration
  698                 'capabilities'                        => array(
  699                         'admin' => array(
  700                                 'view_site_list',
  701                                 'view_reports',
  702                                  'view_reports_ecommerce',
  703                                 'edit_settings',
  704                                 'edit_sites',
  705                                 'edit_users',
  706                                 'edit_modules'
  707                         ),
  708                         'analyst' => array('view_site_list', 'view_reports', 'view_reports_ecommerce'),
  709                         'viewer' => array('view_site_list', 'view_reports'),
  710                         'everyone' => array()
  711                 ),
  712                 'numGoals'                            => 15,
  713                 'numGoalGroups'                        => 5,
  714                 'enableEcommerceReporting'            => false, // move to site settings
  715                 'currencyLocal'                        => 'en_US', // move to site settings
  716                 'currencyISO3'                        => 'USD',   // move to site settings
  717                 'memcachedServers'                    => array(),
  718                 'memcachedPersisantConnections'        => true,
  719                 'cacheType'                            => 'file',
  720                 'disabledEndpoints'                    => array(),
  721                 'disableAllEndpoints'                => false,
  722                 'processQueuesJobSchedule'            => '10 * * * *',
  723                 'maxCustomVars'                        => 5, //sdk
  724                 'update_session_user_name'            => true, // updates the session with latest user_name value
  725                 'log_owa_user_names'                => true,  // logs the OWA user name as the user_name property on events
  726                 'logo_image_path'                    => 'base/i/owa-logo-100w.png',
  727                 'use_64bit_hash'                    => false,
  728                 'user_id_illegal_chars'                => array( " ", ";", "'", "\"", "|", ")", "("),
  729                 'archive_old_events'                => true, // used by event queues to archive processed events.
  730                 'request_mode'                      => 'web_app',
  731                 'db_supported_types'                => ['mysql' => 'MySQL']
  732             )
  733         );
  734 
  735      }
  736 
  737      /**
  738       * sets the basic path settings in the config object like "public_path" / "images_url" ...
  739       * @return void
  740       */
  741      private function setupPaths() {
  742 
  743          //build base url
  744          $base_url = '';
  745          $proto  = "http";
  746 
  747         if(isset($_SERVER['HTTPS'])) {
  748             $proto .= 's';
  749         }
  750         if(isset($_SERVER['SERVER_NAME'])) {
  751             $base_url .= $proto.'://'.$_SERVER['SERVER_NAME'];
  752         }
  753 
  754         if(isset($_SERVER['SERVER_PORT'])) {
  755             if($_SERVER['SERVER_PORT'] != 80) {
  756                 $base_url .= ':'.$_SERVER['SERVER_PORT'];
  757             }
  758         }
  759         // there is some plugin use case where this is needed i think. if not get rid of it.
  760         if (!defined('OWA_PUBLIC_URL')) {
  761             define('OWA_PUBLIC_URL', '');
  762         }
  763 
  764         // set base url
  765         $this->set('base', 'base_url', $base_url);
  766 
  767         //set public path if not defined in config file
  768         $public_path = $this->get('base', 'public_path');
  769 
  770         if (empty($public_path)) {
  771             $public_path = OWA_PATH.'/public/';
  772             $this->set('base','public_path', $public_path);
  773         }
  774 
  775         // set various paths
  776         $public_url = $this->get('base', 'public_url');
  777         $main_url = $public_url.'index.php';
  778         $this->set('base','main_url', $main_url);
  779         $this->set('base','main_absolute_url', $main_url);
  780         $modules_url = $public_url.'modules/';
  781         $this->set('base','modules_url', $modules_url);
  782         //$this->set('base','action_url',$public_url.'action.php');
  783         $this->set('base','images_url', $modules_url);
  784         $this->set('base','images_absolute_url',$modules_url);
  785         $this->set('base','log_url',$public_url.'log.php');
  786         $this->set('base','rest_api_url',$public_url.'api/index.php');
  787 
  788         $this->set('base', 'error_log_file', OWA_DATA_DIR . 'logs/errors_'. owa_coreAPI::generateInstanceSpecificHash() .'.txt');
  789         $this->set('base', 'async_log_dir', OWA_DATA_DIR . 'logs/');
  790 
  791         owa_coreAPI::debug('check for http host');
  792         // Set cookie domain
  793         if (!empty($_SERVER['HTTP_HOST'])) {
  794 
  795             $this->setCookieDomain();
  796         }
  797      }
  798 
  799      /**
  800       * Writes the config file based on the default config file - but with the given database credentials
  801       *
  802       * @param array $config_values with the database setting keys
  803       */
  804      public function createConfigFile($config_values) {
  805 
  806          if (file_exists(OWA_DIR.'owa-config.php')) {
  807              owa_coreAPI::error("Your config file already exists. If you need to change your configuration, edit that file at: ".OWA_DIR.'owa-config.php');
  808              require_once(OWA_DIR . 'owa-config.php');
  809             return true;
  810          }
  811 
  812          if (!file_exists(OWA_DIR.'owa-config-dist.php')) {
  813              $errorMsg = "We can't find the configuration file template. Are you sure you installed OWA's files correctly? Exiting.";
  814              owa_coreAPI::error($errorMsg);
  815              throw new Exception($errorMsg);
  816          }
  817 
  818          $configFileTemplate = file(OWA_DIR . 'owa-config-dist.php');
  819          owa_coreAPI::debug('found sample config file.');
  820 
  821          $handle = fopen(OWA_DIR . 'owa-config.php', 'w');
  822 
  823         foreach ($configFileTemplate as $line_num => $line) {
  824             switch (substr($line,0,20)) {
  825                 case "define('OWA_DB_TYPE'":
  826                     fwrite($handle, str_replace("yourdbtypegoeshere", $config_values['db_type'], $line));
  827                     break;
  828                 case "define('OWA_DB_NAME'":
  829                     fwrite($handle, str_replace("yourdbnamegoeshere", $config_values['db_name'], $line));
  830                     break;
  831                 case "define('OWA_DB_USER'":
  832                     fwrite($handle, str_replace("yourdbusergoeshere", $config_values['db_user'], $line));
  833                     break;
  834                 case "define('OWA_DB_PASSW":
  835                     fwrite($handle, str_replace("yourdbpasswordgoeshere", $config_values['db_password'], $line));
  836                     break;
  837                 case "define('OWA_DB_HOST'":
  838                     fwrite($handle, str_replace("yourdbhostgoeshere", $config_values['db_host'], $line));
  839                     break;
  840                 case "define('OWA_DB_PORT'":
  841                     fwrite($handle, str_replace("3306", $config_values['db_port'], $line));
  842                     break;
  843                 case "define('OWA_PUBLIC_U":
  844                     fwrite($handle, str_replace("http://domain/path/to/owa/", $config_values['public_url'], $line));
  845                     break;
  846                 case "define('OWA_NONCE_KE":
  847                     fwrite($handle, str_replace("yournoncekeygoeshere", owa_coreAPI::secureRandomString(64), $line));
  848                     break;
  849                 case "define('OWA_NONCE_SA":
  850                     fwrite($handle, str_replace("yournoncesaltgoeshere", owa_coreAPI::secureRandomString(64), $line));
  851                     break;
  852                 case "define('OWA_AUTH_KEY":
  853                     fwrite($handle, str_replace("yourauthkeygoeshere", owa_coreAPI::secureRandomString(64), $line));
  854                     break;
  855                 case "define('OWA_AUTH_SAL":
  856                     fwrite($handle, str_replace("yourauthsaltgoeshere", owa_coreAPI::secureRandomString(64), $line));
  857                     break;
  858                 default:
  859                     fwrite($handle, $line);
  860             }
  861         }
  862 
  863         fclose($handle);
  864         chmod(OWA_DIR . 'owa-config.php', 0750);
  865         owa_coreAPI::debug('Config file created');
  866         require_once(OWA_DIR . 'owa-config.php');
  867         return true;
  868 
  869     }
  870 
  871     function reset($module) {
  872 
  873         if ($module) {
  874 
  875             $defaults = array();
  876             $defaults['install_complete'] = true;
  877             $defaults['schema_version'] = $this->get($module, 'schema_version');
  878             $this->replace('base', $defaults, true);
  879             return $this->save();
  880         } else {
  881             return false;
  882         }
  883     }
  884 
  885     /**
  886      * sets and checks the cookie domain setting
  887      *
  888      * @param unknown_type $domain
  889      */
  890     public function setCookieDomain ($domain = '') {
  891 
  892         $explicit = false;
  893 
  894         if ( ! $domain ) {
  895             $domain = $_SERVER['HTTP_HOST'];
  896             $explicit = true;
  897         }
  898 
  899         // strip port, add leading period etc.
  900         $domain = owa_lib::sanitizeCookieDomain($domain);
  901 
  902         // Set the cookie domain only if the domain name is a Fully qualified domain name (FQDN)
  903         // i.e. avoid attempts to set cookie domain for e.g. "localhost" as that is not valid
  904 
  905         //check for two dots in the domain name
  906         $twodots = substr_count($domain, '.');
  907 
  908         if ( $twodots >= 2 ) {
  909 
  910             // unless www.domain.com is passed explicitly
  911             // strip the www from the domain.
  912             if ( ! $explicit ) {
  913                 $part = substr( $domain, 0, 5 );
  914                 if ($part === '.www.') {
  915                     //strip .www.
  916                     $domain = substr( $domain, 5);
  917                     // add back the leading period
  918                     $domain = '.'.$domain;
  919                 }
  920             }
  921 
  922             $this->set('base','cookie_domain', $domain);
  923             owa_coreAPI::debug("Setting cookie domain to $domain");
  924          } else {
  925              owa_coreAPI::debug("Not setting cookie domain as $domain is not a FQDN.");
  926          }
  927      }
  928 
  929     function __destruct() {
  930 
  931         if ($this->is_dirty) {
  932             $this->save();
  933         }
  934     }
  935 
  936     /**
  937      * Adds a capability ot a role, creating the role if it does
  938      * not already exist. Also adds the capability to the
  939      * siteAccessRequired list if role is not 'everyone'.
  940      *
  941      * @param $role                        string    role name.
  942      * @param $capability                string    capability name.
  943      * @param $isSiteAccesssRequired    boolean    flag for adding to SA list.
  944      *
  945      */
  946     function addCapabilityToRole( $role, $capability, $isSiteAccessRequired = false ) {
  947 
  948         $caps = $this->get('base', 'capabilities');
  949 
  950         // check to make sure role exists
  951         if ( ! isset( $caps[ $role ] ) || ! is_array( $caps[ $role ] ) ) {
  952             $caps[ $role ] = array();
  953         }
  954 
  955         //add capability to role
  956         if ( is_array( $capability ) ) {
  957             //merge new values
  958             $caps[ $role ] = array_merge($caps[ $role ], $capability);
  959         } else {
  960             $caps[ $role ][] = $capability;
  961         }
  962 
  963         // unique the array
  964         $caps[ $role ] = array_unique( $caps[ $role ] );
  965         // set new values
  966 
  967         $this->set('base', 'capabilities', $caps);
  968 
  969         // make site access is required, if role is not 'everyone'
  970         if ( ! $role === 'everyone' && $isSiteAccessRequired ) {
  971             $sar = $this->get('base', 'capabilitiesThatRequireSiteAccess');
  972             $sar[] = $capability;
  973             // unique the array
  974             $sar = array_unique( $sar );
  975             $this->set('base', 'capabilitiesThatRequireSiteAccess', $sar);
  976         }
  977     }
  978 
  979     function removeCapabilityFromRole( $role, $capability ) {
  980 
  981         $caps = $this->get('base', 'capabilities');
  982 
  983         if ( isset( $caps[ $role ] ) && in_array( $capability, $caps[ $role ] ) ) {
  984             $caps[ $role ] = array_flip($caps[ $role ]);
  985             unset( $caps[ $role ][ $capability ] );
  986             $caps[ $role ] = array_unique( array_flip($caps[ $role ] ) );
  987             $this->set('base', 'capabilities', $caps);
  988         }
  989     }
  990 
  991     function removeSiteAccessRequiredFromCapability( $capability ) {
  992 
  993         $sar = $this->get('base', 'capabilitiesThatRequireSiteAccess');
  994 
  995         if ( in_array( $capability, $sar ) ) {
  996             $sar = array_flip( $sar );
  997             unset( $sar[ $capability ] );
  998             $sar = array_unique( array_flip($sar ) );
  999             $this->set('base', 'capabilitiesThatRequireSiteAccess', $sar);
 1000         }
 1001     }
 1002 
 1003     function getAllRolesAndCapabilities() {
 1004         return $this->get('base', 'capabilities');
 1005     }
 1006 
 1007     function getCapabilitiesThatRequireSiteAccess() {
 1008         return $this->get('base', 'capabilitiesThatRequireSiteAccess');
 1009     }
 1010 
 1011     function getCapabilitiesForRole( $role ) {
 1012 
 1013         $caps = $this->get('base', 'capabilities');
 1014 
 1015         if ( isset( $caps[ $role ] ) ) {
 1016             return $caps[ $role ];
 1017         }
 1018     }
 1019 }
 1020 
 1021 ?>