public static function init()
 {
     if (!self::$initialized) {
         Profiler::StartTimer("DNSResolver::Init()", 3);
         $cfg = ConfigManager::singleton();
         if (isset($cfg->servers["dnsresolver"]["ttl"])) {
             self::$ttl = $cfg->servers["dnsresolver"]["ttl"];
         }
         if (isset($cfg->servers["dnsresolver"]["cache"])) {
             self::$cache = $cfg->servers["dnsresolver"]["cache"];
         }
         // parse /etc/resolv.conf to get domain/search suffixes
         if (file_exists("/etc/resolv.conf")) {
             $resolv = file("/etc/resolv.conf");
             for ($i = 0; $i < count($resolv); $i++) {
                 if (preg_match("/^\\s*(.*?)\\s+(.*)\\s*\$/", $resolv[$i], $m)) {
                     switch ($m[1]) {
                         case 'domain':
                             self::$domain = $m[2];
                             array_unshift(self::$search, self::$domain);
                             break;
                         case 'search':
                             self::$search[] = $m[2];
                             break;
                     }
                 }
             }
             self::$search[] = "";
         }
         self::$initialized = true;
         Profiler::StopTimer("DNSResolver::Init()");
     }
 }
Exemple #2
0
function smarty_block_config($params, $content, &$smarty)
{
    global $webapp;
    static $initialized = false;
    if (empty($params->skipcobrand)) {
        // FIXME - this should also apply to page_component's getCobrandContent() somehow...
        $cfgmgr = ConfigManager::singleton();
        if (!$initialized) {
            $heirarchy = $cfgmgr->GetConfigHeirarchy("cobrand." . $webapp->cobrand);
            foreach (array_reverse($heirarchy) as $cfgname) {
                // Walk heirarchy from bottom up
                if (preg_match("/^cobrand\\.(.*)\$/", $cfgname, $m) || $cfgname == "base") {
                    // FIXME - most general-purpose would be to use the cobrand key as imagedir (s/\./\//g?)
                    $cobrandname = $cfgname == "base" ? $cfgname : $m[1];
                    if (!empty($cobrandname)) {
                        DependencyManager::add(array("type" => "component", "name" => "cobrands." . $cobrandname, "priority" => 4));
                        //DependencyManager::add(array("type"=>"component", "name"=>"cobrands.".$cobrandname."-fixes", "priority"=>4));
                    }
                }
            }
            $initialized = true;
        }
    }
    return trim($content);
}
 function GenerateURL($dimensions, $args = NULL)
 {
     //Profiler::StartTimer("TFProductImage::GenerateURL()");
     $urlhash = md5($this->realurl);
     $dimensions = $this->ParseDimensions($dimensions);
     $dim = reset($dimensions);
     // Get first item and reset array pointer
     $dimensionstr = $dim[0] . "x" . $dim[1];
     if (!empty(self::$cache[$urlhash]) && !empty(self::$cache[$urlhash][$dimensionstr])) {
         $ret = self::$cache[$urlhash][$dimensionstr];
         if (!is_array($this->urls)) {
             $this->urls = array();
         }
         $this->urls = array_merge($this->urls, self::$cache[$urlhash]);
     } else {
         $cfg = ConfigManager::singleton();
         $sitecfg = $cfg->current["dependencies"]["image"];
         $servercfg = $cfg->servers["image"];
         $host = any($args["host"], $sitecfg["host"], $servercfg["host"]);
         $skipcache = any($args["skipcache"], $sitecfg["skipcache"], $servercfg["skipcache"], false);
         $ssl = any($args["ssl"], $sitecfg["ssl"], $servercfg["ssl"], false);
         $direct = any($args["direct"], $sitecfg["direct"], $servercfg["direct"], false);
         $matte = any($args["matte"], $sitecfg["matte"], $servercfg["matte"], true);
         $resize = any($args["resize"], $sitecfg["resize"], $servercfg["resize"], 1.0);
         $siteid = any($args["siteid"], 0);
         $category = any($args["category"], "miscellaneous");
         foreach ($dimensions as $dimstr => $dim) {
             $img = $this->FixOriginURL($this->realurl, $dim);
             if ($direct) {
                 $this->urls[$dimstr] = $img;
             } else {
                 $imgURL = "http" . ($ssl ? "s" : "") . "://" . $host . "/images/" . $this->encodeImageUrl($img, $dim[0], $dim[1], $siteid, $category);
                 $imgURLExtras = array();
                 if (!empty($skipcache)) {
                     $imgURLExtras[] = "bypass=1";
                 }
                 if (isset($matte)) {
                     $imgURLExtras[] = "m=" . (any($dim[2]["m"], $matte) ? 1 : 0);
                 }
                 if (!empty($resize)) {
                     $imgURLExtras[] = "g=" . any($dim[2]["g"], $resize);
                 }
                 $imgArgs = implode("&", $imgURLExtras);
                 $fullURL = $imgURL . (!empty($imgArgs) ? "?" . $imgArgs : "");
                 $this->urls[$dimstr] = $fullURL;
             }
         }
         $ret = $this->urls[$dimensionstr];
         self::$cache[$urlhash][$dimensionstr] = $ret;
     }
     //Profiler::StopTimer("TFProductImage::GenerateURL()");
     return $ret;
 }
