Пример #1
0
 /**
  * Define and load page components into the ComponentManager.
  * @todo Полный рефакторинг!
  */
 public function loadComponents(callable $getStructure)
 {
     // определяем и загружаем описания content- и layout- частей страницы
     $structure = call_user_func($getStructure, $this->getID());
     // вызывается ли компонент в single режиме?
     $actionParams = $this->request->getPath(Request::PATH_ACTION);
     if (sizeof($actionParams) > 1 && $actionParams[0] == self::SINGLE_SEGMENT) {
         /*
          * Устанавливаем смещение пути на количество существующих
          * сегментов + 1 зарезирвированный сегмент + 1 сегмент
          * имени компонента.
          */
         $this->request->setPathOffset($this->request->getPathOffset() + 2);
         $this->setProperty('single', 'single');
         if ($actionParams[1] == 'pageToolBar') {
             $this->componentManager->add($this->componentManager->createComponent('pageToolBar', 'Energine\\share\\components\\DivisionEditor', ['state' => 'showPageToolbar']));
         } else {
             if (!($blockDescription = ComponentManager::findBlockByName($structure, $actionParams[1]))) {
                 throw new SystemException('ERR_NO_SINGLE_COMPONENT', SystemException::ERR_CRITICAL, $actionParams[1]);
             }
             if (E()->getController()->getViewMode() == DocumentController::TRANSFORM_STRUCTURE_XML) {
                 $int = new IRQ();
                 $int->setStructure($blockDescription);
                 throw $int;
             }
             if ($c = ComponentManager::createBlockFromDescription($blockDescription)) {
                 $this->componentManager->add($c);
             }
         }
     } else {
         if (E()->getController()->getViewMode() == DocumentController::TRANSFORM_STRUCTURE_XML) {
             $int = new IRQ();
             $int->setStructure($structure);
             throw $int;
         }
         foreach ($structure->children() as $XML) {
             if ($c = ComponentManager::createBlockFromDescription($XML)) {
                 $this->componentManager->add($c);
             }
         }
         /*
          * Добавляем к набору компонентов страницы
          * обязательные стандартные компоненты:
          *     - BreadCrumbs
          */
         $this->componentManager->add($this->componentManager->createComponent('breadCrumbs', $this->breadCrumbsClass));
         //Если пользователь не авторизован и авторизационный домен не включает текущеий домен - то добавляем компонент для кроссдоменной авторизации
         if (!$this->user->isAuthenticated() && strpos(E()->getSiteManager()->getCurrentSite()->host, $this->getConfigValue('site.domain')) === false) {
             $this->componentManager->add($this->componentManager->createComponent('cdAuth', 'Energine\\share\\components\\CrossDomainAuth'));
         }
     }
 }
Пример #2
0
/**
 * Smarty {component} plugin
 *
 * Type:     function<br>
 * Name:     component<br>
 * Purpose:  Execute and print the output of a named component
 *
 * @author James Baicoianu
 * @param array
 * @param Smarty
 * @return string|null if the assign parameter is passed, Smarty assigns the
 *                     result to a template variable
 */
