Ejemplo n.º 1
1
 /**
  * Executes this task.
  */
 public function main()
 {
     if ($this->path === null) {
         throw new BuildException('The path attribute must be specified');
     }
     $check = new AgaviModuleFilesystemCheck();
     $check->setConfigDirectory($this->project->getProperty('module.config.directory'));
     $check->setPath($this->path->getAbsolutePath());
     if (!$check->check()) {
         throw new BuildException('The path attribute must be a valid module base directory');
     }
     /* We don't know whether the module is configured or not here, so load the
      * values we want properly. */
     $this->tryLoadAgavi();
     $this->tryBootstrapAgavi();
     require_once AgaviConfigCache::checkConfig(sprintf('%s/%s/module.xml', $this->path->getAbsolutePath(), (string) $this->project->getProperty('module.config.directory')));
     $actionPath = AgaviToolkit::expandVariables(AgaviToolkit::expandDirectives(AgaviConfig::get(sprintf('modules.%s.agavi.action.path', strtolower($this->path->getName())), '%core.module_dir%/${moduleName}/actions/${actionName}Action.class.php')), array('moduleName' => $this->path->getName()));
     $pattern = '#^' . AgaviToolkit::expandVariables(str_replace('\\$\\{actionName\\}', '${actionName}', preg_quote($actionPath, '#')), array('actionName' => '(?P<action_name>.*?)')) . '$#';
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->path->getAbsolutePath()));
     for (; $iterator->valid(); $iterator->next()) {
         $rdi = $iterator->getInnerIterator();
         if ($rdi->isDot() || !$rdi->isFile()) {
             continue;
         }
         $file = $rdi->getPathname();
         if (preg_match($pattern, $file, $matches)) {
             $this->log(str_replace(DIRECTORY_SEPARATOR, '.', $matches['action_name']));
         }
     }
 }
 private function importModuleXML($accessLocation)
 {
     $config = (include AgaviConfigCache::checkConfig(AgaviToolkit::expandDirectives($accessLocation)));
     $this->instances = array_merge_recursive($this->instances, $config["instances"]);
     $this->defaults = array_merge_recursive($this->defaults, $config["defaults"]);
     $this->hosts = array_merge_recursive($this->hosts, $config["hosts"]);
 }
 protected function parseRoutesAndFiles(AgaviRouting $routing, $routes, &$data)
 {
     $controller = $this->context->getController();
     $request = $this->context->getRequest();
     foreach ($routes as $route) {
         $outputTypes = array();
         $routeName = $route->getAttribute('name');
         if ($routeName !== '*' && is_null($routing->getRoute($routeName))) {
             throw new AgaviConfigurationException('Route name "' . $routeName . '" does not exist or is not correct.');
         }
         if ($route->hasAttribute('output_type')) {
             foreach (explode(' ', $route->getAttribute('output_type')) as $ot) {
                 if ($controller->getOutputType($ot)) {
                     $outputTypes[] = $ot;
                 }
             }
         } else {
             $outputTypes[] = $controller->getOutputType()->getName();
             // Defaults to HTML
         }
         foreach ($route->get('filelist') as $filelist) {
             $metatype = $filelist->getAttribute('metatype');
             foreach ($filelist->getElementsByTagName('file') as $file) {
                 foreach ($outputTypes as $ot) {
                     if ($file->hasAttribute('name')) {
                         $data[$routeName][$ot][$metatype][$file->getAttribute('name')] = AgaviToolkit::expandDirectives($file->getValue());
                     } else {
                         $data[$routeName][$ot][$metatype][] = AgaviToolkit::expandDirectives($file->getValue());
                     }
                 }
             }
         }
     }
 }
 /**
  * Execute this configuration handler.
  *
  * @param      AgaviXmlConfigDomDocument The document to parse.
  *
  * @return     string Data to be written to a cache file.
  *
  * @throws     <b>AgaviParseException</b> If a requested configuration file is
  *                                        improperly formatted.
  *
  * @author     Sean Kerr <*****@*****.**>
  * @author     Dominik del Bondio <*****@*****.**>
  * @author     David Zülke <*****@*****.**>
  * @since      0.9.0
  */
 public function execute(AgaviXmlConfigDomDocument $document)
 {
     // set up our default namespace
     $document->setDefaultNamespace(self::XML_NAMESPACE, 'compile');
     $config = $document->documentURI;
     $data = array();
     // let's do our fancy work
     foreach ($document->getConfigurationElements() as $configuration) {
         if (!$configuration->has('compiles')) {
             continue;
         }
         foreach ($configuration->get('compiles') as $compileFile) {
             $file = trim($compileFile->getValue());
             $file = AgaviToolkit::expandDirectives($file);
             $file = self::replacePath($file);
             $file = realpath($file);
             if (!is_readable($file)) {
                 // file doesn't exist
                 $error = 'Configuration file "%s" specifies nonexistent ' . 'or unreadable file "%s"';
                 $error = sprintf($error, $config, $compileFile->getValue());
                 throw new AgaviParseException($error);
             }
             if (AgaviConfig::get('core.debug', false)) {
                 // debug mode, just require() the files, makes for nicer stack traces
                 $contents = 'require(' . var_export($file, true) . ');';
             } else {
                 // no debug mode, so make things fast
                 $contents = $this->formatFile(file_get_contents($file));
             }
             // append file data
             $data[$file] = $contents;
         }
     }
     return $this->generate($data, $config);
 }
