/** * load configuration from a file * * @access public * @param string $configFile full path of the config file * @param array $options various options, depending on the reader * @return array $config complete configuration */ function loadConfigFile($configFile, $options = array()) { if (!function_exists("wddx_add_vars")) { return patErrorManager::raiseError(PATCONFIGURATION_ERROR_DRIVER_NOT_WORKING, "WDDX extension is not installed on your system."); } $fp = @fopen($configFile, "r"); $wddx = fread($fp, filesize($configFile)); $conf = wddx_deserialize($wddx); if ($conf === NULL) { return patErrorManager::raiseError(PATCONFIGURATION_ERROR_CONFIG_INVALID, "{$configFile} is no valid WDDX file."); } return array("config" => $conf, "externalFiles" => array(), "cacheAble" => true); }
/** * create an ini representation of the current config * * @access private * @param array $config config to serialize * @param array $options options for the serialization * @return string $content xml representation */ function serializeConfig($config, $options) { if (!function_exists("wddx_add_vars")) { return patErrorManager::raiseError(PATCONFIGURATION_ERROR_DRIVER_NOT_WORKING, "WDDX extension is not installed on your system."); } if (!isset($options["comment"])) { $options["comment"] = "Configuration generated by patConfiguration v" . $this->configObj->systemVars["appVersion"] . ", (c) " . implode(",", $this->configObj->systemVars["author"]); } $options["comment"] = $this->replaceXMLSpecialchars($options["comment"]); $packet_id = wddx_packet_start($options["comment"]); foreach ($config as $key => $value) { ${$key} = $value; wddx_add_vars($packet_id, $key); } $packet = wddx_packet_end($packet_id); $config = "<?xml version=\"1.0\" encoding=\"{$this->configObj->encoding}\"?>" . $packet; return $config; }
/** * call the function * * @access public * @param array parameters of the function (= attributes of the tag) * @param string content of the tag * @return string content to insert into the template */ function call($params, $content) { $tmpl = $params['template']; unset($params['template']); if (!$this->_tmpl->exists($tmpl)) { return patErrorManager::raiseError(PATTEMPLATE_FUNCTION_CALL_ERROR_NO_TEMPLATE, 'Template ' . $tmpl . ' does not exist'); } /** * clear template and all of its dependencies */ $this->_tmpl->clearTemplate($tmpl, true); /** * add variables */ $this->_tmpl->addVars($tmpl, $params); $this->_tmpl->addVar($tmpl, 'CONTENT', $content); /** * get content */ return $this->_tmpl->getParsedTemplate($tmpl); }
/** * load the translation file * * @access private * @param string current input that is used by patTemplate * @return boolean true on success */ function _loadTranslationFile($input) { foreach ($this->_globalconfig['lang'] as $lang) { $translationFile = sprintf($this->_config[$input]['langFile'], $lang); if (!file_exists($translationFile)) { if ($this->_tmpl->getOption('translationAutoCreate') && file_exists($this->_config[$input]['sentenceFile'])) { if (!@copy($this->_config[$input]['sentenceFile'], $translationFile)) { patErrorManager::raiseWarning(PATTTEMPLATE_FUNCTION_TRANSLATE_WARNING_LANGFILE_NOT_CREATABLE, 'A language file could not be created', 'Tried to create the language file [' . $translationFile . ']. Please check that I have write access to the parent folder, or turn off the translateAutoCreate option and create it manually.'); } } continue; } $tmp = @parse_ini_file($translationFile); if (is_array($tmp)) { $tmp = array_map(array($this, '_unescape'), $tmp); $this->_translation[$input] = $tmp; return true; } } return false; }
/** * compile a template * * @access public * @param string name of the template */ function compileTemplate($template) { $name = strtolower($template); if (!isset($this->_templates[$template])) { return patErrorManager::raiseWarning(PATTEMPLATE_WARNING_NO_TEMPLATE, "Template '{$name}' does not exist."); } /** * check, if the template has been loaded * and load it if necessary. */ if ($this->_templates[$template]['loaded'] !== true) { if ($this->_templates[$template]['attributes']['parse'] == 'on') { $result = $this->readTemplatesFromInput($this->_templates[$template]['attributes']['src'], $this->_templates[$template]['attributes']['reader'], null, $template); } else { $result = $this->loadTemplateFromInput($this->_templates[$template]['attributes']['src'], $this->_templates[$template]['attributes']['reader'], $template); } if (patErrorManager::isError($result)) { return $result; } } $this->_addToCode(''); $this->_addToCode('/**'); $this->_addToCode(' * Compiled version of ' . $template); $this->_addToCode(' *'); $this->_addToCode(' * Template type is ' . $this->_templates[$template]['attributes']['type']); $this->_addToCode(' */'); /** * start the output */ $this->_addToCode('function ' . $template . '()'); $this->_addToCode('{'); $this->_addToCode('$this->_prepareCompiledTemplate( "' . $template . '" );', 1); $this->_addToCode('$this->prepareTemplate( "' . $template . '" );', 1); /** * attributes */ $this->_addToCode('$this->_templates["' . $template . '"]["attributes"] = unserialize( \'' . serialize($this->_templates[$template]['attributes']) . '\' );', 1, 'Read the attributes'); /** * copyVars */ $this->_addToCode('$this->_templates["' . $template . '"]["copyVars"] = unserialize( \'' . serialize($this->_templates[$template]['copyVars']) . '\' );', 1, 'Read the copyVars'); /** * check visibility */ $this->_addToCode('if( $this->_templates["' . $template . '"]["attributes"]["visibility"] != "hidden" ) {', 1, 'Check, whether template is hidden'); /** * autoloop the template */ $this->_addToCode('$this->_templates["' . $template . '"]["iteration"] = 0;', 2, 'Reset the iteration'); $this->_addToCode('$loop = count( $this->_vars["' . $template . '"]["rows"] );', 2, 'Get the amount of loops'); $this->_addToCode('$loop = max( $loop, 1 );', 2); $this->_addToCode('$this->_templates["' . $template . '"]["loop"] = $loop;', 2); $this->_addToCode('for( $i = 0; $i < $loop; $i++ ) {', 2, 'Traverse all variables.'); /** * fetch the variables */ $this->_addToCode('unset( $this->_templates["' . $template . '"]["vars"] );', 3); $this->_addToCode('$this->_fetchVariables("' . $template . '");', 3); /** * different templates have to be compiled differently */ switch ($this->_templates[$template]['attributes']['type']) { /** * modulo template */ case 'modulo': $this->_compileModuloTemplate($template); break; /** * simple condition template */ /** * simple condition template */ case 'simplecondition': $this->_compileSimpleConditionTemplate($template); break; /** * condition template */ /** * condition template */ case 'condition': $this->_compileConditionTemplate($template); break; /** * standard template */ /** * standard template */ default: $this->_compileStandardTemplate($template); break; } $this->_addToCode('$this->_templates["' . $template . '"]["iteration"]++;', 3); $this->_addToCode('}', 2); $this->_addToCode('}', 1); $this->_addToCode('}'); /** * remember this template */ array_push($this->_compiledTemplates, $template); }
/** * Displays useful information about all or named templates * * This method breaks BC, as it now awaits an array instead of * unlimited parameters. * * @param mixed array of templates that should be dumped, or null if you * want all templates to be dumped * @param string dumper * @access public */ function dump($restrict = null, $dumper = 'Html') { if (is_string($restrict)) { $restrict = array($restrict); } $dumper =& $this->loadModule('Dump', $dumper); if (patErrorManager::isError($dumper)) { return $dumper; } if (is_null($restrict)) { $templates = $this->_templates; $vars = $this->_vars; } else { $restrict = array_map('strtolower', $restrict); $templates = array(); $vars = array(); foreach ($this->_templates as $name => $spec) { if (!in_array($name, $restrict)) { continue; } $templates[$name] = $spec; $vars[$name] = $this->_vars[$name]; } } $dumper->displayHeader(); $dumper->dumpGlobals($this->_globals); $dumper->dumpTemplates($templates, $vars); $dumper->displayFooter(); return true; }
/** * parse an external xml file * * @param string filename, without dirname * @return boolean true on success, patError on failure */ function parseXMLFile($file) { // add it to included files array_push($this->includedFiles, $file); $parserCount = count($this->parsers); $this->parsers[$parserCount] = $this->createParser(); if (!($fp = @fopen($file, 'r'))) { return patErrorManager::raiseError(PATCONFIGURATION_ERROR_FILE_NOT_FOUND, 'Could not open XML file ' . $file); } array_push($this->xmlFiles, $file); flock($fp, LOCK_SH); while ($data = fread($fp, 4096)) { if (!xml_parse($this->parsers[$parserCount], $data, feof($fp))) { $message = sprintf('XML error: %s at line %d in file %s', xml_error_string(xml_get_error_code($this->parsers[$parserCount])), xml_get_current_line_number($this->parsers[$parserCount]), $file); array_pop($this->xmlFiles); flock($fp, LOCK_UN); fclose($fp); xml_parser_free($this->parsers[$parserCount]); return patErrorManager::raiseError(PATCONFIGURATION_ERROR_CONFIG_INVALID, $message); } } array_pop($this->xmlFiles); flock($fp, LOCK_UN); fclose($fp); xml_parser_free($this->parsers[$parserCount]); return true; }
/** * Get a static property. * * Static properties are stored in an array in a global variable, * until PHP5 is ready to use. * * @static * @param string property name * @return mixed property value * @see setStaticProperty() */ function &getStaticProperty($property) { if (isset($GLOBALS["_patForms"][$property])) { return $GLOBALS["_patForms"][$property]; } return patErrorManager::raiseWarning(PATFORMS_ERROR_NO_STATIC_PROPERTY, 'Static property "' . $property . '" could not be retreived, it does not exist.'); }
<?php require_once _CFG_XML_PATERROR; patErrorManager::setErrorHandling(E_ALL, 'verbose'); require_once _CFG_XML_PATCONFIG; function xmlconfig_info() { $info["nombre"] = "XMLConfig"; $info["version"] = "1.0"; $info["grupo"] = "servicios"; $info["visible"] = "false"; return $info; } function xmlconfig_test() { $test = array(); $test[0] = true; $test[1] = "mod_xmlconfig test...<br>"; $test[1] .= "==================<br>"; if ($test[0]) { $test[1] .= "El módulo esta correctamente instalado<br>"; } return $test; } function xmlconfig_buscaid($id, $XML_RUTA) { $conf = new patConfiguration(); $conf->setConfigDir(_CFG_XML_CONFIG_DIR); $conf->parseConfigFile($XML_RUTA); $x = 0; for ($i = 1; $x < count($conf->getConfigValue()); $i++) {
/** * get the contents of a file * * @access private * @param string filename * @return string file contents */ function _getFileContents($file) { if (!$this->_isRemote && (!file_exists($file) || !is_readable($file))) { return patErrorManager::raiseError(PATTEMPLATE_READER_ERROR_NO_INPUT, "Could not load templates from {$file}."); } if (function_exists('file_get_contents')) { $content = @file_get_contents($file); } else { $content = implode('', file($file)); } /** * store the file name */ array_push($this->_files, $file); return $content; }
/** * handle a variable * * @access private * @param array attributes of the var tag * @param string cdata between the tags (will be used as default) * @return boolean true on success */ function _handleVariable($attributes, $data) { if (!isset($attributes['name'])) { return patErrorManager::raiseError(PATTEMPLATE_READER_ERROR_NO_NAME_SPECIFIED, $this->_createErrorMessage('Variable needs a name attribute')); } $specs = array(); /** * get name */ $name = strtoupper($attributes['name']); unset($attributes['name']); $specs['name'] = $name; /** * use data as default value */ if (isset($attributes['default'])) { $data = $attributes['default']; $specs['default'] = $data; unset($attributes['default']); } else { if (!empty($data)) { $specs['default'] = $data; } } /** * add it to template, if it's not hidden */ if (!isset($attributes['hidden']) || $attributes['hidden'] == 'no') { $this->_characterData($this->_startTag . strtoupper($name) . $this->_endTag); } if (isset($attributes['hidden'])) { unset($attributes['hidden']); } /** * copy value from any other variable */ if (isset($attributes['copyfrom'])) { $specs['copyfrom'] = strtoupper($attributes['copyfrom']); if (strstr($specs['copyfrom'], '.')) { $specs['copyfrom'] = explode('.', $specs['copyfrom']); $specs['copyfrom'][0] = strtolower($specs['copyfrom'][0]); } unset($attributes['copyfrom']); } if (isset($attributes['modifier'])) { $modifier = $attributes['modifier']; unset($attributes['modifier']); $type = isset($attributes['modifiertype']) ? $attributes['modifiertype'] : 'auto'; if (isset($attributes['modifiertype'])) { unset($attributes['modifiertype']); } $specs['modifier'] = array('mod' => $modifier, 'type' => $type, 'params' => $attributes); } if (!empty($specs)) { $this->_addToParentTemplate('varspecs', $specs, $name); } }
/** * [helper method] wrapper for the {@link createTag()} method which automates the tag * creation by creating the tag from the current attribute collection and element type. * * @access protected * @return mixed $result The created tag, or false if failed. * @see elementType * @see attributes * @see createTag() */ function toHtml() { $attributes = $this->getAttributesFor($this->getFormat()); if (patErrorManager::isError($attributes)) { return $attributes; } return $this->createTag($this->elementType[$this->getFormat()], "full", $attributes); }
/** * write a configfile * * * @access public * @param string $filename name of the configfile * @param string $format format of the config file * @param array $options options, see the writer driver for details */ function writeConfigFile($filename, $options = NULL, $oldOptions = NULL) { // older versions needed the filetype as secand parameter if (!is_array($options)) { $options = array('filetype' => $options); } // options had to be specified as third param prior to version 2.0 if (is_array($oldOptions)) { $options = array_merge($oldOptions, $options); } // no filetype given, extract from filename if (isset($options['filetype']) && !empty($options['filetype'])) { $filetype = $options['filetype']; } else { $filetype = $this->_getFiletype($filename); } $writer =& $this->_getDriver($filetype, 'Writer'); if (!is_object($writer)) { return $writer; } // seriaize the content $content = $writer->serializeConfig($this->conf, $options); if ($content) { $file = $this->getFullPath($filename, NULL, false); if (patErrorManager::isError($file)) { return $file; } $fp = @fopen($file, 'w'); if ($fp) { flock($fp, LOCK_EX); fputs($fp, $content); flock($fp, LOCK_UN); fclose($fp); $oldMask = umask(00); chmod($file, 0666); umask($oldMask); } } }
/** * Returns a parsed template * * @access public * @param string $name The name of the template */ function fetch($name) { $result = $this->getParsedTemplate($name, true); /** * error happened */ if (patErrorManager::isError($result)) { return $result; } return $result; }
/** * create an xml representation of the current config * * @access private * @param array $config config to serialize * @param array $options options for the serialization * @return string $content xml representation */ function serializeConfig($config, $options) { if (!isset($options["mode"])) { $options["mode"] = "plain"; } $this->openTags = array(); ksort($config); reset($config); if ($options["mode"] == "pretty") { $options["nl"] = "\n"; } else { $options["nl"] = ""; } $options["depth"] = 0; $xml = "<?xml version=\"1.0\" encoding=\"{$this->configObj->encoding}\"?>\n"; $xml .= "<configuration>" . $options["nl"]; // add comment in pretty mode if ($options["mode"] == "pretty") { $xml .= "\t<!--\n"; $xml .= "\t\tConfiguration generated by patConfiguration v" . $this->configObj->systemVars["appVersion"] . "\n"; $xml .= "\t\t(c) " . implode(",", $this->configObj->systemVars["author"]) . "\n"; $xml .= "\t\tdownload at http://www.php-tools.net\n"; $xml .= "\t\tgenerated on " . date("Y-m-d H:i:s", time()) . "\n"; $xml .= "\t-->\n"; } ++$options["depth"]; foreach ($config as $key => $value) { $path = explode(".", $key); switch (count($path)) { case 0: patErrorManager::raiseWarning(PATCONFIGURATION_WARNING_CONFIGVALUE_WITHOUT_NAME, "configValue without name found!"); default: $openNew = array(); $tag = array_pop($path); $start = max(count($path), count($this->openTags)); for ($i = $start - 1; $i >= 0; $i--) { if (!isset($this->openTags[$i]) || $path[$i] != $this->openTags[$i]) { if (count($this->openTags) > 0) { array_pop($this->openTags); $options["depth"]--; if ($options["mode"] == "pretty") { $xml .= str_repeat("\t", $options["depth"]); } $xml .= "</path>" . $options["nl"]; } if (isset($path[$i])) { array_push($openNew, $path[$i]); } } } while ($path = array_pop($openNew)) { array_push($this->openTags, $path); $xml .= str_repeat("\t", $options["depth"]); $xml .= "<path name=\"" . $path . "\">" . $options["nl"]; $options['depth']++; } $xml .= $this->createTag($tag, $value, $options); break; } } // close all open tags while ($open = array_pop($this->openTags)) { --$options["depth"]; $xml .= str_repeat("\t", $options["depth"]); $xml .= "</path>" . $options["nl"]; } $xml .= "</configuration>"; return $xml; }
/** * Parse the template location syntax to a query * * @access private * @param string * @param DB_common */ function parseInputStringToQuery($input, $db) { // Input is no query if (strstr($input, 'SELECT') !== false) { return $input; } $matches = array(); if (!preg_match('/^([a-z]+)\\[([^]]+)\\]\\/@([a-z]+)$/i', $input, $matches)) { return patErrorManager::raiseError(PATTEMPLATE_READER_DB_ERROR_UNKNOWN_INPUT, 'Could not parse input string.'); } $table = $matches[1]; $templateField = $matches[3]; $where = array(); $tmp = explode(',', $matches[2]); foreach ($tmp as $clause) { list($field, $value) = explode('=', trim($clause)); if ($field[0] !== '@') { return patErrorManager::raiseError(PATTEMPLATE_READER_DB_ERROR_UNKNOWN_INPUT, 'Could not parse input string.'); } $field = substr($field, 1); array_push($where, $field . '=' . $db->quoteSmart($value)); } $query = sprintf('SELECT %s FROM %s WHERE %s', $templateField, $table, implode(' AND ', $where)); return $query; }
/** * call the function * * @access public * @param array parameters of the function (= attributes of the tag) * @param string content of the tag * @return string content to insert into the template */ function call($params, $content) { // get the name of the template to use if (isset($params['template'])) { $tmpl = $params['template']; unset($params['template']); } elseif (isset($params['_originalTag'])) { $tmpl = $params['_originalTag']; unset($params['_originalTag']); } else { return patErrorManager::raiseError(PATTEMPLATE_FUNCTION_CALL_ERROR_NO_TEMPLATE, 'No template for Call function specified.'); } if (!$this->_tmpl->exists($tmpl)) { $tmpl = strtolower($tmpl); // try some autoloading magic $componentLocation = $this->_tmpl->getOption('componentFolder'); $componentExtension = $this->_tmpl->getOption('componentExtension'); $filename = $componentLocation . '/' . $tmpl . '.' . $componentExtension; $this->_tmpl->readTemplatesFromInput($filename); // still does not exist if (!$this->_tmpl->exists($tmpl)) { return patErrorManager::raiseError(PATTEMPLATE_FUNCTION_CALL_ERROR_NO_TEMPLATE, 'Template ' . $tmpl . ' does not exist'); } } /** * clear template and all of its dependencies */ $this->_tmpl->clearTemplate($tmpl, true); /** * add variables */ $this->_tmpl->addVars($tmpl, $params); $this->_tmpl->addVar($tmpl, 'CONTENT', $content); /** * get content */ return $this->_tmpl->getParsedTemplate($tmpl); }
/** * handleError: die * display error-message and die * * @access private * @param object $error patError-Object * @param array $options options for handler * @return object $error error-object * @see raise() */ function &handleErrorDie(&$error, $options) { $level_human = patErrorManager::translateErrorLevel($error->getLevel()); if (isset($_SERVER['HTTP_HOST'])) { // output as html jexit("<br /><b>pat-{$level_human}</b> " . $error->getMessage() . "<br />\n"); } else { // output as simple text if (defined('STDERR')) { fwrite(STDERR, "pat-{$level_human} " . $error->getMessage() . "\n"); } else { jexit("pat-{$level_human} " . $error->getMessage() . "\n"); } } return $error; }
/** * write a configfile * * * @access public * @param string $filename name of the configfile * @param string $format format of the config file * @param array $options options, see the writer driver for details */ function writeConfigFile($filename, $options = NULL, $oldOptions = NULL) { // older versions needed the filetype as secand parameter if (!is_array($options)) { $options = array('filetype' => $options); } // options had to be specified as third param prior to version 2.0 if (is_array($oldOptions)) { $options = array_merge($oldOptions, $options); } // no filetype given, extract from filename if (isset($options['filetype']) && !empty($options['filetype'])) { $filetype = $options['filetype']; } else { $filetype = $this->_getFiletype($filename); } $writer =& $this->_getDriver($filetype, 'Writer'); if (patErrorManager::isError($writer)) { return $writer; } // serialize the content $content = $writer->serializeConfig($this->conf, $options); if (patErrorManager::isError($content)) { return $content; } $file = $this->getFullPath($filename, NULL, false); if (patErrorManager::isError($file)) { return $file; } $fp = @fopen($file, 'w'); if (!$fp) { return patErrorManager::raiseError(PATCONFIGURATION_ERROR_FILE_NOT_WRITABLE, 'Could not write configuration to file [' . $file . '], file could not be opened.'); } flock($fp, LOCK_EX); fputs($fp, $content); flock($fp, LOCK_UN); fclose($fp); $oldMask = umask(00); chmod($file, 0666); umask($oldMask); return true; }