Exemple #4
0
 public function controller_header($args)
 {
     if (empty($this->shown["header"])) {
         // Only allow header once per page
         $cfg = ConfigManager::singleton();
         $vars["tracking"] = any(ConfigManager::get("tracking"), $cfg->servers["tracking"], array());
         $this->shown["header"] = true;
         $vars["theme"] = any(ConfigManager::get("page.theme"), array_get($cfg->servers, "page.theme"));
         return $this->GetTemplate("./header.tpl", $vars);
     }
     return "";
 }
 function GetModels()
 {
     $models = array();
     $cfg = ConfigManager::singleton();
     if ($modeldir = opendir($cfg->locations["config"] . "/model")) {
         while ($file = readdir($modeldir)) {
             if (preg_match("/(.*?)\\.model\$/", $file, $m)) {
                 $models[] = $m[1];
             }
         }
     }
     sort($models);
     return $models;
 }
Exemple #6
0
/**
 * Smarty {img} plugin
 *
 * Type:     function<br>
 * Name:     img<br>
 * Purpose:  Get the correct image (cobranded, server, etc)
 *
 * @author Ben HOLLAND!!!
 * @param array
 * @param Smarty
 * @return string|null if the assign parameter is passed, Smarty assigns the
 *                     result to a template variable
 */
