示例#1
0
 public static function lookup($hostname)
 {
     self::init();
     Profiler::StartTimer("DNSResolver::lookup()", 2);
     $data = DataManager::singleton();
     $records = $apc = NULL;
     $cachekey = "dnsresolver.lookup.{$hostname}";
     if (self::$cache && !empty($data->caches["apc"]) && $data->caches["apc"]["default"]->enabled) {
         $apc = $data->caches["apc"]["default"];
         $cached = $apc->get($cachekey);
         if ($cached !== false) {
             $records = unserialize($cached);
             Logger::Info("DNSResolver: found '{$hostname}' in APC cache");
         }
     }
     if ($records === NULL) {
         Logger::Info("DNSResolver: Looking up '{$hostname}'");
         foreach (self::$search as $suffix) {
             $fqdn = $hostname . (!empty($suffix) ? "." . $suffix : "");
             $records = dns_get_record($fqdn, DNS_A);
             if (!empty($records)) {
                 break;
             }
         }
         if (self::$cache && !empty($records) && $apc !== NULL && $apc->enabled) {
             $ttl = any(self::$ttl, $records[0]["ttl"]);
             $apc->set($cachekey, serialize($records), array("lifetime" => $ttl));
         }
     }
     Profiler::StopTimer("DNSResolver::lookup()");
     return $records;
 }
示例#2
0
 function component_generate($args, $output = "text")
 {
     // Only return this data when run from the commandline
     if ($output == "commandline") {
         $ret = "[not found]";
         if (!empty($args["model"])) {
             $data = DataManager::singleton();
             $model = new ORMModel($args["model"]);
             $ret = $model->Generate();
         }
     } else {
         $ret = "";
     }
     return $ret;
 }
示例#3
0
 function Generate()
 {
     if (!empty($this->classes)) {
         $data = DataManager::singleton();
         foreach ($this->classes as $cls => $classcfg) {
             $primary = array();
             $keys = array();
             if (!empty($classcfg->keys)) {
                 foreach ($classcfg->keys as $k => $v) {
                     $columns = explode(",", $v);
                     foreach ($columns as $c) {
                         if ($k == "primary") {
                             $primary[] = trim($c);
                         } else {
                             $keys[trim($c)][] = $k;
                         }
                     }
                 }
             }
             $result = $data->Query("db." . $classcfg->table . ".schema:nocache", "show columns from " . $classcfg->table);
             foreach ($result->rows as $row) {
                 $rowargs = array();
                 if ($row->key == "PRI" || in_array($row->field, $primary)) {
                     $rowargs["pk"] = true;
                 }
                 if ($row->null == "NO") {
                     $rowargs["notnull"] = true;
                 }
                 if (preg_match("/^(.*?)\\(([\\d\\.,]+)\\)(?:\\s+(.*))?\$/", $row->type, $m)) {
                     $rowtype = $m[1];
                     $rowargs["length"] = $m[2];
                     if (!empty($m[3])) {
                         $rowargs[$m[3]] = true;
                     }
                 } else {
                     $rowtype = $row->type;
                 }
                 if (isset($row->default) && $row->default !== "") {
                     $rowargs["default"] = $row->default;
                 }
                 if (isset($keys[$row->field])) {
                     $rowargs["keys"] = implode(",", $keys[$row->field]);
                 }
                 $this->classes->{$cls}->props[$row->field] = array($row->field, $rowtype);
                 if (!empty($rowargs)) {
                     $this->classes->{$cls}->props[$row->field][] = $rowargs;
                 }
             }
         }
     }
     return json_indent(json_encode($this), 5);
     //return json_encode($this);
 }