Ejemplo n.º 5
0
 public function testExpandDirectives()
 {
     AgaviConfig::set('whatever', 'something');
     $value = "whatever %directive% asdasdasd %whatever% ";
     $result = "whatever %directive% asdasdasd something ";
     $this->assertEquals($result, AgaviToolkit::expandDirectives($value));
 }
 public function initialize(AgaviContext $ctx, array $parameters = array())
 {
     parent::initialize($ctx, $parameters);
     $this->dqlViews = (include AgaviConfigCache::checkConfig(AgaviToolkit::expandDirectives('%core.module_dir%/Api/config/views.xml')));
     $this->view = $parameters["view"];
     $this->viewParameters = isset($parameters["parameters"]) ? $parameters["parameters"] : array();
     $this->validateTarget();
     $connection = $this->defaultConnection;
     if (isset($parameters["connection"])) {
         $connection = $parameters["connection"];
     }
     if ($this->view["connection"]) {
         $connection = $this->view["connection"];
     }
     AppKitLogger::verbose("Switching to connection %s", $connection);
     $db = $this->getContext()->getDatabaseManager()->getDatabase($connection);
     $this->useRetained = $db->useRetained();
     $this->connection = $ctx->getDatabaseConnection($connection);
     if ($this->connection != "icinga") {
         $ctx->getModel("DBALMetaManager", "Api")->switchIcingaDatabase($connection);
     }
     $this->user = $this->getContext()->getUser()->getNsmUser();
     $this->parseBaseDQL();
     $this->parseCustomVariables();
     $this->parseDQLExtensions();
     $this->parseDependencies();
 }
Ejemplo n.º 7
0
 public static function loadConfig()
 {
     if (self::$configLoaded) {
         return;
     }
     self::$config = (include AgaviConfigCache::checkConfig(AgaviToolkit::expandDirectives('%core.module_dir%/Api/config/access.xml')));
     self::$configLoaded = true;
 }