function smarty_function_img($args, &$smarty)
{
    global $webapp;
    static $heirarchy;
    static $imgcache;
    Profiler::StartTimer("smarty_function_img", 2);
    if ($heirarchy === null) {
        $cfgmgr = ConfigManager::singleton();
        $heirarchy = $cfgmgr->GetConfigHeirarchy("cobrand." . $webapp->cobrand);
    }
    $imagedir = any(DependencyManager::$locations["images"], "htdocs/images");
    $imagedirwww = any(DependencyManager::$locations["imageswww"], "/images");
    if (!empty($args["src"]) && !preg_match("/^https?:/", $args["src"])) {
        if (isset($imgcache[$args["src"]])) {
            $args["src"] = $imgcache[$args["src"]];
        } else {
            $origsrc = $args["src"];
            $found = false;
            foreach ($heirarchy as $cfgname) {
                if (preg_match("/^cobrand\\.(.*)\$/", $cfgname, $m)) {
                    // FIXME - most general-purpose would be to use the cobrand key as imagedir (s/\./\//g?)
                    if (file_exists($imagedir . "/cobrands/{$m[1]}/{$args["src"]}")) {
                        $args["src"] = $imagedirwww . "/cobrands/{$m[1]}/{$args["src"]}";
                        $found = true;
                        break;
                    }
                }
            }
            if (!$found) {
                $args["src"] = $imagedirwww . "/" . $args["src"];
            }
            $imgcache[$origsrc] = $args["src"];
        }
    }
    $ret = "<img ";
    foreach ($args as $k => $v) {
        $ret .= "{$k}=\"{$v}\" ";
    }
    $ret .= "/>";
    Profiler::StopTimer("smarty_function_img");
    if (!empty($args["src"])) {
        return $ret;
    }
}
 public function __construct($name = NULL, $role = NULL)
 {
     if ($role === NULL) {
         $cfg = ConfigManager::singleton();
         $role = isset($cfg->servers["role"]) ? $cfg->servers["role"] : "dev";
     }
     if ($name !== NULL) {
         $this->Load($name, $role);
     }
 }
 static function contents($type, $args, $extra = NULL)
 {
     $ret = array("content" => "", "lastmodified" => 0, "loaded" => array());
     $url = '';
     $argsep = '/';
     $valsep = '-';
     $cfg = ConfigManager::singleton();
     $typemap = array("javascript" => array("dir" => $cfg->locations["scripts"], "extension" => "js"), "css" => array("dir" => $cfg->locations["css"], "extension" => "css"));
     $extension = $typemap[$type]["extension"];
     $extensionlen = strlen($extension);
     foreach ($args as $k => $v) {
         if ($k[0] != '_') {
             $componentdir = realpath($typemap[$type]["dir"] . "/{$k}");
             $files = explode(" ", $v);
             foreach ($files as $file) {
                 if (substr($file, -($extensionlen + 1), $extensionlen + 1) == ".{$extension}") {
                     $file = substr($file, 0, -($extensionlen + 1));
                 }
                 $fname = $componentdir . "/" . $file . "." . $extension;
                 $realfname = realpath($fname);
                 if (file_exists($fname) && $fname == $realfname) {
                     $modtime = filemtime($fname);
                     if ($modtime > $ret["lastmodified"]) {
                         $ret["lastmodified"] = $modtime;
                     }
                     //$ret["content"] .= "\n/* ### File: " . $fname . " ### */\n";
                     $ret["content"] .= file_get_contents($fname);
                     $ret["loaded"][$k][] = $file;
                     //$ret["content"] .= "\n/* ### This code has been appended via DependencyCombiner ### */\n";
                     if (!empty($extra)) {
                         $ret["content"] .= $extra;
                     }
                 }
             }
         }
     }
     return $ret;
 }
 /**
  * LocalConfigManager::commitCommands
  * 
  * Given a set of indexes to commit, commit them using ConfigManager then delete them from the stored commands
  * @param $indexes array [1,4,5]
  * @return bool success
  **/
 public function commitCommands($indexes)
 {
     $cfg = ConfigManager::singleton();
     $status = true;
     $commandsToRun = array();
     if (!empty($indexes)) {
         foreach ($this->storedCommands as $key => $value) {
             if (in_array($key, $indexes)) {
                 $commandsToRun[] = $this->storedCommands[$key];
             }
         }
         foreach ($commandsToRun as $cmd) {
             $setcurrent = true;
             $skipcache = true;
             $skipLocalConfig = true;
             //load an unmodified version of the cobrand, otherwise the localconfig changes will have already been applied
             //and committing the commands won't work outside of this session, as they'll already have been
             //temporarily applied by the localconfig calls in getConfig()/Load(). To make the commits
             //be applied to the db pass the $skipLocalConfig flag
             $cfg->GetConfig($cmd['cobrand'], $setcurrent, $cmd['role'], $skipcache, $skipLocalConfig);
             switch ($cmd['action']) {
                 case 'update':
                     $skipLocalConfig = true;
                     $newcfg = array($cmd['name'] => array('value' => $cmd['val'], 'type' => $cmd['type']));
                     $status = $cfg->Update($cmd['cobrand'], $newcfg, $cmd['role'], null, $skipLocalConfig);
                     if (!$status) {
                         print_pre('Update failed for ' . print_r($cmd, true));
                     }
                     break;
                 case 'delete':
                     $keys = explode('.', $cmd['name']);
                     $depth = count($keys);
                     $currentDepth = 1;
                     $deleteConfig = array();
                     $arrayPtr =& $deleteConfig;
                     foreach ($keys as $key) {
                         if ($currentDepth == $depth) {
                             $arrayPtr[$key] = 1;
                         } else {
                             $arrayPtr[$key] = array();
                         }
                         $arrayPtr =& $arrayPtr[$key];
                         $currentDepth++;
                     }
                     unset($arrayPtr);
                     $status = $cfg->Update($cmd['cobrand'], array(), $cmd['role'], $deleteConfig, $skipLocalConfig);
                     if (!$status) {
                         print_pre('Delete failed for ' . print_r($cmd, true));
                     }
                     break;
                 case 'create':
                     $skipLocalConfig = true;
                     $status = $cfg->AddConfigValue($cmd['cobrand'], array('key' => $cmd['name'], 'value' => $cmd['val'], 'type' => $cmd['type']), $cmd['role'], $skipLocalConfig);
                     if (!$status) {
                         print_pre('create failed for ' . print_r($cmd, true));
                     }
                     break;
             }
         }
         $this->deleteCommands($indexes);
     } else {
         $status = false;
     }
     return $status;
 }
 function ApplySingleOverride(&$final, $param_key, $param_value = NULL, $param_args = NULL, $applysettings = true)
 {
     $cfg = ConfigManager::singleton();
     $logmsg = "Applying URL map for {$param_key} ({$param_value})";
     if (!empty($param_args["override"])) {
         $cfg->ConfigMerge($cfg->current, $param_args["override"]);
         $param_args = ConfigManager::get("search.request.override.{$param_key}");
     }
     $new_value = NULL;
     if (!empty($param_args["values"][$param_value])) {
         $valuemap = $param_args["values"][$param_value];
         if (is_array($valuemap)) {
             if (!empty($valuemap["override"])) {
                 $cfg->ConfigMerge($cfg->current, $valuemap["override"]);
                 $param_args = ConfigManager::get("search.request.override.{$param_key}");
             }
             if (isset($valuemap["newvalue"])) {
                 $new_value = $valuemap["newvalue"];
                 $logmsg .= " (newvalue: '{$new_value}')";
             } else {
                 $new_value = $param_value;
             }
         } else {
             $new_value = $param_args["values"][$param_value];
         }
     } else {
         $new_value = $param_value;
     }
     if (!empty($param_args["key"]) && $new_value !== NULL) {
         array_set($final, $param_args["key"], $new_value);
         //array_unset($final,$param_key);
     }
     if (!empty($param_args["alsooverride"])) {
         $alsolog = "";
         //print_pre($param_values["alsooverride"]);
         foreach ($param_args["alsooverride"] as $also_key => $also_value) {
             $also_params = ConfigManager::get("search.request.override.{$also_key}");
             if (!empty($also_params)) {
                 $alsolog .= (!empty($alsolog) ? "; " : "") . "{$also_key}={$also_value}";
                 $this->ApplySingleOverride($final, $also_key, $also_value, $also_params, $applyoverrides);
             }
         }
         if (!empty($alsolog)) {
             $logmsg .= "(ALSO: {$alsolog})";
         }
     }
     if ($applysettings && !empty($param_args["settings"])) {
         $settingslog = "";
         $updated_settings = ConfigManager::get("search.request.override.{$param_key}.settings");
         if (!empty($updated_settings)) {
             $flattened_settings = array_flatten($updated_settings);
             $user = User::singleton();
             foreach ($flattened_settings as $setting_key => $setting_value) {
                 $settingslog .= (!empty($settingslog) ? "; " : "") . "{$setting_key}={$setting_value}";
                 $user->SetPreference($setting_key, $setting_value, "temporary");
             }
         }
         if (!empty($settingslog)) {
             $logmsg .= " (SETTINGS: {$settingslog})";
         }
     }
     Logger::Info($logmsg);
 }
