Inheritance: implements Behat\Behat\Context\Context, implements PhpSpec\Matcher\MatchersProviderInterface
Exemple #1
0
function ShowExamples($oP, $sExpression)
{
    $bUsingExample = false;
    $aExamples = array('Pedagogic examples' => array("Web applications" => "SELECT WebApplication", "Person having an 'A' in their name" => "SELECT Person AS B WHERE B.name LIKE '%A%'", "Servers having a name like dbserver1.demo.com or dbserver023.foo.fr" => "SELECT Server WHERE name REGEXP '^dbserver[0-9]+\\\\..+\\\\.[a-z]{2,3}\$'", "Changes planned on new year's day" => "SELECT Change AS ch WHERE ch.start_date >= '2009-12-31' AND ch.end_date <= '2010-01-01'", "IPs in a range" => "SELECT DatacenterDevice AS dev WHERE INET_ATON(dev.managementip) > INET_ATON('10.22.32.224') AND INET_ATON(dev.managementip) < INET_ATON('10.22.32.255')", "Persons below a given root organization" => "SELECT Person AS P JOIN Organization AS Node ON P.org_id = Node.id JOIN Organization AS Root ON Node.parent_id BELOW Root.id WHERE Root.id=1"), 'Usefull examples' => array("NW interfaces of equipment in production for customer 'Demo'" => "SELECT PhysicalInterface AS if JOIN DatacenterDevice AS dev ON if.connectableci_id = dev.id WHERE dev.status = 'production' AND dev.organization_name = 'Demo'", "My tickets" => "SELECT Ticket AS t WHERE t.agent_id = :current_contact_id", "People being owner of an active ticket" => "SELECT Person AS p JOIN UserRequest AS u ON u.agent_id = p.id WHERE u.status != 'closed'", "Contracts terminating in the next thirty days" => "SELECT Contract AS c WHERE c.end_date > NOW() AND c.end_date < DATE_ADD(NOW(), INTERVAL 30 DAY)", "Orphan tickets (opened one hour ago, still not assigned)" => "SELECT UserRequest AS u WHERE u.start_date < DATE_SUB(NOW(), INTERVAL 60 MINUTE) AND u.status = 'new'", "Long lasting incidents (duration > 8 hours)" => "SELECT UserRequest AS u WHERE u.close_date > DATE_ADD(u.start_date, INTERVAL 8 HOUR)"));
    $aDisplayData = array();
    $oAppContext = new ApplicationContext();
    $sContext = $oAppContext->GetForForm();
    foreach ($aExamples as $sTopic => $aQueries) {
        foreach ($aQueries as $sDescription => $sOql) {
            $sHighlight = '';
            $sDisable = '';
            if ($sOql == $sExpression) {
                // this one is currently being tested, highlight it
                $sHighlight = "background-color:yellow;";
                $sDisable = 'disabled';
                // and remember we are testing a query of the list
                $bUsingExample = true;
            }
            //$aDisplayData[$sTopic][] = array(
            $aDisplayData[Dict::S('UI:RunQuery:QueryExamples')][] = array('desc' => "<div style=\"{$sHighlight}\">" . htmlentities($sDescription, ENT_QUOTES, 'UTF-8') . "</div>", 'oql' => "<div style=\"{$sHighlight}\">" . htmlentities($sOql, ENT_QUOTES, 'UTF-8') . "</div>", 'go' => "<form method=\"get\"><input type=\"hidden\" name=\"expression\" value=\"{$sOql}\"><input type=\"submit\" value=\"" . Dict::S('UI:Button:Test') . "\" {$sDisable}>{$sContext}</form>\n");
        }
    }
    $aDisplayConfig = array();
    $aDisplayConfig['desc'] = array('label' => Dict::S('UI:RunQuery:HeaderPurpose'), 'description' => Dict::S('UI:RunQuery:HeaderPurpose+'));
    $aDisplayConfig['oql'] = array('label' => Dict::S('UI:RunQuery:HeaderOQLExpression'), 'description' => Dict::S('UI:RunQuery:HeaderOQLExpression+'));
    $aDisplayConfig['go'] = array('label' => '', 'description' => '');
    foreach ($aDisplayData as $sTopic => $aQueriesDisplayData) {
        $bShowOpened = $bUsingExample;
        $oP->StartCollapsibleSection($sTopic, $bShowOpened);
        $oP->table($aDisplayConfig, $aQueriesDisplayData);
        $oP->EndCollapsibleSection();
    }
}
 public function testLoadIniFile()
 {
     $this->loader->addConfig(__DIR__ . '/contextLoad.xml');
     $this->assertEquals('value', $this->context->getIniValue('section.name'));
     $this->assertEquals(array('value1', 'value2'), $this->context->getIniValue('section.table'));
     $this->assertEquals('root', $this->context->getIniValue('db.login'));
     $this->assertEquals('', $this->context->getIniValue('db.password'));
 }
 public function testImport()
 {
     $this->loader->addConfig(__DIR__ . '/contextLoad.xml');
     $bean = $this->context->getBeanDefinition('test9');
     $this->assertNotNull($bean);
     $this->assertInstanceOf('\\org\\equinox\\ioc\\BeanDefinition', $bean);
     $this->assertEquals('TestClass9', $bean->getClassName());
 }
 /**
  * Evaluate the value definition that can be find in a property definition
  * @param string $this->value check is the value contenu somthing like ${properyName} and replace the value if needed
  * @return String
  */
 protected function getValueProperty(ApplicationContext $context, $value)
 {
     if (strpos($value, '${') === 0) {
         $len = strlen($value);
         if (strrpos($value, '}') === $len - 1) {
             $propertyName = substr($value, 2, $len - 3);
             return $context->getIniValue($propertyName);
         }
     }
     return $this->value;
 }
 /**
  * 获得应用程序上下文实例
  */
 public static function getContext()
 {
     if (is_null(self::$instance) || !isset(self::$instance)) {
         self::$instance = new self();
     }
     return self::$instance;
 }
 /**
  * Add a new bean to the definition liste
  * @param $bean SimpleXMLElement
  * @return unknown_type
  */
 private function addBean(\SimpleXMLElement $bean, $xmlFile)
 {
     $compo = new Component();
     $compo->doNode($bean);
     $this->context->addComponents($compo);
     return;
 }
Exemple #7
0
/**
 * Adds the context parameters to the audit query
 */
function FilterByContext(DBSearch &$oFilter, ApplicationContext $oAppContext)
{
    $sObjClass = $oFilter->GetClass();
    $aContextParams = $oAppContext->GetNames();
    $aCallSpec = array($sObjClass, 'MapContextParam');
    if (is_callable($aCallSpec)) {
        foreach ($aContextParams as $sParamName) {
            $sValue = $oAppContext->GetCurrentValue($sParamName, null);
            if ($sValue != null) {
                $sAttCode = call_user_func($aCallSpec, $sParamName);
                // Returns null when there is no mapping for this parameter
                if ($sAttCode != null && MetaModel::IsValidAttCode($sObjClass, $sAttCode)) {
                    // Check if the condition points to a hierarchical key
                    if ($sAttCode == 'id') {
                        // Filtering on the objects themselves
                        $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($sObjClass);
                        if ($sHierarchicalKeyCode !== false) {
                            $oRootFilter = new DBObjectSearch($sObjClass);
                            $oRootFilter->AddCondition($sAttCode, $sValue);
                            $oFilter->AddCondition_PointingTo($oRootFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW);
                            // Use the 'below' operator by default
                            $bConditionAdded = true;
                        }
                    } else {
                        $oAttDef = MetaModel::GetAttributeDef($sObjClass, $sAttCode);
                        $bConditionAdded = false;
                        if ($oAttDef->IsExternalKey()) {
                            $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
                            if ($sHierarchicalKeyCode !== false) {
                                $oRootFilter = new DBObjectSearch($oAttDef->GetTargetClass());
                                $oRootFilter->AddCondition('id', $sValue);
                                $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
                                $oHKFilter->AddCondition_PointingTo($oRootFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW);
                                // Use the 'below' operator by default
                                $oFilter->AddCondition_PointingTo($oHKFilter, $sAttCode);
                                $bConditionAdded = true;
                            }
                        }
                    }
                    if (!$bConditionAdded) {
                        $oFilter->AddCondition($sAttCode, $sValue);
                    }
                }
            }
        }
    }
}
 public function testStaticProperty()
 {
     $this->loader->addConfig(__DIR__ . '/contextStaticProperty.xml');
     $bean = $this->context->getBeanDefinition('test3');
     $this->assertInstanceOf('\\org\\equinox\\ioc\\BeanDefinition', $bean);
     $properties = $bean->getProperties();
     $this->assertInternalType('array', $properties);
     $this->assertEquals(4, count($properties));
     $prop = new BeanProperty();
     $expected = array(array('name' => 'prop1', 'value' => 'biloubila', 'ref' => null), array('name' => 'prop2', 'value' => '<bold>créée</bold>', 'ref' => null), array('name' => 'prop66', 'value' => null, 'ref' => 'otherBean'), array('name' => 'dataSource', 'value' => null, 'ref' => 'dsn'));
     for ($i = 0; $i < 4; $i++) {
         $prop = $properties[$i];
         $this->assertInstanceOf('\\org\\equinox\\ioc\\BeanProperty', $prop);
         $this->assertEquals($expected[$i]['name'], $prop->getName());
         $this->assertEquals($expected[$i]['value'], $prop->getValue());
         $this->assertEquals($expected[$i]['ref'], $prop->getRef());
     }
 }
Exemple #9
0
 /**
  * 加载配置文件
  */
 public static function loadConfig()
 {
     $context = ApplicationContext::getContext();
     $constants = get_defined_constants(true);
     foreach ($constants['user'] as $key => $val) {
         Config::$key($val);
     }
     include_once Config::SITE_CONF() . "/sherry.conf.php";
     $map = new ControllerMap();
     $map->setPackages($packages);
     $context->setControllerMap($map);
 }
Exemple #10
0
 public function run()
 {
     require dirname(__FILE__) . '/init.php';
     try {
         ConfLoader::loadConfig();
         $context = ApplicationContext::getContext();
         $map = $context->getControllerMap();
         $url = new Url();
         $actionMap = $map->getAction($url->getPackage(), $url->getAction());
         $controller = ControllerFactory::Create($actionMap['class']);
         $actionAppointer = ActionAppointer::getInstance();
         $actionAppointer->setController($controller);
         $actionAppointer->appointer($actionMap);
     } catch (FileException $fe) {
         $fe->getTraceAsString();
     } catch (CheckedException $ce) {
         $ce->getTraceAsString();
     } catch (Exception $e) {
         $e->getTraceAsString();
     }
 }
 /**
  * Load the application context Xml File, if a cache file name is provided
  * check if the context is in cache before loading 
  */
 public function loadContext($configFile, array $includePath, $cacheFile = null)
 {
     $cache = null;
     if ($cacheFile != null) {
         $cache = new \org\equinox\utils\cache\CacheFile();
         $cache->setFileName($cacheFile);
         $cache->load();
         $cachedContext = $cache->get('applicationContext');
         if ($cachedContext != null) {
             $this->context = $cachedContext;
             $this->context->initializeNotLazyBeans();
             return;
         }
     }
     $this->context = new ApplicationContext();
     $loader = new XmlContextLoader($this->context, $includePath);
     $loader->addConfig($configFile);
     if (!empty($cache)) {
         $cache->put('applicationContext', $this->context);
     }
     $this->context->initializeNotLazyBeans();
 }
 /**
  * 
  * @param String $filename réal path of the php file to scan ex: /home/project/src/org/foo/bar.php
  * @param String $namespace the name space of this file ex: org\foo
  * @return void
  * @throws IocException
  */
 protected function scanFile($filename, $namespace)
 {
     if (!is_file($filename)) {
         \org\equinox\utils\Logger::error("({$filename}) is not a file!");
         throw new IocException("({$filename}) is not a file!");
     }
     include_once $filename;
     $name = basename($filename);
     $className = $namespace . '\\' . substr($name, 0, strpos($name, '.'));
     if (class_exists($className)) {
         $ref = new \ReflectionAnnotatedClass($className);
         $listAnnotation = $ref->getAllAnnotations();
         if (empty($listAnnotation)) {
             return;
             // this class is not a Component !
         }
         $bean = new BeanDefinition();
         $bean->setClassName($className);
         foreach ($listAnnotation as $annotation) {
             if ($annotation instanceof annotations\ClassAnnotation) {
                 $annotation->doBean($bean, $className);
             }
         }
         if ($bean->getId() == null) {
             throw new IocException("Equinox annotation found but no @Component annotation found (mandatory) in {$className}");
         }
         $listProperties = $ref->getProperties();
         foreach ($listProperties as $property) {
             $this->doProperty($bean, $property);
         }
         $listMethod = $ref->getMethods();
         foreach ($listMethod as $method) {
             $this->doMethod($bean, $method);
         }
         $this->context->addBeanDefinition($bean);
     }
 }
 /**
  * Add result details - object reference
  *
  * @param string sLabel
  * @param object oObject
  */
 public function AddResultObject($sLabel, $oObject)
 {
     $oAppContext = new ApplicationContext();
     $this->m_aResult[$sLabel] = array('id' => $oObject->GetKey(), 'name' => $oObject->GetRawName(), 'url' => $oAppContext->MakeObjectUrl(get_class($oObject), $oObject->GetKey(), null, false));
 }