Ejemplo n.º 8
0
 /**
  * Load Propel config
  * 
  * @param      AgaviDatabaseManager The database manager of this instance.
  * @param      array                An assoc array of initialization params.
  *
  * @author     David Zülke <*****@*****.**>
  * @since      0.10.0
  */
 public function initialize(AgaviDatabaseManager $databaseManager, array $parameters = array())
 {
     parent::initialize($databaseManager, $parameters);
     $configPath = AgaviToolkit::expandDirectives($this->getParameter('config'));
     $datasource = $this->getParameter('datasource', null);
     $use_as_default = $this->getParameter('use_as_default', false);
     $config = (require $configPath);
     if ($datasource === null || $datasource == 'default') {
         if (isset($config['propel']['datasources']['default'])) {
             $datasource = $config['propel']['datasources']['default'];
         } elseif (isset($config['datasources']['default'])) {
             $datasource = $config['datasources']['default'];
         } else {
             throw new AgaviDatabaseException('No datasource given for Propel connection, and no default datasource specified in runtime configuration file.');
         }
     }
     if (!class_exists('Propel')) {
         include 'propel/Propel.php';
     }
     if (!Propel::isInit()) {
         Propel::init($configPath);
     }
     $is13 = version_compare(Propel::VERSION, '1.4', '<');
     // grab the configuration values and inject possibly defined overrides for this data source
     if ($is13) {
         // old-style config array; PropelConfiguration was added after 1.3.0, http://trac.agavi.org/ticket/1195
         $config = Propel::getConfiguration();
         $config['datasources'][$datasource]['adapter'] = $this->getParameter('overrides[adapter]', $config['datasources'][$datasource]['adapter']);
         $config['datasources'][$datasource]['connection'] = array_merge($config['datasources'][$datasource]['connection'], $this->getParameter('overrides[connection]', array()));
         // also the autoload classes
         $config['datasources'][$datasource]['classes'] = array_merge($config['datasources'][$datasource]['classes'], $this->getParameter('overrides[classes]', array()));
         // and init queries
         if (!isset($config['datasources'][$datasource]['connection']['settings']['queries']['query'])) {
             $config['datasources'][$datasource]['connection']['settings']['queries']['query'] = array();
         }
         // array cast because "query" might be a string if just one init query was given, http://trac.agavi.org/ticket/1194
         $config['datasources'][$datasource]['connection']['settings']['queries']['query'] = array_merge((array) $config['datasources'][$datasource]['connection']['settings']['queries']['query'], (array) $this->getParameter('init_queries'));
         // set the new config
         Propel::setConfiguration($config);
     } else {
         $config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
         $overrides = (array) $this->getParameter('overrides');
         // set override values
         foreach ($overrides as $key => $value) {
             $config->setParameter($key, $value);
         }
         // handle init queries in a cross-adapter fashion (they all support the "init_queries" param)
         $queries = (array) $config->getParameter('datasources.' . $datasource . '.connection.settings.queries.query', array());
         // yes... it's one array, [connection][settings][queries][query], with all the init queries from the config, so we append to that
         $queries = array_merge($queries, (array) $this->getParameter('init_queries'));
         $config->setParameter('datasources.' . $datasource . '.connection.settings.queries.query', $queries);
     }
     if (true === $this->getParameter('enable_instance_pooling')) {
         Propel::enableInstancePooling();
     } elseif (false === $this->getParameter('enable_instance_pooling')) {
         Propel::disableInstancePooling();
     }
 }
 public function initialize(AgaviContext $context, array $parameters = array())
 {
     parent::initialize($context, $parameters);
     $this->config = (include AgaviConfigCache::checkConfig(AgaviToolkit::expandDirectives('%core.module_dir%/Api/config/icingaCommands.xml')));
     $this->user = $context->getUser();
     if ($this->user->getNsmUser()->hasTarget('IcingaCommandRestrictions')) {
         $this->filterCommandsByUser($this->config);
     }
 }
 /**
  * Execute this configuration handler.
  *
  * @param      AgaviXmlConfigDomDocument The document to handle.
  *
  * @return     string Data to be written to a cache file.
  *
  * @throws     <b>AgaviUnreadableException</b> If a requested configuration
  *                                             file does not exist or is not
  *                                             readable.
  * @throws     <b>AgaviParseException</b> If a requested configuration file is
  *                                        improperly formatted.
  *
  * @author     Dominik del Bondio <*****@*****.**>
  * @author     Noah Fontes <*****@*****.**>
  * @author     David Zülke <*****@*****.**>
  * @since      0.11.0
  */
 public function execute(AgaviXmlConfigDomDocument $document)
 {
     // set up our default namespace
     $document->setDefaultNamespace(self::XML_NAMESPACE, 'config_handlers');
     // init our data arrays
     $handlers = array();
     foreach ($document->getConfigurationElements() as $configuration) {
         if (!$configuration->has('handlers')) {
             continue;
         }
         // let's do our fancy work
         foreach ($configuration->get('handlers') as $handler) {
             $pattern = $handler->getAttribute('pattern');
             $category = AgaviToolkit::normalizePath(AgaviToolkit::expandDirectives($pattern));
             $class = $handler->getAttribute('class');
             $transformations = array(AgaviXmlConfigParser::STAGE_SINGLE => array(), AgaviXmlConfigParser::STAGE_COMPILATION => array());
             if ($handler->has('transformations')) {
                 foreach ($handler->get('transformations') as $transformation) {
                     $path = AgaviToolkit::literalize($transformation->getValue());
                     $for = $transformation->getAttribute('for', AgaviXmlConfigParser::STAGE_SINGLE);
                     $transformations[$for][] = $path;
                 }
             }
             $validations = array(AgaviXmlConfigParser::STAGE_SINGLE => array(AgaviXmlConfigParser::STEP_TRANSFORMATIONS_BEFORE => array(AgaviXmlConfigParser::VALIDATION_TYPE_RELAXNG => array(), AgaviXmlConfigParser::VALIDATION_TYPE_SCHEMATRON => array(), AgaviXmlConfigParser::VALIDATION_TYPE_XMLSCHEMA => array()), AgaviXmlConfigParser::STEP_TRANSFORMATIONS_AFTER => array(AgaviXmlConfigParser::VALIDATION_TYPE_RELAXNG => array(), AgaviXmlConfigParser::VALIDATION_TYPE_SCHEMATRON => array(), AgaviXmlConfigParser::VALIDATION_TYPE_XMLSCHEMA => array())), AgaviXmlConfigParser::STAGE_COMPILATION => array(AgaviXmlConfigParser::STEP_TRANSFORMATIONS_BEFORE => array(AgaviXmlConfigParser::VALIDATION_TYPE_RELAXNG => array(), AgaviXmlConfigParser::VALIDATION_TYPE_SCHEMATRON => array(), AgaviXmlConfigParser::VALIDATION_TYPE_XMLSCHEMA => array()), AgaviXmlConfigParser::STEP_TRANSFORMATIONS_AFTER => array(AgaviXmlConfigParser::VALIDATION_TYPE_RELAXNG => array(), AgaviXmlConfigParser::VALIDATION_TYPE_SCHEMATRON => array(), AgaviXmlConfigParser::VALIDATION_TYPE_XMLSCHEMA => array())));
             if ($handler->has('validations')) {
                 foreach ($handler->get('validations') as $validation) {
                     $path = AgaviToolkit::literalize($validation->getValue());
                     $type = null;
                     if (!$validation->hasAttribute('type')) {
                         $type = $this->guessValidationType($path);
                     } else {
                         $type = $validation->getAttribute('type');
                     }
                     $for = $validation->getAttribute('for', AgaviXmlConfigParser::STAGE_SINGLE);
                     $step = $validation->getAttribute('step', AgaviXmlConfigParser::STEP_TRANSFORMATIONS_AFTER);
                     $validations[$for][$step][$type][] = $path;
                 }
             }
             $handlers[$category] = isset($handlers[$category]) ? $handlers[$category] : array('parameters' => array());
             $handlers[$category] = array('class' => $class, 'parameters' => $handler->getAgaviParameters($handlers[$category]['parameters']), 'transformations' => $transformations, 'validations' => $validations);
         }
     }
     $data = array('return ' . var_export($handlers, true));
     return $this->generate($data, $document->documentURI);
 }
 /**
  * Execute this configuration handler.
  *
  * @param      AgaviXmlConfigDomDocument The document to parse.
  *
  * @return     string Data to be written to a cache file.
  *
  * @throws     <b>AgaviParseException</b> If a requested configuration file is
  *                                        improperly formatted.
  *
  * @author     Sean Kerr <*****@*****.**>
  * @author     Dominik del Bondio <*****@*****.**>
  * @author     Noah Fontes <*****@*****.**>
  * @author     David Zülke <*****@*****.**>
  * @since      0.9.0
  */
 public function execute(AgaviXmlConfigDomDocument $document)
 {
     // set up our default namespace
     $document->setDefaultNamespace(self::XML_NAMESPACE, 'autoload');
     $classes = $namespaces = array();
     foreach ($document->getConfigurationElements() as $configuration) {
         if (!$configuration->has('autoloads')) {
             continue;
         }
         // let's do our fancy work
         foreach ($configuration->get('autoloads') as $autoload) {
             // we can have variables in the filename
             $path = AgaviToolkit::expandDirectives($autoload->getValue());
             // sanity check; XML Schema can't do <xs:choice> on attributes...
             if (($isClass = $autoload->hasAttribute('class')) && $autoload->hasAttribute('namespace')) {
                 $error = sprintf('Configuration file "%s" specifies both "class" and "namespace" attribute for path "%s"', $document->documentURI, $path);
                 throw new AgaviParseException($error);
             }
             // prepend the app dir if the path is not absolute
             $file = self::replacePath($path);
             // check if absolute path is readable or try to resolve it against the include path
             if (!file_exists($file) && ($path == $file || !($file = stream_resolve_include_path($path)))) {
                 // the class path doesn't exist and couldn't be resolved against the include path either
                 $error = sprintf('Configuration file "%s" specifies %s "%s" with non-existent path "%s"', $document->documentURI, $isClass ? 'file' : 'namespace', $isClass ? $autoload->getAttribute('class') : $autoload->getAttribute('namespace'), $path);
                 throw new AgaviParseException($error);
             }
             if ($isClass) {
                 // it's a class
                 $classes[$autoload->getAttribute('class')] = $file;
             } else {
                 // it's a whole namespace
                 // trim backslashes from the namespace and trailing slashes or backslashes from the path
                 $namespaces[trim($autoload->getAttribute('namespace'), '\\')] = rtrim($file, '/\\');
             }
         }
     }
     $code = array('AgaviAutoloader::addClasses(' . var_export($classes, true) . ');', 'AgaviAutoloader::addNamespaces(' . var_export($namespaces, true) . ');');
     return $this->generate($code, $document->documentURI);
 }
 /**
  * Execute this configuration handler.
  *
  * @param      AgaviXmlConfigDomDocument The document to parse.
  *
  * @return     string Data to be written to a cache file.
  *
  * @throws     <b>AgaviParseException</b> If a requested configuration file is
  *                                        improperly formatted.
  *
  * @author     Sean Kerr <*****@*****.**>
  * @author     Dominik del Bondio <*****@*****.**>
  * @author     Noah Fontes <*****@*****.**>
  * @since      0.9.0
  */
 public function execute(AgaviXmlConfigDomDocument $document)
 {
     // set up our default namespace
     $document->setDefaultNamespace(self::XML_NAMESPACE, 'autoload');
     $data = array();
     foreach ($document->getConfigurationElements() as $configuration) {
         if (!$configuration->has('autoloads')) {
             continue;
         }
         // let's do our fancy work
         foreach ($configuration->get('autoloads') as $autoload) {
             // we can have variables in the filename
             $file = AgaviToolkit::expandDirectives($autoload->getValue());
             // we need the filename w/o app dir prepended since the file could
             // be placed in the include path
             $originalFile = $file;
             // if the filename is not absolute we assume its relative to the app dir
             $file = self::replacePath($file);
             $class = $autoload->getAttribute('name');
             if (!($fp = @fopen($file, 'r', true))) {
                 if ($originalFile != $file && ($fpOriginal = @fopen($originalFile, 'r', true))) {
                     $file = $originalFile;
                     $fp = $fpOriginal;
                 } else {
                     // the class path doesn't exist
                     $error = 'Configuration file "%s" specifies class "%s" with ' . 'nonexistent or unreadable file "%s"';
                     $error = sprintf($error, $document->documentURI, $class, $file);
                     throw new AgaviParseException($error);
                 }
             }
             fclose($fp);
             $data[$class] = $file;
         }
     }
     $code = array('return ' . var_export($data, true) . ';');
     return $this->generate($code, $document->documentURI);
 }