示例#4
0
 function App($rootdir, $args)
 {
     Profiler::StartTimer("WebApp", 1);
     Profiler::StartTimer("WebApp::Init", 1);
     Profiler::StartTimer("WebApp::TimeToDisplay", 1);
     $GLOBALS["webapp"] = $this;
     register_shutdown_function(array('Logger', 'processShutdown'));
     ob_start();
     $this->rootdir = $rootdir;
     $this->debug = !empty($args["debug"]);
     $this->getAppVersion();
     Logger::Info("WebApp Initializing (" . $this->appversion . ")");
     Logger::Info("Path: " . get_include_path());
     $this->initAutoLoaders();
     Logger::Info("Turning Pandora flag on");
     if (class_exists("PandoraLog")) {
         $pandora = PandoraLog::singleton();
         $pandora->setFlag(true);
     }
     $this->locations = array("scripts" => "htdocs/scripts", "css" => "htdocs/css", "tmp" => "tmp", "config" => "config");
     $this->request = $this->ParseRequest(NULL, $args);
     $this->locations["basedir"] = $this->request["basedir"];
     $this->locations["scriptswww"] = $this->request["basedir"] . "/scripts";
     $this->locations["csswww"] = $this->request["basedir"] . "/css";
     $this->locations["imageswww"] = $this->request["basedir"] . "/images";
     $this->InitProfiler();
     $this->cfg = ConfigManager::singleton($rootdir);
     $this->InitProfiler();
     // reinitialize after loading the config
     $this->locations = array_merge($this->locations, $this->cfg->locations);
     $this->data = DataManager::singleton($this->cfg);
     set_error_handler(array($this, "HandleError"), error_reporting());
     DependencyManager::init($this->locations);
     if ($this->initialized()) {
         try {
             $this->session = SessionManager::singleton();
             // Set sticky debug flag
             if (isset($this->request["args"]["debug"])) {
                 $this->debug = $_SESSION["debug"] = $this->request["args"]["debug"] == 1;
             } else {
                 if (!empty($_SESSION["debug"])) {
                     $this->debug = $_SESSION["debug"];
                 }
             }
             $this->cobrand = $this->GetRequestedConfigName($this->request);
             $this->cfg->GetConfig($this->cobrand, true, $this->cfg->role);
             $this->ApplyConfigOverrides();
             $this->locations = DependencyManager::$locations = $this->cfg->locations;
             // And the google analytics flag
             if (isset($this->request["args"]["GAalerts"])) {
                 $this->GAalerts = $this->session->temporary["GAalerts"] = $this->request["args"]["GAalerts"] == 1 ? 1 : 0;
             } else {
                 if (!empty($this->session->temporary["GAalerts"])) {
                     $this->GAalerts = $this->session->temporary["GAalerts"];
                 } else {
                     $this->GAalerts = 0;
                 }
             }
             $this->apiversion = any($this->request["args"]["apiversion"], ConfigManager::get("api.version.default"), 0);
             $this->tplmgr = TemplateManager::singleton($this->rootdir);
             $this->tplmgr->assign_by_ref("webapp", $this);
             $this->components = ComponentManager::singleton($this);
             $this->orm = OrmManager::singleton();
             //$this->tplmgr->SetComponents($this->components);
         } catch (Exception $e) {
             print $this->HandleException($e);
         }
     } else {
         $fname = "./templates/uninitialized.tpl";
         if (($path = file_exists_in_path($fname, true)) !== false) {
             print file_get_contents($path . "/" . $fname);
         }
     }
     $this->user = User::singleton();
     $this->user->InitActiveUser($this->request);
     // Merge permanent user settings from the URL
     if (!empty($this->request["args"]["settings"])) {
         foreach ($this->request["args"]["settings"] as $k => $v) {
             $this->user->SetPreference($k, $v, "user");
         }
     }
     // ...and then do the same for session settings
     if (!empty($this->request["args"]["sess"])) {
         foreach ($this->request["args"]["sess"] as $k => $v) {
             $this->user->SetPreference($k, $v, "temporary");
         }
     }
     // And finally, initialize abtests
     if (class_exists(ABTestManager)) {
         Profiler::StartTimer("WebApp::Init - abtests", 2);
         $this->abtests = ABTestmanager::singleton(array("cobrand" => $this->cobrand, "v" => $this->request["args"]["v"]));
         Profiler::StopTimer("WebApp::Init - abtests");
     }
     Profiler::StopTimer("WebApp::Init");
 }