function smarty_function_component($args, &$smarty)
{
    global $webapp;
    $ret = "";
    if (!empty($args["name"])) {
        if (!empty($args["componentargs"])) {
            $componentargs = array_merge($args, $args["componentargs"]);
            unset($componentargs["componentargs"]);
        } else {
            $componentargs = $args;
        }
        $componentmgr = ComponentManager::singleton();
        $componentargs = $componentmgr->GetDispatchArgs($args["name"], $componentargs);
        $component = $componentmgr->Get($args["name"], $componentargs);
        if ($component !== NULL) {
            $ret = $component->HandlePayload($componentargs, "inline");
            if (is_array($ret)) {
                /*
                $webapp->response["type"] = "text/xml";
                $ret = $smarty->GenerateXML($ret);
                */
            } else {
                if ($ret instanceof ComponentResponse) {
                    $response = $ret->getOutput("inline");
                    $ret = $response[1];
                } else {
                    $escapes = array();
                    if (!empty($args["escape"])) {
                        $escapes = explode("|", $args["escape"]);
                    }
                    foreach ($escapes as $escape) {
                        $ret = $escape($ret);
                    }
                }
            }
        } else {
            $ret = "[Unknown component: " . $args["name"] . "]";
        }
    }
    return $ret;
}
                    case 'INSTALL':
                        //install component
                        $componentManager->getComponent($keywords[1])->install(true);
                        break;
                    case 'REMOVE':
                        //remove component
                        $componentManager->getComponent($keywords[1])->remove();
                        break;
                    case 'LIST':
                        //list installed components
                        $componentManager->listInstalledComponents();
                        break;
                    case 'END':
                        //end of input
                        break;
                }
            }
            if (!feof($handle)) {
                echo "Error: unexpected fgets() fail\n";
            }
            echo "\n";
            fclose($handle);
            //var_dump($componentManager->getComponents());
        }
    }
}
if (file_exists($_SERVER['argv'][1])) {
    ComponentManager::getInstance()->main();
} else {
    echo "The file {$_SERVER['argv'][1]} does not exist\n";
}
Пример #4
0
 /**
  * Perform a multi-part request.  Format:
  * [
  *    {"component": <componentname>, "args": { ... }},
  *    ...
  * ]
  *
  * Supported parameters:
  *   - component : name of component to call
  *   - args      : associative array of arguments for this component.  supports basic variable subtitution.
  *   - output    : output type for this component (js,xml,ajax,json,data; defaults to "data")
  *   - target    : if using .json or .ajax output types, the id to inject this content into on the client side
  *   - assign    : make the output of this component available for variable substitution in args
  * 
  */
 public function controller_multirequest($args, $output)
 {
     /*
      * Example request:
      *
      * [
      *    {"component":"browse","args":{},"assign":"browse"},
      *    {"component":"utils.list","args":{"itemcomponent":"browse.node","itemclass":"tf_browse_node","items":"$browse.node.products"},"output":"snip"}
      * ]
      *
      */
     $vars = array();
     $isajax = $output == "ajax" || $output == "json";
     if (!empty($args["requests"])) {
         $requests = is_string($args["requests"]) ? json_decode($args["requests"], true) : $args["requests"];
         if (is_array($requests)) {
             $cmanager = ComponentManager::singleton();
             foreach ($requests as $k => $req) {
                 if (!empty($req["component"])) {
                     $componentargs = any($req["args"], array());
                     // Perform variable substitution if requested.
                     // Any arg that starts with a $ is treated as a variable reference
                     foreach ($componentargs as $argname => $argval) {
                         if ($argval[0] == '$') {
                             $argreplace = array_get($args, substr($argval, 1));
                             if (!empty($argreplace)) {
                                 $componentargs[$argname] = $argreplace;
                             } else {
                                 $componentargs[$argname] = "";
                             }
                         }
                     }
                     $componentoutput = any($req["output"], $isajax && !empty($req["target"]) ? "snip" : "data");
                     //$componentresponse = ComponentManager::fetch($req["component"], $componentargs, $componentoutput);
                     $path = "/" . str_replace(".", "/", $req["component"]);
                     $response = $cmanager->Dispatch($path, $componentargs, $componentoutput, false);
                     $componentresponse = $response["content"];
                     if (!empty($req["assign"])) {
                         // assign component output back into args array
                         $args[$req["assign"]] = $componentresponse;
                     }
                     if ($isajax) {
                         // special handling for ajaxlib response type
                         if (!empty($req["target"]) && $componentoutput != "data") {
                             $vars[$req["target"]] = $componentresponse;
                         } else {
                             if ($componentoutput == "snip" || $componentoutput == "html" || $componentoutput == "xhtml") {
                                 $varkey = any($req["target"], $req["assign"], $k);
                                 $vars["xhtml"][$varkey] = $componentresponse;
                             } else {
                                 if (!$req["ignore"]) {
                                     // dont include ignored responses in XHR return data
                                     $varkey = any($req["target"], $req["assign"], $k);
                                     if ($req["expose"]) {
                                         // only include in XHR response properties that match EXPOSE comma seperated string
                                         $inclusion_properties = explode(",", $req["expose"]);
                                         $allow = array();
                                         for ($i = 0; $i < count($inclusion_properties); $i++) {
                                             $property = $inclusion_properties[$i];
                                             $allow[$property] = $componentresponse[$property];
                                         }
                                         $vars["data"][$varkey] = $allow;
                                     } else {
                                         // send everything
                                         $vars["data"][$varkey] = $componentresponse;
                                     }
                                 }
                             }
                         }
                     } else {
                         // standard handling is to return each component response in order
                         $vars["responses"][$k] = $componentresponse;
                     }
                 }
             }
         } else {
             // JSON parse failed
             // TODO - return some sort of error code
         }
     }
     // no default HTML template....should there be?
     return $this->GetComponentResponse(null, $vars);
 }
