Beispiel #1
0
 function testEmails($locale, $referenceLocale)
 {
     import('install.Installer');
     // Bring in data dir
     $errors = array();
     $xmlParser = new XMLParser();
     $referenceEmails =& $xmlParser->parse(INSTALLER_DATA_DIR . "/data/locale/{$referenceLocale}/email_templates_data.xml");
     $emails =& $xmlParser->parse(INSTALLER_DATA_DIR . "/data/locale/{$locale}/email_templates_data.xml");
     $emailsTable =& $emails->getChildByName('table');
     $referenceEmailsTable =& $referenceEmails->getChildByName('table');
     $matchedReferenceEmails = array();
     // Pass 1: For all translated emails, check that they match
     // against reference translations.
     for ($emailIndex = 0; ($email =& $emailsTable->getChildByName('row', $emailIndex)) !== null; $emailIndex++) {
         // Extract the fields from the email to be tested.
         $fields = $this->extractFields($email);
         // Locate the reference email and extract its fields.
         for ($referenceEmailIndex = 0; ($referenceEmail =& $referenceEmailsTable->getChildByName('row', $referenceEmailIndex)) !== null; $referenceEmailIndex++) {
             $referenceFields = $this->extractFields($referenceEmail);
             if ($referenceFields['email_key'] == $fields['email_key']) {
                 break;
             }
         }
         // Check if a matching reference email was found.
         if (!isset($referenceEmail) || $referenceEmail === null) {
             $errors[EMAIL_ERROR_EXTRA_EMAIL][] = array('key' => $fields['email_key']);
             continue;
         }
         // We've successfully found a matching reference email.
         // Compare it against the translation.
         $bodyParams = $this->getParameterNames($fields['body']);
         $referenceBodyParams = $this->getParameterNames($referenceFields['body']);
         if ($bodyParams !== $referenceBodyParams) {
             $errors[EMAIL_ERROR_DIFFERING_PARAMS][] = array('key' => $fields['email_key'], 'mismatch' => array_diff($bodyParams, $referenceBodyParams));
         }
         $subjectParams = $this->getParameterNames($fields['subject']);
         $referenceSubjectParams = $this->getParameterNames($referenceFields['subject']);
         if ($subjectParams !== $referenceSubjectParams) {
             $errors[EMAIL_ERROR_DIFFERING_PARAMS][] = array('key' => $fields['email_key'], 'mismatch' => array_diff($subjectParams, $referenceSubjectParams));
         }
         $matchedReferenceEmails[] = $fields['email_key'];
         unset($email);
         unset($referenceEmail);
     }
     // Pass 2: Make sure that there are no missing translations.
     for ($referenceEmailIndex = 0; ($referenceEmail =& $referenceEmailsTable->getChildByName('row', $referenceEmailIndex)) !== null; $referenceEmailIndex++) {
         // Extract the fields from the email to be tested.
         $referenceFields = $this->extractFields($referenceEmail);
         if (!in_array($referenceFields['email_key'], $matchedReferenceEmails)) {
             $errors[EMAIL_ERROR_MISSING_EMAIL][] = array('key' => $referenceFields['email_key']);
         }
     }
     $this->displayEmailErrors($locale, $errors);
 }
    /**
     * Scan the plugin registry for custom roles, tasks and commands,
     * and register them as existing.
     */
    function scan()
    {
        static $scanned = false;
        if ($scanned) {
            return;
        }

        $scanned = true;
        $parser = new XMLParser;
        $schemapath = Main::getDataPath();
        if (!file_exists(Main::getDataPath() . '/channel-1.0.xsd')) {
            $schemapath = realpath(__DIR__ . '/../../data');
        }

        $roleschema    = $schemapath . '/customrole-2.0.xsd';
        $taskschema    = $schemapath . '/customtask-2.0.xsd';
        $commandschema = $schemapath . '/customcommand-2.0.xsd';

        try {
            foreach (Config::current()->channelregistry as $channel) {
                foreach ($this->listPackages($channel->name) as $package) {
                    $chan = $channel->name;
                    $files = $this->info($package, $chan, 'installedfiles');
                    // each package may only have 1 role, task or command
                    foreach ($files as $path => $info) {
                        switch ($info['role']) {
                            case 'customrole' :
                                $roleinfo = $parser->parse($path, $roleschema);
                                $roleinfo = $roleinfo['role'];
                                static::makeAutoloader($roleinfo, 'role');
                                Installer\Role::registerCustomRole($roleinfo);
                                continue 2;
                            case 'customtask' :
                                $taskinfo = $parser->parse($path, $taskschema);
                                $taskinfo = $taskinfo['task'];
                                static::makeAutoloader($taskinfo, 'task');
                                Task\Common::registerCustomTask($taskinfo);
                                continue 2;
                            case 'customcommand' :
                                $commands = $parser->parse($path, $commandschema);
                                $this->addCommand($commands['commands']['command']);
                                continue 2;
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            Logger::log(0, 'Unable to add all custom roles/tasks/commands: ' . $e);
        }
    }
Beispiel #3
0
 /**
  * Install conference settings from an XML file.
  * @param $id int ID of scheduled conference/conference for settings to apply to
  * @param $filename string Name of XML file to parse and install
  * @param $paramArray array Optional parameters for variable replacement in settings
  */
 function installSettings($id, $filename, $paramArray = array())
 {
     $xmlParser = new XMLParser();
     $tree = $xmlParser->parse($filename);
     if (!$tree) {
         $xmlParser->destroy();
         return false;
     }
     foreach ($tree->getChildren() as $setting) {
         $nameNode =& $setting->getChildByName('name');
         $valueNode =& $setting->getChildByName('value');
         if (isset($nameNode) && isset($valueNode)) {
             $type = $setting->getAttribute('type');
             $isLocaleField = $setting->getAttribute('locale');
             $name =& $nameNode->getValue();
             if ($type == 'date') {
                 $value = strtotime($valueNode->getValue());
             } elseif ($type == 'object') {
                 $arrayNode =& $valueNode->getChildByName('array');
                 $value = $this->_buildObject($arrayNode, $paramArray);
             } else {
                 $value = $this->_performReplacement($valueNode->getValue(), $paramArray);
             }
             // Replace translate calls with translated content
             $this->updateSetting($id, $name, $isLocaleField ? array(Locale::getLocale() => $value) : $value, $type, $isLocaleField);
         }
     }
     $xmlParser->destroy();
 }
Beispiel #4
0
 /**
  * Parse an XML file with the specified handler and return data in an object.
  * @see xml.XMLParser::parse()
  * @param $handler reference to the handler to use with the parser.
  */
 function &parseWithHandler($file, &$handler)
 {
     $parser = new XMLParser();
     $parser->setHandler($handler);
     $data =& $parser->parse($file);
     $parser->destroy();
     return $data;
 }
 /**
  * Parse an RT version XML file.
  * @param $file string path to the XML file
  * @return RTVersion
  */
 function &parse($file)
 {
     $parser = new XMLParser();
     $tree = $parser->parse($file);
     $parser->destroy();
     $version = false;
     if ($tree !== false) {
         $version =& $this->parseVersion($tree);
     }
     $tree->destroy();
     return $version;
 }
 /**
  * Parse and return DHL tracking details.
  *
  * @inheritdoc
  */
 public function fetchData($trackingNumber)
 {
     $link = 'http://track.dhl-usa.com/TrackByNbr.asp?ShipmentNumber=' . $trackingNumber;
     $html = $this->fetchUrl($link);
     if (!preg_match_all('#<input type="hidden" name="hdnXML([^"]+)" value="([^"]+)"/>#', $html, $matches, PREG_SET_ORDER)) {
         // XML tracking details not found
         return false;
     }
     $stats = array();
     $locations = array();
     $xml = '';
     foreach ($matches as $match) {
         $xml .= $match[2];
     }
     $xml = html_entity_decode($xml);
     $parser = new XMLParser();
     $obj = $parser->parse($xml);
     if (!isset($obj->track->trackshipments->shipment->result->code->data) && $obj->track->trackshipments->shipment->result->code->data != 1) {
         // XML document could not be parsed
         return false;
     }
     $stats['service'] = isset($obj->track->trackshipments->shipment->service->desc->data) ? $obj->track->trackshipments->shipment->service->desc->data : '';
     $stats['departure'] = isset($obj->track->trackshipments->shipment->pickup->date->data) ? $obj->track->trackshipments->shipment->pickup->date->data : '';
     $stats['destination'] = isset($obj->track->trackshipments->shipment->destinationdescr->location->data) ? $obj->track->trackshipments->shipment->destinationdescr->location->data : '';
     $stats['arrival'] = isset($obj->track->trackshipments->shipment->delivery->date->data) ? $obj->track->trackshipments->shipment->delivery->date->data : '';
     if (isset($obj->track->trackshipments->shipment->trackinghistory->status)) {
         if (!is_array($obj->track->trackshipments->shipment->trackinghistory->status)) {
             $obj->track->trackshipments->shipment->trackinghistory->status = array($obj->track->trackshipments->shipment->trackinghistory->status);
         }
         foreach ($obj->track->trackshipments->shipment->trackinghistory->status as $history) {
             $row = array();
             $row['location'] = $history->location->city->data . ', ';
             if (isset($history->location->state->data) && !empty($history->location->state->data)) {
                 $row['location'] .= $history->location->state->data . ', ';
             }
             if (isset($history->location->country->data) && !empty($history->location->country->data)) {
                 $row['location'] .= $history->location->country->data;
             }
             $row['location'] = rtrim($row['location'], ', ');
             $row['time'] = $history->date->data . ' ' . $history->time->data;
             $row['status'] = $history->statusdesc->data;
             $locations[] = $row;
             if (!isset($stats['status'])) {
                 $stats['status'] = $history->statusdesc->data;
             }
             if (!isset($stats['last_location'])) {
                 $stats['last_location'] = $row['location'];
             }
         }
     }
     return array('details' => $stats, 'locations' => $locations);
 }
 /**
  * Cast a given value
  *
  * Error codes returned are:
  * <ul>
  *   <li>invalid_chars - if input contains characters not allowed for XML</li>
  *   <li>not_well_formed - if input cannot be parsed to XML</li>
  * </ul>
  *
  * @param   array value
  * @return  string error or array on success
  */
 public function check($value)
 {
     foreach ($value as $v) {
         if (strlen($v) > strcspn($v, Node::XML_ILLEGAL_CHARS)) {
             return 'invalid_chars';
         }
         try {
             $p = new XMLParser();
             $p->parse('<doc>' . $v . '</doc>');
         } catch (XMLFormatException $e) {
             return 'not_well_formed';
         }
     }
     return NULL;
 }
Beispiel #8
0
 function doupdate()
 {
     include_once HDWIKI_ROOT . '/lib/xmlparser.class.php';
     $sendversion = base64_encode(serialize(array('v' => HDWIKI_VERSION, 'r' => HDWIKI_RELEASE, 'c' => WIKI_CHARSET, 'u' => WIKI_URL)));
     $xmlfile = "http://kaiyuan.hudong.com/update.php?v={$sendversion}";
     $xmlparser = new XMLParser();
     $xmlnav = $xmlparser->parse($xmlfile);
     $isupdate = $xmlnav[0]['child'][0]['content'];
     $version = $xmlnav[0]['child'][1]['content'];
     $release = $xmlnav[0]['child'][2]['content'];
     $url = $xmlnav[0]['child'][3]['content'];
     $description = $xmlnav[0]['child'][4]['content'];
     $json = '{"isupdate":"' . $isupdate . '","version":"' . $version . '","release":"' . $release . '","url":"' . $url . '","description":"' . $description . '"}';
     echo $json;
 }
 /**
  * format - prune the registry based on xml config
  *
  * @param string    XMLpath
  * @param Registry  registry
  *
  * @return array
  */
 public static function format($xmlFilePath, $uri, Registry $registry)
 {
     $xml = file_get_contents($xmlFilePath);
     $xmlParser = new XMLParser();
     $params = $xmlParser->parse($xml, $uri, 'outputParam');
     unset($xmlParser);
     $output = array();
     if (count($params) < 1) {
         if (self::PARANOID_MODE) {
             error_log('XML is missing CherryPicker configs for ' . $uri);
             throw new XMLNodeNotConfiguredException('XML is missing CherryPicker configs for ' . $uri);
         }
         //not paranoid? ok - dump the whole registry to the user
         foreach ($registry->toArray() as $key => $value) {
             $output[self::trimNamespacing($key)] = $registry->{$key};
         }
         return $output;
     }
     foreach ($params as $key) {
         self::formatValue($key, $output, $registry);
     }
     return $output;
 }
 /**
  * Fetches the statuses of the circuit boards from the database.
  * @throws Exception If a query fails to execute.
  */
 public function fetchUpdates()
 {
     $soap = new SoapClientWrapper();
     $messages = $soap->getNewMessages();
     $database = new DatabaseWrapper();
     $database->connect(DB_NAME);
     foreach ($messages as $message) {
         $xmlParser = new XMLParser($message);
         $xmlParser->parse();
         $parsedMessage = $xmlParser->getParsedData();
         $validator = new SMSValidator($parsedMessage);
         try {
             $msisdn = $validator->validateMSISDN();
             $status = $validator->validateStatus();
             $information = $database->queryBoardInformation($msisdn);
             $update = new CircuitBoard($information, $status);
             $database->updateBoardStatus($msisdn, $status);
             $this->model->addUpdate($update);
         } catch (Exception $e) {
             continue;
         }
     }
 }
Beispiel #11
0
 private function _getRates($response)
 {
     $doc = new \XMLDocument();
     $xp = new \XMLParser();
     $xp->setDocument($doc);
     $xp->parse($response);
     $doc = $xp->getDocument();
     $rates = array();
     $results = array();
     if (is_object($doc->root)) {
         $root = $doc->getRoot();
         if ($root->getElementByName('ratesAndServicesResponse')) {
             $service_rates = $root->getElementByName('ratesAndServicesResponse');
             $shipment = $service_rates->getElementsByName('product');
             $currencies = Registry::get('currencies');
             if (!empty($currencies['CAD'])) {
                 for ($i = 0; $i < count($shipment); $i++) {
                     $id = $shipment[$i]->getAttribute("id");
                     if (!empty($id) && $id > 0) {
                         $rates[$id] = array('rate' => floatval($shipment[$i]->getValueByPath("rate")) * $currencies['CAD']['coefficient']);
                         if ($shipment[$i]->getValueByPath("deliveryDate") != '') {
                             $rates[$id]['delivery_time'] = $shipment[$i]->getValueByPath("deliveryDate");
                         }
                         unset($id);
                     }
                 }
                 $results['cost'] = $rates;
             } else {
                 $results['error'] = __('canada_post_activation_error');
             }
         } elseif ($root->getElementByName('error')) {
             $results['error'] = $root->getValueByPath('/error/statusMessage');
         }
     }
     return $results;
 }
 /**
  * Parse and execute the scheduled tasks in the specified file.
  * @param $file string
  */
 function parseTasks($file)
 {
     $xmlParser = new XMLParser();
     $tree = $xmlParser->parse($file);
     if (!$tree) {
         $xmlParser->destroy();
         printf("Unable to parse file \"%s\"!\n", $file);
         exit(1);
     }
     foreach ($tree->getChildren() as $task) {
         $className = $task->getAttribute('class');
         $frequency = $task->getChildByName('frequency');
         if (isset($frequency)) {
             $canExecute = ScheduledTaskHelper::checkFrequency($className, $frequency);
         } else {
             // Always execute if no frequency is specified
             $canExecute = true;
         }
         if ($canExecute) {
             $this->executeTask($className, ScheduledTaskHelper::getTaskArgs($task));
         }
     }
     $xmlParser->destroy();
 }
 /**
  * Parse an XML data file into SQL statements.
  * @param $file string path to the XML file to parse
  * @return array the array of SQL statements parsed
  */
 function parseData($file)
 {
     $this->sql = array();
     $parser = new XMLParser();
     $tree = $parser->parse($file);
     if (!$tree) {
         return array();
     }
     $allTables = $this->dbconn->MetaTables();
     foreach ($tree->getChildren() as $type) {
         switch ($type->getName()) {
             case 'table':
                 $fieldDefaultValues = array();
                 // Match table element
                 foreach ($type->getChildren() as $row) {
                     switch ($row->getName()) {
                         case 'field_default':
                             // Match a default field element
                             list($fieldName, $value) = $this->_getFieldData($row);
                             $fieldDefaultValues[$fieldName] = $value;
                             break;
                         case 'row':
                             // Match a row element
                             $fieldValues = array();
                             foreach ($row->getChildren() as $field) {
                                 // Get the field names and values for this INSERT
                                 list($fieldName, $value) = $this->_getFieldData($field);
                                 $fieldValues[$fieldName] = $value;
                             }
                             $fieldValues = array_merge($fieldDefaultValues, $fieldValues);
                             if (count($fieldValues) > 0) {
                                 $this->sql[] = sprintf('INSERT INTO %s (%s) VALUES (%s)', $type->getAttribute('name'), join(', ', array_keys($fieldValues)), join(', ', array_values($fieldValues)));
                             }
                             break;
                         default:
                             assert(false);
                     }
                 }
                 break;
             case 'sql':
                 // Match sql element (set of SQL queries)
                 foreach ($type->getChildren() as $child) {
                     switch ($child->getName()) {
                         case 'drop':
                             if (!isset($dbdict)) {
                                 $dbdict = @NewDataDictionary($this->dbconn);
                             }
                             $table = $child->getAttribute('table');
                             $column = $child->getAttribute('column');
                             if ($column) {
                                 // NOT PORTABLE; do not use this
                                 $this->sql[] = $dbdict->DropColumnSql($table, $column);
                             } else {
                                 $this->sql[] = $dbdict->DropTableSQL($table);
                             }
                             break;
                         case 'rename':
                             if (!isset($dbdict)) {
                                 $dbdict = @NewDataDictionary($this->dbconn);
                             }
                             $table = $child->getAttribute('table');
                             $column = $child->getAttribute('column');
                             $to = $child->getAttribute('to');
                             if ($column) {
                                 // Make sure the target column does not yet exist.
                                 // This is to guarantee idempotence of upgrade scripts.
                                 $run = false;
                                 if (in_array($table, $allTables)) {
                                     $columns =& $this->dbconn->MetaColumns($table, true);
                                     if (!isset($columns[strtoupper($to)])) {
                                         // Only run if the column has not yet been
                                         // renamed.
                                         $run = true;
                                     }
                                 } else {
                                     // If the target table does not exist then
                                     // we assume that another rename entry will still
                                     // rename it and we should run after it.
                                     $run = true;
                                 }
                                 if ($run) {
                                     $colId = strtoupper($column);
                                     $flds = '';
                                     if (isset($columns[$colId])) {
                                         $col = $columns[$colId];
                                         if ($col->max_length == "-1") {
                                             $max_length = '';
                                         } else {
                                             $max_length = $col->max_length;
                                         }
                                         $fld = array('NAME' => $col->name, 'TYPE' => $dbdict->MetaType($col), 'SIZE' => $max_length);
                                         if ($col->primary_key) {
                                             $fld['KEY'] = 'KEY';
                                         }
                                         if ($col->auto_increment) {
                                             $fld['AUTOINCREMENT'] = 'AUTOINCREMENT';
                                         }
                                         if ($col->not_null) {
                                             $fld['NOTNULL'] = 'NOTNULL';
                                         }
                                         if ($col->has_default) {
                                             $fld['DEFAULT'] = $col->default_value;
                                         }
                                         $flds = array($colId => $fld);
                                     } else {
                                         assert(false);
                                     }
                                     $this->sql[] = $dbdict->RenameColumnSQL($table, $column, $to, $flds);
                                 }
                             } else {
                                 // Make sure the target table does not yet exist.
                                 // This is to guarantee idempotence of upgrade scripts.
                                 if (!in_array($to, $allTables)) {
                                     $this->sql[] = $dbdict->RenameTableSQL($table, $to);
                                 }
                             }
                             break;
                         case 'query':
                             $driver = $child->getAttribute('driver');
                             if (empty($driver) || $this->dbconn->databaseType === $driver) {
                                 $this->sql[] = $child->getValue();
                             }
                             break;
                     }
                 }
                 break;
         }
     }
     return $this->sql;
 }
 function getEmailTemplates($locale)
 {
     $files = TranslatorAction::getEmailFileMap($locale);
     $returner = array();
     foreach ($files as $templateFile => $templateDataFile) {
         $xmlParser = new XMLParser();
         $data = null;
         if (file_exists($templateDataFile)) {
             $data =& $xmlParser->parse($templateDataFile);
         }
         if ($data) {
             foreach ($data->getChildren() as $emailNode) {
                 $returner[$emailNode->getAttribute('key')] = array('subject' => $emailNode->getChildValue('subject'), 'body' => $emailNode->getChildValue('body'), 'description' => $emailNode->getChildValue('description'), 'templateFile' => $templateFile, 'templateDataFile' => $templateDataFile);
             }
         }
         unset($xmlParser, $data);
     }
     return $returner;
 }
Beispiel #15
0
function fn_arb_get_error($result, $request_type)
{
    $doc = new XMLDocument();
    $xp = new XMLParser();
    $xp->setDocument($doc);
    $xp->parse($result);
    $doc = $xp->getDocument();
    $return = array();
    if (is_object($doc->root)) {
        $root = $doc->getRoot();
        $shipments = $root->getElementsByName($request_type);
        if ($shipments) {
            for ($k = 0; $k < count($shipments); $k++) {
                $faults = $shipments[$k]->getElementByName("Faults");
                if (!empty($faults)) {
                    $fault = $faults->getElementsByName("Fault");
                    for ($i = 0; $i < count($fault); $i++) {
                        $return[] = $fault[$i]->getValueByPath("/Desc") . ($fault[$i]->getElementByName("Context") ? ' (' . trim($fault[$i]->getValueByPath("/Context")) . ')' : '');
                    }
                }
            }
        }
    }
    return implode(' / ', $return);
}
Beispiel #16
0
 function parseCrontab()
 {
     $xmlParser = new XMLParser();
     // TODO: make this a plugin setting, rather than assuming.
     $tree = $xmlParser->parse(Config::getVar('general', 'registry_dir') . '/scheduledTasks.xml');
     if (!$tree) {
         $xmlParser->destroy();
         // TODO: graceful error handling
         fatalError('Error parsing scheduled tasks XML.');
     }
     $tasks = array();
     foreach ($tree->getChildren() as $task) {
         $frequency = $task->getChildByName('frequency');
         $args = array();
         $index = 0;
         while (($arg = $task->getChildByName('arg', $index)) != null) {
             array_push($args, $arg->getValue());
             $index++;
         }
         $tasks[] = array('className' => $task->getAttribute('class'), 'frequency' => $frequency ? $frequency->getAttributes() : null, 'args' => $args);
     }
     $xmlParser->destroy();
     // Store the object.
     $this->updateSetting(0, 0, 'crontab', $tasks, 'object');
 }
Beispiel #17
0
 /**
  * Load the XML file and move the settings to the DB
  * @param $contextId
  * @param $filename
  * @return boolean true === success
  */
 function installSettings($contextId, $filename)
 {
     $xmlParser = new XMLParser();
     $tree = $xmlParser->parse($filename);
     if (!$tree) {
         $xmlParser->destroy();
         return false;
     }
     foreach ($tree->getChildren() as $setting) {
         $roleId = hexdec($setting->getAttribute('roleId'));
         $nameKey = $setting->getAttribute('name');
         $abbrevKey = $setting->getAttribute('abbrev');
         $permitSelfRegistration = $setting->getAttribute('permitSelfRegistration');
         $defaultStages = explode(',', $setting->getAttribute('stages'));
         $userGroup = $this->newDataObject();
         // create a role associated with this user group
         $userGroup = $this->newDataObject();
         $userGroup->setRoleId($roleId);
         $userGroup->setContextId($contextId);
         $userGroup->setPermitSelfRegistration($permitSelfRegistration);
         $userGroup->setDefault(true);
         // insert the group into the DB
         $userGroupId = $this->insertObject($userGroup);
         // Install default groups for each stage
         if (is_array($defaultStages)) {
             // test for groups with no stage assignments
             foreach ($defaultStages as $stageId) {
                 if (!empty($stageId) && $stageId <= WORKFLOW_STAGE_ID_PRODUCTION && $stageId >= WORKFLOW_STAGE_ID_SUBMISSION) {
                     $this->assignGroupToStage($contextId, $userGroupId, $stageId);
                 }
             }
         }
         // add the i18n keys to the settings table so that they
         // can be used when a new locale is added/reloaded
         $this->updateSetting($userGroup->getId(), 'nameLocaleKey', $nameKey);
         $this->updateSetting($userGroup->getId(), 'abbrevLocaleKey', $abbrevKey);
         // install the settings in the current locale for this context
         $this->installLocale(AppLocale::getLocale(), $contextId);
     }
     return true;
 }
Beispiel #18
0
 /**
  * Load the XML file and move the settings to the DB
  * @param $pressId
  * @param $filename
  */
 function installSettings($pressId, $filename)
 {
     $xmlParser = new XMLParser();
     $tree = $xmlParser->parse($filename);
     if (!$tree) {
         $xmlParser->destroy();
         return false;
     }
     foreach ($tree->getChildren() as $setting) {
         $roleId = hexdec($setting->getAttribute('roleId'));
         $nameKey = $setting->getAttribute('name');
         $abbrevKey = $setting->getAttribute('abbrev');
         $defaultStages = explode(",", $setting->getAttribute('stages'));
         $userGroup =& $this->newDataObject();
         // create a role associated with this user group
         $role =& new Role($roleId);
         $userGroup =& $this->newDataObject();
         $userGroup->setRoleId($roleId);
         $userGroup->setPath($role->getPath());
         $userGroup->setPressId($pressId);
         $userGroup->setDefault(true);
         // insert the group into the DB
         $userGroupId = $this->insertUserGroup($userGroup);
         // Install default groups for each stage
         foreach ($defaultStages as $stageId) {
             if (!empty($stageId) && $stageId <= WORKFLOW_STAGE_ID_PRODUCTION && $stageId >= WORKFLOW_STAGE_ID_SUBMISSION) {
                 $userGroupStageAssignmentDao =& DAORegistry::getDAO('UserGroupStageAssignmentDAO');
                 $userGroupStageAssignmentDao->assignGroupToStage($pressId, $userGroupId, $stageId);
             }
         }
         // add the i18n keys to the settings table so that they
         // can be used when a new locale is added/reloaded
         $this->updateSetting($userGroup->getId(), 'nameLocaleKey', $nameKey);
         $this->updateSetting($userGroup->getId(), 'abbrevLocaleKey', $abbrevKey);
         // install the settings in the current locale for this press
         $this->installLocale(Locale::getLocale(), $pressId);
     }
 }
 /**
  * Install locale field Only journal settings from an XML file.
  * @param $journalId int ID of journal for settings to apply to
  * @param $filename string Name of XML file to parse and install
  * @param $paramArray array Optional parameters for variable replacement in settings
  * @param $locale string locale id for which settings will be loaded
  */
 function reloadLocalizedDefaultSettings($journalId, $filename, $paramArray, $locale)
 {
     $xmlParser = new XMLParser();
     $tree = $xmlParser->parse($filename);
     if (!$tree) {
         $xmlParser->destroy();
         return false;
     }
     foreach ($tree->getChildren() as $setting) {
         $nameNode =& $setting->getChildByName('name');
         $valueNode =& $setting->getChildByName('value');
         if (isset($nameNode) && isset($valueNode)) {
             $type = $setting->getAttribute('type');
             $isLocaleField = $setting->getAttribute('locale');
             $name =& $nameNode->getValue();
             //skip all settings that are not locale fields
             if (!$isLocaleField) {
                 continue;
             }
             if ($type == 'object') {
                 $arrayNode =& $valueNode->getChildByName('array');
                 $value = $this->_buildLocalizedObject($arrayNode, $paramArray, $locale);
             } else {
                 $value = $this->_performLocalizedReplacement($valueNode->getValue(), $paramArray, $locale);
             }
             // Replace translate calls with translated content
             $this->updateSetting($journalId, $name, array($locale => $value), $type, true);
         }
     }
     $xmlParser->destroy();
 }
        if (is_null($this->last)) {
            $this->root =& $node;
        } else {
            $this->last->addChild(&$node);
        }
        $this->last =& $node;
    }
    function end($parser, $name)
    {
        $this->last =& $this->last->parent;
    }
    function cdata($parser, $data)
    {
        if (!is_null($this->last)) {
            $this->last->setContent(trim($data));
        }
    }
    function &getRoot()
    {
        return $this->root;
    }
}
$xml_file = 'presentations/slides/sdphp/data/sdphp_talk2.xml';
$xmldoc = implode('', file($xml_file));
$parser = new XMLParser();
$parser->parse($xmldoc);
$root = $parser->getRoot();
echo "<pre>\n" . $root->toString() . "</pre>\n";
?>
 
 function parsePluginInfoFile($file)
 {
     $pluginInfo = array();
     $pluginInfoFile = SP_PLUGINPATH . "/" . $file . "/" . SP_PLUGININFOFILE;
     if (file_exists($pluginInfoFile)) {
         $xml = new XMLParser();
         $pInfo = $xml->parse($pluginInfoFile);
         if (!empty($pInfo[0]['child'])) {
             foreach ($pInfo[0]['child'] as $info) {
                 $infoCol = strtolower($info['name']);
                 $pluginInfo[$infoCol] = $info['content'];
             }
         }
     }
     $pluginInfo['label'] = empty($pluginInfo['label']) ? $file : $pluginInfo['label'];
     $pluginInfo['version'] = empty($pluginInfo['version']) ? '1.0.0' : $pluginInfo['version'];
     $pluginInfo['author'] = empty($pluginInfo['author']) ? 'Seo Panel' : $pluginInfo['author'];
     $pluginInfo['website'] = empty($pluginInfo['website']) ? SP_PLUGINSITE : $pluginInfo['website'];
     return $pluginInfo;
 }
Beispiel #22
0
 /**
  * Gets error message from shipping service server
  *
  * @param  string $response Response from Shipping service server
  * @return string Text of error or false if no errors
  */
 public function processErrors($response)
 {
     $doc = new \XMLDocument();
     $xp = new \XMLParser();
     $xp->setDocument($doc);
     $xp->parse($response);
     $doc = $xp->getDocument();
     $return = array();
     if (is_object($doc->root)) {
         $root = $doc->getRoot();
         // distinguish error reports from not available services
         if ($root->name == 'res:ErrorResponse') {
             $path = array('Response', 'Status');
         } else {
             $path = array('GetQuoteResponse', 'Note');
         }
         foreach ($path as $node) {
             $root = $root->getElementsByName($node);
             if ($root) {
                 $root = $root[0];
             } else {
                 break;
             }
         }
         if ($root) {
             $conditions = $root->getElementsByName('Condition');
             foreach ($conditions as $condition) {
                 $error_code = trim($condition->getValueByPath('ConditionCode'));
                 $error_text = trim($condition->getValueByPath('ConditionData'));
                 $return[] = "({$error_code}) {$error_text}";
             }
         }
     }
     return implode(' / ', $return);
 }
 /**
  * Parse the installation descriptor XML file.
  * @return boolean
  */
 function parseInstaller()
 {
     // Read installation descriptor file
     $this->log(sprintf('load: %s', $this->descriptor));
     $xmlParser = new XMLParser();
     $installPath = $this->isPlugin ? $this->descriptor : INSTALLER_DATA_DIR . DIRECTORY_SEPARATOR . $this->descriptor;
     $installTree = $xmlParser->parse($installPath);
     if (!$installTree) {
         // Error reading installation file
         $xmlParser->destroy();
         $this->setError(INSTALLER_ERROR_GENERAL, 'installer.installFileError');
         return false;
     }
     $versionString = $installTree->getAttribute('version');
     if (isset($versionString)) {
         $this->newVersion =& Version::fromString($versionString);
     } else {
         $this->newVersion = $this->currentVersion;
     }
     // Parse descriptor
     $this->parseInstallNodes($installTree);
     $xmlParser->destroy();
     $result = $this->getErrorType() == 0;
     HookRegistry::call('Installer::parseInstaller', array(&$this, &$result));
     return $result;
 }
Beispiel #24
0
function fn_ups_get_rates($result)
{
    $doc = new XMLDocument();
    $xp = new XMLParser();
    $xp->setDocument($doc);
    $xp->parse($result);
    $doc = $xp->getDocument();
    $return = array();
    if (is_object($doc->root)) {
        $responseStatusCode = $doc->getValueByPath('RatingServiceSelectionResponse/Response/ResponseStatusCode');
        $root = $doc->getRoot();
        $shipment = $root->getElementsByName("RatedShipment");
        for ($i = 0; $i < count($shipment); $i++) {
            $service_code = $shipment[$i]->getValueByPath("/Service/Code");
            $total_charge = $shipment[$i]->getValueByPath("/TotalCharges/MonetaryValue");
            if (!($service_code && $total_charge)) {
                continue;
            }
            //$rated_packages = $shipment[$i]->getElementsByName("RatedPackage");
            //$days_to_delivery = $shipment[$i]->getValueByPath("/GuaranteedDaysToDelivery");
            //$delivery_time = $shipment[$i]->getValueByPath("/ScheduledDeliveryTime");
            if (!empty($total_charge)) {
                $return[$service_code] = $total_charge;
            }
        }
    }
    return $return;
}
Beispiel #25
0
 /**
  * Install the given filter configuration file.
  * @param $filterConfigFile string
  * @return boolean true when successful, otherwise false
  */
 function installFilterConfig($filterConfigFile)
 {
     static $filterHelper = false;
     // Parse the filter configuration.
     $xmlParser = new XMLParser();
     $tree =& $xmlParser->parse($filterConfigFile);
     // Validate the filter configuration.
     if (!$tree) {
         $xmlParser->destroy();
         return false;
     }
     // Get the filter helper.
     if ($filterHelper === false) {
         import('lib.pkp.classes.filter.FilterHelper');
         $filterHelper = new FilterHelper();
     }
     // Are there any filter groups to be installed?
     $filterGroupsNode =& $tree->getChildByName('filterGroups');
     if (is_a($filterGroupsNode, 'XMLNode')) {
         $filterHelper->installFilterGroups($filterGroupsNode);
     }
     // Are there any filters to be installed?
     $filtersNode =& $tree->getChildByName('filters');
     if (is_a($filtersNode, 'XMLNode')) {
         foreach ($filtersNode->getChildren() as $filterNode) {
             /* @var $filterNode XMLNode */
             $filterHelper->configureFilter($filterNode);
         }
     }
     // Get rid of the parser.
     $xmlParser->destroy();
     unset($xmlParser);
     return true;
 }
Beispiel #26
0
 /**
  * Construct an XML tree from a file.
  *
  * <code>
  *   $tree= Tree::fromFile(new File('foo.xml'));
  * </code>
  *
  * @param   io.File file
  * @param   string c default __CLASS__ class name
  * @return  xml.Tree
  * @throws  xml.XMLFormatException in case of a parser error
  * @throws  io.IOException in case reading the file fails
  */
 public static function fromFile($file, $c = __CLASS__)
 {
     $parser = new XMLParser();
     $tree = new $c();
     $parser->setCallback($tree);
     $parser->parse(FileUtil::getContents($file));
     // Fetch actual encoding from parser
     $tree->setEncoding($parser->getEncoding());
     delete($parser);
     return $tree;
 }
 function &getDocument($fileName)
 {
     $parser = new XMLParser();
     $returner =& $parser->parse($fileName);
     return $returner;
 }
 /**
  * Install plugin settings from an XML file.
  * @param $pluginName name of plugin for settings to apply to
  * @param $filename string Name of XML file to parse and install
  * @param $paramArray array Optional parameters for variable replacement in settings
  */
 function installSettings($contextId, $pluginName, $filename, $paramArray = array())
 {
     $xmlParser = new XMLParser();
     $tree = $xmlParser->parse($filename);
     if (!$tree) {
         $xmlParser->destroy();
         return false;
     }
     // Check for existing settings and leave them if they are already in place.
     $currentSettings = $this->getPluginSettings($contextId, $pluginName);
     foreach ($tree->getChildren() as $setting) {
         $nameNode = $setting->getChildByName('name');
         $valueNode = $setting->getChildByName('value');
         if (isset($nameNode) && isset($valueNode)) {
             $type = $setting->getAttribute('type');
             $name = $nameNode->getValue();
             // If the setting already exists, respect it.
             if (isset($currentSettings[$name])) {
                 continue;
             }
             if ($type == 'object') {
                 $arrayNode = $valueNode->getChildByName('array');
                 $value = $this->_buildObject($arrayNode, $paramArray);
             } else {
                 $value = $this->_performReplacement($valueNode->getValue(), $paramArray);
             }
             // Replace translate calls with translated content
             $this->updateSetting($contextId, $pluginName, $name, $value, $type);
         }
     }
     $xmlParser->destroy();
 }
 private function process_xml($value)
 {
     if (!strlen($value)) {
         return;
     }
     $value = CutXMLEncoding($value);
     $xml_parser = new XMLParser($value);
     $parsed_xml = $xml_parser->parse();
     if (!$xml_parser->isError || is_array($parsed_xml)) {
         $this->rec_scan_xml_array($parsed_xml);
     } else {
         $this->log->add("ERR_XML_PARSE");
     }
 }
Beispiel #30
0
function fn_qb_get_xml_body($response)
{
    $doc = new XMLDocument();
    $xp = new XMLParser();
    $xp->setDocument($doc);
    $xp->parse($response);
    $doc = $xp->getDocument();
    $root = $doc->getRoot();
    return $root;
}