Example #1
0
 public function controller_header($args)
 {
     if (empty($this->shown["header"])) {
         // Only allow header once per page
         $this->shown["header"] = true;
         $agents = array('mac', 'windows', 'linux', 'unix', 'android', 'ios', 'ipad', 'iphone', 'ipod', 'mobile', 'webkit', 'chrome', 'firefox', 'msie', 'opera', 'safari');
         $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
         $classes = '';
         for ($i = 1; $i <= count($agents); $i++) {
             if (strpos($useragent, $agents[$i])) {
                 $classes .= ' ' . $agents[$i];
             }
         }
         $args["classes"] = $classes;
         $args["agent"] = $useragent;
         $dependencies = ConfigManager::get("dependencies.load");
         if (!empty($dependencies)) {
             foreach ($dependencies as $dependency) {
                 if (!empty($dependency["enabled"])) {
                     $dependency_args = array();
                     foreach ($dependency["args"] as $dependency_name => $dependency_arg) {
                         $dependency_args[$dependency_name] = $dependency_arg;
                     }
                     DependencyManager::add($dependency_args);
                 }
             }
         }
         $args["native"] = any(ConfigManager::get("native"), array("enabled" => false));
         return $this->GetTemplate("./header.tpl", $args);
     }
     return "";
 }
Example #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);
}
Example #3
0
 /**
  * addAppDependency.
  *
  * @param   string  $extensionmainjs  Param
  * @param   array   &$dependencies    {key2 => {key1, keyi}}
  * @param   array   &$paths           {key1 => pathjs1, key2 => pathjs2}
  *
  * @return	string
  */
 public function addAppDependency($extensionmainjs, &$dependencies = array(), &$paths = array())
 {
     $appName = parent::addAppDependency($extensionmainjs, $dependencies, $paths);
     $this->appPaths = array_merge($this->appPaths, $paths);
     $this->_addDependencyArray($dependencies);
     $moreDependencies = $this->_discoverDependencies($paths);
     $this->_addDependencyArray($moreDependencies);
 }
 /**
  * @covers jk\sys\DependencyManager::register
  */
 public function testRegister2()
 {
     \Yii::$container->clear('jarekkozak\\sys\\IProperties');
     DependencyManager::register(['jarekkozak\\sys\\IProperties' => function () {
         return new \jarekkozak\sys\Properties(['values' => ['prop1' => 'test1']]);
     }]);
     $a = \Yii::$container->get('jarekkozak\\sys\\TestDPM');
     self::assertInstanceOf('jarekkozak\\sys\\Properties', $a->prop);
     self::assertEquals('test1', $a->prop->getProperty('prop1'));
 }
Example #5
0
 public static function loadBasicDummyData()
 {
     TestManager::clearDatabase();
     $database = new DatabaseManager();
     UserManager::verifyTable($database);
     AddonManager::verifyTable($database);
     BoardManager::verifyTable($database);
     TagManager::verifyTable($database);
     GroupManager::verifyTable($database);
     DependencyManager::verifyTable($database);
     CommentManager::verifyTable($database);
     RatingManager::verifyTable($database);
     BuildManager::verifyTable($database);
     StatManager::verifyTable($database);
     ScreenshotManager::verifyTable($database);
     if (!$database->query("INSERT INTO `addon_boards` (name, video, description) VALUES ('General Content', 'general_content_bg', 'Bricks, Events, Sounds, Prints, Environments, and much more!')")) {
         throw new Exception("Database error: " . $database->error());
     }
     if (!$database->query("INSERT INTO `addon_boards` (name, video, description) VALUES ('Minigames', 'minigames_bg', 'Weapons, Vehicles, Gamemodes, and all your gaming needs!')")) {
         throw new Exception("Database error: " . $database->error());
     }
     if (!$database->query("INSERT INTO `addon_boards` (name, video, description) VALUES ('Client Mods', 'client_mods_bg', 'Mods that run on your client.')")) {
         throw new Exception("Database error: " . $database->error());
     }
     if (!$database->query("INSERT INTO `addon_boards` (name, video, description) VALUES ('Bargain Bin', 'bargain_bin_bg', 'A home for \\'special\\' content.')")) {
         throw new Exception("Database error: " . $database->error());
     }
     if (!$database->query("INSERT INTO `users` (username, blid, password, email, salt, verified) VALUES ('testuser', '4833', '1d8436e97ef95a7a6151f47b909167c77cfe1985ee5500efa8d46cfe825abc59', '*****@*****.**', '273eb4', '1')")) {
         throw new Exception("Database error: " . $database->error());
     }
     //the default json types likely need to be reworked
     if (!$database->query("INSERT INTO `addon_addons` (board, blid, name, filename, description, approved, versionInfo, authorInfo, reviewInfo) VALUES ('1', '4833', 'crapy adon', 'sciprt_hax.zip', 'bad addone pls delete', '1', '{}', '[]', '[]')")) {
         throw new Exception("Database error: " . $database->error());
     }
     StatManager::addStatsToAddon(1);
     if (!$database->query("INSERT INTO `addon_tags` (name, base_color, icon) VALUES ('dum tag', 'ff6600', 'brokenimage')")) {
         throw new Exception("Database error: " . $database->error());
     }
     if (!$database->query("INSERT INTO `addon_tagmap` (aid, tid) VALUES ('1', '1')")) {
         throw new Exception("Database error: " . $database->error());
     }
     if (!$database->query("INSERT INTO `group_groups` (leader, name, description, color, icon) VALUES ('4833', 'legion of dumies', 'a group for people who just want to be in a group', '00ff00', 'brokenimage')")) {
         throw new Exception("Database error: " . $database->error());
     }
     if (!$database->query("INSERT INTO `group_usermap` (gid, blid, administrator) VALUES ('1', '4833', '1')")) {
         throw new Exception("Database error: " . $database->error());
     }
     if (!$database->query("INSERT INTO `addon_comments` (blid, aid, comment) VALUES ('4833', '1', 'glorious addon comrade')")) {
         throw new Exception("Database error: " . $database->error());
     }
     if (!$database->query("INSERT INTO `addon_ratings` (blid, aid, rating) VALUES ('4833', '1', '1')")) {
         throw new Exception("Database error: " . $database->error());
     }
 }