Пример #5
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");
 }
Пример #6
0
 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;
 }
Пример #7
0
 function Init($args, $locations)
 {
     foreach ($args as $k => $v) {
         $this->{$k} = $v;
     }
     if (!empty($args["name"]) && !empty($args["component"]) && !isset(self::$templates[$args["name"]])) {
         self::$templates[$args["name"]] = ComponentManager::fetch($args["component"], $args["componentargs"]);
         DependencyManager::add(array("type" => "component", "name" => "tplmgr.tplmgr", "priority" => 2));
     }
 }
Пример #8
0
 function controller_componentdetails($args)
 {
     $vars["root"] = any($args["root"], true);
     $vars["id"] = any($args["id"], false);
     if (!empty($args["component"])) {
         $components = ComponentManager::fetch("utils.componentlist", array("tree" => true), "data");
         $key = str_replace(".", ".components.", $args["component"]);
         $vars["component"] = array_get($components["components"], $key);
         $vars["componentargs"] = any($args["componentargs"], array());
         $vars["events"] = any($args["events"], array());
     }
     return $this->GetComponentResponse("./componentdetails.tpl", $vars);
 }
Пример #9
0
 private function loadComponents()
 {
     $this->componentManager->setAllServiceProvidersFrom(__DIR__ . "/../Components");
     $this->componentManager->registerServiceProviders();
     $this->componentManager->callBootMethodOfServiceProviders();
 }
Пример #10
0
 /**
  * Renders the form. If $context is null or a Zend_View it'll render it
  * normally. Otherwise, it passes the form object to a component for further
  * processing. Note, even if passed to a second controller, it's still 
  * possible to render the form in traditional Zend style with {$form}
  * 
  * @param object $context [optional]
  * @param object $args [optional]
  * @return string HTML output
  */
 public function render($context = NULL, $args = array())
 {
     if ($context == NULL) {
         $context = new Zend_View();
     }
     if ($context instanceof Zend_View_Interface) {
         return parent::render($context);
     } else {
         $args = array_merge($args, array('form' => $this));
         $componentOutput = ComponentManager::fetch($context, $args);
         return $componentOutput;
     }
 }
Пример #11
0
 function PostProcess(&$output, $simpledebug = false)
 {
     global $webapp;
     Profiler::StartTimer("TemplateManager::PostProcess()");
     $matchregex = "/\\[\\[(\\w[^\\[\\]{}:|]*)(?:[:|](.*?))?\\]\\]/";
     if (!is_array($output)) {
         // FIXME - we should probably still postprocess if we're returning XML
         if (preg_match_all($matchregex, $output, $matches, PREG_SET_ORDER)) {
             $search = $replace = array();
             foreach ($matches as $m) {
                 $search[] = $m[0];
                 $replace[] = !empty($this->varreplace[$m[1]]) ? htmlspecialchars($this->varreplace[$m[1]]) : (!empty($m[2]) ? $m[2] : "");
             }
             $pos = array_search("[[debug]]", $search);
             if ($pos !== false) {
                 // if there are errors, check for access and force debug
                 $show_debug = $webapp->debug;
                 /*
                 if (Logger::hasErrors()) {
                   $user = User::singleton();
                   if ($user->HasRole("DEBUG") || $user->HasRole("ADMIN") || $user->HasRole("QA")) {
                     $show_debug = true;
                   }
                 }
                 */
                 if ($show_debug) {
                     //$replace[$pos] = $this->GetTemplate("debug.tpl");
                     $replace[$pos] = $simpledebug ? Logger::Display(E_ALL) : ComponentManager::fetch("elation.debug");
                 } else {
                     $replace[$pos] = "";
                 }
             }
             if (($pos = array_search("[[dependencies]]", $search)) !== false) {
                 $replace[$pos] = DependencyManager::display();
                 // Sometimes dependencies also use postprocessing variables, so parse those and add them to the list too
                 // FIXME - could be cleaner, this is copy-pasta of the first parsing pass above
                 if (preg_match_all($matchregex, $replace[$pos], $submatches, PREG_SET_ORDER)) {
                     foreach ($submatches as $sm) {
                         $search[] = $sm[0];
                         $replace[] = !empty($this->varreplace[$sm[1]]) ? htmlspecialchars($this->varreplace[$sm[1]]) : (!empty($sm[2]) ? $sm[2] : "");
                     }
                 }
             }
             $output = str_replace($search, $replace, $output);
         }
     }
     Profiler::StopTimer("TemplateManager::PostProcess()");
     return $output;
 }