Exemple #14
0
        ReportErrorAndExit("Invalid OQL query: '{$sExpression}'.\n" . $e->getMessage());
    } catch (Exception $e) {
        ReportErrorAndExit($e->getMessage());
    }
    exit;
}
/////////////////////////////////////////////////////////////////////////////
//
// Web Server mode
//
/////////////////////////////////////////////////////////////////////////////
try {
    require_once APPROOT . '/application/loginwebpage.class.inc.php';
    LoginWebPage::DoLogin();
    // Check user rights and prompt if needed
    ApplicationContext::SetUrlMakerClass('iTopStandardURLMaker');
    // Main parameters
    $sExpression = utils::ReadParam('expression', null, true, 'raw_data');
    $sQueryId = utils::ReadParam('query', null, true, 'raw_data');
    $sFormat = utils::ReadParam('format', null, true);
    $sFileName = utils::ReadParam('filename', '', true, 'string');
    $bInteractive = utils::ReadParam('interactive', false);
    $sMode = utils::ReadParam('mode', '');
    if ($bInteractive) {
        InteractiveShell($sExpression, $sQueryId, $sFormat, $sFileName, $sMode);
    } else {
        $oExporter = CheckParameters($sExpression, $sQueryId, $sFormat);
        $sMimeType = $oExporter->GetMimeType();
        if ($sMimeType == 'text/html') {
            $oP = new NiceWebPage('iTop export');
            $oP->add_style("body { overflow: auto; }");
 /**
  * Retrieves the currently active menu (if any, otherwise the first menu is the default)
  * @return string The Id of the currently active menu
  */
 public static function GetActiveNodeId()
 {
     $oAppContext = new ApplicationContext();
     $sMenuId = $oAppContext->GetCurrentValue('menu', null);
     if ($sMenuId === null) {
         // Make sure the root menu is sorted on 'rank'
         usort(self::$aRootMenus, array('ApplicationMenu', 'CompareOnRank'));
         $oFirstGroup = self::GetMenuNode(self::$aRootMenus[0]['index']);
         $aChildren = self::$aMenusIndex[$oFirstGroup->GetIndex()]['children'];
         usort($aChildren, array('ApplicationMenu', 'CompareOnRank'));
         $oMenuNode = self::GetMenuNode($aChildren[0]['index']);
         $sMenuId = $oMenuNode->GetMenuId();
     }
     return $sMenuId;
 }
    protected function RenderChart($oPage, $sId, $aValues, $sDrillDown = '', $aRows = array())
    {
        // 1- Compute Open Flash Chart data
        //
        $aValueKeys = array();
        $index = 0;
        if (count($aValues) > 0 && $sDrillDown != '') {
            $oFilter = DBObjectSearch::FromOQL($sDrillDown);
            $sClass = $oFilter->GetClass();
            $sOQLClause = str_replace('SELECT ' . $sClass, '', $sDrillDown);
            $aSQLColNames = array_keys(current($aRows));
            // Read the list of columns from the current (i.e. first) element of the array
            $oAppContext = new ApplicationContext();
            $sURL = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=search_oql&search_form=0&oql_class=' . $sClass . '&format=html&' . $oAppContext->GetForLink() . '&oql_clause=';
        }
        $aURLs = array();
        foreach ($aValues as $key => $value) {
            // Make sure that values are integers (so that max() will work....)
            // and build an array of STRING with the keys (numeric keys are transformed into string by PHP :-(
            $aValues[$key] = (int) $value;
            $aValueKeys[] = (string) $key;
            // Build the custom query for the 'drill down' on each element
            if ($sDrillDown != '') {
                $sFilter = $sOQLClause;
                foreach ($aSQLColNames as $sColName) {
                    $sFilter = str_replace(':' . $sColName, "'" . addslashes($aRows[$key][$sColName]) . "'", $sFilter);
                    $aURLs[$index] = $sURL . urlencode($sFilter);
                }
            }
            $index++;
        }
        $oChart = new open_flash_chart();
        if ($this->m_sType == 'bars') {
            $oChartElement = new bar_glass();
            if (count($aValues) > 0) {
                $maxValue = max($aValues);
            } else {
                $maxValue = 1;
            }
            $oYAxis = new y_axis();
            $aMagicValues = array(1, 2, 5, 10);
            $iMultiplier = 1;
            $index = 0;
            $iTop = $aMagicValues[$index % count($aMagicValues)] * $iMultiplier;
            while ($maxValue > $iTop) {
                $index++;
                $iTop = $aMagicValues[$index % count($aMagicValues)] * $iMultiplier;
                if ($index % count($aMagicValues) == 0) {
                    $iMultiplier = $iMultiplier * 10;
                }
            }
            //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n";
            $oYAxis->set_range(0, $iTop, $iMultiplier);
            $oChart->set_y_axis($oYAxis);
            $aBarValues = array();
            foreach ($aValues as $iValue) {
                $oBarValue = new bar_value($iValue);
                $oBarValue->on_click("ofc_drilldown_{$sId}");
                $aBarValues[] = $oBarValue;
            }
            $oChartElement->set_values($aBarValues);
            //$oChartElement->set_values(array_values($aValues));
            $oXAxis = new x_axis();
            $oXLabels = new x_axis_labels();
            // set them vertical
            $oXLabels->set_vertical();
            // set the label text
            $oXLabels->set_labels($aValueKeys);
            // Add the X Axis Labels to the X Axis
            $oXAxis->set_labels($oXLabels);
            $oChart->set_x_axis($oXAxis);
        } else {
            $oChartElement = new pie();
            $oChartElement->set_start_angle(35);
            $oChartElement->set_animate(true);
            $oChartElement->set_tooltip('#label# - #val# (#percent#)');
            $oChartElement->set_colours(array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664'));
            $aData = array();
            foreach ($aValues as $sValue => $iValue) {
                $oPieValue = new pie_value($iValue, $sValue);
                //@@ BUG: not passed via ajax !!!
                $oPieValue->on_click("ofc_drilldown_{$sId}");
                $aData[] = $oPieValue;
            }
            $oChartElement->set_values($aData);
            $oChart->x_axis = null;
        }
        // Title given in HTML
        //$oTitle = new title($this->m_sTitle);
        //$oChart->set_title($oTitle);
        $oChart->set_bg_colour('#FFFFFF');
        $oChart->add_element($oChartElement);
        $sData = $oChart->toPrettyString();
        $sData = json_encode($sData);
        // 2- Declare the Javascript function that will render the chart data\
        //
        $oPage->add_script(<<<EOF
function ofc_get_data_{$sId}()
{
\treturn {$sData};
}
EOF
);
        if (count($aURLs) > 0) {
            $sURLList = '';
            foreach ($aURLs as $index => $sURL) {
                $sURLList .= "\taURLs[{$index}] = '" . addslashes($sURL) . "';\n";
            }
            $oPage->add_script(<<<EOF
function ofc_drilldown_{$sId}(index)
{
\tvar aURLs = new Array();
{$sURLList}
\tvar sURL = aURLs[index];
\t
\twindow.location.href = sURL; // Navigate ! 
}
EOF
);
        }
        // 3- Insert the Open Flash chart
        //
        $oPage->add("<div id=\"{$sId}\"><div>\n");
        $oPage->add_ready_script(<<<EOF
swfobject.embedSWF(\t"../images/open-flash-chart.swf", 
\t"{$sId}", 
\t"100%", "300","9.0.0",
\t"expressInstall.swf",
\t{"get-data":"ofc_get_data_{$sId}", "id":"{$sId}"}, 
\t{'wmode': 'transparent'}
);
EOF
);
    }
Exemple #17
0
 public function __construct()
 {
     $this->_dataSourceBean = ApplicationContext::getBeanByClass('org.autoset.santorini.BasicDataSource');
 }
 /**
  * Get the form to create a new object of the 'target' class
  */
 public function GetObjectCreationForm(WebPage $oPage, $oCurrObject)
 {
     // Set all the default values in an object and clone this "default" object
     $oNewObj = MetaModel::NewObject($this->sTargetClass);
     // 1st - set context values
     $oAppContext = new ApplicationContext();
     $oAppContext->InitObjectFromContext($oNewObj);
     // 2nd set the default values from the constraint on the external key... if any
     if ($oCurrObject != null && $this->sAttCode != '') {
         $oAttDef = MetaModel::GetAttributeDef(get_class($oCurrObject), $this->sAttCode);
         $aParams = array('this' => $oCurrObject);
         $oSet = $oAttDef->GetAllowedValuesAsObjectSet($aParams);
         $aConsts = $oSet->ListConstantFields();
         $sClassAlias = $oSet->GetFilter()->GetClassAlias();
         if (isset($aConsts[$sClassAlias])) {
             foreach ($aConsts[$sClassAlias] as $sAttCode => $value) {
                 $oNewObj->Set($sAttCode, $value);
             }
         }
     }
     // 3rd - set values from the page argument 'default'
     $oNewObj->UpdateObjectFromArg('default');
     $sDialogTitle = '';
     $oPage->add('<div id="ac_create_' . $this->iId . '"><div class="wizContainer" style="vertical-align:top;"><div id="dcr_' . $this->iId . '">');
     $oPage->add("<h1>" . MetaModel::GetClassIcon($this->sTargetClass) . "&nbsp;" . Dict::Format('UI:CreationTitle_Class', MetaModel::GetName($this->sTargetClass)) . "</h1>\n");
     cmdbAbstractObject::DisplayCreationForm($oPage, $this->sTargetClass, $oNewObj, array(), array('formPrefix' => $this->iId, 'noRelations' => true));
     $oPage->add('</div></div></div>');
     //		$oPage->add_ready_script("\$('#ac_create_$this->iId').dialog({ width: $(window).width()*0.8, height: 'auto', autoOpen: false, modal: true, title: '$sDialogTitle'});\n");
     $oPage->add_ready_script("\$('#ac_create_{$this->iId}').dialog({ width: 'auto', height: 'auto', maxHeight: \$(window).height() - 50, autoOpen: false, modal: true, title: '{$sDialogTitle}'});\n");
     $oPage->add_ready_script("\$('#dcr_{$this->iId} form').removeAttr('onsubmit');");
     $oPage->add_ready_script("\$('#dcr_{$this->iId} form').bind('submit.uilinksWizard', oACWidget_{$this->iId}.DoCreateObject);");
 }
 /**
  * Display the final step of the wizard: a confirmation screen
  */
 public function DisplayFinalStep($iStepIndex, $aFieldsMap)
 {
     $oAppContext = new ApplicationContext();
     $this->m_oPage->add("<div class=\"wizContainer\" id=\"wizStep{$iStepIndex}\" style=\"display:none;\">\n");
     $this->m_oPage->add("<a name=\"step{$iStepIndex}\" />\n");
     $this->m_oPage->P(Dict::S('UI:Wizard:FinalStepTitle'));
     $this->m_oPage->add("<input type=\"hidden\" name=\"operation\" value=\"wizard_apply_new\" />\n");
     $this->m_oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"" . utils::GetNewTransactionId() . "\" />\n");
     $this->m_oPage->add("<input type=\"hidden\" id=\"wizard_json_obj\" name=\"json_obj\" value=\"\" />\n");
     $sScript = "function OnEnterStep{$iStepIndex}() {\n";
     foreach ($aFieldsMap as $iInputId => $sAttCode) {
         $sScript .= "\toWizardHelper.UpdateCurrentValue('{$sAttCode}');\n";
     }
     $sScript .= "\toWizardHelper.Preview('object_preview');\n";
     $sScript .= "\t\$('#wizard_json_obj').val(oWizardHelper.ToJSON());\n";
     $sScript .= "}\n";
     $this->m_oPage->add_script($sScript);
     $this->m_oPage->add("<div id=\"object_preview\">\n");
     $this->m_oPage->add("</div>\n");
     $this->m_oPage->add($oAppContext->GetForForm());
     $this->m_oPage->add("<input type=\"button\" value=\"" . Dict::S('UI:Button:Back') . "\" onClick=\"GoToStep({$iStepIndex}, {$iStepIndex} - 1)\" />");
     $this->m_oPage->add("<input type=\"submit\" value=\"Create " . MetaModel::GetName($this->m_sClass) . "\" />\n");
     $this->m_oPage->add("</div>\n");
     $this->m_oPage->add("</form>\n");
 }
$_SERVER['HTTP_USER_AGENT'] = 'crowdfusion-cli';
$_SERVER['QUERY_STRING'] = '';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['CLI_REQUEST'] = true;
$_SERVER['REQUEST_URI'] = $request_uri;
$_GET = array();
$_POST = array();
if (strpos($request_uri, '?') !== false) {
    $_SERVER['QUERY_STRING'] = substr($request_uri, strpos($request_uri, '?') + 1);
    parse_str($_SERVER['QUERY_STRING'], $_GET);
}
$now = microtime(true);
define('PATH_ROOT_SYM', dirname(__FILE__) . '/');
define('PATH_ROOT', realpath(dirname(__FILE__) . '/'));
define('PATH_BUILD', PATH_ROOT . '/build');
define('PATH_APP', PATH_ROOT . '/app');
define('PATH_SYSTEM', PATH_ROOT . '/system');
require PATH_SYSTEM . '/context/ApplicationContext.php';
$hotDeploy = !$compiled;
//////////////////////
// SYSTEM BOOTSTRAP //
//////////////////////
$contextResources = array(PATH_SYSTEM . '/core', PATH_ROOT . '/crowdfusion', PATH_APP . '/plugins');
$postContextResources = array();
if (!empty($custom_context)) {
    $postContextResources[] = $custom_context;
}
$ApplicationContext = new ApplicationContext($contextResources, $options = array('determineContext' => true, 'hotDeploy' => $hotDeploy, 'cacheDir' => PATH_BUILD . '/deploy/', 'systemFile' => PATH_BUILD . '/system.xml', 'environmentsFile' => PATH_BUILD . '/environments.xml', 'systemContextDir' => PATH_SYSTEM . '/config/context'), $postContextResources);
$Dispatcher = $ApplicationContext->object('Dispatcher');
$Dispatcher->processRequest();
//error_log(((microtime(TRUE) - $now)*1000).'ms, '.$ApplicationContext->getNumInstancesCreated().' instances, mem usage: '.FileSystemUtils::humanFilesize(memory_get_peak_usage(true), 4));
    /**
     * Display the graph inside the given page, with the "filter" drawer above it
     * @param WebPage $oP
     * @param hash $aResults
     * @param string $sRelation
     * @param ApplicationContext $oAppContext
     * @param array $aExcludedObjects
     */
    function Display(WebPage $oP, $aResults, $sRelation, ApplicationContext $oAppContext, $aExcludedObjects = array(), $sObjClass = null, $iObjKey = null, $sContextKey, $aContextParams = array())
    {
        $aContextDefs = static::GetContextDefinitions($sContextKey, true, $aContextParams);
        $aExcludedByClass = array();
        foreach ($aExcludedObjects as $oObj) {
            if (!array_key_exists(get_class($oObj), $aExcludedByClass)) {
                $aExcludedByClass[get_class($oObj)] = array();
            }
            $aExcludedByClass[get_class($oObj)][] = $oObj->GetKey();
        }
        $oP->add("<div class=\"not-printable\">\n");
        $oP->add("<div id=\"ds_flash\" class=\"SearchDrawer\" style=\"display:none;\">\n");
        if (!$oP->IsPrintableVersion()) {
            $oP->add_ready_script(<<<EOF
\t\$( "#tabbedContent_0" ).tabs({ heightStyle: "fill" });
EOF
);
        }
        $oP->add_ready_script(<<<EOF
\t\$("#dh_flash").click( function() {
\t\t\$("#ds_flash").slideToggle('normal', function() { \$("#ds_flash").parent().resize(); \$("#dh_flash").trigger('toggle_complete'); } );
\t\t\$("#dh_flash").toggleClass('open');
\t});
    \$('#ReloadMovieBtn').button().button('disable');
EOF
);
        $aSortedElements = array();
        foreach ($aResults as $sClassIdx => $aObjects) {
            foreach ($aObjects as $oCurrObj) {
                $sSubClass = get_class($oCurrObj);
                $aSortedElements[$sSubClass] = MetaModel::GetName($sSubClass);
            }
        }
        asort($aSortedElements);
        $idx = 0;
        foreach ($aSortedElements as $sSubClass => $sClassName) {
            $oP->add("<span style=\"padding-right:2em; white-space:nowrap;\"><input type=\"checkbox\" id=\"exclude_{$idx}\" name=\"excluded[]\" value=\"{$sSubClass}\" checked onChange=\"\$('#ReloadMovieBtn').button('enable')\"><label for=\"exclude_{$idx}\">&nbsp;" . MetaModel::GetClassIcon($sSubClass) . "&nbsp;{$sClassName}</label></span> ");
            $idx++;
        }
        $oP->add("<p style=\"text-align:right\"><button type=\"button\" id=\"ReloadMovieBtn\" onClick=\"DoReload()\">" . Dict::S('UI:Button:Refresh') . "</button></p>");
        $oP->add("</div>\n");
        $oP->add("<div class=\"HRDrawer\"></div>\n");
        $oP->add("<div id=\"dh_flash\" class=\"DrawerHandle\">" . Dict::S('UI:ElementsDisplayed') . "</div>\n");
        $oP->add("</div>\n");
        // class="not-printable"
        $aAdditionalContexts = array();
        foreach ($aContextDefs as $sKey => $aDefinition) {
            $aAdditionalContexts[] = array('key' => $sKey, 'label' => Dict::S($aDefinition['dict']), 'oql' => $aDefinition['oql'], 'default' => array_key_exists('default', $aDefinition) && $aDefinition['default'] == 'yes');
        }
        $sDirection = utils::ReadParam('d', 'horizontal');
        $iGroupingThreshold = utils::ReadParam('g', 5);
        $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot() . 'js/fraphael.js');
        $oP->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot() . 'css/jquery.contextMenu.css');
        $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot() . 'js/jquery.contextMenu.js');
        $oP->add_linked_script(utils::GetAbsoluteUrlAppRoot() . 'js/simple_graph.js');
        try {
            $this->InitFromGraphviz();
            $sExportAsPdfURL = '';
            $sExportAsPdfURL = utils::GetAbsoluteUrlAppRoot() . 'pages/ajax.render.php?operation=relation_pdf&relation=' . $sRelation . '&direction=' . ($this->bDirectionDown ? 'down' : 'up');
            $oAppcontext = new ApplicationContext();
            $sContext = $oAppContext->GetForLink();
            $sDrillDownURL = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=details&class=%1$s&id=%2$s&' . $sContext;
            $sExportAsDocumentURL = utils::GetAbsoluteUrlAppRoot() . 'pages/ajax.render.php?operation=relation_attachment&relation=' . $sRelation . '&direction=' . ($this->bDirectionDown ? 'down' : 'up');
            $sLoadFromURL = utils::GetAbsoluteUrlAppRoot() . 'pages/ajax.render.php?operation=relation_json&relation=' . $sRelation . '&direction=' . ($this->bDirectionDown ? 'down' : 'up');
            $sAttachmentExportTitle = '';
            if ($sObjClass != null && $iObjKey != null) {
                $oTargetObj = MetaModel::GetObject($sObjClass, $iObjKey, false);
                if ($oTargetObj) {
                    $sAttachmentExportTitle = Dict::Format('UI:Relation:AttachmentExportOptions_Name', $oTargetObj->GetName());
                }
            }
            $sId = 'graph';
            $sStyle = '';
            if ($oP->IsPrintableVersion()) {
                // Optimize for printing on A4/Letter vertically
                $sStyle = 'margin-left:auto; margin-right:auto;';
                $oP->add_ready_script("\$('.simple-graph').width(18/2.54*96).resizable({ stop: function() { \$(window).trigger('resized'); }});");
                // Default width about 18 cm, since most browsers assume 96 dpi
            }
            $oP->add('<div id="' . $sId . '" class="simple-graph" style="' . $sStyle . '"></div>');
            $aParams = array('source_url' => $sLoadFromURL, 'sources' => $this->bDirectionDown ? $this->aSourceObjects : $this->aSinkObjects, 'excluded' => $aExcludedByClass, 'grouping_threshold' => $iGroupingThreshold, 'export_as_pdf' => array('url' => $sExportAsPdfURL, 'label' => Dict::S('UI:Relation:ExportAsPDF')), 'export_as_attachment' => array('url' => $sExportAsDocumentURL, 'label' => Dict::S('UI:Relation:ExportAsAttachment'), 'obj_class' => $sObjClass, 'obj_key' => $iObjKey), 'drill_down' => array('url' => $sDrillDownURL, 'label' => Dict::S('UI:Relation:DrillDown')), 'labels' => array('export_pdf_title' => Dict::S('UI:Relation:PDFExportOptions'), 'export_as_attachment_title' => $sAttachmentExportTitle, 'export' => Dict::S('UI:Button:Export'), 'cancel' => Dict::S('UI:Button:Cancel'), 'title' => Dict::S('UI:RelationOption:Title'), 'untitled' => Dict::S('UI:RelationOption:Untitled'), 'include_list' => Dict::S('UI:RelationOption:IncludeList'), 'comments' => Dict::S('UI:RelationOption:Comments'), 'grouping_threshold' => Dict::S('UI:RelationOption:GroupingThreshold'), 'refresh' => Dict::S('UI:Button:Refresh'), 'check_all' => Dict::S('UI:SearchValue:CheckAll'), 'uncheck_all' => Dict::S('UI:SearchValue:UncheckAll'), 'none_selected' => Dict::S('UI:Relation:NoneSelected'), 'nb_selected' => Dict::S('UI:SearchValue:NbSelected'), 'additional_context_info' => Dict::S('UI:Relation:AdditionalContextInfo'), 'zoom' => Dict::S('UI:Relation:Zoom'), 'loading' => Dict::S('UI:Loading')), 'page_format' => array('label' => Dict::S('UI:Relation:PDFExportPageFormat'), 'values' => array('A3' => Dict::S('UI:PageFormat_A3'), 'A4' => Dict::S('UI:PageFormat_A4'), 'Letter' => Dict::S('UI:PageFormat_Letter'))), 'page_orientation' => array('label' => Dict::S('UI:Relation:PDFExportPageOrientation'), 'values' => array('P' => Dict::S('UI:PageOrientation_Portrait'), 'L' => Dict::S('UI:PageOrientation_Landscape'))), 'additional_contexts' => $aAdditionalContexts, 'context_key' => $sContextKey);
            if (!extension_loaded('gd')) {
                // PDF export requires GD
                unset($aParams['export_as_pdf']);
            }
            if (!extension_loaded('gd') || is_null($sObjClass) || is_null($iObjKey)) {
                // Export as Attachment requires GD (for building the PDF) AND a valid objclass/objkey couple
                unset($aParams['export_as_attachment']);
            }
            $oP->add_ready_script("\$('#{$sId}').simple_graph(" . json_encode($aParams) . ");");
        } catch (Exception $e) {
            $oP->add('<div>' . $e->getMessage() . '</div>');
        }
        $oP->add_script(<<<EOF
\t\t
\tfunction DoReload()
\t{
\t\t\$('#ReloadMovieBtn').button('disable');
\t\ttry
\t\t{
\t\t\tvar aExcluded = [];
\t\t\t\$('input[name^=excluded]').each( function() {
\t\t\t\tif (!\$(this).prop('checked'))
\t\t\t\t{
\t\t\t\t\taExcluded.push(\$(this).val());
\t\t\t\t}
\t\t\t} );
\t\t\t\$('#graph').simple_graph('option', {excluded_classes: aExcluded});
\t\t\t\$('#graph').simple_graph('reload');
\t\t}
\t\tcatch(err)
\t\t{
\t\t\talert(err);
\t\t}
\t}
EOF
);
    }