Example #6
0
 /**
  * Run any dependency that fields may have
  *
  * @return void
  */
 function updateDependentField($filter_fields = null)
 {
     // This is ignored when coming via a webservice as it's only needed for display and not just raw data.
     // It results in a huge performance gain when pulling multiple records via webservices.
     if (!isset($GLOBALS['service_object']) && !$this->is_updated_dependent_fields) {
         require_once "include/Expressions/DependencyManager.php";
         if (empty($filter_fields)) {
             $filterFields = $this->field_defs;
         } else {
             $filterFields = array_intersect_key($this->field_defs, $filter_fields);
         }
         $deps = DependencyManager::getDependentFieldDependencies($filterFields);
         foreach ($deps as $dep) {
             if ($dep->getFireOnLoad()) {
                 $dep->fire($this);
             }
         }
     }
 }
Example #7
0
<?php

//collects together all the information needed by /addons/addon.php
if (!isset($_GET['id'])) {
    return false;
}
require_once realpath(dirname(__DIR__) . "/class/AddonManager.php");
require_once realpath(dirname(__DIR__) . "/class/UserManager.php");
require_once realpath(dirname(__DIR__) . "/class/TagManager.php");
require_once realpath(dirname(__DIR__) . "/class/DependencyManager.php");
$addon = AddonManager::getFromID($_GET['id'] + 0);
if ($addon === false) {
    return false;
}
$user = UserManager::getFromBLID($addon->blid);
$tagIDs = $addon->getTags();
$dependencyIDs = $addon->getDependencies();
$tags = [];
$dependencies = [];
foreach ($tagIDS as $tid) {
    $tags[] = TagManager::getFromID($tid);
}
foreach ($dependencyIDs as $did) {
    $dependencies[] = DependencyManager::getFromID($did);
}
//to do: replace "downloads" with "stats"
$response = ["addon" => $addon, "user" => $user, "tags" => $tags, "dependencies" => $dependencies, "downloads" => $addon->getTotalDownloads()];
return $response;
Example #8
0
 /**
  * Builds up module client cache files
  *
  * @param array $platforms A list of platforms to build for. Uses the first
  *                         platform in the list as the platform.
  * @param string $type     The type of file to create the cache for.
  * @param array $modules   The module to create the cache for.
  * @param MetaDataContextInterface|null $context Metadata context
  */
 public static function buildModuleClientCache($platforms, $type, $modules = array(), MetaDataContextInterface $context = null, $noCache = false)
 {
     if (is_string($modules)) {
         // They just want one module
         $modules = array($modules);
     } elseif (count($modules) == 0) {
         // They want all of the modules
         $modules = array_keys($GLOBALS['app_list_strings']['moduleList']);
     }
     if (!$context) {
         $context = new MetaDataContextDefault();
     }
     foreach ($modules as $module) {
         $seed = BeanFactory::getBean($module);
         $fileList = self::getClientFiles($platforms, $type, $module, $context, $seed);
         $moduleResults = self::getClientFileContents($fileList, $type, $module, $seed);
         if ($type == "view") {
             foreach ($moduleResults as $view => $defs) {
                 if (!is_array($defs) || empty($seed) || empty($seed->field_defs)) {
                     continue;
                 }
                 $meta = !empty($defs['meta']) ? $defs['meta'] : array();
                 $deps = array_merge(DependencyManager::getDependenciesForFields($seed->field_defs, ucfirst($view) . "View"), DependencyManager::getDependenciesForView($meta, ucfirst($view) . "View", $module));
                 if (!empty($deps)) {
                     if (!isset($meta['dependencies']) || !is_array($meta['dependencies'])) {
                         $moduleResults[$view]['meta']['dependencies'] = array();
                     }
                     foreach ($deps as $dep) {
                         $moduleResults[$view]['meta']['dependencies'][] = $dep->getDefinition();
                     }
                 }
             }
         }
         if ($noCache) {
             return $moduleResults;
         } else {
             $basePath = sugar_cached('modules/' . $module . '/clients/' . $platforms[0]);
             sugar_mkdir($basePath, null, true);
             $output = "<?php\n\$clientCache['" . $module . "']['" . $platforms[0] . "']['" . $type . "'] = " . var_export($moduleResults, true) . ";\n\n";
             sugar_file_put_contents_atomic($basePath . '/' . $type . '.php', $output);
         }
     }
 }