Пример #12
0
 public function remove()
 {
     if (!$this->isInstalled()) {
         echo "  {$this->getName()} is not  installed.\n";
         return;
     }
     if (!empty($this->dependents)) {
         /** @var Component $dependent */
         foreach ($this->dependents as $dependent) {
             if (ComponentManager::getInstance()->getComponent($dependent)->isInstalled()) {
                 echo "  {$this->getName()} is still needed.\n";
                 return;
             }
         }
     }
     echo "  Removing {$this->getName()}\n";
     $this->installed = false;
     /** @var Component $dependency */
     foreach ($this->dependencies as $dependency) {
         /** @var Component $component */
         $component = ComponentManager::getInstance()->getComponent($dependency);
         foreach ($component->getDependents() as $dependent) {
             if (ComponentManager::getInstance()->getComponent($dependent)->isInstalled()) {
                 return;
             }
         }
         if (!$component->explicitInstall) {
             $component->remove();
         }
     }
 }
Пример #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");
 }
Пример #14
0
 public function controller_footer($args)
 {
     // Assemble page-level args for Google Analytics --
     global $webapp;
     $analytics = Analytics::singleton();
     $componentmgr = ComponentManager::singleton();
     $args['cobrand'] = $webapp->cobrand;
     $args['store_name'] = $this->sanitizeStrForGA($analytics->store_name);
     if ($webapp->request['referer']['host'] && !stristr($webapp->request['referer']['host'], $webapp->request['host'])) {
         $args['query'] = $this->getQueryFromURL($webapp->request['referrer'], $args['store_name']);
     } else {
         $args['query'] = $this->sanitizeStrForGA(any($analytics->search["input"]["query"], $analytics->qpmreq->query, 'none'));
     }
     $args['bs'] = $componentmgr->pagecfg;
     //testing
     $args['pagegroup'] = $componentmgr->pagecfg['pagegroup'];
     $args['pagetype'] = $componentmgr->pagecfg['pagename'];
     $args['status'] = any($analytics->status, $webapp->response['http_status']);
     $args['total'] = $analytics->total;
     $args['GAenabled'] = $args['pagegroup'] ? any(ConfigManager::get("tracking.googleanalytics.enabled"), $webapp->cfg->servers['tracking']['googleanalytics']['enabled']) : 0;
     $args['GAalerts'] = $webapp->GAalerts;
     $args['trackingcode'] = any(ConfigManager::get("tracking.googleanalytics.trackingcode"), $webapp->cfg->servers['tracking']['googleanalytics']['trackingcode']);
     $args['enable_native_tracking'] = ConfigManager::get("tracking.enable_native_tracking", NULL);
     $args['category'] = any($analytics->category, $analytics->pandora_result['top_category'], $analytics->item->category, $analytics->qpmquery['protocolheaders']['category'], 'none');
     $args['subcategory'] = preg_replace("#\\s#", "_", any($analytics->subcategory, $analytics->pandora_result['top_subcategory'], 'none'));
     $args['city'] = "Mountain View";
     $args['state'] = "CA";
     $args['country'] = "USA";
     if ($analytics->city && $analytics->state) {
         $args['city'] = ucWords($analytics->city);
         $args['state'] = $analytics->state;
         $args['country'] = "USA";
     }
     if (in_array($args['cobrand'], array('paypaluk', 'thefinduk', 'paypalcanada'))) {
         $args['city'] = 'unknown';
         $args['state'] = 'unknown';
         $args['country'] = $args['cobrand'] == 'paypalcanada' ? "Canada" : "UK";
     }
     $args['pagenum'] = any($analytics->pandora_result['page_num'], 1);
     $args['version'] = any(ABTestManager::getVersion(), "unknown");
     $args['filters'] = $analytics->qpmreq->filter['brand'] ? '1' : '0';
     $args['filters'] .= $analytics->qpmreq->filter['color'] ? '1' : '0';
     $args['filters'] .= $analytics->qpmreq->filter['storeswithdeals'] ? '1' : '0';
     //(coupons)
     $args['filters'] .= $analytics->qpmquery['headers']['localshopping'] ? '1' : '0';
     //(local)
     $args['filters'] .= $analytics->qpmquery['headers']['market'] == 'green' ? '1' : '0';
     //(green)
     $args['filters'] .= $analytics->qpmreq->filter['minimall'] ? '1' : '0';
     //(marketplaces)
     $args['filters'] .= $analytics->qpmreq->filter['filter']['price'] ? '1' : '0';
     $args['filters'] .= $analytics->qpmreq->filter['sale'] ? '1' : '0';
     $args['filters'] .= $analytics->qpmreq->filter['store'] ? '1' : '0';
     $args['filters'] .= $analytics->qpmreq->filter['freeshipping'] ? '1' : '0';
     $args['alpha'] = $analytics->alpha;
     $args['browse'] = $analytics->browse;
     $session = SessionManager::singleton();
     $args['is_new_user'] = $session->is_new_user;
     $args['is_new_session'] = $session->is_new_session;
     $user = User::singleton();
     $args['is_logged_in'] = $user->isLoggedIn();
     $args['usertype'] = $user->usertype;
     $args['userid'] = $user->userid;
     $args['useremail'] = $user->email;
     $estimated_birth_year = $user->getUserSetting('estimated_birth_year');
     $gender = $user->gender;
     $user_gender = $gender == 'F' ? 'female' : 'male';
     //if($user->getUserSetting("tracking.user.demographics_dimension") != 1) {
     $args['birth_year'] = $estimated_birth_year;
     $args['user_gender'] = $user_gender;
     $location = $user->GetLocation();
     if ($location['city'] && $location['state']) {
         $args['demo_location'] = $location['city'] . ',' . $location['state'];
     }
     //$user->setUserSetting("tracking.user.demographics_dimension", "1");
     //}
     $args['cfg_cobrand'] = $webapp->cfg->servers["cobrand"];
     $args['request_cobrand'] = $webapp->request["args"]["cobrand"];
     //$args['GAenabled'] = 1; //testing only
     if (empty($this->shown["footer"])) {
         // Only allow footer once per page
         $this->shown["footer"] = true;
         return $this->GetComponentResponse("./footer.tpl", $args);
     }
     return "";
 }