Ejemplo n.º 13
0
 /**
  * Returns the literal value. By default, that means whitespace is trimmed,
  * boolean literals ("on", "yes", "true", "no", "off", "false") are converted
  * and configuration directives ("%core.app_dir%") are expanded.
  *
  * Takes attributes {http://www.w3.org/XML/1998/namespace}space and
  * {http://agavi.org/agavi/config/global/envelope/1.1}literalize into account
  * when computing the literal value. This way, users can control the trimming
  * and the literalization of values.
  * 
  * AEP-100 has a list of all the conversion rules that apply.
  *
  * @return     mixed The element content converted according to the rules
  *                   defined in AEP-100.
  *
  * @author     David Zülke <*****@*****.**>
  * @since      1.1.0
  */
 public function getLiteralValue()
 {
     $value = $this->getValue();
     // XML specifies [\x9\xA\xD\x20] as whitespace
     // trim strips more than that
     // no problem though, because these other chars aren't legal in XML
     $trimmedValue = trim($value);
     $preserveWhitespace = $this->getAttributeNS(AgaviXmlConfigParser::NAMESPACE_XML_1998, 'space') == 'preserve';
     $literalize = AgaviToolkit::literalize($this->getAttributeNS(AgaviXmlConfigParser::NAMESPACE_AGAVI_ENVELOPE_LATEST, 'literalize')) !== false;
     if ($literalize) {
         if ($preserveWhitespace && ($trimmedValue === '' || $value != $trimmedValue)) {
             // we must preserve whitespace, and there is leading or trailing whitespace in the original value, so we won't run AgaviToolkit::literalize(), which trims the input and then converts "true" to a boolean and so forth
             // however, we should still expand possible occurrences of config directives
             $value = AgaviToolkit::expandDirectives($value);
         } else {
             // no need to preserve whitespace, or no leading/trailing whitespace, which means we can expand "true", "false" and so forth using AgaviToolkit::literalize()
             $value = AgaviToolkit::literalize($trimmedValue);
         }
     } elseif (!$preserveWhitespace) {
         $value = $trimmedValue;
         if ($value === '') {
             // with or without literalize, an empty string must be converted to NULL if xml:space is default (see ticket #1203 and AEP-100)
             $value = null;
         }
     }
     return $value;
 }
 /**
  * Replace configuration directive identifiers in a string.
  *
  * @param      string The value on which to run the replacement procedure.
  *
  * @return     string The new value.
  *
  * @author     Sean Kerr <*****@*****.**>
  * @author     Johan Mjones <*****@*****.**>
  * @author     David Zülke <*****@*****.**>
  * @since      0.9.0
  *
  * @deprecated Use AgaviToolkit::expandDirectives() instead.
  */
 public static function replaceConstants($value)
 {
     return AgaviToolkit::expandDirectives($value);
 }
 /**
  * Validate a given document according to XMLSchema-instance (xsi)
  * declarations.
  *
  * @param      AgaviXmlConfigDomDocument The document to act upon.
  *
  * @author     David Zülke <*****@*****.**>
  * @author     Noah Fontes <*****@*****.**>
  * @since      1.0.0
  */
 public static function validateXsi(AgaviXmlConfigDomDocument $document)
 {
     // next, find (and validate against) XML schema instance declarations
     $sources = array();
     if ($document->documentElement->hasAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
         // find locations. for namespaces, they are space separated pairs of a namespace URI and a schema location
         $locations = preg_split('/\\s+/', $document->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation'));
         for ($i = 1; $i < count($locations); $i = $i + 2) {
             $sources[] = $locations[$i];
         }
     }
     // no namespace? then it's only one schema location in this attribute
     if ($document->documentElement->hasAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'noNamespaceSchemaLocation')) {
         $sources[] = $document->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'noNamespaceSchemaLocation');
     }
     if ($sources) {
         // we have instances to validate against...
         $schemas = array();
         foreach ($sources as &$source) {
             // so for each location, we need to grab the file and validate against this grabbed source code, as libxml often has a hard time retrieving stuff over HTTP
             $source = AgaviToolkit::expandDirectives($source);
             if (parse_url($source, PHP_URL_SCHEME) === null && !AgaviToolkit::isPathAbsolute($source)) {
                 // the schema location is relative to the XML file
                 $source = dirname($document->documentURI) . DIRECTORY_SEPARATOR . $source;
             }
             $schema = @file_get_contents($source);
             if ($schema === false) {
                 throw new AgaviUnreadableException(sprintf('XML Schema validation file "%s" for configuration file "%s" does not exist or is unreadable', $source, $document->documentURI));
             }
             $schemas[] = $schema;
         }
         // now validate them all
         self::validateXmlschemaSource($document, $schemas);
     }
 }
 private function importModuleXML($accessLocation)
 {
     $document = new AgaviXmlConfigDomDocument();
     $document->load(AgaviToolkit::expandDirectives($accessLocation));
     $this->fetchDQLViews($this->setupXPath($document));
 }
 /**
  * Execute this configuration handler.
  *
  * @param      AgaviXmlConfigDomDocument The document to parse.
  *
  * @return     string Data to be written to a cache file.
  *
  * @throws     <b>AgaviUnreadableException</b> If a requested configuration
  *                                             file does not exist or is not
  *                                             readable.
  * @throws     <b>AgaviParseException</b> If a requested configuration file is
  *                                        improperly formatted.
  *
  * @author     David Zülke <*****@*****.**>
  * @author     Dominik del Bondio <*****@*****.**>
  * @author     Sean Kerr <*****@*****.**>
  * @since      0.9.0
  */
 public function execute(AgaviXmlConfigDomDocument $document)
 {
     // set up our default namespace
     $document->setDefaultNamespace(self::XML_NAMESPACE, 'settings');
     // init our data array
     $data = array();
     $prefix = 'core.';
     foreach ($document->getConfigurationElements() as $cfg) {
         // let's do our fancy work
         if ($cfg->has('system_actions')) {
             foreach ($cfg->get('system_actions') as $action) {
                 $name = $action->getAttribute('name');
                 $data[sprintf('actions.%s_module', $name)] = $action->getChild('module')->getValue();
                 $data[sprintf('actions.%s_action', $name)] = $action->getChild('action')->getValue();
             }
         }
         // loop over <setting> elements; there can be many of them
         foreach ($cfg->get('settings') as $setting) {
             $localPrefix = $prefix;
             // let's see if this buddy has a <settings> parent with valuable information
             if ($setting->parentNode->localName == 'settings') {
                 if ($setting->parentNode->hasAttribute('prefix')) {
                     $localPrefix = $setting->parentNode->getAttribute('prefix');
                 }
             }
             $settingName = $localPrefix . $setting->getAttribute('name');
             if ($setting->hasAgaviParameters()) {
                 $data[$settingName] = $setting->getAgaviParameters();
             } else {
                 $data[$settingName] = $setting->getLiteralValue();
             }
         }
         if ($cfg->has('exception_templates')) {
             foreach ($cfg->get('exception_templates') as $exception_template) {
                 $tpl = AgaviToolkit::expandDirectives($exception_template->getValue());
                 if (!is_readable($tpl)) {
                     throw new AgaviConfigurationException('Exception template "' . $tpl . '" does not exist or is unreadable');
                 }
                 if ($exception_template->hasAttribute('context')) {
                     foreach (array_map('trim', explode(' ', $exception_template->getAttribute('context'))) as $ctx) {
                         $data['exception.templates.' . $ctx] = $tpl;
                     }
                 } else {
                     $data['exception.default_template'] = AgaviToolkit::expandDirectives($tpl);
                 }
             }
         }
     }
     $code = 'AgaviConfig::fromArray(' . var_export($data, true) . ');';
     return $this->generate($code, $document->documentURI);
 }