Example #9
0
 /**
  * createDependencyJavascript
  * Builds the javascript required to execute calculated/dependent fields
  * and module-view dependences.
  *
  * @param array $fieldDefs The fields defs for the current module.
  * @param array $viewDefs the viewdefs for the current view.
  * @param string $view the current view type.
  */
 function createDependencyJavascript($fieldDefs, $viewDefs, $view, $module = null)
 {
     //Use a doWhen to wait for the page to be fulled loaded (!SUGAR.util.ajaxCallInProgress())
     // TODO check if this isn't broken...
     $js = "<script type=text/javascript>\n" . "SUGAR.util.doWhen('!SUGAR.util.ajaxCallInProgress()', function(){\n" . "SUGAR.forms.AssignmentHandler.registerView('{$view}');\n";
     if ($view == 'ConvertLead') {
         $fieldDefs = $this->prepareCalculationFields($fieldDefs, $module);
     }
     $js .= DependencyManager::getLinkFields($fieldDefs, $view);
     $dependencies = array_merge(DependencyManager::getDependenciesForFields($fieldDefs, $view), DependencyManager::getDependenciesForView($viewDefs, $view, $module));
     foreach ($dependencies as $dep) {
         $js .= $dep->getJavascript($view);
     }
     //Detail views do not use the view name as the input ID.
     $viewId = $view == "DetailView" ? "{$module}_detailview_tabs" : $view;
     $js .= "\nYAHOO.util.Event.onContentReady('{$viewId}', SUGAR.forms.AssignmentHandler.loadComplete);";
     $js .= "});</script>";
     return $js;
 }
 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;
 }
Example #11
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");
 }
 public function testIsFinishedFunctionality()
 {
     $op1 = new GenericOperation(1);
     $op2 = new GenericOperation(2);
     $dm = new DependencyManager();
     $dm->addOperation($op1);
     $dm->addOperation($op2);
     $dm->addDependencyByOperation($op1, $op2);
     $this->assertFalse($dm->isFinished());
     $dm->markAsExecuted($op1);
     $this->assertFalse($dm->isFinished());
     $dm->markAsExecuted($op2);
     $this->assertTrue($dm->isFinished());
 }
Example #13
0
 public function getDependencies()
 {
     return DependencyManager::getDependenciesFromAddonID($this->id);
 }
 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));
     }
 }
 public static function removeDependencyByAddon($target, $required)
 {
     $database = new DatabaseManager();
     DependencyManager::verifyTable($database);
     $resource = $database->query("SELECT `id` FROM `addon_dependencies` WHERE `target` = '" . $database->sanitize($target->getID()) . "' AND `requirement` = '" . $database->sanitize($required->getID()) . "' LIMIT 1");
     if (!$resource) {
         throw new Exception("Database error: " . $database->error());
     }
     if ($resource->num_rows == 0) {
         $resource->close();
         return false;
     }
     $id = $resource->fetch_object()->id;
     $resource->close();
     //if(!$database->query("DELETE FROM `addon_dependencies` WHERE `target` = '" . $database->sanitize($target->getID()) . "' AND `requirement` = '" . $database->sanitize($required->getID()) . "'")) {
     if (!$database->query("DELETE FROM `addon_dependencies` WHERE `id` = '" . $database->sanitize($id) . "'")) {
         throw new Exception("Error removing dependency entry: " . $database->error());
     }
 }