Пример #15
0
 function controller_panel($args, $output = "inline")
 {
     $ret = "";
     $selected = $args["selected"];
     $vars["placement"] = $args["placement"];
     // FIXME - we currently don't do anything with placements
     $vars["panel"]["parent"] = any($args["parent"], "");
     if (!empty($vars["panel"]["parent"]) && !empty($args["panelname"])) {
         $vars["panel"]["name"] = $vars["panel"]["parent"] . "." . $args["panelname"];
     } else {
         $vars["panel"]["name"] = $args["type"];
     }
     $vars["panel"]["cfg"] = $this->PanelSort(any($args["panel"], ConfigManager::get("panels.types.{$vars["panel"]["name"]}")));
     $vars["panel"]["id"] = any($args["id"], $vars["panel"]["cfg"]["id"], "tf_utils_panel_" . str_replace(".", "_", $vars["panel"]["name"]));
     $vars["panel"]["type"] = any($args["type"], "panel");
     $vars["panel"]["enabled"] = any($args["enabled"], isset($vars["panel"]["cfg"]["enabled"]) ? $vars["panel"]["cfg"]["enabled"] : true);
     $vars["panel"]["args"] = any($args["panelargs"], array());
     $vars["panel"]["info"] = array("type", $vars["panel"]["type"], "id" => $vars["panel"]["id"], "name" => $vars["panel"]["name"]);
     $vars["panel"]["json_include"] = any($args["json_include"], $vars["panel"]["cfg"]["json_include"], 0);
     $vars["panel"]["json_only"] = any($args["json_only"], $vars["panel"]["cfg"]["json_only"], 0);
     $vars["panel"]["noclear"] = any($vars["panel"]["cfg"]["noclear"], 0);
     $items = $vars["panel"]["cfg"]["items"];
     // If the apicomponent option is set for this panel, execute the specified component
     if (!empty($vars["panel"]["cfg"]["apicomponent"])) {
         $apicomponentargs = array_merge_recursive(any($vars["panel"]["cfg"]["apicomponentargs"], array()), $args);
         if ($output != "html" && $output != "inline" && $output != "popup" && $output != "snip") {
             $ret = ComponentManager::fetch($vars["panel"]["cfg"]["apicomponent"], $apicomponentargs, $output);
         } else {
             $vars["apicomponentoutput"] = ComponentManager::fetch($vars["panel"]["cfg"]["apicomponent"], $apicomponentargs, "data");
         }
     }
     if ($selected && $items[$selected]) {
         foreach ($items as $k => $v) {
             unset($items[$k]["selected"]);
         }
         $items[$selected]["selected"] = "true";
         $vars["panel"]["cfg"]["items"] = $items;
         //print_pre($items);
     }
     if ($args['uid']) {
         $vars['panel']['uid'] = $args['uid'];
         $vars['panel']['cfg']['targetid'] = $vars['panel']['cfg']['targetid'] . '_' . $args['uid'];
     }
     if ($output == "ajax") {
         $ret = array();
         $ajaxpanels = self::PanelFilterAjax($vars["panel"]["cfg"]);
         foreach ($ajaxpanels as $k => $p) {
             if ($p["component"] == "utils.panel") {
                 // Execute subpanels as AJAX requests and merge their results in with ours
                 $subret = ComponentManager::fetch($p["component"], $p["componentargs"], "ajax");
                 $ret = array_merge($ret, $subret);
             } else {
                 $ret[$vars["panel"]["id"] . "_" . $k] = ComponentManager::fetch($p["component"], $p["componentargs"]);
             }
         }
     } else {
         if (empty($ret)) {
             if (!empty($vars["panel"]["enabled"])) {
                 $ret = $this->GetTemplate("./panel.tpl", $vars);
             }
         }
     }
     return $ret;
 }