Ejemplo n.º 18
0
 /**
  * Evaluates a given AgaviConfig per-module directive using the given info.
  *
  * @param      string The name of the module
  * @param      string The relevant name fragment of the directive
  * @param      array  The variables to expand in the directive value.
  *
  * @return     string The final value
  *
  * @author     David Zülke <*****@*****.**>
  * @since      1.0.0
  */
 public static function evaluateModuleDirective($moduleName, $directiveNameFragment, $variables = array())
 {
     return AgaviToolkit::expandVariables(AgaviToolkit::expandDirectives(AgaviConfig::get(sprintf('modules.%s.%s', strtolower($moduleName), $directiveNameFragment))), $variables);
 }
 /**
  * Takes a nested array of AgaviConfigValueHolder containing the routing
  * information and creates the routes in the given routing.
  *
  * @param      AgaviRouting The routing instance to create the routes in.
  * @param      mixed        The "roles" node (element or node list)
  * @param      string       The name of the parent route (if any).
  *
  * @author     Dominik del Bondio <*****@*****.**>
  * @since      0.11.0
  */
 protected function parseRoutes(AgaviRouting $routing, $routes, $parent = null)
 {
     foreach ($routes as $route) {
         $pattern = AgaviToolkit::expandDirectives($route->getAttribute('pattern'));
         $opts = array();
         if ($route->hasAttribute('imply')) {
             $opts['imply'] = AgaviToolkit::literalize($route->getAttribute('imply'));
         }
         if ($route->hasAttribute('cut')) {
             $opts['cut'] = AgaviToolkit::literalize($route->getAttribute('cut'));
         }
         if ($route->hasAttribute('stop')) {
             $opts['stop'] = AgaviToolkit::literalize($route->getAttribute('stop'));
         }
         if ($route->hasAttribute('name')) {
             $opts['name'] = AgaviToolkit::expandDirectives($route->getAttribute('name'));
         }
         if ($route->hasAttribute('source')) {
             $opts['source'] = AgaviToolkit::expandDirectives($route->getAttribute('source'));
         }
         if ($route->hasAttribute('constraint')) {
             $opts['constraint'] = array_map('trim', explode(' ', trim(AgaviToolkit::expandDirectives($route->getAttribute('constraint')))));
         }
         // values which will be set when the route matched
         if ($route->hasAttribute('action')) {
             $opts['action'] = AgaviToolkit::expandDirectives($route->getAttribute('action'));
         }
         if ($route->hasAttribute('locale')) {
             $opts['locale'] = AgaviToolkit::expandDirectives($route->getAttribute('locale'));
         }
         if ($route->hasAttribute('method')) {
             $opts['method'] = AgaviToolkit::expandDirectives($route->getAttribute('method'));
         }
         if ($route->hasAttribute('module')) {
             $opts['module'] = AgaviToolkit::expandDirectives($route->getAttribute('module'));
         }
         if ($route->hasAttribute('output_type')) {
             $opts['output_type'] = AgaviToolkit::expandDirectives($route->getAttribute('output_type'));
         }
         if ($route->has('ignores')) {
             foreach ($route->get('ignores') as $ignore) {
                 $opts['ignores'][] = $ignore->getValue();
             }
         }
         if ($route->has('defaults')) {
             foreach ($route->get('defaults') as $default) {
                 $opts['defaults'][$default->getAttribute('for')] = $default->getValue();
             }
         }
         if ($route->has('callbacks')) {
             $opts['callbacks'] = array();
             foreach ($route->get('callbacks') as $callback) {
                 $opts['callbacks'][] = array('class' => $callback->getAttribute('class'), 'parameters' => $callback->getAgaviParameters());
             }
         }
         $opts['parameters'] = $route->getAgaviParameters();
         if (isset($opts['name']) && $parent) {
             // don't overwrite $parent since it's used later
             $parentName = $parent;
             if ($opts['name'][0] == '.') {
                 while ($parentName && isset($this->unnamedRoutes[$parentName])) {
                     $parentRoute = $routing->getRoute($parentName);
                     $parentName = $parentRoute['opt']['parent'];
                 }
                 $opts['name'] = $parentName . $opts['name'];
             }
         }
         if (isset($opts['action']) && $parent) {
             if ($opts['action'][0] == '.') {
                 $parentRoute = $routing->getRoute($parent);
                 // unwind all empty 'action' attributes of the parent(s)
                 while ($parentRoute && empty($parentRoute['opt']['action'])) {
                     $parentRoute = $routing->getRoute($parentRoute['opt']['parent']);
                 }
                 if (!empty($parentRoute['opt']['action'])) {
                     $opts['action'] = $parentRoute['opt']['action'] . $opts['action'];
                 }
             }
         }
         $name = $routing->addRoute($pattern, $opts, $parent);
         if (!isset($opts['name']) || $opts['name'] !== $name) {
             $this->unnamedRoutes[$name] = true;
         }
         if ($route->has('routes')) {
             $this->parseRoutes($routing, $route->get('routes'), $name);
         }
     }
 }