示例#5
0
 function controller_abtests($args, $output = "inline")
 {
     $user = User::Singleton();
     if (!($user->isLoggedIn() && $user->HasRole("ADMIN"))) {
         return ComponentManager::fetch("elation.accessviolation", NULL, "componentresponse");
     }
     $data = DataManager::singleton();
     $req = $this->root->request['args'];
     $vars['err_msg'] = "";
     if ($req['save_scope']) {
         // prepare to save new abtest - make sure we are not creating an active collision
         if ($req['status'] == 'active') {
             $sql = "SELECT * FROM userdata.abtest\n          WHERE status='active'\n          AND cobrand=:cobrand\n          AND effective_dt != :effective_dt";
             if ($req['save_scope'] != 'all') {
                 $sql .= " AND role = :role";
             }
             $query = DataManager::Query("db.abtests.abtest:nocache", $sql, array(":cobrand" => $req['cobrand'], ":effective_dt" => $req['effective_dt'], ":role" => $req['role']));
             if ($query->results) {
                 $vars['err_msg'] = "***Save Aborted -- Active Status Collision -- " . $req['cobrand'] . " " . $query->results[0]->effective_dt;
             }
         }
         if (!$vars['err_msg']) {
             // write new abtest group to database
             $roles = array($req['role']);
             if ($req['save_scope'] == 'all') {
                 $roles = array('dev', 'test', 'live', 'elation');
             }
             foreach ($roles as $role) {
                 DataManager::Query("db.abtests.abtest:nocache", "DELETE FROM userdata.abtest\n                          WHERE effective_dt=:effective_dt\n                          AND cobrand=:cobrand\n                          AND role=:role", array(":effective_dt" => $req["effective_dt"], ":cobrand" => $req["cobrand"], ":role" => $role));
                 foreach ($req['version'] as $k => $v) {
                     DataManager::Query("db.abtests.abtest:nocache", "INSERT INTO userdata.abtest\n                            SET version=:version,\n                               percent=:percent,\n                                effective_dt=:effective_dt,\n                                duration_days=:duration_days,\n                                status=:status,\n                                cobrand=:cobrand,\n                                config=:config,\n                                role=:role,\n                                is_base=:is_base", array(":version" => $v, ":percent" => $req['percent'][$k], ":effective_dt" => $req['effective_dt'], ":duration_days" => $req['duration'], ":status" => $req['status'], ":cobrand" => $req['cobrand'], ":config" => $req['config'][$k], ":role" => $role, ":is_base" => $req['isbase_position'] == $k ? '1' : '0'));
                 }
             }
         }
         //fall into new lookup---
     }
     $query = DataManager::Query("db.abtests.abtest:nocache", "SELECT * FROM userdata.abtest ORDER BY status, role, cobrand, effective_dt", array());
     $vars['last_version'] = 0;
     foreach ($query->results as $res) {
         $vars['abtest'][$res->status][$res->role][$res->cobrand][$res->effective_dt][] = array('Version' => $res->version, 'Percent' => $res->percent, 'Duration' => $res->duration_days, 'Config' => $res->config, 'IsBase' => $res->is_base);
         if ($vars['last_version'] < $res->version) {
             $vars['last_version'] = $res->version;
         }
     }
     $config = ConfigManager::singleton();
     $cobrands = $config->GetCobrandList('name');
     $cobrand_test = "";
     foreach ($cobrands['cobrand'] as $k => $v) {
         preg_match('#\\.([^.]+)#', $v->name, $matches);
         if ($cobrand_test != $matches[1]) {
             $vars['cobrands'][] = $matches[1];
         }
         $cobrand_test = $matches[1];
     }
     for ($i = 0; $i < 40; $i++) {
         $vars['dates'][] = date("Y-m-d", 86400 * $i + time());
     }
     $content = $this->GetTemplate("./abtests.tpl", $vars);
     if ($output == "ajax") {
         $ret["tf_debug_tab_abtests"] = $content;
     } else {
         $ret = $content;
     }
     return $ret;
 }