Пример #16
0
 /**
  * Create component container from description.
  *
  * @param \SimpleXMLElement $containerDescription Container description.
  * @param array $externalParams Additional attributes.
  * @return ComponentContainer
  *
  * @throws SystemException ERR_NO_CONTAINER_NAME
  */
 public static function createFromDescription(\SimpleXMLElement $containerDescription, array $externalParams = [])
 {
     $properties['tag'] = $containerDescription->getName();
     $attributes = $containerDescription->attributes();
     if (in_array($containerDescription->getName(), ['page', 'content'])) {
         $properties['name'] = $properties['tag'];
     } elseif (!isset($attributes['name'])) {
         $properties['name'] = uniqid('name_');
     }
     foreach ($attributes as $propertyName => $propertyValue) {
         $properties[(string) $propertyName] = (string) $propertyValue;
     }
     $name = $properties['name'];
     unset($properties['name']);
     $properties = array_merge($properties, $externalParams);
     $value = null;
     $containerDescriptionValue = trim((string) $containerDescription);
     if (!empty($containerDescriptionValue)) {
         $value = $containerDescriptionValue;
     }
     $result = new ComponentContainer($name, $properties, $value);
     foreach ($containerDescription as $blockDescription) {
         if ($c = ComponentManager::createBlockFromDescription($blockDescription, $externalParams)) {
             $result->add($c);
         }
     }
     return $result;
 }
Пример #17
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);
 }
Пример #18
0
 function HandlePayload(&$args, $output = "inline")
 {
     /*
     if (($path = file_exists_in_path("templates/404.tpl", true)) !== false) {
       return $this->GetTemplate($path . "/templates/404.tpl", $this);
     }
     return $this->GetTemplate("404.tpl", $this);
     */
     return ComponentManager::fetch("elation.404", array("name" => $this->fullname), $output);
 }