Ejemplo n.º 20
0
 /**
  * Executes the task.
  */
 public function main()
 {
     if ($this->property === null) {
         throw new BuildException('The property attribute must be specified');
     }
     if ($this->string === null) {
         throw new BuildException('The string attribute must be specified');
     }
     $this->tryLoadAgavi();
     $this->tryBootstrapAgavi();
     $assigns = array();
     foreach ($this->variables as $variable) {
         $assigns[$variable->getName()] = $variable->getValue();
     }
     $result = AgaviToolkit::expandVariables($this->expandDirectives ? AgaviToolkit::expandDirectives($this->string) : $this->string, $assigns);
     $this->project->setUserProperty($this->property, $result);
 }
 private function initializeAutosettings()
 {
     // Try to set the web path to correct urls within the frontend
     if (AgaviConfig::get('core.default_context') == 'web') {
         // Try to set the web path to correct urls within the frontend
         if (AgaviConfig::get('org.icinga.appkit.web_path', null) == null) {
             AgaviConfig::set('org.icinga.appkit.web_path', AppKitStringUtil::extractWebPath(), true, true);
         }
     }
     include AgaviConfigCache::checkConfig(AgaviToolkit::expandDirectives('%core.config_dir%/schedules.xml'));
     // Global temp directory
     AgaviConfig::set('core.tmp_dir', AgaviConfig::get('core.data_dir') . '/tmp');
 }
 public function removeRestrictedCommands()
 {
     $data = $this->data;
     if (!isset($data["option"])) {
         return;
     }
     if (!isset($data["option"]["commands"])) {
         return;
     }
     if (!isset($data["option"]["commands"]["items"])) {
         return;
     }
     $items = $data["option"]["commands"]["items"];
     if (!is_array($items)) {
         return;
     }
     $config = (include AgaviConfigCache::checkConfig(AgaviToolkit::expandDirectives('%core.module_dir%/Api/config/icingaCommands.xml')));
     $toRemove = array();
     foreach ($items as $cmd_name => $cmd_def) {
         if (!isset($config[$cmd_name])) {
             $toRemove[] = $cmd_name;
             continue;
         }
         if (!$config[$cmd_name]["isSimple"]) {
             $toRemove[] = $cmd_name;
         }
     }
     foreach ($toRemove as $removeItem) {
         unset($data["option"]["commands"]["items"][$removeItem]);
     }
     $this->data = $data;
 }
 /**
  * Execute this configuration handler.
  *
  * @param      AgaviXmlConfigDomDocument The document to parse.
  *
  * @return     string Data to be written to a cache file.
  *
  * @throws     <b>AgaviUnreadableException</b> If a requested configuration
  *                                             file does not exist or is not
  *                                             readable.
  * @throws     <b>AgaviParseException</b> If a requested configuration file is
  *                                        improperly formatted.
  *
  * @author     David Zülke <*****@*****.**>
  * @since      0.11.0
  */
 public function execute(AgaviXmlConfigDomDocument $document)
 {
     // set up our default namespace
     $document->setDefaultNamespace(self::XML_NAMESPACE, 'output_types');
     // remember the config file path
     $config = $document->documentURI;
     $data = array();
     $defaultOt = null;
     foreach ($document->getConfigurationElements() as $cfg) {
         if (!$cfg->has('output_types')) {
             continue;
         }
         $otnames = array();
         foreach ($cfg->get('output_types') as $outputType) {
             $otname = $outputType->getAttribute('name');
             if (in_array($otname, $otnames)) {
                 throw new AgaviConfigurationException('Duplicate Output Type "' . $otname . '" in ' . $config);
             }
             $otnames[] = $otname;
         }
         if (!$cfg->getChild('output_types')->hasAttribute('default')) {
             throw new AgaviConfigurationException('No default Output Type specified in ' . $config);
         }
         foreach ($cfg->get('output_types') as $outputType) {
             $outputTypeName = $outputType->getAttribute('name');
             $data[$outputTypeName] = isset($data[$outputTypeName]) ? $data[$outputTypeName] : array('parameters' => array(), 'default_renderer' => null, 'renderers' => array(), 'layouts' => array(), 'default_layout' => null, 'exception_template' => null);
             if ($outputType->has('renderers')) {
                 foreach ($outputType->get('renderers') as $renderer) {
                     $rendererName = $renderer->getAttribute('name');
                     $data[$outputTypeName]['renderers'][$rendererName] = array('class' => $renderer->getAttribute('class'), 'instance' => null, 'parameters' => $renderer->getAgaviParameters(array()));
                 }
                 $data[$outputTypeName]['default_renderer'] = $outputType->getChild('renderers')->getAttribute('default');
             }
             if ($outputType->has('layouts')) {
                 foreach ($outputType->get('layouts') as $layout) {
                     $layers = array();
                     if ($layout->has('layers')) {
                         foreach ($layout->get('layers') as $layer) {
                             $slots = array();
                             if ($layer->has('slots')) {
                                 foreach ($layer->get('slots') as $slot) {
                                     $slots[$slot->getAttribute('name')] = array('action' => $slot->getAttribute('action'), 'module' => $slot->getAttribute('module'), 'output_type' => $slot->getAttribute('output_type'), 'request_method' => $slot->getAttribute('method'), 'parameters' => $slot->getAgaviParameters(array()));
                                 }
                             }
                             $layers[$layer->getAttribute('name')] = array('class' => $layer->getAttribute('class', $this->getParameter('default_layer_class', 'AgaviFileTemplateLayer')), 'parameters' => $layer->getAgaviParameters(array()), 'renderer' => $layer->getAttribute('renderer'), 'slots' => $slots);
                         }
                     }
                     $data[$outputTypeName]['layouts'][$layout->getAttribute('name')] = array('layers' => $layers, 'parameters' => $layout->getAgaviParameters(array()));
                 }
                 $data[$outputTypeName]['default_layout'] = $outputType->getChild('layouts')->getAttribute('default');
             }
             if ($outputType->hasAttribute('exception_template')) {
                 $data[$outputTypeName]['exception_template'] = AgaviToolkit::expandDirectives($outputType->getAttribute('exception_template'));
                 if (!is_readable($data[$outputTypeName]['exception_template'])) {
                     throw new AgaviConfigurationException('Exception template "' . $data[$outputTypeName]['exception_template'] . '" does not exist or is unreadable');
                 }
             }
             $data[$outputTypeName]['parameters'] = $outputType->getAgaviParameters($data[$outputTypeName]['parameters']);
         }
         $defaultOt = $cfg->getChild('output_types')->getAttribute('default');
     }
     if (!isset($data[$defaultOt])) {
         $error = 'Configuration file "%s" specifies undefined default Output Type "%s".';
         $error = sprintf($error, $document->documentURI, $defaultOt);
         throw new AgaviConfigurationException($error);
     }
     $code = array();
     foreach ($data as $outputTypeName => $outputType) {
         $code[] = '$ot = new AgaviOutputType();';
         $code[] = sprintf('$ot->initialize($this->context, %s, %s, %s, %s, %s, %s, %s);', var_export($outputType['parameters'], true), var_export($outputTypeName, true), var_export($outputType['renderers'], true), var_export($outputType['default_renderer'], true), var_export($outputType['layouts'], true), var_export($outputType['default_layout'], true), var_export($outputType['exception_template'], true));
         $code[] = sprintf('$this->outputTypes[%s] = $ot;', var_export($outputTypeName, true));
     }
     $code[] = sprintf('$this->defaultOutputType = %s;', var_export($defaultOt, true));
     return $this->generate($code, $config);
 }
 public function readJsonFromConfig()
 {
     $config = (include AgaviConfigCache::checkConfig(AgaviToolkit::expandDirectives('%core.config_dir%/menu.xml')));
     $menu = $this->getAllowedMenuPoints($config);
     return $menu;
 }
 /**
  * Converts an AgaviXmlConfigDomElement into an array.
  *
  * @param      AgaviXmlConfigDomElement The configuration element to convert.
  * @param      bool                     Whether this is a top level element.
  *
  * @return     array The configuration values as an array.
  *
  * @author     Dominik del Bondio <*****@*****.**>
  * @author     David Zülke <*****@*****.**>
  * @since      0.11.0
  */
 protected function convertToArray(AgaviXmlConfigDomElement $item, $topLevel = false)
 {
     $idAttribute = $this->getParameter('id_attribute', 'name');
     $valueKey = $this->getParameter('value_key', 'value');
     $forceArrayValues = $this->getParameter('force_array_values', false);
     $attributePrefix = $this->getParameter('attribute_prefix', '');
     $literalize = $this->getParameter('literalize', true);
     $singularParentName = AgaviInflector::singularize($item->getName());
     $data = array();
     $attribs = $item->getAttributes();
     $numAttribs = count($attribs);
     if ($idAttribute && $item->hasAttribute($idAttribute)) {
         $numAttribs--;
     }
     foreach ($item->getAttributes() as $name => $value) {
         if ($topLevel && in_array($name, array('context', 'environment')) || $name == $idAttribute) {
             continue;
         }
         if ($literalize) {
             $value = AgaviToolkit::literalize($value);
         }
         if (!isset($data[$name])) {
             $data[$attributePrefix . $name] = $value;
         }
     }
     if (!(int) $item->ownerDocument->getXpath()->evaluate(sprintf('count(*[namespace-uri() = "%s"])', $item->ownerDocument->getDefaultNamespaceUri()), $item)) {
         if ($literalize) {
             $val = $item->getLiteralValue();
         } else {
             $val = $item->getValue();
         }
         if ($val === null) {
             $val = '';
         }
         if (!$topLevel && ($numAttribs || $forceArrayValues)) {
             $data[$valueKey] = $val;
         } elseif (!$topLevel) {
             $data = $val;
         }
     } else {
         $names = array();
         $children = $item->ownerDocument->getXpath()->query(sprintf('*[namespace-uri() = "%s"]', $item->ownerDocument->getDefaultNamespaceUri()), $item);
         foreach ($children as $child) {
             $names[] = $child->getName();
         }
         $dupes = array();
         foreach (array_unique(array_diff_assoc($names, array_unique($names))) as $name) {
             $dupes[] = $name;
         }
         foreach ($children as $key => $child) {
             $hasId = $idAttribute && $child->hasAttribute($idAttribute);
             $isDupe = in_array($child->getName(), $dupes);
             $hasParent = $child->getName() == $singularParentName && $item->getName() != $singularParentName;
             if (($hasId || $isDupe) && !$hasParent) {
                 // it's one of multiple tags in this level without the respective plural form as the parent node
                 if (!isset($data[$idx = AgaviInflector::pluralize($child->getName())])) {
                     $data[$idx] = array();
                 }
                 $hasParent = true;
                 $to =& $data[$idx];
             } else {
                 $to =& $data;
             }
             if ($hasId) {
                 $key = $child->getAttribute($idAttribute);
                 if ($literalize) {
                     // no literalize, just constants!
                     $key = AgaviToolkit::expandDirectives($key);
                 }
                 $to[$key] = $this->convertToArray($child);
             } elseif ($hasParent) {
                 $to[] = $this->convertToArray($child);
             } else {
                 $to[$child->getName()] = $this->convertToArray($child);
             }
         }
     }
     return $data;
 }