/**
 * Smarty {dependency} plugin
 *
 * Type:     function<br>
 * Name:     dependency<br>
 * Purpose:  Register a dependency to be printed in the header
 *
 * @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_dependency($args, &$smarty)
{
    DependencyManager::add($args);
}
Example #17
0
foreach ($screenshots as $sid) {
    $ss = ScreenshotManager::getFromId($sid);
    echo "<div style=\"padding: 5px; margin: 10px 10px; background-color: #eee; display:inline-block; width: 128px; vertical-align: middle\">";
    echo "<a target=\"_blank\" href=\"/addons/screenshot.php?id=" . $sid . "\">";
    echo "<img src=\"" . $ss->getThumbUrl() . "\" /></a>";
    echo "</div>";
}
?>
	</div>
	<?php 
$deps = DependencyManager::getDependenciesFromAddonID($_GET['id']);
if (sizeof($deps) > 0) {
    echo "<hr /><div style=\"text-align:center\">";
    echo "<b>This add-on has some dependencies or add-ons that it requires to run:</b><br/><br/>";
    foreach ($deps as $did) {
        $dep = DependencyManager::getFromId($did);
        $rid = $dep->getRequired();
        $requiredAddon = AddonManager::getFromId($rid);
        echo "<div style=\"padding: 10px; background-color: #ffbbbb; display: inline-block; border-radius: 5px\"><a href=\"addon.php?id=" . $requiredAddon->getId() . "\">" . $requiredAddon->getName() . "</a></div>";
    }
    echo "</div>";
}
?>
	<div class="tile">
		<div class="comments" id="commentSection">
			<form action="" method="post">
				<?php 
include realpath(dirname(__DIR__) . "/ajax/getComments.php");
?>
			</form>
		</div>
Example #18
0
 /**
  * initPlatform
  *
  * @param   array  &$dependencies  Param
  * @param   array  &$paths         Param
  *
  * @return	void
  */
 protected function initPlatformNg(&$dependencies, &$paths)
 {
     parent::initPlatformNg($dependencies, $paths);
     $this->_addRequire();
 }
Example #19
0
    /**
     * Called from process(). This method will display the correct javascript.
     */
    protected function _displayJavascript()
    {
        global $locale, $sugar_config, $timedate;
        if ($this->_getOption('show_javascript')) {
            if (!$this->_getOption('show_header')) {
                $langHeader = get_language_header();
                echo <<<EOHTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html {$langHeader}>
<head>
EOHTML;
            }
            $js_vars = array("sugar_cache_dir" => "cache/");
            if (isset($this->bean->module_dir)) {
                $js_vars['module_sugar_grp1'] = $this->bean->module_dir;
            }
            if (isset($_REQUEST['action'])) {
                $js_vars['action_sugar_grp1'] = $_REQUEST['action'];
            }
            echo '<script>jscal_today = 1000*' . $timedate->asUserTs($timedate->getNow()) . '; if(typeof app_strings == "undefined") app_strings = new Array();</script>';
            // Make sure the necessary cache files are in place
            $jsFiles = array("sugar_grp1.js", "sugar_grp1_yui.js", "sugar_grp1_jquery.js");
            ensureJSCacheFilesExist($jsFiles);
            echo getVersionedScript('cache/include/javascript/sugar_grp1_jquery.js');
            echo getVersionedScript('cache/include/javascript/sugar_grp1_yui.js');
            echo getVersionedScript('cache/include/javascript/sugar_grp1.js');
            $version_mark = getVersionedPath(null);
            echo '<script>SUGAR = SUGAR || {}; SUGAR.VERSION_MARK = ' . json_encode($version_mark) . ';</script>';
            // output necessary config js in the top of the page
            $config_js = $this->getSugarConfigJS();
            if (!empty($config_js)) {
                echo "<script>\n" . implode("\n", $config_js) . "</script>\n";
            }
            // CSRF form token
            echo $this->getCsrfFormTokenJscript();
            if (isset($sugar_config['email_sugarclient_listviewmaxselect'])) {
                echo "<script>SUGAR.config.email_sugarclient_listviewmaxselect = {$GLOBALS['sugar_config']['email_sugarclient_listviewmaxselect']};</script>";
            }
            $image_server = defined('TEMPLATE_URL') ? TEMPLATE_URL . '/' : '';
            echo '<script type="text/javascript">SUGAR.themes.image_server="' . $image_server . '";</script>';
            // cn: bug 12274 - create session-stored key to defend against CSRF
            echo '<script type="text/javascript">var name_format = "' . $locale->getLocaleFormatMacro() . '";</script>';
            echo self::getJavascriptValidation();
            if (!is_file(sugar_cached('jsLanguage/') . $GLOBALS['current_language'] . '.js')) {
                require_once 'include/language/jsLanguage.php';
                jsLanguage::createAppStringsCache($GLOBALS['current_language']);
            }
            echo getVersionedScript('cache/jsLanguage/' . $GLOBALS['current_language'] . '.js', $GLOBALS['sugar_config']['js_lang_version']);
            echo $this->_getModLanguageJS();
            echo getVersionedScript('include/javascript/productTour.js');
            if (isset($sugar_config['disc_client']) && $sugar_config['disc_client']) {
                echo getVersionedScript('modules/Sync/headersync.js');
            }
            if (!is_file(sugar_cached("Expressions/functions_cache.js"))) {
                $GLOBALS['updateSilent'] = true;
                include "include/Expressions/updatecache.php";
            }
            if (inDeveloperMode()) {
                echo getVersionedScript('cache/Expressions/functions_cache_debug.js');
            } else {
                echo getVersionedScript('cache/Expressions/functions_cache.js');
            }
            require_once "include/Expressions/DependencyManager.php";
            echo "\n" . '<script type="text/javascript">' . DependencyManager::getJSUserVariables($GLOBALS['current_user']) . "</script>\n";
            //echo out the $js_vars variables as javascript variables
            echo "<script type='text/javascript'>\n";
            foreach ($js_vars as $var => $value) {
                echo "var {$var} = '{$value}';\n";
            }
            echo "</script>\n";
        }
    }