示例#6
0
 /**
  * This function will be called at script shutdown via PHP script shutdown.
  * It will loop through the errors and warning and send one email
  * and/or write the errors/warnings to the file IO.
  */
 public static function processShutdown()
 {
     global $webapp;
     // settings
     $sitecfg = array("logger" => Configmanager::get("logger"));
     $sitecfg = $sitecfg["logger"]["email"] && $sitecfg["logger"]["file"] ? $sitecfg : self::getDefaultLoggerConfig();
     // email section
     $level_setting = self::convertLevelToNumeric($sitecfg["logger"]["email"]["level"]);
     $interval = $sitecfg["logger"]["email"]["interval"] > 0 ? $sitecfg["logger"]["email"]["interval"] : 10;
     // default to 10 minutes
     if ($level_setting > 0 && $lvl <= $level_setting && $sitecfg["logger"]["email"]["email_to"]) {
         $data_mgr = DataManager::singleton();
         // loop through them and send the ones that should be sent
         $email_msg = "";
         foreach (self::$log_emails as $email) {
             if ($email["level"] <= $level_setting) {
                 $cache_val = DataManager::Query("memcache.data", $email["cache_key"]);
                 if (time() - $cache_val["sent_timestamp"] >= $interval * 60) {
                     $num_times = $cache_val["count"] + 1;
                     $header = "From: " . $_SERVER["SERVER_ADMIN"] . "\n";
                     $subject = "Warning/Error message from " . $_SERVER["SERVER_ADMIN"];
                     // append the # of times this warning/error has occurred
                     $email_msg .= self::NEWLINE . self::NEWLINE . self::NEWLINE . "Number of times happened since last email = " . $num_times . self::NEWLINE . $email["content"];
                     if ($data_mgr) {
                         $cache_val["count"] = 0;
                         $cache_val["sent_timestamp"] = time();
                         DataManager::QueryInsert("memcache.data", $email["cache_key"], $cache_val);
                     }
                 } else {
                     if ($data_mgr) {
                         $cache_val["count"] += 1;
                         DataManager::QueryInsert("memcache.data", $email["cache_key"], $cache_val);
                     }
                 }
             }
         }
         if ($email_msg) {
             mail($sitecfg["logger"]["email"]["email_to"], $subject, $email_msg, $header);
         }
     }
     // log file to IO
     $level_setting = self::convertLevelToNumeric($sitecfg["logger"]["file"]["level"]);
     if ($level_setting > 0 && $sitecfg["logger"]["file"]["path"]) {
         $file_msg = "";
         foreach (self::$log_files as $file) {
             if ($file["level"] <= $level_setting) {
                 $file_msg .= $file["content"] . self::NEWLINE;
             }
         }
         $folder = rtrim($sitecfg["logger"]["file"]["path"], "/");
         $fname = $folder . "/uilogger." . date("YmdH") . "0000";
         // create folder if not already there
         if (file_exists($folder) == false) {
             mkdir($folder, 0777);
         }
         $file_exist = false;
         if (file_exists($fname) == false) {
             $file_exist = is_writable($folder) && touch($fname);
         } else {
             $file_exist = true;
         }
         if ($file_exist && is_writable($fname)) {
             file_put_contents($fname, $file_msg, FILE_APPEND);
         }
     }
     $timestats = array("page" => any($webapp->components->pagecfg["pagename"], $webapp->request["path"]), "total" => Profiler::GetTime("WebApp"));
     if (($time = Profiler::GetTime("QPMWrapper:Query()")) != NULL) {
         $timestats["qpm"] = $time;
     }
     if (($time = Profiler::GetTime("QPMThriftWrapper:Query()")) != NULL) {
         $timestats["qpm"] += $time;
     }
     if (($time = Profiler::GetTime("QPMWrapper:Query() - first byte")) != NULL) {
         $timestats["qpmfirstbyte"] = $time;
     }
     if (($time = Profiler::GetTime("DBWrapper:Query()")) != NULL) {
         $timestats["db"] = $time;
     }
     if (($time = Profiler::GetTime("WebApp::TimeToDisplay")) != NULL) {
         $timestats["firstbyte"] = $time;
     }
     if (($time = Profiler::GetTime("WebApp::Display() - Conteg")) != NULL) {
         $timestats["output"] = $time;
     }
     if (($time = Profiler::GetTime("Conteg::compress")) != NULL) {
         $timestats["compress"] = $time;
     }
     if (($time = Profiler::GetTime("Postprocessing")) != NULL) {
         $timestats["postprocessing"] = $time;
     }
     DataManager::Query("stats.default.blah:nocache", "www.timing.total", $timestats);
     $data = DataManager::singleton();
     if ($data) {
         $data->Quit();
         // shutdown to make sure sockets are flushed
     }
 }
 public function loadFromCache()
 {
     $cachekey = "config.{$this->role}.{$this->name}";
     $data = DataManager::singleton();
     $cachewrapper =& $data->caches["apc"]["default"];
     if (($cachedresult = $cachewrapper->get($cachekey)) !== false) {
         $configobj = unserialize($cachedresult);
         Logger::Info("Found '{$cachekey}' in apc cache (revision=" . $cacheobj->revision . ")");
         $allversions = $this->GetAllRevisions($role);
         Logger::Debug($allversions);
         foreach ($cacheobj->heirarchy as $i => $inc) {
             if ($cacheobj->versions[$inc] < $allversions[$inc]) {
                 Logger::Warn("Revision number for '{$name}' parent '{$inc}' is out of date (old revision=" . $cacheobj->versions[$inc] . " new revision=" . $allversions[$inc] . ")");
                 $ret = array();
                 $skipcache = true;
                 for ($j = $i; $j >= 0; $j--) {
                     // Clear cache entries for anything above this one
                     Logger::Info("Delete cache: {$includes[$j]}");
                     /*
                      // FIXME - need to invalidate instead of deleting
                       $cachewrapper->delete("config.$role.{$includes[$j]}");
                       $cachewrapper->delete("config.$role.{$includes[$j]}.heirarchy");
                       $cachewrapper->delete("config.$role.{$includes[$j]}.versions");
                     */
                 }
             }
         }
     }
 }