Ejemplo n.º 26
0
 /**
  * Runs AgaviToolkit::expandDirectives() on all attributes and text nodes of
  * the given file and writes a it to a new file in the Agavi cache directory.
  *
  * @param      string The path to the xml file
  * 
  * @return     string The path to the expanded file
  *
  * @author     Dominik del Bondio <*****@*****.**>
  * @since      1.1.0
  */
 private static function expandConfiguration($file)
 {
     // file does not exist, let PHPUnit handle that case
     if (!is_readable($file) || !is_file($file)) {
         return $file;
     }
     $doc = new DOMDocument();
     $doc->substituteEntities = true;
     $doc->load($file);
     $xpath = new DOMXPath($doc);
     $attributeNodes = $xpath->query('//@*');
     foreach ($attributeNodes as $attributeNode) {
         $attributeNode->value = AgaviToolkit::expandDirectives($attributeNode->value);
     }
     $textNodes = $xpath->query('//text()');
     foreach ($textNodes as $textNode) {
         $textNode->nodeValue = AgaviToolkit::expandDirectives($textNode->nodeValue);
     }
     $translatedFile = AgaviConfigCache::getCacheName($file);
     AgaviConfigCache::writeCacheFile($file, $translatedFile, $doc->saveXML());
     return $translatedFile;
 }