Exemple #22
0
    return $bRes;
}
///////////////////////////////////////////////////////////////////////////////
//
// Main program
//
///////////////////////////////////////////////////////////////////////////////
try {
    require_once APPROOT . '/application/startup.inc.php';
    require_once APPROOT . '/application/portalwebpage.class.inc.php';
    $oAppContext = new ApplicationContext();
    $sOperation = utils::ReadParam('operation', '');
    require_once APPROOT . '/application/loginwebpage.class.inc.php';
    LoginWebPage::DoLogin(false, true);
    // Check user rights and prompt if needed
    ApplicationContext::SetUrlMakerClass('MyPortalURLMaker');
    $aClasses = explode(',', MetaModel::GetConfig()->Get('portal_tickets'));
    $sMainClass = trim(reset($aClasses));
    if (!class_exists($sMainClass)) {
        $oP = new WebPage(Dict::S('Portal:Title'));
        $oP->p(dict::Format('Portal:NoRequestMgmt', UserRights::GetUserFriendlyName()));
    } else {
        $oUserOrg = GetUserOrg();
        $sCode = $oUserOrg->Get('code');
        $sAlternateStylesheet = '';
        if (@file_exists("./{$sCode}/portal.css")) {
            $sAlternateStylesheet = "{$sCode}";
        }
        $oP = new PortalWebPage(Dict::S('Portal:Title'), $sAlternateStylesheet);
        $oP->EnableDisconnectButton(utils::CanLogOff());
        $oP->SetWelcomeMessage(Dict::Format('Portal:WelcomeUserOrg', UserRights::GetUserFriendlyName(), $oUserOrg->GetName()));
 /**
  * Perform all the needed checks to delete one (or more) objects
  */
 public static function DeleteObjects(WebPage $oP, $sClass, $aObjects, $bPreview, $sCustomOperation, $aContextData = array())
 {
     $oDeletionPlan = new DeletionPlan();
     foreach ($aObjects as $oObj) {
         if ($bPreview) {
             $oObj->CheckToDelete($oDeletionPlan);
         } else {
             $oObj->DBDeleteTracked(CMDBObject::GetCurrentChange(), null, $oDeletionPlan);
         }
     }
     if ($bPreview) {
         if (count($aObjects) == 1) {
             $oObj = $aObjects[0];
             $oP->add("<h1>" . Dict::Format('UI:Delete:ConfirmDeletionOf_Name', $oObj->GetName()) . "</h1>\n");
         } else {
             $oP->add("<h1>" . Dict::Format('UI:Delete:ConfirmDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)) . "</h1>\n");
         }
         // Explain what should be done
         //
         $aDisplayData = array();
         foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes) {
             foreach ($aDeletes as $iId => $aData) {
                 $oToDelete = $aData['to_delete'];
                 $bAutoDel = $aData['mode'] == DEL_SILENT || $aData['mode'] == DEL_AUTO;
                 if (array_key_exists('issue', $aData)) {
                     if ($bAutoDel) {
                         if (isset($aData['requested_explicitely'])) {
                             $sConsequence = Dict::Format('UI:Delete:CannotDeleteBecause', $aData['issue']);
                         } else {
                             $sConsequence = Dict::Format('UI:Delete:ShouldBeDeletedAtomaticallyButNotPossible', $aData['issue']);
                         }
                     } else {
                         $sConsequence = Dict::Format('UI:Delete:MustBeDeletedManuallyButNotPossible', $aData['issue']);
                     }
                 } else {
                     if ($bAutoDel) {
                         if (isset($aData['requested_explicitely'])) {
                             $sConsequence = '';
                             // not applicable
                         } else {
                             $sConsequence = Dict::S('UI:Delete:WillBeDeletedAutomatically');
                         }
                     } else {
                         $sConsequence = Dict::S('UI:Delete:MustBeDeletedManually');
                     }
                 }
                 $aDisplayData[] = array('class' => MetaModel::GetName(get_class($oToDelete)), 'object' => $oToDelete->GetHyperLink(), 'consequence' => $sConsequence);
             }
         }
         foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate) {
             foreach ($aToUpdate as $iId => $aData) {
                 $oToUpdate = $aData['to_reset'];
                 if (array_key_exists('issue', $aData)) {
                     $sConsequence = Dict::Format('UI:Delete:CannotUpdateBecause_Issue', $aData['issue']);
                 } else {
                     $sConsequence = Dict::Format('UI:Delete:WillAutomaticallyUpdate_Fields', $aData['attributes_list']);
                 }
                 $aDisplayData[] = array('class' => MetaModel::GetName(get_class($oToUpdate)), 'object' => $oToUpdate->GetHyperLink(), 'consequence' => $sConsequence);
             }
         }
         $iImpactedIndirectly = $oDeletionPlan->GetTargetCount() - count($aObjects);
         if ($iImpactedIndirectly > 0) {
             if (count($aObjects) == 1) {
                 $oObj = $aObjects[0];
                 $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencing_Object', $iImpactedIndirectly, $oObj->GetName()));
             } else {
                 $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencingTheObjects', $iImpactedIndirectly));
             }
             $oP->p(Dict::S('UI:Delete:ReferencesMustBeDeletedToEnsureIntegrity'));
         }
         if ($iImpactedIndirectly > 0 || $oDeletionPlan->FoundStopper()) {
             $aDisplayConfig = array();
             $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
             $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
             $aDisplayConfig['consequence'] = array('label' => 'Consequence', 'description' => Dict::S('UI:Delete:Consequence+'));
             $oP->table($aDisplayConfig, $aDisplayData);
         }
         if ($oDeletionPlan->FoundStopper()) {
             if ($oDeletionPlan->FoundSecurityIssue()) {
                 $oP->p(Dict::S('UI:Delete:SorryDeletionNotAllowed'));
             } elseif ($oDeletionPlan->FoundManualOperation()) {
                 $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
             } else {
                 $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
             }
             $oAppContext = new ApplicationContext();
             $oP->add("<form method=\"post\">\n");
             $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"" . utils::ReadParam('transaction_id') . "\">\n");
             $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"" . Dict::S('UI:Button:Back') . "\">\n");
             $oP->add("<input DISABLED type=\"submit\" name=\"\" value=\"" . Dict::S('UI:Button:Delete') . "\">\n");
             $oP->add($oAppContext->GetForForm());
             $oP->add("</form>\n");
         } else {
             if (count($aObjects) == 1) {
                 $oObj = $aObjects[0];
                 $id = $oObj->GetKey();
                 $oP->p('<h1>' . Dict::Format('UI:Delect:Confirm_Object', $oObj->GetHyperLink()) . '</h1>');
             } else {
                 $oP->p('<h1>' . Dict::Format('UI:Delect:Confirm_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)) . '</h1>');
             }
             foreach ($aObjects as $oObj) {
                 $aKeys[] = $oObj->GetKey();
             }
             $oFilter = new DBObjectSearch($sClass);
             $oFilter->AddCondition('id', $aKeys, 'IN');
             $oSet = new CMDBobjectSet($oFilter);
             $oP->add('<div id="0">');
             CMDBAbstractObject::DisplaySet($oP, $oSet, array('display_limit' => false, 'menu' => false));
             $oP->add("</div>\n");
             $oP->add("<form method=\"post\">\n");
             foreach ($aContextData as $sKey => $value) {
                 $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"{$value}\">\n");
             }
             $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"" . utils::GetNewTransactionId() . "\">\n");
             $oP->add("<input type=\"hidden\" name=\"operation\" value=\"{$sCustomOperation}\">\n");
             $oP->add("<input type=\"hidden\" name=\"filter\" value=\"" . $oFilter->Serialize() . "\">\n");
             $oP->add("<input type=\"hidden\" name=\"class\" value=\"{$sClass}\">\n");
             foreach ($aObjects as $oObj) {
                 $oP->add("<input type=\"hidden\" name=\"selectObject[]\" value=\"" . $oObj->GetKey() . "\">\n");
             }
             $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"" . Dict::S('UI:Button:Back') . "\">\n");
             $oP->add("<input type=\"submit\" name=\"\" value=\"" . Dict::S('UI:Button:Delete') . "\">\n");
             $oAppContext = new ApplicationContext();
             $oP->add($oAppContext->GetForForm());
             $oP->add("</form>\n");
         }
     } else {
         // Execute the deletion
         //
         if (count($aObjects) == 1) {
             $oObj = $aObjects[0];
             $oP->add("<h1>" . Dict::Format('UI:Title:DeletionOf_Object', $oObj->GetName()) . "</h1>\n");
         } else {
             $oP->add("<h1>" . Dict::Format('UI:Title:BulkDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)) . "</h1>\n");
         }
         // Security - do not allow the user to force a forbidden delete by the mean of page arguments...
         if ($oDeletionPlan->FoundSecurityIssue()) {
             throw new CoreException(Dict::S('UI:Error:NotEnoughRightsToDelete'));
         }
         if ($oDeletionPlan->FoundManualOperation()) {
             throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseManualOpNeeded'));
         }
         if ($oDeletionPlan->FoundManualDelete()) {
             throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseOfDepencies'));
         }
         // Report deletions
         //
         $aDisplayData = array();
         foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes) {
             foreach ($aDeletes as $iId => $aData) {
                 $oToDelete = $aData['to_delete'];
                 if (isset($aData['requested_explicitely'])) {
                     $sMessage = Dict::S('UI:Delete:Deleted');
                 } else {
                     $sMessage = Dict::S('UI:Delete:AutomaticallyDeleted');
                 }
                 $aDisplayData[] = array('class' => MetaModel::GetName(get_class($oToDelete)), 'object' => $oToDelete->GetName(), 'consequence' => $sMessage);
             }
         }
         // Report updates
         //
         foreach ($oDeletionPlan->ListUpdates() as $sTargetClass => $aToUpdate) {
             foreach ($aToUpdate as $iId => $aData) {
                 $oToUpdate = $aData['to_reset'];
                 $aDisplayData[] = array('class' => MetaModel::GetName(get_class($oToUpdate)), 'object' => $oToUpdate->GetHyperLink(), 'consequence' => Dict::Format('UI:Delete:AutomaticResetOf_Fields', $aData['attributes_list']));
             }
         }
         // Report automatic jobs
         //
         if ($oDeletionPlan->GetTargetCount() > 0) {
             if (count($aObjects) == 1) {
                 $oObj = $aObjects[0];
                 $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Object', $oObj->GetName()));
             } else {
                 $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Several_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)));
             }
             $aDisplayConfig = array();
             $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
             $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
             $aDisplayConfig['consequence'] = array('label' => 'Done', 'description' => Dict::S('UI:Delete:Done+'));
             $oP->table($aDisplayConfig, $aDisplayData);
         }
     }
 }
    /**
     * Outputs (via some echo) the complete HTML page by assembling all its elements
     */
    public function output()
    {
        $sAbsURLAppRoot = addslashes($this->m_sRootUrl);
        //$this->set_base($this->m_sRootUrl.'pages/');
        $sForm = $this->GetSiloSelectionForm();
        $this->DisplayMenu();
        // Compute the menu
        // Call the extensions to add content to the page, so that they can also add styles or scripts
        $sBannerExtraHtml = '';
        foreach (MetaModel::EnumPlugins('iPageUIExtension') as $oExtensionInstance) {
            $sBannerExtraHtml .= $oExtensionInstance->GetBannerHtml($this);
        }
        $sNorthPane = '';
        foreach (MetaModel::EnumPlugins('iPageUIExtension') as $oExtensionInstance) {
            $sNorthPane .= $oExtensionInstance->GetNorthPaneHtml($this);
        }
        if (UserRights::IsAdministrator() && ExecutionKPI::IsEnabled()) {
            $sNorthPane .= '<div id="admin-banner"><span style="padding:5px;">' . ExecutionKPI::GetDescription() . '<span></div>';
        }
        //$sSouthPane = '<p>Peak memory Usage: '.sprintf('%.3f MB', memory_get_peak_usage(true) / (1024*1024)).'</p>';
        $sSouthPane = '';
        foreach (MetaModel::EnumPlugins('iPageUIExtension') as $oExtensionInstance) {
            $sSouthPane .= $oExtensionInstance->GetSouthPaneHtml($this);
        }
        // Put here the 'ready scripts' that must be executed after all others
        $aMultiselectOptions = array('header' => true, 'checkAllText' => Dict::S('UI:SearchValue:CheckAll'), 'uncheckAllText' => Dict::S('UI:SearchValue:UncheckAll'), 'noneSelectedText' => Dict::S('UI:SearchValue:Any'), 'selectedText' => Dict::S('UI:SearchValue:NbSelected'), 'selectedList' => 1);
        $sJSMultiselectOptions = json_encode($aMultiselectOptions);
        $this->add_ready_script(<<<EOF
\t\t// Since the event is only triggered when the hash changes, we need to trigger
\t\t// the event now, to handle the hash the page may have loaded with.
\t\t\$(window).trigger( 'hashchange' );
\t\t
\t\t// Some table are sort-able, some are not, let's fix this
\t\t\$('table.listResults').each( function() { FixTableSorter(\$(this)); } );
\t\t
\t\t\$('.multiselect').multiselect({$sJSMultiselectOptions});

\t\tFixSearchFormsDisposition();

EOF
);
        if ($this->GetOutputFormat() == 'html') {
            foreach ($this->a_headers as $s_header) {
                header($s_header);
            }
        }
        $s_captured_output = $this->ob_get_clean_safe();
        $sHtml = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
        $sHtml .= "<html>\n";
        $sHtml .= "<head>\n";
        // Make sure that Internet Explorer renders the page using its latest/highest/greatest standards !
        $sHtml .= "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n";
        $sHtml .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
        $sHtml .= "<title>" . htmlentities($this->s_title, ENT_QUOTES, 'UTF-8') . "</title>\n";
        $sHtml .= $this->get_base_tag();
        // Stylesheets MUST be loaded before any scripts otherwise
        // jQuery scripts may face some spurious problems (like failing on a 'reload')
        foreach ($this->a_linked_stylesheets as $a_stylesheet) {
            if ($a_stylesheet['condition'] != "") {
                $sHtml .= "<!--[if {$a_stylesheet['condition']}]>\n";
            }
            $sHtml .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$a_stylesheet['link']}\" />\n";
            if ($a_stylesheet['condition'] != "") {
                $sHtml .= "<![endif]-->\n";
            }
        }
        // special stylesheet for printing, hides the navigation gadgets
        $sHtml .= "<link rel=\"stylesheet\" media=\"print\" type=\"text/css\" href=\"../css/print.css\" />\n";
        if ($this->GetOutputFormat() == 'html') {
            $sHtml .= $this->output_dict_entries(true);
            // before any script so that they can benefit from the translations
            foreach ($this->a_linked_scripts as $s_script) {
                // Make sure that the URL to the script contains the application's version number
                // so that the new script do NOT get reloaded from the cache when the application is upgraded
                if (strpos($s_script, '?') === false) {
                    $s_script .= "?itopversion=" . ITOP_VERSION;
                } else {
                    $s_script .= "&itopversion=" . ITOP_VERSION;
                }
                $sHtml .= "<script type=\"text/javascript\" src=\"{$s_script}\"></script>\n";
            }
            $this->add_script("var iPaneVisWatchDog  = window.setTimeout('FixPaneVis()',5000);\n\$(document).ready(function() {\n{$this->m_sInitScript};\nwindow.setTimeout('onDelayedReady()',10)\n});");
            if (count($this->m_aReadyScripts) > 0) {
                $this->add_script("\nonDelayedReady = function() {\n" . implode("\n", $this->m_aReadyScripts) . "\n}\n");
            }
            if (count($this->a_scripts) > 0) {
                $sHtml .= "<script type=\"text/javascript\">\n";
                foreach ($this->a_scripts as $s_script) {
                    $sHtml .= "{$s_script}\n";
                }
                $sHtml .= "</script>\n";
            }
        }
        if (count($this->a_styles) > 0) {
            $sHtml .= "<style>\n";
            foreach ($this->a_styles as $s_style) {
                $sHtml .= "{$s_style}\n";
            }
            $sHtml .= "</style>\n";
        }
        $sHtml .= "<link rel=\"search\" type=\"application/opensearchdescription+xml\" title=\"iTop\" href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/opensearch.xml.php\" />\n";
        $sHtml .= "<link rel=\"shortcut icon\" href=\"" . utils::GetAbsoluteUrlAppRoot() . "images/favicon.ico\" />\n";
        $sHtml .= "</head>\n";
        $sHtml .= "<body>\n";
        // Render the revision number
        if (ITOP_REVISION == '$WCREV$') {
            // This is NOT a version built using the buil system, just display the main version
            $sVersionString = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
        } else {
            // This is a build made from SVN, let display the full information
            $sVersionString = Dict::Format('UI:iTopVersion:Long', ITOP_VERSION, ITOP_REVISION, ITOP_BUILD_DATE);
        }
        // Render the text of the global search form
        $sText = htmlentities(utils::ReadParam('text', '', false, 'raw_data'), ENT_QUOTES, 'UTF-8');
        $sOnClick = "";
        if (empty($sText)) {
            // if no search text is supplied then
            // 1) the search text is filled with "your search"
            // 2) clicking on it will erase it
            $sText = Dict::S("UI:YourSearch");
            $sOnClick = " onclick=\"this.value='';this.onclick=null;\"";
        }
        // Render the tabs in the page (if any)
        $this->s_content = $this->m_oTabs->RenderIntoContent($this->s_content);
        if ($this->GetOutputFormat() == 'html') {
            $oAppContext = new ApplicationContext();
            $sUserName = UserRights::GetUser();
            $sIsAdmin = UserRights::IsAdministrator() ? '(Administrator)' : '';
            if (UserRights::IsAdministrator()) {
                $sLogonMessage = Dict::Format('UI:LoggedAsMessage+Admin', $sUserName);
            } else {
                $sLogonMessage = Dict::Format('UI:LoggedAsMessage', $sUserName);
            }
            $sLogOffMenu = "<span id=\"logOffBtn\"><ul><li><img src=\"../images/onOffBtn.png\"><ul>";
            $sLogOffMenu .= "<li><span>{$sLogonMessage}</span></li>\n";
            $aActions = array();
            $oPrefs = new URLPopupMenuItem('UI:Preferences', Dict::S('UI:Preferences'), utils::GetAbsoluteUrlAppRoot() . "pages/preferences.php?" . $oAppContext->GetForLink());
            $aActions[$oPrefs->GetUID()] = $oPrefs->GetMenuItem();
            if (utils::CanLogOff()) {
                $oLogOff = new URLPopupMenuItem('UI:LogOffMenu', Dict::S('UI:LogOffMenu'), utils::GetAbsoluteUrlAppRoot() . 'pages/logoff.php?operation=do_logoff');
                $aActions[$oLogOff->GetUID()] = $oLogOff->GetMenuItem();
            }
            if (UserRights::CanChangePassword()) {
                $oChangePwd = new URLPopupMenuItem('UI:ChangePwdMenu', Dict::S('UI:ChangePwdMenu'), utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?loginop=change_pwd');
                $aActions[$oChangePwd->GetUID()] = $oChangePwd->GetMenuItem();
            }
            utils::GetPopupMenuItems($this, iPopupMenuExtension::MENU_USER_ACTIONS, null, $aActions);
            $oAbout = new JSPopupMenuItem('UI:AboutBox', Dict::S('UI:AboutBox'), 'return ShowAboutBox();');
            $aActions[$oAbout->GetUID()] = $oAbout->GetMenuItem();
            $sLogOffMenu .= $this->RenderPopupMenuItems($aActions);
            $sRestrictions = '';
            if (!MetaModel::DBHasAccess(ACCESS_ADMIN_WRITE)) {
                if (!MetaModel::DBHasAccess(ACCESS_ADMIN_WRITE)) {
                    $sRestrictions = Dict::S('UI:AccessRO-All');
                }
            } elseif (!MetaModel::DBHasAccess(ACCESS_USER_WRITE)) {
                $sRestrictions = Dict::S('UI:AccessRO-Users');
            }
            $sApplicationBanner = '';
            if (strlen($sRestrictions) > 0) {
                $sAdminMessage = trim(MetaModel::GetConfig()->Get('access_message'));
                $sApplicationBanner .= '<div id="admin-banner">';
                $sApplicationBanner .= '<img src="../images/locked.png" style="vertical-align:middle;">';
                $sApplicationBanner .= '&nbsp;<b>' . $sRestrictions . '</b>';
                if (strlen($sAdminMessage) > 0) {
                    $sApplicationBanner .= '&nbsp;<b>' . $sAdminMessage . '</b>';
                }
                $sApplicationBanner .= '</div>';
            }
            if (strlen($this->m_sMessage)) {
                $sApplicationBanner .= '<div id="admin-banner"><span style="padding:5px;">' . $this->m_sMessage . '<span></div>';
            }
            $sApplicationBanner .= $sBannerExtraHtml;
            if (!empty($sNorthPane)) {
                $sNorthPane = '<div id="bottom-pane" class="ui-layout-north">' . $sNorthPane . '</div>';
            }
            if (!empty($sSouthPane)) {
                $sSouthPane = '<div id="bottom-pane" class="ui-layout-south">' . $sSouthPane . '</div>';
            }
            $sIconUrl = Utils::GetConfig()->Get('app_icon_url');
            $sOnlineHelpUrl = MetaModel::GetConfig()->Get('online_help');
            //$sLogOffMenu = "<span id=\"logOffBtn\" style=\"height:55px;padding:0;margin:0;\"><img src=\"../images/onOffBtn.png\"></span>";
            $sDisplayIcon = utils::GetAbsoluteUrlAppRoot() . 'images/itop-logo.png';
            if (file_exists(MODULESROOT . 'branding/main-logo.png')) {
                $sDisplayIcon = utils::GetAbsoluteUrlModulesRoot() . 'branding/main-logo.png';
            }
            $sHtml .= $sNorthPane;
            $sHtml .= '<div id="left-pane" class="ui-layout-west">';
            $sHtml .= '<!-- Beginning of the left pane -->';
            $sHtml .= ' <div class="ui-layout-north">';
            $sHtml .= ' <div id="header-logo">';
            $sHtml .= ' <div id="top-left"></div><div id="logo"><a href="' . htmlentities($sIconUrl, ENT_QUOTES, 'UTF-8') . '"><img src="' . $sDisplayIcon . '" title="' . htmlentities($sVersionString, ENT_QUOTES, 'UTF-8') . '" style="border:0; margin-top:16px; margin-right:40px;"/></a></div>';
            $sHtml .= ' </div>';
            $sHtml .= ' <div class="header-menu">';
            if (!MetaModel::GetConfig()->Get('demo_mode')) {
                $sHtml .= '		<div class="icon ui-state-default ui-corner-all"><span id="tPinMenu" class="ui-icon ui-icon-pin-w">pin</span></div>';
            }
            $sHtml .= '		<div style="text-align:center;">' . self::FilterXSS($sForm) . '</div>';
            $sHtml .= ' </div>';
            $sHtml .= ' </div>';
            $sHtml .= ' <div id="menu" class="ui-layout-center">';
            $sHtml .= '		<div id="inner_menu">';
            $sHtml .= '			<div id="accordion">';
            $sHtml .= self::FilterXSS($this->m_sMenu);
            $sHtml .= '			<!-- Beginning of the accordion menu -->';
            $sHtml .= '			<!-- End of the accordion menu-->';
            $sHtml .= '			</div>';
            $sHtml .= '		</div> <!-- /inner menu -->';
            $sHtml .= ' </div> <!-- /menu -->';
            $sHtml .= ' <div class="footer ui-layout-south"><div id="combodo_logo"><a href="http://www.combodo.com" title="www.combodo.com" target="_blank"><img src="../images/logo-combodo.png"/></a></div></div>';
            $sHtml .= '<!-- End of the left pane -->';
            $sHtml .= '</div>';
            $sHtml .= '<div class="ui-layout-center">';
            $sHtml .= ' <div id="top-bar" style="width:100%">';
            $sHtml .= self::FilterXSS($sApplicationBanner);
            $sHtml .= '		<div id="global-search"><form action="' . utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php"><table><tr><td></td><td id="g-search-input"><input type="text" name="text" value="' . $sText . '"' . $sOnClick . '/></td>';
            $sHtml .= '<td><input type="image" src="../images/searchBtn.png"/></a></td>';
            $sHtml .= '<td><a style="background:transparent;" href="' . $sOnlineHelpUrl . '" target="_blank"><img style="border:0;padding-left:20px;padding-right:10px;" title="' . Dict::S('UI:Help') . '" src="../images/help.png"/></td>';
            $sHtml .= '<td style="padding-right:20px;padding-left:10px;">' . self::FilterXSS($sLogOffMenu) . '</td><td><input type="hidden" name="operation" value="full_text"/></td></tr></table></form></div>';
            //echo '<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="hidden" name="operation" value="full_text"/></td></tr></table></form></div>';
            $sHtml .= ' </div>';
            $sHtml .= ' <div class="ui-layout-content" style="overflow:auto;">';
            $sHtml .= ' <!-- Beginning of page content -->';
            $sHtml .= self::FilterXSS($this->s_content);
            $sHtml .= ' <!-- End of page content -->';
            $sHtml .= ' </div>';
            $sHtml .= '</div>';
            $sHtml .= $sSouthPane;
            // Add the captured output
            if (trim($s_captured_output) != "") {
                $sHtml .= "<div id=\"rawOutput\" title=\"Debug Output\"><div style=\"height:500px; overflow-y:auto;\">" . self::FilterXSS($s_captured_output) . "</div></div>\n";
            }
            $sHtml .= "<div id=\"at_the_end\">" . self::FilterXSS($this->s_deferred_content) . "</div>";
            $sHtml .= "<div style=\"display:none\" title=\"ex2\" id=\"ex2\">Please wait...</div>\n";
            // jqModal Window
            $sHtml .= "<div style=\"display:none\" title=\"dialog\" id=\"ModalDlg\"></div>";
            $sHtml .= "<div style=\"display:none\" id=\"ajax_content\"></div>";
        } else {
            $sHtml .= self::FilterXSS($this->s_content);
        }
        $sHtml .= "</body>\n";
        $sHtml .= "</html>\n";
        if ($this->GetOutputFormat() == 'html') {
            $oKPI = new ExecutionKPI();
            echo $sHtml;
            $oKPI->ComputeAndReport('Echoing (' . round(strlen($sHtml) / 1024) . ' Kb)');
        } else {
            if ($this->GetOutputFormat() == 'pdf' && $this->IsOutputFormatAvailable('pdf')) {
                if (@is_readable(APPROOT . 'lib/MPDF/mpdf.php')) {
                    require_once APPROOT . 'lib/MPDF/mpdf.php';
                    $oMPDF = new mPDF('c');
                    $oMPDF->mirroMargins = false;
                    if ($this->a_base['href'] != '') {
                        $oMPDF->setBasePath($this->a_base['href']);
                        // Seems that the <BASE> tag is not recognized by mPDF...
                    }
                    $oMPDF->showWatermarkText = true;
                    if ($this->GetOutputOption('pdf', 'template_path')) {
                        $oMPDF->setImportUse();
                        // Allow templates
                        $oMPDF->SetDocTemplate($this->GetOutputOption('pdf', 'template_path'), 1);
                    }
                    $oMPDF->WriteHTML($sHtml);
                    $sOutputName = $this->s_title . '.pdf';
                    if ($this->GetOutputOption('pdf', 'output_name')) {
                        $sOutputName = $this->GetOutputOption('pdf', 'output_name');
                    }
                    $oMPDF->Output($sOutputName, 'I');
                }
            }
        }
        DBSearch::RecordQueryTrace();
        ExecutionKPI::ReportStats();
    }
 protected function _DoExecute($oTrigger, $aContextArgs, &$oLog)
 {
     $sPreviousUrlMaker = ApplicationContext::SetUrlMakerClass();
     try {
         $sScriptPath = $this->Get('script_path');
         if (!is_executable($sScriptPath)) {
             throw new Exception('cannot execute script');
         }
         $sCMD = '';
         $aParams = explode("\n", $this->Get('params'));
         array_walk($aParams, function (&$aParam) {
             $aParam = explode('=', $aParam);
             $aParam = array_map('trim', $aParam);
         });
         foreach ($aParams as $aParam) {
             if (count($aParam) == 2) {
                 $sVarName = $aParam[0];
                 $sVarValue = MetaModel::ApplyParams($aParam[1], $aContextArgs);
                 if ($sVarValue == $aParam[1]) {
                     $sVarValue = '';
                     // Значит ApplyParams не нашел такого плейсхолдера
                     if ($this->IsBeingTested() && !is_null($oLog)) {
                         $oLog->Set('log', $oLog->Get('log') . "There is no value for placeholder: {$aParam['1']}\n");
                     }
                 }
             } else {
                 $sVarName = $aParam[0];
                 $sVarValue = MetaModel::ApplyParams($aParam[0], $aContextArgs);
                 if ($sVarValue == $aParam[0]) {
                     $sVarValue = '';
                     if ($this->IsBeingTested() && !is_null($oLog)) {
                         $oLog->Set('log', $oLog->Get('log') . "There is no value for placeholder: {$aParam['0']}\n");
                     }
                 }
             }
             $sVarName = str_replace('->', '_', $sVarName);
             $sVarName = str_replace('$', '', $sVarName);
             $sVarName = strtoupper($sVarName);
             $sCMD .= $sVarName . '="' . $sVarValue . '" ';
         }
         $sCMD .= ' ' . $sScriptPath;
         if ($this->IsBeingTested()) {
             if (!is_null($oLog)) {
                 $oLog->Set('log', $oLog->Get('log') . "Start executing shell command:\n{$sCMD}");
             }
             return "Script will be started.";
         }
         if (!is_null($oLog)) {
             $oLog->Set('log', shell_exec($sCMD));
         }
         return "Script {$sScriptPath} successfully started.";
     } catch (Exception $e) {
         ApplicationContext::SetUrlMakerClass($sPreviousUrlMaker);
         throw $e;
         // Ошибка выбрасывается на верхний уровень и записывается в лог оповещения.
     }
     ApplicationContext::SetUrlMakerClass($sPreviousUrlMaker);
 }
 /**
  * Renders the "Actions" popup menu for the given set of objects
  * 
  * Note that the menu links containing (or ending) with a hash (#) will have their fragment
  * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is
  * displayed, to correspond to the current hash/fragment in the page. This allows modifying
  * an object in with the same tab active by default as the tab that was active when selecting
  * the "Modify..." action.
  */
 public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
 {
     if ($this->m_sStyle == 'popup') {
         $this->m_sStyle = 'list';
     }
     $sHtml = '';
     $oAppContext = new ApplicationContext();
     $sContext = $oAppContext->GetForLink();
     if (!empty($sContext)) {
         $sContext = '&' . $sContext;
     }
     $sClass = $this->m_oFilter->GetClass();
     $oReflectionClass = new ReflectionClass($sClass);
     $oSet = new CMDBObjectSet($this->m_oFilter);
     $sFilter = $this->m_oFilter->serialize();
     $sFilterDesc = $this->m_oFilter->ToOql(true);
     $aActions = array();
     $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass);
     $sRootUrl = utils::GetAbsoluteUrlAppRoot();
     // 1:n links, populate the target object as a default value when creating a new linked object
     if (isset($aExtraParams['target_attr'])) {
         $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id'];
     }
     $sDefault = '';
     if (!empty($aExtraParams['default'])) {
         foreach ($aExtraParams['default'] as $sKey => $sValue) {
             $sDefault .= "&default[{$sKey}]={$sValue}";
         }
     }
     $bIsCreationAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_CREATE) == UR_ALLOWED_YES && $oReflectionClass->IsSubclassOf('cmdbAbstractObject');
     switch ($oSet->Count()) {
         case 0:
             // No object in the set, the only possible action is "new"
             if ($bIsCreationAllowed) {
                 $aActions['UI:Menu:New'] = array('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=new&class={$sClass}{$sContext}{$sDefault}");
             }
             break;
         case 1:
             $oObj = $oSet->Fetch();
             $id = $oObj->GetKey();
             $bLocked = false;
             if (MetaModel::GetConfig()->Get('concurrent_lock_enabled')) {
                 $aLockInfo = iTopOwnershipLock::IsLocked(get_class($oObj), $id);
                 if ($aLockInfo['locked']) {
                     $bLocked = true;
                     //$this->AddMenuSeparator($aActions);
                     //$aActions['concurrent_lock_unlock'] = array ('label' => Dict::S('UI:Menu:ReleaseConcurrentLock'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}");
                 }
             }
             $bRawModifiedAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES && $oReflectionClass->IsSubclassOf('cmdbAbstractObject');
             $bIsModifyAllowed = !$bLocked && $bRawModifiedAllowed;
             $bIsDeleteAllowed = !$bLocked && UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
             // Just one object in the set, possible actions are "new / clone / modify and delete"
             if (!isset($aExtraParams['link_attr'])) {
                 if ($bIsModifyAllowed) {
                     $aActions['UI:Menu:Modify'] = array('label' => Dict::S('UI:Menu:Modify'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=modify&class={$sClass}&id={$id}{$sContext}#");
                 }
                 if ($bIsCreationAllowed) {
                     $aActions['UI:Menu:New'] = array('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=new&class={$sClass}{$sContext}{$sDefault}");
                 }
                 if ($bIsDeleteAllowed) {
                     $aActions['UI:Menu:Delete'] = array('label' => Dict::S('UI:Menu:Delete'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=delete&class={$sClass}&id={$id}{$sContext}");
                 }
                 // Transitions / Stimuli
                 if (!$bLocked) {
                     $aTransitions = $oObj->EnumTransitions();
                     if (count($aTransitions)) {
                         $this->AddMenuSeparator($aActions);
                         $aStimuli = Metamodel::EnumStimuli(get_class($oObj));
                         foreach ($aTransitions as $sStimulusCode => $aTransitionDef) {
                             $iActionAllowed = get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction' ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO;
                             switch ($iActionAllowed) {
                                 case UR_ALLOWED_YES:
                                     $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=stimulus&stimulus={$sStimulusCode}&class={$sClass}&id={$id}{$sContext}");
                                     break;
                                 default:
                                     // Do nothing
                             }
                         }
                     }
                 }
                 // Relations...
                 $aRelations = MetaModel::EnumRelationsEx($sClass);
                 if (count($aRelations)) {
                     $this->AddMenuSeparator($aActions);
                     foreach ($aRelations as $sRelationCode => $aRelationInfo) {
                         if (array_key_exists('down', $aRelationInfo)) {
                             $aActions[$sRelationCode . '_down'] = array('label' => $aRelationInfo['down'], 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=swf_navigator&relation={$sRelationCode}&direction=down&class={$sClass}&id={$id}{$sContext}");
                         }
                         if (array_key_exists('up', $aRelationInfo)) {
                             $aActions[$sRelationCode . '_up'] = array('label' => $aRelationInfo['up'], 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=swf_navigator&relation={$sRelationCode}&direction=up&class={$sClass}&id={$id}{$sContext}");
                         }
                     }
                 }
                 if ($bLocked && $bRawModifiedAllowed) {
                     // Add a special menu to kill the lock, but only to allowed users who can also modify this object
                     $aAllowedProfiles = MetaModel::GetConfig()->Get('concurrent_lock_override_profiles');
                     $bCanKill = false;
                     $oUser = UserRights::GetUserObject();
                     $aUserProfiles = array();
                     if (!is_null($oUser)) {
                         $oProfileSet = $oUser->Get('profile_list');
                         while ($oProfile = $oProfileSet->Fetch()) {
                             $aUserProfiles[$oProfile->Get('profile')] = true;
                         }
                     }
                     foreach ($aAllowedProfiles as $sProfile) {
                         if (array_key_exists($sProfile, $aUserProfiles)) {
                             $bCanKill = true;
                             break;
                         }
                     }
                     if ($bCanKill) {
                         $this->AddMenuSeparator($aActions);
                         $aActions['concurrent_lock_unlock'] = array('label' => Dict::S('UI:Menu:KillConcurrentLock'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=kill_lock&class={$sClass}&id={$id}{$sContext}");
                     }
                 }
                 /*
                 $this->AddMenuSeparator($aActions);
                 // Static menus: Email this page & CSV Export
                 $sUrl = ApplicationContext::MakeObjectUrl($sClass, $id);
                 $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl));
                 $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
                 // The style tells us whether the menu is displayed on a list of one object, or on the details of the given object 
                 if ($this->m_sStyle == 'list')
                 {
                 	// Actions specific to the list
                 	$sOQL = addslashes($sFilterDesc);
                 	$aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
                 }
                 */
             }
             $this->AddMenuSeparator($aActions);
             foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) {
                 $oSet->Rewind();
                 foreach ($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl) {
                     $aActions[$sLabel] = array('label' => $sLabel, 'url' => $sUrl);
                 }
             }
             break;
         default:
             // Check rights
             // New / Modify
             $bIsModifyAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) && $oReflectionClass->IsSubclassOf('cmdbAbstractObject');
             $bIsBulkModifyAllowed = !MetaModel::IsAbstract($sClass) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet) && $oReflectionClass->IsSubclassOf('cmdbAbstractObject');
             $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet);
             if (isset($aExtraParams['link_attr'])) {
                 $id = $aExtraParams['object_id'];
                 $sTargetAttr = $aExtraParams['target_attr'];
                 $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr);
                 $sTargetClass = $oAttDef->GetTargetClass();
                 $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet);
                 if ($bIsModifyAllowed) {
                     $aActions['UI:Menu:Add'] = array('label' => Dict::S('UI:Menu:Add'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=modify_links&class={$sClass}&link_attr=" . $aExtraParams['link_attr'] . "&target_class={$sTargetClass}&id={$id}&addObjects=true{$sContext}");
                 }
                 if ($bIsBulkModifyAllowed) {
                     $aActions['UI:Menu:Manage'] = array('label' => Dict::S('UI:Menu:Manage'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=modify_links&class={$sClass}&link_attr=" . $aExtraParams['link_attr'] . "&target_class={$sTargetClass}&id={$id}{$sContext}");
                 }
                 //if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => 'Remove All...', 'url' => "#"); }
             } else {
                 // many objects in the set, possible actions are: new / modify all / delete all
                 if ($bIsCreationAllowed) {
                     $aActions['UI:Menu:New'] = array('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=new&class={$sClass}{$sContext}{$sDefault}");
                 }
                 if ($bIsBulkModifyAllowed) {
                     $aActions['UI:Menu:ModifyAll'] = array('label' => Dict::S('UI:Menu:ModifyAll'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=select_for_modify_all&class={$sClass}&filter=" . urlencode($sFilter) . "{$sContext}");
                 }
                 if ($bIsBulkDeleteAllowed) {
                     $aActions['UI:Menu:BulkDelete'] = array('label' => Dict::S('UI:Menu:BulkDelete'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=select_for_deletion&filter=" . urlencode($sFilter) . "{$sContext}");
                 }
                 // Stimuli
                 $aStates = MetaModel::EnumStates($sClass);
                 // Do not perform time consuming computations if there are too may objects in the list
                 $iLimit = MetaModel::GetConfig()->Get('complex_actions_limit');
                 if (count($aStates) > 0 && ($iLimit == 0 || $oSet->Count() < $iLimit)) {
                     // Life cycle actions may be available... if all objects are in the same state
                     //
                     // Group by <state>
                     $oGroupByExp = new FieldExpression(MetaModel::GetStateAttributeCode($sClass), $this->m_oFilter->GetClassAlias());
                     $aGroupBy = array('__state__' => $oGroupByExp);
                     $aQueryParams = array();
                     if (isset($aExtraParams['query_params'])) {
                         $aQueryParams = $aExtraParams['query_params'];
                     }
                     $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy);
                     $aRes = CMDBSource::QueryToArray($sSql);
                     if (count($aRes) == 1) {
                         // All objects are in the same state...
                         $sState = $aRes[0]['__state__'];
                         $aTransitions = Metamodel::EnumTransitions($sClass, $sState);
                         if (count($aTransitions)) {
                             $this->AddMenuSeparator($aActions);
                             $aStimuli = Metamodel::EnumStimuli($sClass);
                             foreach ($aTransitions as $sStimulusCode => $aTransitionDef) {
                                 $oSet->Rewind();
                                 // As soon as the user rights implementation will browse the object set,
                                 // then we might consider using OptimizeColumnLoad() here
                                 $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet);
                                 $iActionAllowed = get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction' ? $iActionAllowed : UR_ALLOWED_NO;
                                 switch ($iActionAllowed) {
                                     case UR_ALLOWED_YES:
                                     case UR_ALLOWED_DEPENDS:
                                         $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=select_bulk_stimulus&stimulus={$sStimulusCode}&state={$sState}&class={$sClass}&filter=" . urlencode($sFilter) . "{$sContext}");
                                         break;
                                     default:
                                         // Do nothing
                                 }
                             }
                         }
                     }
                 }
                 /*
                 $this->AddMenuSeparator($aActions);
                 $sUrl = utils::GetAbsoluteUrlAppRoot();
                 $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=$sFilterDesc&body=".urlencode("{$sUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."{$sContext}"));
                 $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}");
                 $sOQL = addslashes($sFilterDesc);
                 $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')");
                 */
             }
     }
     $this->AddMenuSeparator($aActions);
     foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) {
         $oSet->Rewind();
         foreach ($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $data) {
             if (is_array($data)) {
                 // New plugins can provide javascript handlers via the 'onclick' property
                 //TODO: enable extension of different menus by checking the 'target' property ??
                 $aActions[$sLabel] = array('label' => $sLabel, 'url' => isset($data['url']) ? $data['url'] : '#', 'onclick' => isset($data['onclick']) ? $data['onclick'] : '');
             } else {
                 // Backward compatibility with old plugins
                 $aActions[$sLabel] = array('label' => $sLabel, 'url' => $data);
             }
         }
     }
     // New extensions based on iPopupMenuItem interface
     switch ($this->m_sStyle) {
         case 'list':
             $oSet->Rewind();
             $param = $oSet;
             $iMenuId = iPopupMenuExtension::MENU_OBJLIST_ACTIONS;
             break;
         case 'details':
             $oSet->Rewind();
             $param = $oSet->Fetch();
             $iMenuId = iPopupMenuExtension::MENU_OBJDETAILS_ACTIONS;
             break;
     }
     utils::GetPopupMenuItems($oPage, $iMenuId, $param, $aActions);
     $aFavoriteActions = array();
     $aCallSpec = array($sClass, 'GetShortcutActions');
     if (is_callable($aCallSpec)) {
         $aShortcutActions = call_user_func($aCallSpec, $sClass);
         foreach ($aActions as $key => $aAction) {
             if (in_array($key, $aShortcutActions)) {
                 $aFavoriteActions[] = $aAction;
                 unset($aActions[$key]);
             }
         }
     } else {
         $aShortcutActions = array();
     }
     if (count($aFavoriteActions) > 0) {
         $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>" . Dict::S('UI:Menu:OtherActions') . "\n<ul>\n";
     } else {
         $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>" . Dict::S('UI:Menu:Actions') . "\n<ul>\n";
     }
     $sHtml .= $oPage->RenderPopupMenuItems($aActions, $aFavoriteActions);
     static $bPopupScript = false;
     if (!$bPopupScript) {
         // Output this once per page...
         $oPage->add_ready_script("\$(\"div.itop_popup>ul\").popupmenu();\n");
         $bPopupScript = true;
     }
     return $sHtml;
 }
    public function __construct($sTitle, $sAlternateStyleSheet = '')
    {
        $this->m_sWelcomeMsg = '';
        $this->m_aMenuButtons = array();
        parent::__construct($sTitle);
        $this->add_header("Content-type: text/html; charset=utf-8");
        $this->add_header("Cache-control: no-cache");
        $this->add_linked_stylesheet("../css/jquery.treeview.css");
        $this->add_linked_stylesheet("../css/jquery.autocomplete.css");
        $this->add_linked_stylesheet("../css/jquery.multiselect.css");
        $sAbsURLAppRoot = addslashes(utils::GetAbsoluteUrlAppRoot());
        // Pass it to Javascript scripts
        $sAbsURLModulesRoot = addslashes(utils::GetAbsoluteUrlModulesRoot());
        // Pass it to Javascript scripts
        $oAppContext = new ApplicationContext();
        $sAppContext = addslashes($oAppContext->GetForLink());
        $this->add_dict_entry('UI:FillAllMandatoryFields');
        if ($sAlternateStyleSheet != '') {
            $this->add_linked_stylesheet("../portal/{$sAlternateStyleSheet}/portal.css");
        } else {
            $this->add_linked_stylesheet("../portal/portal.css");
        }
        $this->add_linked_script('../js/jquery.layout.min.js');
        $this->add_linked_script('../js/jquery.ba-bbq.min.js');
        $this->add_linked_script("../js/jquery.tablehover.js");
        $this->add_linked_script("../js/jquery.treeview.js");
        $this->add_linked_script("../js/jquery.autocomplete.js");
        $this->add_linked_script("../js/jquery.positionBy.js");
        $this->add_linked_script("../js/jquery.popupmenu.js");
        $this->add_linked_script("../js/date.js");
        $this->add_linked_script("../js/jquery.tablesorter.min.js");
        $this->add_linked_script("../js/jquery.tablesorter.pager.js");
        $this->add_linked_script("../js/jquery.blockUI.js");
        $this->add_linked_script("../js/utils.js");
        $this->add_linked_script("../js/forms-json-utils.js");
        $this->add_linked_script("../js/swfobject.js");
        $this->add_linked_script("../js/jquery.qtip-1.0.min.js");
        $this->add_linked_script('../js/jquery.multiselect.js');
        $this->add_linked_script("../js/ajaxfileupload.js");
        $this->add_linked_script("../js/ckeditor/ckeditor.js");
        $this->add_linked_script("../js/ckeditor/adapters/jquery.js");
        $sJSDisconnectedMessage = json_encode(Dict::S('UI:DisconnectedDlgMessage'));
        $sJSTitle = json_encode(Dict::S('UI:DisconnectedDlgTitle'));
        $sJSLoginAgain = json_encode(Dict::S('UI:LoginAgain'));
        $sJSStayOnThePage = json_encode(Dict::S('UI:StayOnThePage'));
        $sJSDaysMin = json_encode(array(Dict::S('DayOfWeek-Sunday-Min'), Dict::S('DayOfWeek-Monday-Min'), Dict::S('DayOfWeek-Tuesday-Min'), Dict::S('DayOfWeek-Wednesday-Min'), Dict::S('DayOfWeek-Thursday-Min'), Dict::S('DayOfWeek-Friday-Min'), Dict::S('DayOfWeek-Saturday-Min')));
        $sJSMonthsShort = json_encode(array(Dict::S('Month-01-Short'), Dict::S('Month-02-Short'), Dict::S('Month-03-Short'), Dict::S('Month-04-Short'), Dict::S('Month-05-Short'), Dict::S('Month-06-Short'), Dict::S('Month-07-Short'), Dict::S('Month-08-Short'), Dict::S('Month-09-Short'), Dict::S('Month-10-Short'), Dict::S('Month-11-Short'), Dict::S('Month-12-Short')));
        $iFirstDayOfWeek = (int) Dict::S('Calendar-FirstDayOfWeek');
        $this->add_ready_script(<<<EOF
try
{
\t//add new widget called TruncatedList to properly display truncated lists when they are sorted
\t\$.tablesorter.addWidget({ 
\t    // give the widget a id 
\t    id: "truncatedList", 
\t    // format is called when the on init and when a sorting has finished 
\t    format: function(table)
\t    { 
\t\t\t// Check if there is a "truncated" line
\t\t\tthis.truncatedList = false;  
\t\t\tif (\$("tr td.truncated",table).length > 0)
\t\t\t{
\t\t\t\tthis.truncatedList = true;
\t\t\t}
\t\t\tif (this.truncatedList)
\t\t\t{
\t\t\t\t\$("tr td",table).removeClass('truncated');
\t\t\t\t\$("tr:last td",table).addClass('truncated');
\t\t\t}
\t    } 
\t});
\t\t
\t
\t\$.tablesorter.addWidget({ 
\t    // give the widget a id 
\t    id: "myZebra", 
\t    // format is called when the on init and when a sorting has finished 
\t    format: function(table)
\t    {
\t    \t// Replace the 'red even' lines by 'red_even' since most browser do not support 2 classes selector in CSS, etc..
\t\t\t\$("tbody tr:even",table).addClass('even');
\t\t\t\$("tbody tr.red:even",table).removeClass('red').removeClass('even').addClass('red_even');
\t\t\t\$("tbody tr.orange:even",table).removeClass('orange').removeClass('even').addClass('orange_even');
\t\t\t\$("tbody tr.green:even",table).removeClass('green').removeClass('even').addClass('green_even');
\t    } 
\t});
\t\t
\t\$(".date-pick").datepicker({
\t\tshowOn: 'button',
\t\tbuttonImage: '../images/calendar.png',
\t\tbuttonImageOnly: true,
\t\tdateFormat: 'yy-mm-dd',
\t\tconstrainInput: false,
\t\tchangeMonth: true,
\t\tchangeYear: true,
\t\tdayNamesMin: {$sJSDaysMin},
\t\tmonthNamesShort: {$sJSMonthsShort},
\t\tfirstDay: {$iFirstDayOfWeek}\t\t
\t});

\t\$(".datetime-pick").datepicker({
\t\tshowOn: 'button',
\t\tbuttonImage: '../images/calendar.png',
\t\tbuttonImageOnly: true,
\t\tdateFormat: 'yy-mm-dd 00:00:00',
\t\tconstrainInput: false,
\t\tchangeMonth: true,
\t\tchangeYear: true,
\t\tdayNamesMin: {$sJSDaysMin},
\t\tmonthNamesShort: {$sJSMonthsShort},
\t\tfirstDay: {$iFirstDayOfWeek}
\t});

\t//\$('.resizable').resizable(); // Make resizable everything that claims to be resizable !
\t\$('.caselog_header').click( function () { \$(this).toggleClass('open').next('.caselog_entry').toggle(); });
\t\t\t
\t\$(document).ajaxSend(function(event, jqxhr, options) {
\t\tjqxhr.setRequestHeader('X-Combodo-Ajax', 'true');
\t});
\t\$(document).ajaxError(function(event, jqxhr, options) {
\t\tif (jqxhr.status == 401)
\t\t{
\t\t\t\$('<div>'+{$sJSDisconnectedMessage}+'</div>').dialog({
\t\t\t\tmodal:true,
\t\t\t\ttitle: {$sJSTitle},
\t\t\t\tclose: function() { \$(this).remove(); },
\t\t\t\tminWidth: 400,
\t\t\t\tbuttons: [
\t\t\t\t{ text: {$sJSLoginAgain}, click: function() { window.location.href= GetAbsoluteUrlAppRoot()+'pages/UI.php' } },
\t\t\t\t{ text: {$sJSStayOnThePage}, click: function() { \$(this).dialog('close'); } }
\t\t\t\t]
\t\t\t});
\t\t}
\t});
}
catch(err)
{
\t// Do something with the error !
\talert(err);
}
EOF
);
        $this->add_script(<<<EOF
\tfunction CheckSelection(sMessage, sInputId)
\t{
\t\tvar bResult;
\t\tif (sInputId.length > 0)
\t\t{
\t\t\tbResult = (\$('input[name='+sInputId+']:checked').length > 0);
\t\t}
\t\telse
\t\t{
\t\t\t// First select found...
\t\t\tbResult = (\$('input:checked').length > 0);
\t\t}
\t\tif (!bResult)
\t\t{
\t\t\talert(sMessage);
\t\t}
\t\treturn bResult;
\t}

\t\t
\tfunction GetAbsoluteUrlAppRoot()
\t{
\t\treturn '{$sAbsURLAppRoot}';
\t}
\t
\tfunction GetAbsoluteUrlModulesRoot()
\t{
\t\treturn '{$sAbsURLModulesRoot}';
\t}

\tfunction AddAppContext(sURL)
\t{
\t\tvar sContext = '{$sAppContext}';
\t\tif (sContext.length > 0)
\t\t{
\t\t\tif (sURL.indexOf('?') == -1)
\t\t\t{
\t\t\t\treturn sURL+'?'+sContext;
\t\t\t}\t\t\t\t
\t\t\treturn sURL+'&'+sContext;
\t\t}
\t\treturn sURL;
\t}
\t
\tfunction GoBack(sFormId)
\t{
\t\tvar form = \$('#'+sFormId);
\t\tvar step_back = \$('input[name=step_back]');

\t\tform.unbind('submit'); // De-activate validation

\t\tstep_back.val(1);
\t\tform.submit(); // Go
\t}

\tfunction GoHome()
\t{
\t\tvar form = \$('FORM');
\t\tform.unbind('submit'); // De-activate validation
\t\twindow.location.href = window.location.href.replace(/[&?]operation=[^&]*/, '');
\t\treturn false;
\t}

\tfunction SetWizardNextStep(sStep)
\t{
\t\tvar next_step = \$('input[id=next_step]');
\t\tnext_step.val(sStep);
\t}
\t\t
\t// For disabling the CKEditor at init time when the corresponding textarea is disabled !
\tCKEDITOR.plugins.add( 'disabler',
\t{
\t\tinit : function( editor )
\t\t{
\t\t\teditor.on( 'instanceReady', function(e)
\t\t\t{
\t\t\t\te.removeListener();
\t\t\t\t\$('#'+ editor.name).trigger('update');
\t\t\t});
\t\t}
\t\t
\t});
EOF
);
        // For Wizard helper to process the ajax replies
        $this->add('<div id="ajax_content"></div>');
        // Customize the logo (unless a customer CSS has been defined)
        if ($sAlternateStyleSheet == '') {
            if (file_exists(MODULESROOT . 'branding/portal-logo.png')) {
                $sDisplayIcon = utils::GetAbsoluteUrlModulesRoot() . 'branding/portal-logo.png';
                $this->add_style("div#portal #logo {background: url(\"{$sDisplayIcon}\") no-repeat scroll 0 0 transparent;}");
            }
        }
    }
Exemple #28
0
         // navigate to the dashboard page
         if ($aValues['open_editor']) {
             $oPage->add_ready_script("window.location.href='" . addslashes(utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?c[menu]=' . urlencode($sMenuId)) . "&edit=1';");
             // reloads the page, doing a GET even if we arrived via a POST
         }
     }
     break;
 case 'shortcut_list_dlg':
     $sOQL = utils::ReadParam('oql', '', false, 'raw_data');
     $sTableSettings = utils::ReadParam('table_settings', '', false, 'raw_data');
     ShortcutOQL::GetCreationDlgFromOQL($oPage, $sOQL, $sTableSettings);
     break;
 case 'shortcut_list_create':
     $oForm = ShortcutOQL::GetCreationForm();
     $aValues = $oForm->ReadParams();
     $oAppContext = new ApplicationContext();
     $aContext = $oAppContext->GetAsHash();
     $sContext = serialize($aContext);
     $oShortcut = MetaModel::NewObject("ShortcutOQL");
     $oShortcut->Set('user_id', UserRights::GetUserId());
     $oShortcut->Set("context", $sContext);
     $oShortcut->Set("name", $aValues['name']);
     $oShortcut->Set("oql", $aValues['oql']);
     $iAutoReload = (int) $aValues['auto_reload_sec'];
     if ($aValues['auto_reload'] && $iAutoReload > 0) {
         $oShortcut->Set("auto_reload_sec", max(5, $iAutoReload));
         $oShortcut->Set("auto_reload", 'custom');
     }
     $iId = $oShortcut->DBInsertNoReload();
     $oShortcut->CloneTableSettings($aValues['table_settings']);
     // Add the menu node in the right place
 function GetApplicationContext()
 {
     $oAppContext = new ApplicationContext();
     return $oAppContext->GetForLink();
 }
 public static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '', $sUrlMakerClass = null, $bWithNavigationContext = true)
 {
     if ($sObjKey <= 0) {
         return '<em>' . Dict::S('UI:UndefinedObject') . '</em>';
     }
     // Objects built in memory have negative IDs
     // Safety net
     //
     if (empty($sLabel)) {
         // If the object if not issued from a query but constructed programmatically
         // the label may be empty. In this case run a query to get the object's friendly name
         $oTmpObj = MetaModel::GetObject($sObjClass, $sObjKey, false);
         if (is_object($oTmpObj)) {
             $sLabel = $oTmpObj->GetName();
         } else {
             // May happen in case the target object is not in the list of allowed values for this attribute
             $sLabel = "<em>{$sObjClass}::{$sObjKey}</em>";
         }
         //$sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
     }
     $sHint = MetaModel::GetName($sObjClass) . "::{$sObjKey}";
     $sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext);
     if (strlen($sUrl) > 0) {
         return "<a href=\"{$sUrl}\" title=\"{$sHint}\">{$sLabel}</a>";
     } else {
         return $sLabel;
     }
 }