示例#8
0
 public function setUp()
 {
     $cfg->servers = $this->servers;
     $data = DataManager::singleton($cfg);
 }
示例#9
0
 function App($rootdir, $args)
 {
     Profiler::StartTimer("WebApp", 1);
     Profiler::StartTimer("WebApp::Init", 1);
     Profiler::StartTimer("WebApp::TimeToDisplay", 1);
     // disable notices by default.  This should probably be a config option...
     error_reporting(error_reporting() ^ E_NOTICE);
     // FIXME - xdebug recursion limit causes problems in some components...
     ini_set('xdebug.max_nesting_level', 250);
     $GLOBALS["webapp"] = $this;
     register_shutdown_function(array($this, 'shutdown'));
     ob_start();
     $this->rootdir = $rootdir;
     $this->debug = !empty($args["debug"]);
     $this->getAppVersion();
     Logger::Info("WebApp Initializing (" . $this->appversion . ")");
     Logger::Info("Path: " . get_include_path());
     $this->initAutoLoaders();
     if (class_exists("PandoraLog")) {
         Logger::Info("Turning Pandora flag on");
         $pandora = PandoraLog::singleton();
         $pandora->setFlag(true);
     }
     $this->InitProfiler();
     $this->request = $this->ParseRequest(NULL, $args);
     $this->cfg = ConfigManager::singleton(array("rootdir" => $rootdir, "basedir" => $this->request["basedir"]));
     $this->locations = ConfigManager::getLocations();
     $this->InitProfiler();
     // reinitialize after loading the config
     Profiler::StartTimer("WebApp::Init - handleredirects", 1);
     $this->request = $this->ApplyRedirects($this->request);
     Profiler::StopTimer("WebApp::Init - handleredirects");
     $this->data = DataManager::singleton($this->cfg);
     set_error_handler(array($this, "HandleError"), error_reporting());
     DependencyManager::init($this->locations);
     if ($this->initialized()) {
         try {
             $this->session = SessionManager::singleton();
             // Set sticky debug flag
             if (isset($this->request["args"]["debug"])) {
                 $this->debug = $_SESSION["debug"] = $this->request["args"]["debug"] == 1;
             } else {
                 if (!empty($_SESSION["debug"])) {
                     $this->debug = $_SESSION["debug"];
                 }
             }
             $this->cobrand = $this->GetRequestedConfigName($this->request);
             if (isset($this->request["args"]["_role"])) {
                 $this->role = $this->request["args"]["_role"];
             } else {
                 if (isset($this->cfg->servers["role"])) {
                     $this->role = $this->cfg->servers["role"];
                 } else {
                     $this->role = "dev";
                 }
             }
             $this->cfg->GetConfig($this->cobrand, true, $this->role);
             $this->ApplyConfigOverrides();
             $this->locations = DependencyManager::$locations = $this->cfg->locations;
             // And the google analytics flag
             if (isset($this->request["args"]["GAalerts"])) {
                 $this->GAalerts = $this->session->temporary["GAalerts"] = $this->request["args"]["GAalerts"] == 1 ? 1 : 0;
             } else {
                 if (!empty($this->session->temporary["GAalerts"])) {
                     $this->GAalerts = $this->session->temporary["GAalerts"];
                 } else {
                     $this->GAalerts = 0;
                 }
             }
             $this->apiversion = isset($this->request["args"]["apiversion"]) ? $this->request["args"]["apiversion"] : ConfigManager::get("api.version.default", 0);
             $this->tplmgr = TemplateManager::singleton($this->locations);
             $this->tplmgr->assign_by_ref("webapp", $this);
             $this->components = ComponentManager::singleton($this);
             if (class_exists("OrmManager")) {
                 $this->orm = OrmManager::singleton($this->locations);
             }
             //$this->tplmgr->SetComponents($this->components);
         } catch (Exception $e) {
             print $this->HandleException($e);
         }
     } else {
         $fname = "components/elation/templates/uninitialized.html";
         if (($path = file_exists_in_path($fname, true)) !== false) {
             print file_get_contents($path . "/" . $fname);
         }
     }
     $this->user = User::singleton();
     $this->user->InitActiveUser($this->request);
     // Merge permanent user settings from the URL
     if (!empty($this->request["args"]["settings"])) {
         foreach ($this->request["args"]["settings"] as $k => $v) {
             $this->user->SetPreference($k, $v, "user");
         }
     }
     // ...and then do the same for session settings
     if (!empty($this->request["args"]["sess"])) {
         foreach ($this->request["args"]["sess"] as $k => $v) {
             $this->user->SetPreference($k, $v, "temporary");
         }
     }
     // And finally, initialize abtests
     if (class_exists("ABTestManager")) {
         Profiler::StartTimer("WebApp::Init - abtests", 2);
         $this->abtests = ABTestmanager::singleton(array("cobrand" => $this->cobrand, "v" => $this->request["args"]["v"]));
         Profiler::StopTimer("WebApp::Init - abtests");
     }
     Profiler::StopTimer("WebApp::Init");
 }