Exemple #11
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");
 }
 function getOutput($type)
 {
     $ret = array("text/html", NULL);
     $tplmgr = TemplateManager::singleton();
     switch ($type) {
         case 'ajax':
             $ret = array("application/xml", $tplmgr->GenerateXML($this->data));
             break;
         case 'json':
         case 'jsonp':
             $jsonp = any($_REQUEST["jsonp"], "elation.ajax.processResponse");
             //$ret = array("application/javascript", $jsonp . "(" . json_encode($this->data) . ");");
             $ret = array("application/javascript", $tplmgr->GenerateJavascript($this->data, $jsonp));
             break;
         case 'js':
             $ret = array("application/javascript", @json_encode($this) . "\n");
             break;
         case 'jsi':
             $ret = array("application/javascript", json_indent(@json_encode($this)) . "\n");
             break;
         case 'txt':
             $ret = array("text/plain", $tplmgr->GenerateHTML($tplmgr->GetTemplate($this->template, NULL, $this->data)));
             break;
         case 'xml':
             $ret = array("application/xml", object_to_xml($this, "response"));
             break;
         case 'data':
             $ret = array("", $this->data);
             break;
         case 'componentresponse':
             $ret = array("", $this);
             break;
         case 'popup':
             // Popup is same as HTML, but we only use the bare-minimum html.page frame
             $vars["content"] = $this;
             $ret = array("text/html", ComponentManager::fetch("html.page", $vars, "inline"));
             break;
         case 'snip':
         case 'inline':
         case 'commandline':
             $ret = array("text/html", $tplmgr->GetTemplate($this->template, NULL, $this->data));
             break;
         case 'html':
         case 'fhtml':
         default:
             $cfg = ConfigManager::singleton();
             $framecomponent = any(ConfigManager::get("page.frame"), array_get($cfg->servers, "page.frame"), "html.page");
             // If framecomponent is false/0, just return the raw content
             $ret = array("text/html", empty($framecomponent) ? $this->data["content"] : ComponentManager::fetch($framecomponent, array("content" => $this), "inline"));
             //$ret = array("text/html", $tplmgr->GetTemplate($this->template, NULL, $this->data));
             break;
     }
     if (!empty($this->prefix)) {
         $ret[1] = $this->prefix . $ret[1];
     }
     return $ret;
 }