Example #20
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");
 }
Example #21
0
 /**
 * takes in a seed and creates the list view query based off of that seed
 * if the $limit value is set to -1 then it will use the default limit and offset values
 *
 * it will return an array with two key values
 * 	1. 'data'=> this is an array of row data
 *  2. 'pageData'=> this is an array containg three values
 * 			a.'ordering'=> array('orderBy'=> the field being ordered by , 'sortOrder'=> 'ASC' or 'DESC')
 * 			b.'urls'=>array('baseURL'=>url used to generate other urls ,
 * 							'orderBy'=> the base url for order by
 * 							//the following may not be set (so check empty to see if they are set)
 * 							'nextPage'=> the url for the next group of results,
 * 							'prevPage'=> the url for the prev group of results,
 * 							'startPage'=> the url for the start of the group,
 * 							'endPage'=> the url for the last set of results in the group
 * 			c.'offsets'=>array(
 * 								'current'=>current offset
 * 								'next'=> next group offset
 * 								'prev'=> prev group offset
 * 								'end'=> the offset of the last group
 * 								'total'=> the total count (only accurate if totalCounted = true otherwise it is either the total count if less than the limit or the total count + 1 )
 * 								'totalCounted'=> if a count query was used to get the total count
 *
 * @param SugarBean $seed
 * @param string $where
 * @param int:0 $offset
 * @param int:-1 $limit
 * @param string[]:array() $filter_fields
 * @param array:array() $params
 * 	Potential $params are
 		$params['distinct'] = use distinct key word
 		$params['include_custom_fields'] = (on by default)
         $params['custom_XXXX'] = append custom statements to query
 * @param string:'id' $id_field
 * @return array('data'=> row data, 'pageData' => page data information, 'query' => original query string)
 */
 function getListViewData($seed, $where, $offset = -1, $limit = -1, $filter_fields = array(), $params = array(), $id_field = 'id', $singleSelect = true)
 {
     global $current_user;
     SugarVCR::erase($seed->module_dir);
     $this->seed = $seed;
     $totalCounted = empty($GLOBALS['sugar_config']['disable_count_query']);
     $_SESSION['MAILMERGE_MODULE_FROM_LISTVIEW'] = $seed->module_dir;
     if (empty($_REQUEST['action']) || $_REQUEST['action'] != 'Popup') {
         $_SESSION['MAILMERGE_MODULE'] = $seed->module_dir;
     }
     $this->setVariableName($seed->object_name, $where, $this->listviewName);
     $this->seed->id = '[SELECT_ID_LIST]';
     // if $params tell us to override all ordering
     if (!empty($params['overrideOrder']) && !empty($params['orderBy'])) {
         $order = $this->getOrderBy(strtolower($params['orderBy']), empty($params['sortOrder']) ? '' : $params['sortOrder']);
         // retreive from $_REQUEST
     } else {
         $order = $this->getOrderBy();
         // retreive from $_REQUEST
     }
     // still empty? try to use settings passed in $param
     if (empty($order['orderBy']) && !empty($params['orderBy'])) {
         $order['orderBy'] = $params['orderBy'];
         $order['sortOrder'] = empty($params['sortOrder']) ? '' : $params['sortOrder'];
     }
     //rrs - bug: 21788. Do not use Order by stmts with fields that are not in the query.
     // Bug 22740 - Tweak this check to strip off the table name off the order by parameter.
     // Samir Gandhi : Do not remove the report_cache.date_modified condition as the report list view is broken
     $orderby = $order['orderBy'];
     if (strpos($order['orderBy'], '.') && $order['orderBy'] != "report_cache.date_modified") {
         $orderby = substr($order['orderBy'], strpos($order['orderBy'], '.') + 1);
     }
     if ($orderby != 'date_entered' && !in_array($orderby, array_keys($filter_fields))) {
         $order['orderBy'] = '';
         $order['sortOrder'] = '';
     }
     if (empty($order['orderBy'])) {
         $orderBy = '';
     } else {
         $orderBy = $order['orderBy'] . ' ' . $order['sortOrder'];
         //wdong, Bug 25476, fix the sorting problem of Oracle.
         if (isset($params['custom_order_by_override']['ori_code']) && $order['orderBy'] == $params['custom_order_by_override']['ori_code']) {
             $orderBy = $params['custom_order_by_override']['custom_code'] . ' ' . $order['sortOrder'];
         }
     }
     if (empty($params['skipOrderSave'])) {
         // don't save preferences if told so
         $current_user->setPreference('listviewOrder', $order, 0, $this->var_name);
         // save preference
     }
     if ($seed->isFavoritesEnabled()) {
         $params['favorites'] = !empty($_REQUEST['my_favorites']) ? 2 : 1;
     }
     //Make sure all dependent fields have thier required data
     require_once "include/Expressions/DependencyManager.php";
     $triggers = DependencyManager::getDependentFieldTriggerFields($filter_fields, $this->seed->field_defs);
     foreach ($triggers as $field) {
         $filter_fields[$field] = true;
     }
     // If $params tells us to override for the special last_name, first_name sorting
     if (!empty($params['overrideLastNameOrder']) && $order['orderBy'] == 'last_name') {
         $orderBy = 'last_name ' . $order['sortOrder'] . ', first_name ' . $order['sortOrder'];
     }
     $ret_array = $seed->create_new_list_query($orderBy, $where, $filter_fields, $params, 0, '', true, $seed, $singleSelect);
     $ret_array['inner_join'] = '';
     if (!empty($this->seed->listview_inner_join)) {
         $ret_array['inner_join'] = ' ' . implode(' ', $this->seed->listview_inner_join) . ' ';
     }
     if (!is_array($params)) {
         $params = array();
     }
     if (!isset($params['custom_select'])) {
         $params['custom_select'] = '';
     }
     if (!isset($params['custom_from'])) {
         $params['custom_from'] = '';
     }
     if (!isset($params['custom_where'])) {
         $params['custom_where'] = '';
     }
     if (!isset($params['custom_order_by'])) {
         $params['custom_order_by'] = '';
     }
     $main_query = $ret_array['select'] . $params['custom_select'] . $ret_array['from'] . $params['custom_from'] . $ret_array['inner_join'] . $ret_array['where'] . $params['custom_where'] . $ret_array['order_by'] . $params['custom_order_by'];
     //Prevent multiple (same) ACLAccess calls
     $seedACL['ListView'] = $this->seed->ACLAccess('ListView');
     //C.L. - Fix for 23461
     if (empty($_REQUEST['action']) || $_REQUEST['action'] != 'Popup') {
         $_SESSION['export_where'] = $ret_array['where'];
     }
     if ($limit < -1) {
         $result = $this->db->query($main_query);
     } else {
         if ($limit == -1) {
             $limit = $this->getLimit();
         }
         $dyn_offset = $this->getOffset();
         if ($dyn_offset > 0 || !is_int($dyn_offset)) {
             $offset = $dyn_offset;
         }
         if (strcmp($offset, 'end') == 0) {
             $totalCount = $this->getTotalCount($main_query);
             $offset = floor(($totalCount - 1) / $limit) * $limit;
         }
         if ($seedACL['ListView']) {
             $result = $this->db->limitQuery($main_query, $offset, $limit + 1);
         } else {
             $result = array();
         }
     }
     $data = array();
     $temp = clone $seed;
     $rows = array();
     $count = 0;
     $idIndex = array();
     $id_list = '';
     while (($row = $this->db->fetchByAssoc($result)) != null) {
         if ($count < $limit) {
             $id_list .= ',\'' . $row[$id_field] . '\'';
             $idIndex[$row[$id_field]][] = count($rows);
             $rows[] = $seed->convertRow($row);
         }
         $count++;
     }
     if (!empty($id_list)) {
         $id_list = '(' . substr($id_list, 1) . ')';
     }
     SugarVCR::store($this->seed->module_dir, $main_query);
     if ($count != 0) {
         //NOW HANDLE SECONDARY QUERIES
         if (!empty($ret_array['secondary_select'])) {
             $secondary_query = $ret_array['secondary_select'] . $ret_array['secondary_from'] . ' WHERE ' . $this->seed->table_name . '.id IN ' . $id_list;
             if (isset($ret_array['order_by'])) {
                 $secondary_query .= ' ' . $ret_array['order_by'];
             }
             $secondary_result = $this->db->query($secondary_query);
             $ref_id_count = array();
             while ($row = $this->db->fetchByAssoc($secondary_result)) {
                 $ref_id_count[$row['ref_id']][] = true;
                 foreach ($row as $name => $value) {
                     //add it to every row with the given id
                     foreach ($idIndex[$row['ref_id']] as $index) {
                         $rows[$index][$name] = $value;
                     }
                 }
             }
             $rows_keys = array_keys($rows);
             foreach ($rows_keys as $key) {
                 $rows[$key]['secondary_select_count'] = count($ref_id_count[$rows[$key]['ref_id']]);
             }
         }
         // retrieve parent names
         if (!empty($filter_fields['parent_name']) && !empty($filter_fields['parent_id']) && !empty($filter_fields['parent_type'])) {
             foreach ($idIndex as $id => $rowIndex) {
                 if (!isset($post_retrieve[$rows[$rowIndex[0]]['parent_type']])) {
                     $post_retrieve[$rows[$rowIndex[0]]['parent_type']] = array();
                 }
                 if (!empty($rows[$rowIndex[0]]['parent_id'])) {
                     $post_retrieve[$rows[$rowIndex[0]]['parent_type']][] = array('child_id' => $id, 'parent_id' => $rows[$rowIndex[0]]['parent_id'], 'parent_type' => $rows[$rowIndex[0]]['parent_type'], 'type' => 'parent');
                 }
             }
             if (isset($post_retrieve)) {
                 $parent_fields = $seed->retrieve_parent_fields($post_retrieve);
                 foreach ($parent_fields as $child_id => $parent_data) {
                     //add it to every row with the given id
                     foreach ($idIndex[$child_id] as $index) {
                         $rows[$index]['parent_name'] = $parent_data['parent_name'];
                     }
                 }
             }
         }
         $pageData = array();
         reset($rows);
         $additionalDetailsFile = SugarAutoLoader::existingCustomOne('modules/' . $seed->module_dir . '/metadata/additionalDetails.php');
         while ($row = current($rows)) {
             $temp = clone $seed;
             $dataIndex = count($data);
             if (!isset($temp->custom_fields) && empty($temp->disable_custom_fields)) {
                 $temp->setupCustomFields($temp->module_dir);
             }
             $temp->loadFromRow($row);
             if ($idIndex[$row[$id_field]][0] == $dataIndex) {
                 $pageData['tag'][$dataIndex] = $temp->listviewACLHelper();
             } else {
                 $pageData['tag'][$dataIndex] = $pageData['tag'][$idIndex[$row[$id_field]][0]];
             }
             $temp->updateDependentFieldForListView('', $filter_fields);
             $data[$dataIndex] = $temp->get_list_view_data($filter_fields);
             if ($temp->isFavoritesEnabled()) {
                 $data[$dataIndex]['star'] = SugarFavorites::generateStar(!empty($row['my_favorite']), $temp->module_dir, $temp->id);
             }
             $temp->ACLFilterFieldList($data[$dataIndex]);
             //Preventing multiple (same) ACLAccess calls
             $tempACL['EditView'] = $temp->ACLAccess('EditView');
             $tempACL['DetailView'] = $temp->ACLAccess('DetailView');
             $pageData['rowAccess'][$dataIndex] = array('view' => $tempACL['DetailView'], 'edit' => $tempACL['EditView']);
             $additionalDetailsAllow = $this->additionalDetails && $tempACL['DetailView'] && !empty($additionalDetailsFile);
             //if($additionalDetailsAllow) $pageData['additionalDetails'] = array();
             $additionalDetailsEdit = $tempACL['EditView'];
             if ($additionalDetailsAllow) {
                 if ($this->additionalDetailsAjax) {
                     $ar = $this->getAdditionalDetailsAjax($data[$dataIndex]['ID']);
                 } else {
                     require_once $additionalDetailsFile;
                     $ar = $this->getAdditionalDetails($data[$dataIndex], (empty($this->additionalDetailsFunction) ? 'additionalDetails' : $this->additionalDetailsFunction) . $this->seed->object_name, $additionalDetailsEdit);
                 }
                 $pageData['additionalDetails'][$dataIndex] = $ar['string'];
                 $pageData['additionalDetails']['fieldToAddTo'] = $ar['fieldToAddTo'];
             }
             next($rows);
         }
     }
     $nextOffset = -1;
     $prevOffset = -1;
     $endOffset = -1;
     if ($count > $limit) {
         $nextOffset = $offset + $limit;
     }
     if ($offset > 0) {
         $prevOffset = $offset - $limit;
         if ($prevOffset < 0) {
             $prevOffset = 0;
         }
     }
     $totalCount = $count + $offset;
     if ($count >= $limit && $totalCounted) {
         $totalCount = $this->getTotalCount($main_query);
     }
     SugarVCR::recordIDs($this->seed->module_dir, array_keys($idIndex), $offset, $totalCount);
     $module_names = array('Prospects' => 'Targets');
     $endOffset = floor(($totalCount - 1) / $limit) * $limit;
     $pageData['ordering'] = $order;
     $pageData['ordering']['sortOrder'] = $this->getReverseSortOrder($pageData['ordering']['sortOrder']);
     //get url parameters as an array
     $pageData['queries'] = $this->generateQueries($pageData['ordering']['sortOrder'], $offset, $prevOffset, $nextOffset, $endOffset, $totalCounted);
     //join url parameters from array to a string
     $pageData['urls'] = $this->generateURLS($pageData['queries']);
     $pageData['offsets'] = array('current' => $offset, 'next' => $nextOffset, 'prev' => $prevOffset, 'end' => $endOffset, 'total' => $totalCount, 'totalCounted' => $totalCounted);
     $pageData['bean'] = array('objectName' => $seed->object_name, 'moduleDir' => $seed->module_dir, 'moduleName' => strtr($seed->module_dir, $module_names), 'moduleTitle' => isset($seed->module_title) ? $seed->module_title : null, 'parentTitle' => isset($seed->parent_title) ? $seed->parent_title : null, 'parentModuleDir' => isset($seed->parent_module_dir) ? $seed->parent_module_dir : null, 'createAction' => isset($seed->create_action) ? $seed->create_action : 'EditView', 'showLink' => isset($seed->show_link) ? $seed->show_link : null, 'importable' => $seed->importable);
     $pageData['stamp'] = $this->stamp;
     $pageData['access'] = array('view' => $this->seed->ACLAccess('DetailView'), 'edit' => $this->seed->ACLAccess('EditView'));
     $pageData['idIndex'] = $idIndex;
     if (!$seedACL['ListView']) {
         $pageData['error'] = 'ACL restricted access';
     }
     $queryString = '';
     if (isset($_REQUEST["searchFormTab"]) && $_REQUEST["searchFormTab"] == "advanced_search" || isset($_REQUEST["type_basic"]) && (count($_REQUEST["type_basic"] > 1) || $_REQUEST["type_basic"][0] != "") || isset($_REQUEST["module"]) && $_REQUEST["module"] == "MergeRecords") {
         $queryString = "-advanced_search";
     } else {
         if (isset($_REQUEST["searchFormTab"]) && $_REQUEST["searchFormTab"] == "basic_search") {
             if ($seed->module_dir == "Reports") {
                 $searchMetaData = SearchFormReports::retrieveReportsSearchDefs();
             } else {
                 $searchMetaData = SearchForm::retrieveSearchDefs($seed->module_dir);
             }
             $basicSearchFields = array();
             if (isset($searchMetaData['searchdefs']) && isset($searchMetaData['searchdefs'][$seed->module_dir]['layout']['basic_search'])) {
                 $basicSearchFields = $searchMetaData['searchdefs'][$seed->module_dir]['layout']['basic_search'];
             }
             foreach ($basicSearchFields as $basicSearchField) {
                 $field_name = is_array($basicSearchField) && isset($basicSearchField['name']) ? $basicSearchField['name'] : $basicSearchField;
                 $field_name .= "_basic";
                 if (isset($_REQUEST[$field_name]) && (!is_array($basicSearchField) || !isset($basicSearchField['type']) || $basicSearchField['type'] == 'text' || $basicSearchField['type'] == 'name')) {
                     $queryString = $_REQUEST[$field_name];
                     break;
                 }
             }
         }
     }
     return array('data' => $data, 'pageData' => $pageData, 'query' => $queryString);
 }