示例#10
0
 /**
  * Initialize the session.
  * Start the session.
  */
 protected function init()
 {
     //some al-qada shit here...
     global $webapp;
     $this->data = DataManager::singleton();
     Profiler::StartTimer("SessionManager::Init()", 2);
     $cfgmgr = ConfigManager::singleton();
     $sessionsource = array_get($cfgmgr->servers, "session.datasource");
     if (!empty($sessionsource)) {
         $this->sessionsource = $sessionsource;
     }
     $sessiontable = array_get($cfgmgr->servers, "session.table");
     if (!empty($sessiontable)) {
         $this->sessiontable = $sessiontable;
     }
     /*
     if ($this->data->caches["memcache"]["session"] !== NULL) {
       $this->cache_obj = $this->data->caches["memcache"]["session"];
       //$this->session_cache_expire = $this->data->caches["memcache"]["session"]->lifetime;
     } else {
       // Continue anyway even if cannot connect to memcache.
       // Point the cache_obj to NoCache object
       //print_pre($this->data);
       Logger::Error("SessionManager::init() - Cannot connect to session memcache - " . $this->data->sources);
       $this->cache_obj =& NoCache::singleton();
     }
     */
     // instantiate the pandora object
     $pandora = PandoraLog::singleton();
     // check to see if there is an existing cookie for flsid
     $has_flsid = isset($_COOKIE['flsid']) || isset($_REQUEST['flsid']);
     $this->is_new_session = $has_flsid == 1 ? 0 : 1;
     // register_shutdown_function('session_write_close');
     // Set session cookie params
     $domain = null;
     $sessioncfg = any($cfgmgr->servers["session"], array());
     $sessionpath = any($sessioncfg["cookiepath"], "/");
     if ($sessioncfg["domaincookie"]) {
         // Determine second-level domain, taking into account any known ccSLDs (.co.uk, etc)
         $FQDN = $webapp->request["host"];
         $knownccSLDs = explode(" ", any($sessioncfg["ccSLDs"], ""));
         $parts = explode(".", $FQDN);
         $TLD = array_pop($parts);
         $SLD = array_pop($parts);
         $domain = $SLD . "." . $TLD;
         if (in_array($domain, $knownccSLDs)) {
             $TLD = $domain;
             $SLD = array_pop($parts);
             $domain = $SLD . "." . $domain;
         }
         $excludeDomains = explode(" ", any($sessioncfg["domaincookie_exception"], ""));
         if (in_array($domain, $excludeDomains)) {
             $domain = null;
         }
     }
     session_set_cookie_params(0, $sessionpath, $domain);
     // if flsid was passed via the URL, set it as a cookie
     if (!empty($_GET['flsid'])) {
         setcookie("flsid", $_GET['flsid'], 0, '/', $domain);
         $this->flsid = $_COOKIE['flsid'] = $_GET['flsid'];
     }
     session_set_save_handler(array(&$this, 'open'), array(&$this, 'close'), array(&$this, 'read'), array(&$this, 'write'), array(&$this, 'destroy'), array(&$this, 'gc'));
     // set the garbage collection lifetime (on the DB persist data)
     ini_set('session.gc_maxlifetime', 31536000);
     // 31536000 = 60 * 60 * 24 * 365
     // set the session cookie name
     session_name($this->cookiename);
     // set the cache limiter to 'private' - keeps us from sending Pragma: no-cache
     session_cache_limiter('private');
     // initiate sessionization
     if (!headers_sent()) {
         session_start();
     }
     /**
      * Read the permanent session ID from cookie.
      * If there isn't one, create one.
      */
     // read the permanent cookie
     if (isset($_REQUEST['fluid'])) {
         $fluid_str = $_REQUEST['fluid'];
     } else {
         if (isset($_COOKIE['fl-uid'])) {
             $fluid_str = $_COOKIE['fl-uid'];
         } else {
             if (isset($_SESSION['fluid'])) {
                 $fluid_str = $_SESSION['fluid'];
             }
         }
     }
     $fluid_data = explode(",", $fluid_str);
     $this->fluid = $fluid_data[0];
     $this->session_count = $fluid_data[1] ? $fluid_data[1] : 0;
     $this->last_access = $fluid_data[2] ? $fluid_data[2] : 0;
     $this->first_session_for_day = 0;
     $this->days_since_last_session = 0;
     $this->is_new_user = 0;
     if (empty($this->fluid)) {
         // create new permanent cookie
         $this->is_new_user = 1;
         $this->fluid = $this->generate_fluid();
         $this->session_count = 0;
         $this->last_access = time();
         $this->first_session_for_day = 1;
         $this->days_since_last_session = 0;
         $fluid_data = $this->fluid . ',' . $this->session_count . ',' . $this->last_access;
         //setcookie('fl-uid', $fluid_data, time()+31536000, "/", $domain); // (1 year)
         $pdata_serialize = serialize($_SESSION["persist"]);
         $this->crc = strlen($pdata_serialize) . crc32($pdata_serialize);
     }
     if (!$has_flsid) {
         // new session -- update the permanent cookie
         // Deal with errant mis-named 'fl_uid' cookies...
         // (this code can safely be removed in a year or so, e.g. February 2010)
         // ^^^ perhaps not?
         if ($fluid_data_recover = explode(",", $_COOKIE['fl_uid'])) {
             $this->fluid = any($this->fluid, $fluid_data_recover[0]);
             $this->session_count = $fluid_data_recover[1];
             $this->last_access = $fluid_data_recover[2];
             //setcookie('fl_uid', '', 0, "/", $domain); // delete the errant cookie
         }
         $this->session_count++;
         if (time() > $this->last_access + 86400) {
             $this->days_since_last_session = floor((time() - $this->last_access) / 86400);
             $this->last_access = time();
             $this->first_session_for_day = 1;
         }
         $fluid_data = $this->fluid . ',' . $this->session_count . ',' . $this->last_access;
         if (!headers_sent()) {
             setcookie('fl-uid', $fluid_data, time() + 31536000, "/", $domain);
             // (update the permanent cookie)
         }
     }
     // debugging
     // print "<hr>In SessionManager::init() - cache_obj extended stats = " . print_pre($this->cache_obj->GetExtendedStats());
     /**
      * First, check to see if there is an entry in the memcache for this fluid.
      * If so, use it.
      * If not, query the DB to get the persistent session data.
      * If not in the DB, create a new session.
      */
     //$session_memcache = $this->cache_obj->get($this->flsid);
     // force new flsid/session id regardless if flsid is passed in url
     if ($_REQUEST['event'] == 'new') {
         $this->flsid = session_regenerate_id();
     } else {
         $this->flsid = session_id();
     }
     $session_memcache = DataManager::fetch("memcache.session#{$this->flsid}", $this->flsid);
     //$tmpsession = unserialize($session_memcache);
     if (!empty($session_memcache["fluid"])) {
         $this->fluid = $session_memcache["fluid"];
     }
     if (empty($session_memcache) && !$this->is_new_user) {
         $result = DataManager::QueryFetch($this->sessionsource . "#{$this->fluid}", $this->sessiontable, array("fl_uid" => $this->fluid));
         if ($result && count($result) == 1) {
             $data = current($result);
             $_SESSION["persist"] = unserialize($data["data"]);
             $this->has_db_record = true;
             if (!$_SESSION["persist"]["has_db_record"]) {
                 $_SESSION["persist"]["has_db_record"] = true;
             }
         }
     } else {
         $_SESSION = $session_memcache;
         //Logger::Error(print_r($_SESSION, true));
     }
     $this->has_db_record = $_SESSION["persist"]["has_db_record"] ? true : false;
     // Store permenant session id, actual (temporary) session id,
     // and create pointers to $_SESSION memory space
     $this->flsid = session_id();
     $this->persist =& $_SESSION["persist"];
     $this->temporary =& $_SESSION["temporary"];
     // get from the persist session data if this is a new or registered user
     $userid = $_SESSION["persist"]["user"]["userid"];
     $usertype = $_SESSION["persist"]["user"]["usertype"];
     $userTypeArray = User::$usertypes;
     $pandoraUserTypeNum = any($userTypeArray[$usertype], 0);
     // log this into Pandora
     $pandora_session = array("timestamp" => time(), "session_id" => $this->flsid, "fluid" => $this->fluid, "is_new_user" => $this->is_new_user, "is_registered_user" => $userid ? 1 : 0, "ip_addr" => $_SERVER['REMOTE_ADDR'], "user_agent" => $_SERVER['HTTP_USER_AGENT'], "referrer_url" => $_SERVER['HTTP_REFERER'], "landing_page_url" => "http" . (!empty($_SERVER["HTTPS"]) ? "s" : "") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], "referrer_id" => $webapp->request["args"]["rid"], "widget_id" => $webapp->request["args"]["wid"], "user_registration_id" => "{$pandoraUserTypeNum}.{$userid}", "version" => 0, "cobrand" => $this->root->cobrand, "first_session_for_day" => $this->first_session_for_day, "session_count" => $this->session_count, "days_since_last_session" => $this->days_since_last_session);
     // log this session for data warehouse (once per session)
     if (!$has_flsid) {
         //store the session start time in session
         $_SESSION['session_start_time'] = time();
         $pandora->addData("session", $pandora_session);
     } else {
         Logger::Notice("Pandora: Session already has an flsid. Current start time from session is: " . var_export($_SESSION['session_start_time'], true));
         if (!array_key_exists('session_start_time', $_SESSION)) {
             $_SESSION['session_start_time'] = time();
             Logger::Warn("Pandora: Set or reset the session start time as one did not exist before. Time is: " . var_export($_SESSION['session_start_time'], true));
         } else {
             Logger::Notice("Pandora: Session start time was not reset. Time is: " . var_export($_SESSION['session_start_time'], true));
         }
     }
     //save session data once per session
     //    if(!array_key_exists('pandora_session_data_added', $_SESSION)) {
     //      $pandora->addData("session", $pandora_session);
     //      $_SESSION['pandora_session_data_added'] = true;
     //    }
     $_SESSION["fluid"] = $this->fluid;
     // set the script session ID
     $this->flssid = $this->generate_fluid();
     Profiler::StopTimer("SessionManager::Init()");
 }