Exemple #13
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");
 }
 /**
  * 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()");
 }
Exemple #15
0
 public function controller_header($args)
 {
     $cfg = ConfigManager::singleton();
     $header = ConfigManager::get("page.header", array_get($cfg->servers, "page.header"), null);
     if (!empty($header)) {
         return ComponentManager::fetch($header);
     } else {
         if ($header !== null) {
             return "";
         }
     }
     return $this->GetComponentResponse("./header.tpl", $vars);
 }
Exemple #16
0
 public function init()
 {
     OrmManager::LoadModel("vrcade");
     $cfg = ConfigManager::singleton();
     $cfg->current["page"]["theme"] = "dark";
 }
Exemple #17
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;
 }
Exemple #18
0
 function controller_queries($args)
 {
     $vars["sortby"] = any($args["sortby"], "time");
     $vars["showids"] = any($args["showids"], false);
     $vars["queries"] = array();
     $cfg = ConfigManager::singleton();
     $qlogcfg = any(array_get($cfg->servers, "querylog"));
     $tag = "";
     if (!empty($qlogcfg["tag"])) {
         $tag = "-" . date($qlogcfg["tag"]);
     }
     $querydir = any($qlogcfg["path"], "tmp/queries");
     $vars["file"] = any($args["file"], any($qlogcfg["file"], "querylog") . $tag);
     $fname = $querydir . "/" . $vars["file"];
     $querylogs = array();
     if (file_exists($querydir)) {
         if (($dirh = opendir($querydir)) !== false) {
             while (($f = readdir($dirh)) !== false) {
                 if (strpos($f, ".") === false) {
                     $querylogs[] = $f;
                 }
             }
         }
     }
     sort($querylogs);
     $vars["querylogs"] = implode(";", $querylogs);
     $vars["time_start"] = 0;
     $vars["time_end"] = 0;
     if (!empty($fname) && file_exists($fname)) {
         $fd = fopen($fname, "r");
         $colors = array("qpm" => "#0f0", "qpmthrift" => "#090", "db" => "#00f", "cassandra" => "#900", "memcache" => "#909", "suggest" => "#ff0", "facebook" => "#006");
         $cfg = ConfigManager::singleton();
         $cachefilename = $cfg->locations["tmp"] . "/stats-" . $vars["file"] . "-" . $vars["sortby"] . ".txt";
         $vars["cached"] = false;
         if (file_exists($cachefilename) && filemtime($cachefilename) >= filemtime($fname)) {
             $vars["cached"] = true;
             $cachecontents = file_get_contents($cachefilename);
             if (!empty($cachecontents)) {
                 $cacheobj = json_decode($cachecontents, true);
                 $vars["queries"] = any($cacheobj["queries"], $cacheobj);
                 if (!empty($cacheobj["timerange"])) {
                     $vars["time_start"] = $cacheobj["timerange"][0];
                     $vars["time_end"] = $cacheobj["timerange"][1];
                 }
             }
         } else {
             while (!feof($fd) && ($line = fgets($fd)) !== false) {
                 $q = json_decode($line);
                 if (!empty($q)) {
                     list($id, $qargs) = explode(":", $q->id, 2);
                     list($key, $id) = explode("#", $id, 2);
                     if (!empty($q->ts)) {
                         if ($vars["time_start"] == 0 || $q->ts < $vars["time_start"]) {
                             $vars["time_start"] = $q->ts;
                         }
                         if ($vars["time_end"] == 0 || $q->ts > $vars["time_end"]) {
                             $vars["time_end"] = $q->ts;
                         }
                     }
                     if (empty($id) && (preg_match("/\\.([0-9a-f]+)\$/", $key, $m) || preg_match("/^suggest\\.(.*)\$/", $key, $m))) {
                         $id = $m[1];
                         $key = substr($key, 0, strlen($key) - (strlen($m[1]) + 1));
                     }
                     $ptr =& $vars;
                     $keyparts = explode(".", $key);
                     // prepend "queries" and append the query type (fetch, insert, update, delete, count, query, etc)
                     array_unshift($keyparts, "queries");
                     if (!empty($q->type)) {
                         array_push($keyparts, $q->type);
                     }
                     if (!empty($vars["showids"]) && !empty($id)) {
                         array_push($keyparts, $id);
                     }
                     // Keep a cumulative total for each part of the key heirarchy
                     for ($i = 0; $i < count($keyparts); $i++) {
                         $keypart = $keyparts[$i];
                         if (empty($keypart)) {
                             continue;
                         }
                         if (!isset($ptr[$keypart])) {
                             $ptr[$keypart] = array("data" => array("count" => 0, "time" => 0, "cached" => 0));
                         }
                         $ptr[$keypart]["id"] = implode(".", array_slice($keyparts, 0, $i + 1));
                         $ptr[$keypart]["name"] = $keypart;
                         $ptr[$keypart]["data"]["count"]++;
                         $ptr[$keypart]["data"]["time"] += $q->time;
                         $ptr[$keypart]["data"]["time-per-query"] = $ptr[$keypart]["data"]["time"] / $ptr[$keypart]["data"]["count"];
                         $ptr[$keypart]["data"]['$angularWidth'] = $ptr[$keypart]["data"][$vars["sortby"]];
                         if ($keypart != $keyparts[0] && isset($colors[$keyparts[1]])) {
                             $ptr[$keypart]["data"]['$color'] = $colors[$keyparts[1]];
                         }
                         if ($q->cached) {
                             $ptr[$keypart]["data"]["cached"]++;
                         }
                         if ($i < count($keyparts) - 1) {
                             // Add the "children" element if it doesn't exist, and if we're not at the last keypart
                             if (!isset($ptr[$keypart]["children"])) {
                                 $ptr[$keypart]["children"] = array();
                             }
                             $ptr =& $ptr[$keypart]["children"];
                         }
                     }
                 } else {
                     //print_pre($allqueries[$i]);
                 }
             }
         }
         if (!empty($vars["queries"])) {
             $this->sortTree($vars["queries"], $vars["sortby"]);
             file_put_contents($cachefilename, json_encode(array("timerange" => array($vars["time_start"], $vars["time_end"]), "queries" => $vars["queries"])));
         }
     }
     //unset($vars["queries"]["children"]["qpm"]);
     return $this->GetComponentResponse("./queries.tpl", $vars);
 }
Exemple #19
0
 function ParseShards($shardcfg)
 {
     $cfgmgr = ConfigManager::singleton();
     $locations = $cfgmgr->locations;
     $fname = $locations["config"] . '/' . $shardcfg;
     $shards = false;
     if (file_exists($fname)) {
         $lines = file($fname);
         $bucketnum = 0;
         $filever = strpos($lines[0], "bucket:") ? 1 : 2;
         foreach ($lines as $line) {
             $bucketinfo = sscanf($line, "%s %d %d\n");
             $shards[$bucketnum++] = array("name" => $bucketinfo[0], "servers" => array($bucketinfo[1], $bucketinfo[2]));
         }
     }
     return $shards;
 }
 function Quit()
 {
     if (!empty(self::$querylog)) {
         $cfg = ConfigManager::singleton();
         $qlogcfg = any(array_get($cfg->servers, "querylog"), array());
         if ($qlogcfg["enabled"]) {
             $type = any($qlogcfg["type"], "file");
             switch ($type) {
                 case 'file':
                     $fpath = any($qlogcfg["path"], "tmp/querylog");
                     $fname = any($qlogcfg["file"], "querylog");
                     $tag = "";
                     if (!empty($qlogcfg["tag"])) {
                         $tag = "-" . date($qlogcfg["tag"]);
                     }
                     self::writeLogFile($fpath, $fname . $tag);
                     break;
                 case 'network':
                     self::writeLogNetwork();
                     break;
             }
         }
     }
     $this->CloseAll($this->sources);
 }