function notify($context) { var_dump($context); include_once TOOLKIT . '/class.gateway.php'; $ch = new Gateway(); $ch->init(); $ch->setopt('URL', 'http://rpc.pingomatic.com/'); $ch->setopt('POST', 1); $ch->setopt('CONTENTTYPE', 'text/xml'); $ch->setopt('HTTPVERSION', '1.0'); ##Create the XML request $xml = new XMLElement('methodCall'); $xml->appendChild(new XMLElement('methodName', 'weblogUpdates.ping')); $params = new XMLElement('params'); $param = new XMLElement('param'); $param->appendChild(new XMLElement('value', $this->_Parent->Configuration->get('sitename', 'general'))); $params->appendChild($param); $param = new XMLElement('param'); $param->appendChild(new XMLElement('value', URL)); $params->appendChild($param); $xml->appendChild($params); #### $ch->setopt('POSTFIELDS', $xml->generate(true, 0)); //Attempt the ping $ch->exec(GATEWAY_FORCE_SOCKET); }
function getValuesFromXML() { $xml_location = $this->get('xml_location'); $cache_life = (int) $this->get('cache'); require TOOLKIT . '/util.validators.php'; // allow use of choice params in URL $xml_location = preg_replace('/{\\$root}/', URL, $xml_location); $xml_location = preg_replace('/{\\$workspace}/', WORKSPACE, $xml_location); $doc = new DOMDocument(); if (preg_match($validators['URI'], $xml_location)) { // is a URL, check cache $cache_id = md5('xml_selectbox_' . $xml_location); $cache = new Cacheable($this->_Parent->_Parent->Database); $cachedData = $cache->check($cache_id); if (!$cachedData) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $xml_location); $ch->setopt('TIMEOUT', 6); $xml = $ch->exec(); $writeToCache = true; $cache->write($cache_id, $xml, $cache_life); // Cache life is in minutes not seconds e.g. 2 = 2 minutes $xml = trim($xml); if (empty($xml) && $cachedData) { $xml = $cachedData['data']; } } else { $xml = $cachedData['data']; } $doc->loadXML($xml); } elseif (substr($xml_location, 0, 1) == '/') { // relative to DOCROOT $doc->load(DOCROOT . $this->get('xml_location')); } else { // in extension's /xml folder $doc->load(EXTENSIONS . '/xml_selectbox/xml/' . $this->get('xml_location')); } $xpath = new DOMXPath($doc); $options = array(); foreach ($xpath->query($this->get('item_xpath')) as $item) { $option = array(); $option['text'] = $this->run($xpath, $item, $this->get('text_xpath')); $option['value'] = $this->run($xpath, $item, $this->get('value_xpath')); if (is_null($option['value'])) { $option['value'] = $option['text']; } $options[] = $option; if ($item->hasChildNodes()) { foreach ($xpath->query('*', $item) as $child) { $text = $this->run($xpath, $child, $this->get('text_xpath')); $value = $this->run($xpath, $child, $this->get('value_xpath')); $options[] = array('text' => $option['text'] . " / " . $text, 'value' => $option['value'] . "-" . (!is_null($value) ? $value : $text)); } } } return $options; }
function getValuesFromXML() { $xml_location = $this->get('xml_location'); $cache_life = (int) $this->get('cache'); require TOOLKIT . '/util.validators.php'; // allow use of choice params in URL $xml_location = preg_replace('/{\\$root}/', URL, $xml_location); $xml_location = preg_replace('/{\\$workspace}/', WORKSPACE, $xml_location); if (preg_match($validators['URI'], $xml_location)) { // is a URL, check cache $cache_id = md5('xml_selectbox_' . $xml_location); $cache = new Cacheable($this->_Parent->_Parent->Database); $cachedData = $cache->check($cache_id); if (!$cachedData) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $xml_location); $ch->setopt('TIMEOUT', 6); $xml = $ch->exec(); $writeToCache = true; $cache->write($cache_id, $xml, $cache_life); // Cache life is in minutes not seconds e.g. 2 = 2 minutes $xml = trim($xml); if (empty($xml) && $cachedData) { $xml = $cachedData['data']; } } else { $xml = $cachedData['data']; } $xml = simplexml_load_string($xml); } elseif (substr($xml_location, 0, 1) == '/') { // relative to DOCROOT $xml = simplexml_load_file(DOCROOT . $this->get('xml_location')); } else { // in extension's /xml folder $xml = simplexml_load_file(EXTENSIONS . '/xml_selectbox/xml/' . $this->get('xml_location')); } $options = array(); if (!$xml) { return $options; } $items = $xml->xpath($this->get('item_xpath')); foreach ($items as $item) { $option = array(); $text_xpath = $item->xpath($this->get('text_xpath')); $option['text'] = General::sanitize((string) $text_xpath[0]); if ($this->get('value_xpath') != '') { $value_xpath = $item->xpath($this->get('value_xpath')); $option['value'] = General::sanitize((string) $value_xpath[0]); } if ((string) $option['value'] == '') { $option['value'] = $option['text']; } $options[] = $option; } return $options; }
function getValuesFromXML() { $xml_location = $this->get('xml_location'); if (General::validateURL($xml_location) != '') { // is a URL, check cache $cache_id = md5($xml_location); $cache = new Cacheable($this->_Parent->_Parent->Database); $cachedData = $cache->check($cache_id); $creation = DateTimeObj::get('c'); if (!$cachedData || time() - $cachedData['creation'] > 5 * 60) { if (Mutex::acquire($cache_id, 6, TMP)) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $xml_location); $ch->setopt('TIMEOUT', 6); $xml = $ch->exec(); $writeToCache = true; Mutex::release($cache_id, TMP); $xml = trim($xml); if (empty($xml) && $cachedData) { $xml = $cachedData['data']; } } elseif ($cachedData) { $xml = $cachedData['data']; } } else { $xml = $cachedData['data']; } $xml = simplexml_load_string($xml); } elseif (substr($xml_location, 0, 1) == '/') { // relative to DOCROOT $xml = simplexml_load_file(DOCROOT . $this->get('xml_location')); } else { // in extension's /xml folder $xml = simplexml_load_file(EXTENSIONS . '/xml_selectbox/xml/' . $this->get('xml_location')); } if (!$xml) { return; } $items = $xml->xpath($this->get('item_xpath')); $options = array(); foreach ($items as $item) { $option = array(); $text_xpath = $item->xpath($this->get('text_xpath')); $option['text'] = General::sanitize((string) $text_xpath[0]); if ($this->get('value_xpath') != '') { $value_xpath = $item->xpath($this->get('value_xpath')); $option['value'] = General::sanitize((string) $value_xpath[0]); } if ((string) $option['value'] == '') { $option['value'] = $option['text']; } $options[] = $option; } return $options; }
public function __actionIndex() { // Use external data: if ($this->_fields['source']) { $gateway = new Gateway(); $gateway->init(); $gateway->setopt('URL', $this->_fields['source']); $gateway->setopt('TIMEOUT', 6); // Validate data: $this->_status = $this->_importer->validate($gateway->exec()); if ($this->_status == Importer::__OK__) { $this->_importer->commit(); } } }
function commit() { if (!parent::commit()) { return false; } $id = $this->get('id'); if ($id === false) { return false; } $fields = array(); $fields['field_id'] = $id; $fields['default_location'] = $this->get('default_location'); if (!$fields['default_location']) { $fields['default_location'] = 'Brisbane, Australia'; } include_once TOOLKIT . '/class.gateway.php'; $ch = new Gateway(); $ch->init(); $ch->setopt('URL', 'http://maps.google.com/maps/geo?q=' . urlencode($fields['default_location']) . '&output=xml&key=' . $this->_engine->Configuration->get('google-api-key', 'map-location-field')); $response = $ch->exec(); if (!preg_match('/<Placemark/i', $response)) { $fields['default_location'] = 'Brisbane, Australia'; $fields['default_location_coords'] = '-27.46, 153.025'; } else { $xml = new SimpleXMLElement($response); $coords = preg_split('/,/', $xml->Response->Placemark[0]->Point->coordinates, -1, PREG_SPLIT_NO_EMPTY); $fields['default_location_coords'] = $coords[1] . ',' . $coords[0]; } $this->_engine->Database->query("DELETE FROM `tbl_fields_" . $this->handle() . "` WHERE `field_id` = '{$id}' LIMIT 1"); return $this->_engine->Database->insert($fields, 'tbl_fields_' . $this->handle()); }
private function __geocodeAddress($address, $can_return_default = true) { $coordinates = null; $cache_id = md5('maplocationfield_' . $address); $cache = new Cacheable(Symphony::Database()); $cachedData = $cache->check($cache_id); // no data has been cached if (!$cachedData) { include_once TOOLKIT . '/class.gateway.php'; $ch = new Gateway(); $ch->init(); $ch->setopt('URL', '//maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=false&v=3.13'); $response = json_decode($ch->exec()); $coordinates = $response->results[0]->geometry->location; if ($coordinates && is_object($coordinates)) { $cache->write($cache_id, $coordinates->lat . ', ' . $coordinates->lng, $this->_geocode_cache_expire); // cache lifetime in minutes } } else { $coordinates = $cachedData['data']; } // coordinates is an array, split and return if ($coordinates && is_object($coordinates)) { return $coordinates->lat . ', ' . $coordinates->lng; } elseif ($coordinates) { return $coordinates; } elseif ($return_default) { return $this->_default_coordinates; } }
function displayPublishPanel(&$wrapper, $data = NULL, $flagWithError = NULL, $fieldnamePrefix = NULL, $fieldnamePostfix = NULL) { if (!isset(Administration::instance()->Page)) { return; } // work out what page we are on, get portions of the URL $callback = Administration::instance()->getPageCallback(); $entry_id = $callback['context']['entry_id']; // get an Entry object for this entry $entries = EntryManager::fetch($entry_id); if (is_array($entries)) { $entry = reset($entries); } // parse dynamic portions of the panel URL $url = $this->parseExpression($entry, $this->get('url_expression')); if (!preg_match('/^http/', $url)) { $url = URL . $url; } // create Symphony cookie to pass with each request $cookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/'; session_write_close(); $gateway = new Gateway(); $gateway->init($url); $gateway->setopt('TIMEOUT', 10); $gateway->setopt(CURLOPT_COOKIE, $cookie); $gateway->setopt(CURLOPT_SSL_VERIFYPEER, FALSE); $result = $gateway->exec(); // a unique name for this panel instance $instance_id = $callback['context']['section_handle'] . '_' . $this->get('element_name'); $container = new XMLELement('div', $result); $container->setAttribute('id', $instance_id); $container->setAttribute('class', 'inline frame'); $label = new XMLElement('label', $this->get('label')); $label->appendChild($container); $wrapper->appendChild($label); $asset_index = $this->get('id') * rand(10, 100); // add panel-specific styling $instance_css = '/html-panel/' . $instance_id . '.css'; if (file_exists(WORKSPACE . $instance_css)) { Administration::instance()->Page->addStylesheetToHead(URL . '/workspace' . $instance_css, 'screen', $asset_index++); } // add panel-specific behaviour $instance_js = '/html-panel/' . $instance_id . '.js'; if (file_exists(WORKSPACE . $instance_js)) { Administration::instance()->Page->addScriptToHead(URL . '/workspace' . $instance_js, $asset_index++); } }
public function notify($context) { include_once TOOLKIT . '/class.gateway.php'; $ch = new Gateway(); $ch->init(); $ch->setopt('URL', 'http://rpc.pingomatic.com/'); $ch->setopt('POST', 1); $ch->setopt('CONTENTTYPE', 'text/xml'); $xml = new XMLElement('methodCall'); $xml->appendChild(new XMLElement('methodName', 'weblogUpdates.ping')); $params = new XMLElement('params'); $param = new XMLElement('param'); $param->appendChild(new XMLElement('value', Symphony::Configuration()->get('sitename', 'general'))); $params->appendChild($param); $param = new XMLElement('param'); $param->appendChild(new XMLElement('value', URL)); $params->appendChild($param); $xml->appendChild($params); $ch->setopt('POSTFIELDS', $xml->generate(true, 0)); $ch->exec(GATEWAY_FORCE_SOCKET); }
/** * Builds the attachment section of a multipart email. * * Will return a string containing the section. Can be used to send to * an email server directly. * * @throws EmailGatewayException * @throws Exception * @return string */ protected function getSectionAttachments() { $output = ''; foreach ($this->_attachments as $key => $file) { $tmp_file = false; // If the attachment is a URL, download the file to a temporary location. // This prevents downloading the file twice - once for info, once for data. if (filter_var($file['file'], FILTER_VALIDATE_URL)) { $gateway = new Gateway(); $gateway->init($file['file']); $gateway->setopt('TIMEOUT', 30); $file_content = @$gateway->exec(); $tmp_file = tempnam(TMP, 'attachment'); General::writeFile($tmp_file, $file_content, Symphony::Configuration()->get('write_mode', 'file')); $original_filename = $file['file']; $file['file'] = $tmp_file; // Without this the temporary filename will be used. Ugly! if (is_null($file['filename'])) { $file['filename'] = basename($original_filename); } } else { $file_content = @file_get_contents($file['file']); } if ($file_content !== false && !empty($file_content)) { $output .= $this->boundaryDelimiterLine('multipart/mixed') . $this->contentInfoString($file['mime-type'], $file['file'], $file['filename'], $file['charset']) . EmailHelper::base64ContentTransferEncode($file_content); } else { if (!$tmp_file === false) { $filename = $original_filename; } else { $filename = $file['file']; } throw new EmailGatewayException(__('The content of the file `%s` could not be loaded.', array($filename))); } if (!$tmp_file === false) { General::deleteFile($tmp_file); } } return $output; }
public static function getVideoFeed($video_id) { // Fetch document: $gateway = new Gateway(); $gateway->init(); $gateway->setopt('URL', "http://gdata.youtube.com/feeds/api/videos/{$video_id}"); $gateway->setopt('TIMEOUT', 10); $data = $gateway->exec(); $info = $gateway->getInfoLast(); if ($data == "Invalid id" || empty($data) || $info['http_code'] != 200) { return null; } return DOMDocument::loadXML($data); }
public function __actionEditNormal() { // Validate ----------------------------------------------------------- $fields = $_POST['fields']; // Name: if (!isset($fields['about']['name']) || trim($fields['about']['name']) == '') { $this->_errors['name'] = __('Name must not be empty.'); } // Source: if (!isset($fields['source']) || trim($fields['source']) == '') { $this->_errors['source'] = __('Source must not be empty.'); } else { // Support {$root} $evaluated_source = str_replace('{$root}', URL, $fields['source']); if (!filter_var($evaluated_source, FILTER_VALIDATE_URL)) { $this->_errors['source'] = __('Source is not a valid URL.'); } } // Namespaces --------------------------------------------------------- if (isset($fields['discover-namespaces']) && $fields['discover-namespaces'] == 'yes' && !isset($this->_errors['source'])) { $gateway = new Gateway(); $gateway->init(); $gateway->setopt('URL', $evaluated_source); $gateway->setopt('TIMEOUT', (int) $fields['timeout']); $data = $gateway->exec(); if ($data === false) { $this->_errors['discover-namespaces'] = __('Error loading data from URL, make sure it is valid and that it returns data within 60 seconds.'); } else { preg_match_all('/xmlns:([a-z][a-z-0-9\\-]*)="([^\\"]+)"/i', $data, $matches); if (isset($matches[2][0])) { $namespaces = array(); if (!is_array($fields['namespaces'])) { $fields['namespaces'] = array(); } foreach ($fields['namespaces'] as $namespace) { $namespaces[] = $namespace['name']; $namespaces[] = $namespace['uri']; } foreach ($matches[2] as $index => $uri) { $name = $matches[1][$index]; if (in_array($name, $namespaces) or in_array($uri, $namespaces)) { continue; } $namespaces[] = $name; $namespaces[] = $uri; $fields['namespaces'][] = array('name' => $name, 'uri' => $uri); } } } } // Included elements: if (!isset($fields['included-elements']) || trim($fields['included-elements']) == '') { $this->_errors['included-elements'] = __('Included Elements must not be empty.'); } else { try { $this->_driver->validateXPath($fields['included-elements'], $fields['namespaces']); } catch (Exception $e) { $this->_errors['included-elements'] = $e->getMessage(); } } // Fields: if (isset($fields['fields']) && is_array($fields['fields'])) { foreach ($fields['fields'] as $index => $field) { try { $this->_driver->validateXPath($field['xpath'], $fields['namespaces']); } catch (Exception $e) { if (!isset($this->_errors['fields'])) { $this->_errors['fields'] = array(); } $this->_errors['fields'][$index] = $e->getMessage(); } } } $fields['about']['file'] = isset($this->_fields['about']['file']) ? $this->_fields['about']['file'] : null; $fields['about']['created'] = isset($this->_fields['about']['created']) ? $this->_fields['about']['created'] : null; $fields['about']['updated'] = isset($this->_fields['about']['updated']) ? $this->_fields['about']['updated'] : null; $fields['can-update'] = isset($fields['can-update']) && $fields['can-update'] == 'yes' ? 'yes' : 'no'; $this->_fields = $fields; if (!empty($this->_errors)) { $this->_valid = false; return; } // Save --------------------------------------------------------------- $name = $this->_handle; if (!$this->_driver->setXMLImporter($name, $error, $this->_fields)) { $this->_valid = false; $this->_errors['other'] = $error; return; } if ($this->_editing) { redirect("{$this->_uri}/importers/edit/{$name}/saved/"); } else { redirect("{$this->_uri}/importers/edit/{$name}/created/"); } }
/** * Given a `$url` and `$timeout`, this function will use the `Gateway` * class to determine that it is a valid URL and returns successfully * before the `$timeout`. If it does not, an error message will be * returned, otherwise true. * * @since Symphony 2.3 * @param string $url * @param integer $timeout * If not provided, this will default to 6 seconds * @param string $error * If this function returns false, this variable will be populated with the * error message. * @return array|boolean * Returns an array with the 'data' if it is a valid URL, otherwise a string * containing an error message. */ public static function __isValidURL($url, $timeout = 6, &$error) { if (!filter_var($url, FILTER_VALIDATE_URL)) { $error = __('Invalid URL'); return false; } // Check that URL was provided $gateway = new Gateway(); $gateway->init($url); $gateway->setopt('TIMEOUT', $timeout); $data = $gateway->exec(); $info = $gateway->getInfoLast(); // 28 is CURLE_OPERATION_TIMEDOUT if ($info['curl_error'] == 28) { $error = __('Request timed out. %d second limit reached.', array($timeout)); return false; } elseif ($data === false || $info['http_code'] != 200) { $error = __('Failed to load URL, status code %d was returned.', array($info['http_code'])); return false; } return array('data' => $data); }
/** * Given a URL, Format and Timeout, this function will initalise * Symphony's Gateway class to retrieve the contents of the URL. * * @param string $url * @param string $format * @param integer $timeout * @return array */ public static function fetch($url, $format, $timeout) { $ch = new Gateway(); $ch->init($url); $ch->setopt('TIMEOUT', $timeout); // Set the approtiate Accept: headers depending on the format of the URL. if ($transformer = self::getTransformer($format)) { $accepts = $transformer->accepts(); $ch->setopt('HTTPHEADER', array('Accept: ' . $accepts)); } // use static here to allow late static binding // see http://php.net/manual/en/language.oop5.late-static-bindings.php static::prepareGateway($ch); return array(trim($ch->exec()), $ch->getInfoLast()); }
public function sendEmail($entry_id, $template_id) { $template = $this->getTemplate($template_id); $conditions = $this->getConditions($template_id); $data = $this->getData($template, $entry_id); $xpath = new DOMXPath($data); $email = null; // Find condition: foreach ($conditions as $condition) { if (empty($condition['expression'])) { $email = $condition; break; } $results = $xpath->query($condition['expression']); if ($results->length > 0) { $email = $condition; break; } } if (is_null($email)) { return; } // Replace {xpath} queries: foreach ($email as $key => $value) { $content = $email[$key]; $replacements = array(); // Find queries: preg_match_all('/\\{[^\\}]+\\}/', $content, $matches); // Find replacements: foreach ($matches[0] as $match) { $results = @$xpath->query(trim($match, '{}')); if ($results->length) { $items = array(); foreach ($results as $item) { if (!isset($item->nodeValue)) { continue; } $items[] = $item->nodeValue; } $replacements[$match] = implode(', ', $items); } else { $replacements[$match] = ''; } } $content = str_replace(array_keys($replacements), array_values($replacements), $content); $email[$key] = $content; } // Find generator: $page = $this->getPage($email['page']); $generator = URL; if ($page->path) { $generator .= '/' . $page->path; } $generator .= '/' . $page->handle; $generator = rtrim($generator, '/'); $params = trim($email['params'], '/'); $generator = "{$generator}/{$params}/"; // Fetch generator require_once TOOLKIT . '/class.gateway.php'; $ch = new Gateway(); $ch->init($generator); $ch->setopt('HTTPHEADER', array('X-REQUESTED-WITH: EmailTemplateFilter')); $message = $ch->exec(); // Add values: $email['message'] = (string) $message; $email['condition_id'] = $email['id']; $email['entry_id'] = $entry_id; $email['recipients'] = array_unique(preg_split('/\\s*[,]\\s*/', $email['recipients'])); $email['reply_to'] = isset($email['reply_to']) ? $email['reply_to'] : $email['sender']; $email['reply_to_email'] = isset($email['reply_to_email']) ? $email['reply_to_email'] : $email['senders']; // Remove junk: unset($email['id']); unset($email['expression']); unset($email['type']); unset($email['sortorder']); unset($email['page']); unset($email['params']); $send = Email::create(); $success = false; try { $send->recipients = $email['recipients']; $send->sender_name = $email['sender']; $send->sender_email_address = $email['senders']; $send->reply_to_name = $email['reply_to']; $send->reply_to_email_address = $email['reply_to_email']; $send->subject = $email['subject']; $send->text_html = $email['message']; $send->attachments = $this->findAttachments($email); $send->send(); $success = true; } catch (EmailGatewayException $e) { throw new SymphonyErrorPage('Error sending email. ' . $e->getMessage()); } catch (EmailException $e) { throw new SymphonyErrorPage('Error sending email. ' . $e->getMessage()); } // Log the email: $email['success'] = $success ? 'yes' : 'no'; $email['date'] = DateTimeObj::get('c'); $email['recipients'] = implode(', ', $email['recipients']); Symphony::Database()->insert($email, 'tbl_etf_logs'); return $return; }
public function render(Register $ParameterOutput) { $result = null; $doc = new XMLDocument(); if (isset($this->parameters()->url)) { $this->parameters()->url = self::replaceParametersInString($this->parameters()->url, $ParameterOutput); } if (isset($this->parameters()->xpath)) { $this->parameters()->xpath = self::replaceParametersInString($this->parameters()->xpath, $ParameterOutput); } $cache_id = md5($this->parameters()->url . serialize($this->parameters()->namespaces) . $this->parameters()->xpath); $cache = Cache::instance(); $cachedData = $cache->read($cache_id); $writeToCache = false; $force_empty_result = false; $valid = true; $result = NULL; $creation = DateTimeObj::get('c'); if (isset($this->parameters()->timeout)) { $timeout = (int) max(1, $this->parameters()->timeout); } if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->parameters()->{'cache-timeout'} * 60) { if (Mutex::acquire($cache_id, $timeout, TMP)) { $start = precision_timer(); $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $this->parameters()->url); $ch->setopt('TIMEOUT', $this->parameters()->timeout); $xml = $ch->exec(); $writeToCache = true; $end = precision_timer('STOP', $start); $info = $ch->getInfoLast(); Mutex::release($cache_id, TMP); $xml = trim($xml); if ((int) $info['http_code'] != 200 || !preg_match('/(xml|plain|text)/i', $info['content_type'])) { $writeToCache = false; if (is_array($cachedData) && !empty($cachedData)) { $xml = trim($cachedData['data']); $valid = false; $creation = DateTimeObj::get('c', $cachedData['creation']); } else { $result = $doc->createElement($this->parameters()->{'root-element'}); $result->setAttribute('valid', 'false'); if ($end > $timeout) { $result->appendChild($doc->createElement('error', sprintf('Request timed out. %d second limit reached.', $timeout))); } else { $result->appendChild($doc->createElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type']))); } return $result; } } elseif (strlen($xml) > 0 && !General::validateXML($xml, $errors)) { $writeToCache = false; if (is_array($cachedData) && !empty($cachedData)) { $xml = trim($cachedData['data']); $valid = false; $creation = DateTimeObj::get('c', $cachedData['creation']); } else { $result = $doc->createElement($this->parameters()->{'root-element'}, $doc->createElement('error', __('XML returned is invalid.')), array('valid' => 'false')); return $result; } } elseif (strlen($xml) == 0) { $force_empty_result = true; } } elseif (is_array($cachedData) && !empty($cachedData)) { $xml = trim($cachedData['data']); $valid = false; $creation = DateTimeObj::get('c', $cachedData['creation']); if (empty($xml)) { $force_empty_result = true; } } else { $force_empty_result = true; } } else { $xml = trim($cachedData['data']); $creation = DateTimeObj::get('c', $cachedData['creation']); } if (!$force_empty_result) { $result = new XMLDocument(); $root = $result->createElement($this->parameters()->{'root-element'}); //XPath Approach, saves Transforming the Document. $xDom = new XMLDocument(); $xDom->loadXML($xml); if ($xDom->hasErrors()) { $root->setAttribute('valid', 'false'); $root->appendChild($result->createElement('error', __('XML returned is invalid.'))); $messages = $result->createElement('messages'); foreach ($xDom->getErrors() as $e) { if (strlen(trim($e->message)) == 0) { continue; } $messages->appendChild($result->createElement('item', General::sanitize($e->message))); } $root->appendChild($messages); } else { if ($writeToCache) { $cache->write($cache_id, $xml); } $xpath = new DOMXPath($xDom); ## Namespaces if (is_array($this->parameters()->namespaces) && !empty($this->parameters()->namespaces)) { foreach ($this->parameters()->namespaces as $index => $namespace) { $xpath->registerNamespace($namespace['name'], $namespace['uri']); } } $xpath_list = $xpath->query($this->parameters()->xpath); foreach ($xpath_list as $node) { if ($node instanceof XMLDocument) { $root->appendChild($result->importNode($node->documentElement, true)); } else { $root->appendChild($result->importNode($node, true)); } } $root->setAttribute('status', $valid === true ? 'fresh' : 'stale'); $root->setAttribute('creation', $creation); } } if (!$root->hasChildNodes() || $force_empty_result) { $this->emptyXMLSet($root); } $result->appendChild($root); return $result; }
/** * Get all HTTP response headers and info as an array of arrays. * * @since 1.17 * * @param string $url * @return array * Contains the headers and the infos */ public static function getHttpHead($url) { // Check if we have a cached result if (isset(self::$_result[$url])) { return self::$_result[$url]; } // create the Gateway object $gateway = new Gateway(); // set our url $gateway->init($url); // set some options $gateway->setopt(CURLOPT_URL, $url); $gateway->setopt(CURLOPT_RETURNTRANSFER, true); $gateway->setopt(CURLOPT_HEADER, true); $gateway->setopt(CURLOPT_NOBODY, true); $gateway->setopt(CURLOPT_FOLLOWLOCATION, true); $gateway->setopt(CURLOPT_MAXREDIRS, Image::CURL_MAXREDIRS); // get the raw head response, ignore errors $head = @$gateway->exec(); // Get all info $result = array('headers' => array(), 'info' => $gateway->getInfoLast()); // Clean up $gateway->flush(); if ($head !== false) { $result['headers'] = self::parseHttpHeaderFields($head); } // Save for subsequent requests self::$_result[$url] = $result; return $result; }
$stylesheet->appendChild($template); $stylesheet->setIncludeHeader(true); $xsl = $stylesheet->generate(true); $proc =& new XsltProcess(); $cache_id = md5($this->dsParamURL . serialize($this->dsParamFILTERS) . $this->dsParamXPATH); $cache = new Cacheable($this->_Parent->Database); $cachedData = $cache->check($cache_id); $writeToCache = false; $valid = true; $result = NULL; $creation = DateTimeObj::get('c'); if (!$cachedData || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) { if (Mutex::acquire($cache_id, 6, TMP)) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $this->dsParamURL); $ch->setopt('TIMEOUT', 6); $xml = $ch->exec(); $writeToCache = true; Mutex::release($cache_id, TMP); $xml = trim($xml); if (!empty($xml)) { $valid = General::validateXML($xml, $errors, false, $proc); if (!$valid) { if ($cachedData) { $xml = $cachedData['data']; } else { $result = new XMLElement($this->dsParamROOTELEMENT); $result->setAttribute('valid', 'false'); $result->appendChild(new XMLElement('error', __('XML returned is invalid.'))); }
/** * Builds the attachment section of a multipart email. * * Will return a string containing the section. Can be used to send to * an email server directly. * * @return string */ protected function getSectionAttachments() { $output = ''; foreach ($this->_attachments as $key => $file) { $fileContent = null; // If the attachement is an url if (filter_var($file['file'], FILTER_VALIDATE_URL)) { require_once TOOLKIT . '/class.gateway.php'; // use gateway for urls $gateway = new Gateway(); $gateway->init($file['file']); $gateway->setopt('TIMEOUT', 30); $fileContent = @$gateway->exec(); } else { $fileContent = @file_get_contents($file['file']); } if ($fileContent !== FALSE && !empty($fileContent)) { $output .= $this->boundaryDelimiterLine('multipart/mixed') . $this->contentInfoString(NULL, $file['file'], $file['filename'], $file['charset']) . EmailHelper::base64ContentTransferEncode($fileContent); } else { throw new EmailGatewayException(__('The content of the file `%s` could not be loaded.', array($file['file']))); } } return $output; }
public function render_panel($context) { $config = $context['config']; switch ($context['type']) { case 'datasource_to_table': $ds = DatasourceManager::create($config['datasource'], NULL, false); if (!$ds) { $context['panel']->appendChild(new XMLElement('div', __('The Data Source with the name <code>%s</code> could not be found.', array($config['datasource'])))); return; } $param_pool = array(); $xml = $ds->grab($param_pool); if (!$xml) { return; } $xml = $xml->generate(); require_once TOOLKIT . '/class.xsltprocess.php'; $proc = new XsltProcess(); $data = $proc->process($xml, file_get_contents(EXTENSIONS . '/dashboard/lib/datasource-to-table.xsl')); $context['panel']->appendChild(new XMLElement('div', $data)); break; case 'rss_reader': require_once TOOLKIT . '/class.gateway.php'; require_once CORE . '/class.cacheable.php'; $cache_id = md5('rss_reader_cache' . $config['url']); $cache = new Cacheable(Administration::instance()->Database()); $data = $cache->check($cache_id); if (!$data) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $config['url']); $ch->setopt('TIMEOUT', 6); $new_data = $ch->exec(); $writeToCache = true; if ((int) $config['cache'] > 0) { $cache->write($cache_id, $new_data, $config['cache']); } $xml = $new_data; if (empty($xml) && $data) { $xml = $data['data']; } } else { $xml = $data['data']; } if (!$xml) { $xml = '<error>' . __('Error: could not retrieve panel XML feed.') . '</error>'; } require_once TOOLKIT . '/class.xsltprocess.php'; $proc = new XsltProcess(); $data = $proc->process($xml, file_get_contents(EXTENSIONS . '/dashboard/lib/rss-reader.xsl'), array('show' => $config['show'])); $context['panel']->appendChild(new XMLElement('div', $data)); break; case 'html_block': require_once TOOLKIT . '/class.gateway.php'; require_once CORE . '/class.cacheable.php'; $cache_id = md5('html_block_' . $config['url']); $cache = new Cacheable(Administration::instance()->Database()); $data = $cache->check($cache_id); if (!$data) { $ch = new Gateway(); $ch->init(); $ch->setopt('URL', $config['url']); $ch->setopt('TIMEOUT', 6); $new_data = $ch->exec(); $writeToCache = true; if ((int) $config['cache'] > 0) { $cache->write($cache_id, $new_data, $config['cache']); } $html = $new_data; if (empty($html) && $data) { $html = $data['data']; } } else { $html = $data['data']; } if (!$html) { $html = '<p class="invalid">' . __('Error: could not retrieve panel HTML.') . '</p>'; } $context['panel']->appendChild(new XMLElement('div', $html)); break; case 'symphony_overview': $container = new XMLElement('div'); $dl = new XMLElement('dl'); $dl->appendChild(new XMLElement('dt', __('Website Name'))); $dl->appendChild(new XMLElement('dd', Symphony::Configuration()->get('sitename', 'general'))); $current_version = Symphony::Configuration()->get('version', 'symphony'); require_once TOOLKIT . '/class.gateway.php'; $ch = new Gateway(); $ch->init(); $ch->setopt('URL', 'https://api.github.com/repos/symphonycms/symphony-2/tags'); $ch->setopt('TIMEOUT', $timeout); $repo_tags = $ch->exec(); // tags request found if (is_array($repo_tags)) { $repo_tags = json_decode($repo_tags); $tags = array(); foreach ($repo_tags as $tag) { // remove tags that contain strings if (preg_match('/[a-zA]/i', $tag->name)) { continue; } $tags[] = $tag->name; } natsort($tags); rsort($tags); $latest_version = reset($tags); } else { $latest_version = $current_version; } $needs_update = version_compare($latest_version, $current_version, '>'); $dl->appendChild(new XMLElement('dt', __('Version'))); $dl->appendChild(new XMLElement('dd', $current_version . ($needs_update ? ' (<a href="http://getsymphony.com/download/releases/version/' . $latest_version . '/">' . __('Latest is %s', array($latest_version)) . "</a>)" : ''))); $container->appendChild(new XMLElement('h4', __('Configuration'))); $container->appendChild($dl); $entries = 0; foreach (SectionManager::fetch() as $section) { $entries += EntryManager::fetchCount($section->get('id')); } $dl = new XMLElement('dl'); $dl->appendChild(new XMLElement('dt', __('Sections'))); $dl->appendChild(new XMLElement('dd', (string) count(SectionManager::fetch()))); $dl->appendChild(new XMLElement('dt', __('Entries'))); $dl->appendChild(new XMLElement('dd', (string) $entries)); $dl->appendChild(new XMLElement('dt', __('Data Sources'))); $dl->appendChild(new XMLElement('dd', (string) count(DatasourceManager::listAll()))); $dl->appendChild(new XMLElement('dt', __('Events'))); $dl->appendChild(new XMLElement('dd', (string) count(EventManager::listAll()))); $dl->appendChild(new XMLElement('dt', __('Pages'))); $dl->appendChild(new XMLElement('dd', (string) count(PageManager::fetch()))); $container->appendChild(new XMLElement('h4', __('Statistics'))); $container->appendChild($dl); $context['panel']->appendChild($container); break; case 'markdown_text': $formatter = TextformatterManager::create($config['formatter']); $html = $formatter->run($config['text']); $context['panel']->appendChild(new XMLElement('div', $html)); break; } }
public static function getVideoFeed($video_id) { // Fetch document: $gateway = new Gateway(); $gateway->init(); $gateway->setopt('URL', "http://gdata.youtube.com/feeds/api/videos/{$video_id}"); $gateway->setopt('TIMEOUT', 6); $data = $gateway->exec(); if ($data == "Invalid id") { return null; } return DOMDocument::loadXML($data); }
<?php if (!isset($_REQUEST['auth'])) { General::redirect(URL . '/symphony/'); } $ch = new Gateway(); $ch->init(); $ch->setopt("URL", URL . '/symphony/ajax/'); $ch->setopt("POST", 1); $ch->setopt("POSTFIELDS", array('action' => 'status', 'token' => $_REQUEST['auth'], 'mode' => 'full')); $data = $ch->exec(); $parser = new XmlDoc(); $parser->parseString($data); $doc = $parser->getArray(); unset($parser); $obDate = $Admin->getDateObj(); $rss = new XMLElement('rss'); $rss->setAttribute('version', '2.0'); $channel = new XMLElement('channel'); $channel->addChild(new XMLElement('title', $Admin->getConfigVar('sitename', 'general'))); $channel->addChild(new XMLElement('link', URL)); $channel->addChild(new XMLElement('description', $Admin->getConfigVar('sitename', 'general') . ' Status Feed')); $channel->addChild(new XMLElement('language', 'en-us')); $channel->addChild(new XMLElement('generator', 'Symphony ' . $Admin->getConfigVar('build', 'symphony'))); function flattenFragment($f, $type) { $f = $f[$type]; $flattened = array(); $flattened['attributes'] = $f['attributes']; $flattened['data'] = array(); unset($f['attributes']);
public function execute(array &$param_pool = null) { $result = new XMLElement($this->dsParamROOTELEMENT); // When DS is called out of the Frontend context, this will enable // {$root} and {$workspace} parameters to be evaluated if (empty($this->_env)) { $this->_env['env']['pool'] = array('root' => URL, 'workspace' => WORKSPACE); } try { require_once TOOLKIT . '/class.gateway.php'; require_once TOOLKIT . '/class.xsltprocess.php'; require_once CORE . '/class.cacheable.php'; $this->dsParamURL = $this->parseParamURL($this->dsParamURL); if (isset($this->dsParamXPATH)) { $this->dsParamXPATH = $this->__processParametersInString(stripslashes($this->dsParamXPATH), $this->_env); } // Builds a Default Stylesheet to transform the resulting XML with $stylesheet = new XMLElement('xsl:stylesheet'); $stylesheet->setAttributeArray(array('version' => '1.0', 'xmlns:xsl' => 'http://www.w3.org/1999/XSL/Transform')); $output = new XMLElement('xsl:output'); $output->setAttributeArray(array('method' => 'xml', 'version' => '1.0', 'encoding' => 'utf-8', 'indent' => 'yes', 'omit-xml-declaration' => 'yes')); $stylesheet->appendChild($output); $template = new XMLElement('xsl:template'); $template->setAttribute('match', '/'); $instruction = new XMLElement('xsl:copy-of'); // Namespaces if (isset($this->dsParamNAMESPACES) && is_array($this->dsParamNAMESPACES)) { foreach ($this->dsParamNAMESPACES as $name => $uri) { $instruction->setAttribute('xmlns' . ($name ? ":{$name}" : null), $uri); } } // XPath $instruction->setAttribute('select', $this->dsParamXPATH); $template->appendChild($instruction); $stylesheet->appendChild($template); $stylesheet->setIncludeHeader(true); $xsl = $stylesheet->generate(true); // Check for an existing Cache for this Datasource $cache_id = self::buildCacheID($this); $cache = Symphony::ExtensionManager()->getCacheProvider('remotedatasource'); $cachedData = $cache->check($cache_id); $writeToCache = null; $isCacheValid = true; $creation = DateTimeObj::get('c'); // Execute if the cache doesn't exist, or if it is old. if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) { if (Mutex::acquire($cache_id, $this->dsParamTIMEOUT, TMP)) { $ch = new Gateway(); $ch->init($this->dsParamURL); $ch->setopt('TIMEOUT', $this->dsParamTIMEOUT); // Set the approtiate Accept: headers depending on the format of the URL. if ($this->dsParamFORMAT == 'xml') { $ch->setopt('HTTPHEADER', array('Accept: text/xml, */*')); } elseif ($this->dsParamFORMAT == 'json') { $ch->setopt('HTTPHEADER', array('Accept: application/json, */*')); } elseif ($this->dsParamFORMAT == 'csv') { $ch->setopt('HTTPHEADER', array('Accept: text/csv, */*')); } self::prepareGateway($ch); $data = $ch->exec(); $info = $ch->getInfoLast(); Mutex::release($cache_id, TMP); $data = trim($data); $writeToCache = true; // Handle any response that is not a 200, or the content type does not include XML, JSON, plain or text if ((int) $info['http_code'] != 200 || !preg_match('/(xml|json|csv|plain|text)/i', $info['content_type'])) { $writeToCache = false; $result->setAttribute('valid', 'false'); // 28 is CURLE_OPERATION_TIMEOUTED if ($info['curl_error'] == 28) { $result->appendChild(new XMLElement('error', sprintf('Request timed out. %d second limit reached.', $timeout))); } else { $result->appendChild(new XMLElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type']))); } return $result; } else { if (strlen($data) > 0) { // Handle where there is `$data` // If it's JSON, convert it to XML if ($this->dsParamFORMAT == 'json') { try { require_once TOOLKIT . '/class.json.php'; $data = JSON::convertToXML($data); } catch (Exception $ex) { $writeToCache = false; $errors = array(array('message' => $ex->getMessage())); } } elseif ($this->dsParamFORMAT == 'csv') { try { require_once EXTENSIONS . '/remote_datasource/lib/class.csv.php'; $data = CSV::convertToXML($data); } catch (Exception $ex) { $writeToCache = false; $errors = array(array('message' => $ex->getMessage())); } } elseif ($this->dsParamFORMAT == 'txt') { $txtElement = new XMLElement('entry'); $txtElement->setValue(General::wrapInCDATA($data)); $data = $txtElement->generate(); $txtElement = null; } else { if (!General::validateXML($data, $errors, false, new XsltProcess())) { // If the XML doesn't validate.. $writeToCache = false; } } // If the `$data` is invalid, return a result explaining why if ($writeToCache === false) { $error = new XMLElement('errors'); $error->setAttribute('valid', 'false'); $error->appendChild(new XMLElement('error', __('Data returned is invalid.'))); foreach ($errors as $e) { if (strlen(trim($e['message'])) == 0) { continue; } $error->appendChild(new XMLElement('item', General::sanitize($e['message']))); } $result->appendChild($error); return $result; } } elseif (strlen($data) == 0) { // If `$data` is empty, set the `force_empty_result` to true. $this->_force_empty_result = true; } } } else { // Failed to acquire a lock $result->appendChild(new XMLElement('error', __('The %s class failed to acquire a lock.', array('<code>Mutex</code>')))); } } else { // The cache is good, use it! $data = trim($cachedData['data']); $creation = DateTimeObj::get('c', $cachedData['creation']); } // Visit the data $this->exposeData($data); // If `$writeToCache` is set to false, invalidate the old cache if it existed. if (is_array($cachedData) && !empty($cachedData) && $writeToCache === false) { $data = trim($cachedData['data']); $isCacheValid = false; $creation = DateTimeObj::get('c', $cachedData['creation']); if (empty($data)) { $this->_force_empty_result = true; } } // If `force_empty_result` is false and `$result` is an instance of // XMLElement, build the `$result`. if (!$this->_force_empty_result && is_object($result)) { $proc = new XsltProcess(); $ret = $proc->process($data, $xsl); if ($proc->isErrors()) { $result->setAttribute('valid', 'false'); $error = new XMLElement('error', __('Transformed XML is invalid.')); $result->appendChild($error); $errors = new XMLElement('errors'); foreach ($proc->getError() as $e) { if (strlen(trim($e['message'])) == 0) { continue; } $errors->appendChild(new XMLElement('item', General::sanitize($e['message']))); } $result->appendChild($errors); $result->appendChild(new XMLElement('raw-data', General::wrapInCDATA($data))); } elseif (strlen(trim($ret)) == 0) { $this->_force_empty_result = true; } else { if ($this->dsParamCACHE > 0 && $writeToCache) { $cache->write($cache_id, $data, $this->dsParamCACHE); } $result->setValue(PHP_EOL . str_repeat("\t", 2) . preg_replace('/([\\r\\n]+)/', "\$1\t", $ret)); $result->setAttribute('status', $isCacheValid === true ? 'fresh' : 'stale'); $result->setAttribute('cache-id', $cache_id); $result->setAttribute('creation', $creation); } } } catch (Exception $e) { $result->appendChild(new XMLElement('error', $e->getMessage())); } if ($this->_force_empty_result) { $result = $this->emptyXMLSet(); } $result->setAttribute('url', General::sanitize($this->dsParamURL)); return $result; }
private function getCoords($place) { $key = $this->_engine->Configuration->get('google-api-key', 'address-field'); $url = "http://maps.google.com/maps/geo?q={$place}&output=xml&key={$key}"; $gate = new Gateway(); $gate->init(); $gate->setopt('URL', $url, 'address-field'); $response = $gate->exec(); // Parse the XML to find the coordinates $xml = new SimpleXMLElement($response); return preg_split('/,/', $xml->Response->Placemark[0]->Point->coordinates, -1, PREG_SPLIT_NO_EMPTY); }
public function execute(array &$param_pool = null) { $result = new XMLElement($this->dsParamROOTELEMENT); $this->dsParamURL = $this->parseParamURL($this->dsParamURL); if (isset($this->dsParamXPATH)) { $this->dsParamXPATH = $this->__processParametersInString($this->dsParamXPATH, $this->_env); } $stylesheet = new XMLElement('xsl:stylesheet'); $stylesheet->setAttributeArray(array('version' => '1.0', 'xmlns:xsl' => 'http://www.w3.org/1999/XSL/Transform')); $output = new XMLElement('xsl:output'); $output->setAttributeArray(array('method' => 'xml', 'version' => '1.0', 'encoding' => 'utf-8', 'indent' => 'yes', 'omit-xml-declaration' => 'yes')); $stylesheet->appendChild($output); $template = new XMLElement('xsl:template'); $template->setAttribute('match', '/'); $instruction = new XMLElement('xsl:copy-of'); // Namespaces if (isset($this->dsParamFILTERS) && is_array($this->dsParamFILTERS)) { foreach ($this->dsParamFILTERS as $name => $uri) { $instruction->setAttribute('xmlns' . ($name ? ":{$name}" : null), $uri); } } // XPath $instruction->setAttribute('select', $this->dsParamXPATH); $template->appendChild($instruction); $stylesheet->appendChild($template); $stylesheet->setIncludeHeader(true); $xsl = $stylesheet->generate(true); $cache_id = md5($this->dsParamURL . serialize($this->dsParamFILTERS) . $this->dsParamXPATH); $cache = new Cacheable(Symphony::Database()); $cachedData = $cache->read($cache_id); $writeToCache = false; $valid = true; $creation = DateTimeObj::get('c'); $timeout = isset($this->dsParamTIMEOUT) ? (int) max(1, $this->dsParamTIMEOUT) : 6; // Execute if the cache doesn't exist, or if it is old. if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) { if (Mutex::acquire($cache_id, $timeout, TMP)) { $ch = new Gateway(); $ch->init($this->dsParamURL); $ch->setopt('TIMEOUT', $timeout); $ch->setopt('HTTPHEADER', array('Accept: text/xml, */*')); $data = $ch->exec(); $info = $ch->getInfoLast(); Mutex::release($cache_id, TMP); $data = trim($data); $writeToCache = true; // Handle any response that is not a 200, or the content type does not include XML, plain or text if ((int) $info['http_code'] !== 200 || !preg_match('/(xml|plain|text)/i', $info['content_type'])) { $writeToCache = false; $result->setAttribute('valid', 'false'); // 28 is CURLE_OPERATION_TIMEOUTED if ($info['curl_error'] == 28) { $result->appendChild(new XMLElement('error', sprintf('Request timed out. %d second limit reached.', $timeout))); } else { $result->appendChild(new XMLElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type']))); } return $result; // Handle where there is `$data` } elseif (strlen($data) > 0) { // If the XML doesn't validate.. if (!General::validateXML($data, $errors, false, new XsltProcess())) { $writeToCache = false; } // If the `$data` is invalid, return a result explaining why if ($writeToCache === false) { $element = new XMLElement('errors'); $result->setAttribute('valid', 'false'); $result->appendChild(new XMLElement('error', __('Data returned is invalid.'))); foreach ($errors as $e) { if (strlen(trim($e['message'])) == 0) { continue; } $element->appendChild(new XMLElement('item', General::sanitize($e['message']))); } $result->appendChild($element); return $result; } // If `$data` is empty, set the `force_empty_result` to true. } elseif (strlen($data) == 0) { $this->_force_empty_result = true; } // Failed to acquire a lock } else { $result->appendChild(new XMLElement('error', __('The %s class failed to acquire a lock, check that %s exists and is writable.', array('<code>Mutex</code>', '<code>' . TMP . '</code>')))); } // The cache is good, use it! } else { $data = trim($cachedData['data']); $creation = DateTimeObj::get('c', $cachedData['creation']); } // If `$writeToCache` is set to false, invalidate the old cache if it existed. if (is_array($cachedData) && !empty($cachedData) && $writeToCache === false) { $data = trim($cachedData['data']); $valid = false; $creation = DateTimeObj::get('c', $cachedData['creation']); if (empty($data)) { $this->_force_empty_result = true; } } // If `force_empty_result` is false and `$result` is an instance of // XMLElement, build the `$result`. if (!$this->_force_empty_result && is_object($result)) { $proc = new XsltProcess(); $ret = $proc->process($data, $xsl); if ($proc->isErrors()) { $result->setAttribute('valid', 'false'); $error = new XMLElement('error', __('Transformed XML is invalid.')); $result->appendChild($error); $element = new XMLElement('errors'); foreach ($proc->getError() as $e) { if (strlen(trim($e['message'])) == 0) { continue; } $element->appendChild(new XMLElement('item', General::sanitize($e['message']))); } $result->appendChild($element); } elseif (strlen(trim($ret)) == 0) { $this->_force_empty_result = true; } else { if ($writeToCache) { $cache->write($cache_id, $data, $this->dsParamCACHE); } $result->setValue(PHP_EOL . str_repeat("\t", 2) . preg_replace('/([\\r\\n]+)/', "\$1\t", $ret)); $result->setAttribute('status', $valid === true ? 'fresh' : 'stale'); $result->setAttribute('creation', $creation); } } return $result; }
public function validate($source = null, $remote = true) { if (!function_exists('handleXMLError')) { function handleXMLError($errno, $errstr, $errfile, $errline, $context) { $context['self']->_errors[] = $errstr; } } set_time_limit(900); set_error_handler('handleXMLError'); $self = $this; // F*****g PHP... $options = $this->options(); $passed = true; if ($remote) { if (!is_null($source)) { $options['source'] = $source; } // Support {$root} $options['source'] = str_replace('{$root}', URL, $options['source']); // Parse timeout, default is 60 $timeout = isset($options['timeout']) ? (int) $options['timeout'] : 60; // Fetch document: $gateway = new Gateway(); $gateway->init(); $gateway->setopt('URL', $options['source']); $gateway->setopt('TIMEOUT', $timeout); $data = $gateway->exec(); $info = $gateway->getInfoLast(); if (empty($data) || $info['http_code'] >= 400) { $this->_errors[] = __('No data to import. URL returned HTTP code %d', array($info['http_code'])); $passed = false; } } else { if (!is_null($source)) { $data = $source; } else { $this->_errors[] = __('No data to import.'); $passed = false; } } if (!is_array($options['fields'])) { $this->_errors[] = __('No field mappings have been set for this XML Importer.'); $passed = false; } if (!$passed) { return self::__ERROR_PREPARING__; } // Load document: $xml = new DOMDocument(); $xml->loadXML($data); restore_error_handler(); $xpath = new DOMXPath($xml); $passed = true; // Register namespaces: if (is_array($options['namespaces'])) { foreach ($options['namespaces'] as $namespace) { $xpath->registerNamespace($namespace['name'], $namespace['uri']); } } // Invalid Markup: if (empty($xml)) { $passed = false; } else { if (($entries = $xpath->query($options['included-elements'])) === false) { $this->_errors[] = __('Root expression <code>%s</code> is invalid.', array(General::sanitize($options['included-elements']))); $passed = false; } else { if (is_null($entries) or $entries->length == 0) { $this->_errors[] = __('No entries to import.'); $passed = false; } else { foreach ($options['fields'] as $mapping) { if ($xpath->evaluate(stripslashes($mapping['xpath'])) !== false) { continue; } $field = FieldManager::fetch($mapping['field']); $this->_errors[] = __('\'%s\' expression <code>%s</code> is invalid.', array($field->get('label'), General::sanitize($mapping['xpath']))); $passed = false; } } } } if (!$passed) { return self::__ERROR_PREPARING__; } // Gather data: foreach ($entries as $index => $entry) { $this->_entries[$index] = array('element' => $entry, 'values' => array(), 'errors' => array(), 'entry' => null); foreach ($options['fields'] as $mapping) { $values = $this->getExpressionValue($xml, $entry, $xpath, $mapping['xpath'], $debug); if (isset($mapping['php']) && $mapping['php'] != '') { $php = stripslashes($mapping['php']); // static helper if (preg_match('/::/', $php)) { foreach ($values as $id => $value) { $values[$id] = call_user_func_array($php, array($value)); } } else { foreach ($values as $id => $value) { $function = preg_replace('/\\$value/', "'" . $value . "'", $php); if (!preg_match('/^return/', $function)) { $function = 'return ' . $function; } if (!preg_match('/;$/', $function)) { $function .= ';'; } $values[$id] = @eval($function); } } } $this->_entries[$index]['values'][$mapping['field']] = $values; } } // Validate: $passed = true; foreach ($this->_entries as &$current) { $entry = EntryManager::create(); $entry->set('section_id', $options['section']); $entry->set('author_id', is_null(Symphony::Engine()->Author()) ? '1' : Symphony::Engine()->Author()->get('id')); $values = array(); // Map values: foreach ($current['values'] as $field_id => $value) { $field = FieldManager::fetch($field_id); if (is_array($value)) { if (count($value) === 1) { $value = current($value); } if (count($value) === 0) { $value = ''; } } // Adjust value? if (method_exists($field, 'prepareImportValue') && method_exists($field, 'getImportModes')) { $modes = $field->getImportModes(); if (is_array($modes) && !empty($modes)) { $mode = current($modes); } $value = $field->prepareImportValue($value, $mode, $entry->get('id')); } else { $type = $field->get('type'); if ($type == 'author') { if ($field->get('allow_multiple_selection') == 'no') { if (is_array($value)) { $value = array(implode('', $value)); } } } else { if ($type == 'datetime') { $value = $value[0]; } else { if (is_array($value)) { $value = implode('', $value); } } } } $values[$field->get('element_name')] = $value; } // Validate: if (__ENTRY_FIELD_ERROR__ == $entry->checkPostData($values, $current['errors'])) { $passed = false; } else { if (__ENTRY_OK__ != $entry->setDataFromPost($values, $current['errors'], true, true)) { $passed = false; } } $current['entry'] = $entry; $current['values'] = $values; } if (!$passed) { return self::__ERROR_VALIDATING__; } return self::__OK__; }