/** * Load translation data (TBX file reader) * * @param string $filename TBX file to add, full path must be given for access * @param string $locale Locale has no effect for TBX because TBX defines all languages within * the source file * @param array $option OPTIONAL Options to use * @throws Zend_Translation_Exception * @return array */ protected function _loadTranslationData($filename, $locale, array $options = array()) { $this->_data = array(); if (!is_readable($filename)) { require_once 'Zend/Translate/Exception.php'; throw new Zend_Translate_Exception('Translation file \'' . $filename . '\' is not readable.'); } $encoding = $this->_findEncoding($filename); $this->_file = xml_parser_create($encoding); xml_set_object($this->_file, $this); xml_parser_set_option($this->_file, XML_OPTION_CASE_FOLDING, 0); xml_set_element_handler($this->_file, "_startElement", "_endElement"); xml_set_character_data_handler($this->_file, "_contentElement"); try { Zend_Xml_Security::scanFile($filename); } catch (Zend_Xml_Exception $e) { require_once 'Zend/Translate/Exception.php'; throw new Zend_Translate_Exception($e->getMessage()); } if (!xml_parse($this->_file, file_get_contents($filename))) { $ex = sprintf('XML error: %s at line %d of file %s', xml_error_string(xml_get_error_code($this->_file)), xml_get_current_line_number($this->_file), $filename); xml_parser_free($this->_file); require_once 'Zend/Translate/Exception.php'; throw new Zend_Translate_Exception($ex); } return $this->_data; }
/** * @param string $file * @return SimpleXMLElement * @throws XenForo_Exception */ public static function scanFile($file) { $xml = Zend_Xml_Security::scanFile($file); if (!$xml) { throw new XenForo_Exception("Invalid XML in {$file}"); } return $xml; }
/** * Load configuration XML * * @param string $configurationXml Configuration XML */ public function loadXml($configurationXml) { // Convert to SimpleXMLElement $configurationXml = Zend_Xml_Security::scan($configurationXml); // Assign general settings $this->DataSources->OverallQuotaInMB = (int) $configurationXml->DataSources->OverallQuotaInMB; // Assign Logs settings $this->DataSources->Logs->BufferQuotaInMB = (int) $configurationXml->DataSources->Logs->BufferQuotaInMB; $this->DataSources->Logs->ScheduledTransferPeriodInMinutes = (int) $configurationXml->DataSources->Logs->ScheduledTransferPeriodInMinutes; $this->DataSources->Logs->ScheduledTransferLogLevelFilter = (string) $configurationXml->DataSources->Logs->ScheduledTransferLogLevelFilter; // Assign DiagnosticInfrastructureLogs settings $this->DataSources->DiagnosticInfrastructureLogs->BufferQuotaInMB = (int) $configurationXml->DataSources->DiagnosticInfrastructureLogs->BufferQuotaInMB; $this->DataSources->DiagnosticInfrastructureLogs->ScheduledTransferPeriodInMinutes = (int) $configurationXml->DataSources->DiagnosticInfrastructureLogs->ScheduledTransferPeriodInMinutes; $this->DataSources->DiagnosticInfrastructureLogs->ScheduledTransferLogLevelFilter = (string) $configurationXml->DataSources->DiagnosticInfrastructureLogs->ScheduledTransferLogLevelFilter; // Assign PerformanceCounters settings $this->DataSources->PerformanceCounters->BufferQuotaInMB = (int) $configurationXml->DataSources->PerformanceCounters->BufferQuotaInMB; $this->DataSources->PerformanceCounters->ScheduledTransferPeriodInMinutes = (int) $configurationXml->DataSources->PerformanceCounters->ScheduledTransferPeriodInMinutes; if ($configurationXml->DataSources->PerformanceCounters->Subscriptions && $configurationXml->DataSources->PerformanceCounters->Subscriptions->PerformanceCounterConfiguration) { $subscriptions = $configurationXml->DataSources->PerformanceCounters->Subscriptions; if (count($subscriptions->PerformanceCounterConfiguration) > 1) { $subscriptions = $subscriptions->PerformanceCounterConfiguration; } else { $subscriptions = array($subscriptions->PerformanceCounterConfiguration); } foreach ($subscriptions as $subscription) { $this->DataSources->PerformanceCounters->addSubscription((string) $subscription->CounterSpecifier, (int) $subscription->SampleRateInSeconds); } } // Assign WindowsEventLog settings $this->DataSources->WindowsEventLog->BufferQuotaInMB = (int) $configurationXml->DataSources->WindowsEventLog->BufferQuotaInMB; $this->DataSources->WindowsEventLog->ScheduledTransferPeriodInMinutes = (int) $configurationXml->DataSources->WindowsEventLog->ScheduledTransferPeriodInMinutes; $this->DataSources->WindowsEventLog->ScheduledTransferLogLevelFilter = (string) $configurationXml->DataSources->WindowsEventLog->ScheduledTransferLogLevelFilter; if ($configurationXml->DataSources->WindowsEventLog->Subscriptions && $configurationXml->DataSources->WindowsEventLog->Subscriptions->string) { $subscriptions = $configurationXml->DataSources->WindowsEventLog->Subscriptions; if (count($subscriptions->string) > 1) { $subscriptions = $subscriptions->string; } else { $subscriptions = array($subscriptions->string); } foreach ($subscriptions as $subscription) { $this->DataSources->WindowsEventLog->addSubscription((string) $subscription); } } // Assign Directories settings $this->DataSources->Directories->BufferQuotaInMB = (int) $configurationXml->DataSources->Directories->BufferQuotaInMB; $this->DataSources->Directories->ScheduledTransferPeriodInMinutes = (int) $configurationXml->DataSources->Directories->ScheduledTransferPeriodInMinutes; if ($configurationXml->DataSources->Directories->Subscriptions && $configurationXml->DataSources->Directories->Subscriptions->DirectoryConfiguration) { $subscriptions = $configurationXml->DataSources->Directories->Subscriptions; if (count($subscriptions->DirectoryConfiguration) > 1) { $subscriptions = $subscriptions->DirectoryConfiguration; } else { $subscriptions = array($subscriptions->DirectoryConfiguration); } foreach ($subscriptions as $subscription) { $this->DataSources->Directories->addSubscription((string) $subscription->Path, (string) $subscription->Container, (int) $subscription->DirectoryQuotaInMB); } } }
public static function scanXmlString($xmlString) { if (self::callbackChecker('Zend_Xml_Security', 'scan')) { //Protected method $xmlObj = Zend_Xml_Security::scan($xmlString); if (!$xmlObj) { throw new XenForo_Exception("Invalid XML in {$xmlObj}"); } } else { //Classic PHP method $xmlObj = simplexml_load_string($xmlString); } return $xmlObj; }
/** * Constructor * * @param string $data XML Result * @return void */ public function __construct($data) { set_error_handler(array($this, 'handleXmlErrors')); $this->_sxml = Zend_Xml_Security::scan($data); restore_error_handler(); if ($this->_sxml === false) { if ($this->_errstr === null) { $message = "An error occured while parsing the REST response with simplexml."; } else { $message = "REST Response Error: " . $this->_errstr; $this->_errstr = null; } throw new Zend_Rest_Client_Result_Exception($message); } }
/** * Class constructor. Parse the XML response from a Nirvanix method * call into a decorated SimpleXMLElement element. * * @param string $xml XML response string from Nirvanix * @throws Zend_Service_Nirvanix_Exception */ public function __construct($xml) { $this->_sxml = Zend_Xml_Security::scan($xml); if (!$this->_sxml instanceof SimpleXMLElement) { $this->_throwException("XML could not be parsed from response: {$xml}"); } $name = $this->_sxml->getName(); if ($name != 'Response') { $this->_throwException("Expected XML element Response, got {$name}"); } $code = (int) $this->_sxml->ResponseCode; if ($code != 0) { $msg = (string) $this->_sxml->ErrorMessage; $this->_throwException($msg, $code); } }
/** * Returns a SimpleXML element from the provided file name (or XenForo_Upload object) * provided it is valid. If it is not valid, an error is thrown. * * @param string|XenForo_Upload $file * * @return SimpleXMLElement */ public function getXmlFromFile($file) { if ($file instanceof XenForo_Upload) { $file = $file->getTempFile(); } if (!file_exists($file)) { throw $this->_controller->responseException($this->_controller->responseError(new XenForo_Phrase('please_enter_valid_file_name_requested_file_not_read'))); } try { $xml = Zend_Xml_Security::scanFile($file); if ($xml) { return $xml; } } catch (Exception $e) { } throw $this->_controller->responseException($this->_controller->responseError(new XenForo_Phrase('provided_file_was_not_valid_xml_file'))); }
/** * Zend_Feed_Entry_Abstract constructor * * The Zend_Feed_Entry_Abstract constructor takes the URI of the feed the entry * is part of, and optionally an XML construct (usually a * SimpleXMLElement, but it can be an XML string or a DOMNode as * well) that contains the contents of the entry. * * @param string $uri * @param SimpleXMLElement|DOMNode|string $element * @return void * @throws Zend_Feed_Exception */ public function __construct($uri = null, $element = null) { if (!$element instanceof DOMElement) { if ($element) { // Load the feed as an XML DOMDocument object @ini_set('track_errors', 1); $doc = new DOMDocument(); $doc = @Zend_Xml_Security::scan($element, $doc); @ini_restore('track_errors'); if (!$doc) { // prevent the class to generate an undefined variable notice (ZF-2590) if (!isset($php_errormsg)) { if (function_exists('xdebug_is_enabled')) { $php_errormsg = '(error message not available, when XDebug is running)'; } else { $php_errormsg = '(error message not available)'; } } /** * @see Zend_Feed_Exception */ // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception("DOMDocument cannot parse XML: {$php_errormsg}"); } $element = $doc->getElementsByTagName($this->_rootElement)->item(0); if (!$element) { /** * @see Zend_Feed_Exception */ // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('No root <' . $this->_rootElement . '> element found, cannot parse feed.'); } } else { $doc = new DOMDocument('1.0', 'utf-8'); if ($this->_rootNamespace !== null) { $element = $doc->createElementNS(Zend_Feed::lookupNamespace($this->_rootNamespace), $this->_rootElement); } else { $element = $doc->createElement($this->_rootElement); } } } parent::__construct($element); }
/** * Create auth adapter * * @param string $rolefile File containing XML with users and roles */ public function __construct($rolefile) { $this->_acl = new Zend_Acl(); $xml = Zend_Xml_Security::scanFile($rolefile); /* Roles file format: <roles> <role id=”admin”> <user name=”user1” password=”pwd”/> </role> <role id=”hr”> <user name=”user2” password=”pwd2”/> </role> </roles> */ foreach ($xml->role as $role) { $this->_acl->addRole(new Zend_Acl_Role((string) $role["id"])); foreach ($role->user as $user) { $this->_users[(string) $user["name"]] = array("password" => (string) $user["password"], "role" => (string) $role["id"]); } } }
/** * Extract metadata from document * * @param ZipArchive $package ZipArchive OpenXML package * @return array Key-value pairs containing document meta data */ protected function extractMetaData(ZipArchive $package) { // Data holders $coreProperties = array(); // Read relations and search for core properties $relations = Zend_Xml_Security::scan($package->getFromName("_rels/.rels")); foreach ($relations->Relationship as $rel) { if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_COREPROPERTIES) { // Found core properties! Read in contents... $contents = Zend_Xml_Security::scan($package->getFromName(dirname($rel["Target"]) . "/" . basename($rel["Target"]))); foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_DUBLINCORE) as $child) { $coreProperties[$child->getName()] = (string) $child; } foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_COREPROPERTIES) as $child) { $coreProperties[$child->getName()] = (string) $child; } foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_DUBLINCORETERMS) as $child) { $coreProperties[$child->getName()] = (string) $child; } } } return $coreProperties; }
/** * Search for error from request. * * If any error is found a DOMDocument is returned, this object contains a * DOMXPath object as "ebayFindingXPath" attribute. * * @param Zend_Http_Response $response * @link http://developer.ebay.com/DevZone/finding/CallRef/types/ErrorSeverity.html * @see Zend_Service_Ebay_Finding_Abstract::_initXPath() * @throws Zend_Service_Ebay_Finding_Exception When any error occurrs during request * @return DOMDocument */ protected function _parseResponse(Zend_Http_Response $response) { // error message $message = ''; // first trying, loading XML $dom = new DOMDocument(); if (!($dom = @Zend_Xml_Security::scan($response->getBody(), $dom))) { $message = 'It was not possible to load XML returned.'; } // second trying, check request status if ($response->isError()) { $message = $response->getMessage() . ' (HTTP status code #' . $response->getStatus() . ')'; } // third trying, search for error message into XML response // only first error that contains severiry=Error is read $xpath = new DOMXPath($dom); foreach (self::$_xmlNamespaces as $alias => $uri) { $xpath->registerNamespace($alias, $uri); } $ns = self::XMLNS_FINDING; $nsMs = self::XMLNS_MS; $expression = "//{$nsMs}:errorMessage[1]/{$ns}:error/{$ns}:severity[.='Error']"; $severityNode = $xpath->query($expression)->item(0); if ($severityNode) { $errorNode = $severityNode->parentNode; // ebay message $messageNode = $xpath->query("//{$ns}:message[1]", $errorNode)->item(0); if ($messageNode) { $message = 'eBay error: ' . $messageNode->nodeValue; } else { $message = 'eBay error: unknown'; } // ebay error id $errorIdNode = $xpath->query("//{$ns}:errorId[1]", $errorNode)->item(0); if ($errorIdNode) { $message .= ' (#' . $errorIdNode->nodeValue . ')'; } } // throw exception when an error was detected if (strlen($message) > 0) { /** * @see Zend_Service_Ebay_Finding_Exception */ require_once LIB_DIR . '/Zend/Service/Ebay/Finding/Exception.php'; throw new Zend_Service_Ebay_Finding_Exception($message); } // add xpath to dom document // it allows service_ebay_finding classes use this $dom->ebayFindingXPath = $xpath; return $dom; }
/** * Convert XML to SimpleXml * If user wants DomDocument they can use dom_import_simplexml * * @return SimpleXml Object */ public function readXmlString() { $string = $this->_stream->readLongUTF(); return Zend_Xml_Security::scan($string); //simplexml_load_string($string); }
/** * Converts $response body to a DOM object and checks it. * * @param Zend_Http_Response $response * @return DOMDocument * @throws Zend_Service_Technorati_Exception if response content contains an error message * @access protected */ protected function _convertResponseAndCheckContent(Zend_Http_Response $response) { $dom = new DOMDocument(); $dom = Zend_Xml_Security::scan($response->getBody(), $dom); self::_checkErrors($dom); return $dom; }
/** * Updates instance count in configuration XML. * * @param string|array $roleName The role name * @param string|array $instanceCount The instance count * @param string $configuration XML configuration represented as a string * @throws Zend_Service_WindowsAzure_Management_Exception */ protected function _updateInstanceCountInConfiguration($roleName, $instanceCount, $configuration) { // Change variables if (!is_array($roleName)) { $roleName = array($roleName); } if (!is_array($instanceCount)) { $instanceCount = array($instanceCount); } $configuration = preg_replace('/(<\\?xml[^?]+?)utf-16/i', '$1utf-8', $configuration); //$configuration = '<?xml version="1.0">' . substr($configuration, strpos($configuration, '>') + 2); $xml = Zend_Xml_Security::scan($configuration); // http://www.php.net/manual/en/simplexmlelement.xpath.php#97818 $namespaces = $xml->getDocNamespaces(); $xml->registerXPathNamespace('__empty_ns', $namespaces['']); for ($i = 0; $i < count($roleName); $i++) { $elements = $xml->xpath('//__empty_ns:Role[@name="' . $roleName[$i] . '"]/__empty_ns:Instances'); if (count($elements) == 1) { $element = $elements[0]; $element['count'] = $instanceCount[$i]; } } $configuration = $xml->asXML(); //$configuration = preg_replace('/(<\?xml[^?]+?)utf-8/i', '$1utf-16', $configuration); return $configuration; }
/** * Imports a feed represented by $string. * * @param string $string * @param string $className The class which is used as the return type * @param integer $majorProcolVersion (optional) The major protocol version * of the data model object that is to be created. * @param integer $minorProcolVersion (optional) The minor protocol version * of the data model object that is to be created. * @throws Zend_Gdata_App_Exception * @return Zend_Gdata_App_Feed */ public static function importString($string, $className = 'Zend_Gdata_App_Feed', $majorProtocolVersion = null, $minorProtocolVersion = null) { if (!class_exists($className, false)) { require_once LIB_DIR . '/Zend/Loader.php'; @Zend_Loader::loadClass($className); } // Load the feed as an XML DOMDocument object @ini_set('track_errors', 1); $doc = new DOMDocument(); $doc = @Zend_Xml_Security::scan($string, $doc); @ini_restore('track_errors'); if (!$doc) { require_once LIB_DIR . '/Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception("DOMDocument cannot parse XML: {$php_errormsg}"); } $feed = new $className(); $feed->setMajorProtocolVersion($majorProtocolVersion); $feed->setMinorProtocolVersion($minorProtocolVersion); $feed->transferFromXML($string); $feed->setHttpClient(self::getstaticHttpClient()); return $feed; }
/** * Load a response from an XML response * * Attempts to load a response from an XMLRPC response, autodetecting if it * is a fault response. * * @param string $response * @return boolean True if a valid XMLRPC response, false if a fault * response or invalid input */ public function loadXml($response) { if (!is_string($response)) { $this->_fault = new Zend_XmlRpc_Fault(650); $this->_fault->setEncoding($this->getEncoding()); return false; } try { $xml = Zend_Xml_Security::scan($response); } catch (Zend_Xml_Exception $e) { // Not valid XML $this->_fault = new Zend_XmlRpc_Fault(651); $this->_fault->setEncoding($this->getEncoding()); return false; } if (!empty($xml->fault)) { // fault response $this->_fault = new Zend_XmlRpc_Fault(); $this->_fault->setEncoding($this->getEncoding()); $this->_fault->loadXml($response); return false; } if (empty($xml->params)) { // Invalid response $this->_fault = new Zend_XmlRpc_Fault(652); $this->_fault->setEncoding($this->getEncoding()); return false; } try { if (!isset($xml->params) || !isset($xml->params->param) || !isset($xml->params->param->value)) { require_once 'Zend/XmlRpc/Value/Exception.php'; throw new Zend_XmlRpc_Value_Exception('Missing XML-RPC value in XML'); } $valueXml = $xml->params->param->value->asXML(); $value = Zend_XmlRpc_Value::getXmlRpcValue($valueXml, Zend_XmlRpc_Value::XML_STRING); } catch (Zend_XmlRpc_Value_Exception $e) { $this->_fault = new Zend_XmlRpc_Fault(653); $this->_fault->setEncoding($this->getEncoding()); return false; } $this->setReturnValue($value->getValue()); return true; }
/** * Load XML and parse into request components * * @param string $request * @return boolean True on success, false if an error occurred. */ public function loadXml($request) { if (!is_string($request)) { $this->_fault = new Zend_XmlRpc_Fault(635); $this->_fault->setEncoding($this->getEncoding()); return false; } try { $xml = Zend_Xml_Security::scan($request); } catch (Zend_Xml_Exception $e) { // Not valid XML $this->_fault = new Zend_XmlRpc_Fault(631); $this->_fault->setEncoding($this->getEncoding()); return false; } // Check for method name if (empty($xml->methodName)) { // Missing method name $this->_fault = new Zend_XmlRpc_Fault(632); $this->_fault->setEncoding($this->getEncoding()); return false; } $this->_method = (string) $xml->methodName; // Check for parameters if (!empty($xml->params)) { $types = array(); $argv = array(); foreach ($xml->params->children() as $param) { if (!isset($param->value)) { $this->_fault = new Zend_XmlRpc_Fault(633); $this->_fault->setEncoding($this->getEncoding()); return false; } try { $param = Zend_XmlRpc_Value::getXmlRpcValue($param->value, Zend_XmlRpc_Value::XML_STRING); $types[] = $param->getType(); $argv[] = $param->getValue(); } catch (Exception $e) { $this->_fault = new Zend_XmlRpc_Fault(636); $this->_fault->setEncoding($this->getEncoding()); return false; } } $this->_types = $types; $this->_params = $argv; } $this->_xml = $request; return true; }
/** * Unserialize from WDDX to PHP * * @param string $wddx * @param array $opts * @return mixed * @throws Zend_Serializer_Exception on wddx error */ public function unserialize($wddx, array $opts = array()) { $ret = wddx_deserialize($wddx); if ($ret === null) { // check if the returned NULL is valid // or based on an invalid wddx string try { $simpleXml = Zend_Xml_Security::scan($wddx); if (isset($simpleXml->data[0]->null[0])) { return null; // valid null } $errMsg = 'Can\'t unserialize wddx string'; } catch (Zend_Xml_Exception $e) { $errMsg = $e->getMessage(); } require_once 'Zend/Serializer/Exception.php'; throw new Zend_Serializer_Exception($errMsg); } return $ret; }
/** * Import a feed from a string * * Protects against XXE attack vectors. * * @param string $feed * @return string * @throws Zend_Feed_Exception on detection of an XXE vector */ protected function _importFeedFromString($feed) { if (trim($feed) == '') { require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Remote feed being imported' . ' is an Empty string or comes from an empty HTTP response'); } $doc = new DOMDocument(); $doc = Zend_Xml_Security::scan($feed, $doc); if (!$doc) { // prevent the class to generate an undefined variable notice (ZF-2590) // Build error message $error = libxml_get_last_error(); if ($error && $error->message) { $errormsg = "DOMDocument cannot parse XML: {$error->message}"; } else { $errormsg = "DOMDocument cannot parse XML"; } /** * @see Zend_Feed_Exception */ require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception($errormsg); } return $doc->saveXML($doc->documentElement); }
/** * Set request * * $request may be any of: * - DOMDocument; if so, then cast to XML * - DOMNode; if so, then grab owner document and cast to XML * - SimpleXMLElement; if so, then cast to XML * - stdClass; if so, calls __toString() and verifies XML * - string; if so, verifies XML * * @param DOMDocument|DOMNode|SimpleXMLElement|stdClass|string $request * @return Zend_Soap_Server */ protected function _setRequest($request) { if ($request instanceof DOMDocument) { $xml = $request->saveXML(); } elseif ($request instanceof DOMNode) { $xml = $request->ownerDocument->saveXML(); } elseif ($request instanceof SimpleXMLElement) { $xml = $request->asXML(); } elseif (is_object($request) || is_string($request)) { if (is_object($request)) { $xml = $request->__toString(); } else { $xml = $request; } $dom = new DOMDocument(); try { if (strlen($xml) == 0 || !($dom = Zend_Xml_Security::scan($xml, $dom))) { #require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('Invalid XML'); } } catch (Zend_Xml_Exception $e) { #require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception($e->getMessage()); } } $this->_request = $xml; return $this; }
/** * Gets the document object for this response * * @return DOMDocument the DOM Document for this response. */ public function getDocument() { try { $body = $this->_httpResponse->getBody(); } catch (Zend_Http_Exception $e) { $body = false; } if ($this->_document === null) { if ($body !== false) { // turn off libxml error handling $errors = libxml_use_internal_errors(); $this->_document = new DOMDocument(); $this->_document = Zend_Xml_Security::scan($body, $this->_document); // reset libxml error handling libxml_clear_errors(); libxml_use_internal_errors($errors); } else { $this->_document = false; } } return $this->_document; }
/** * Parses the provided XML text and generates data model classes for * each know element by turning the XML text into a DOM tree and calling * transferFromDOM($element). The first data model element with the same * name as $this->_rootElement is used and the child elements are * recursively parsed. * * @param string $xml The XML text to parse */ public function transferFromXML($xml) { if ($xml) { // Load the feed as an XML DOMDocument object @ini_set('track_errors', 1); $doc = new DOMDocument(); $doc = @Zend_Xml_Security::scan($xml, $doc); @ini_restore('track_errors'); if (!$doc) { // require_once 'Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception("DOMDocument cannot parse XML: {$php_errormsg}"); } $element = $doc->getElementsByTagName($this->_rootElement)->item(0); if (!$element) { // require_once 'Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception('No root <' . $this->_rootElement . '> element'); } $this->transferFromDOM($element); } else { // require_once 'Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception('XML passed to transferFromXML cannot be null'); } }
/** * Import an AppsForYourDomain error from XML. * * @param string $string The XML data to be imported * @return Zend_Gdata_Gapps_ServiceException Provides a fluent interface. * @throws Zend_Gdata_App_Exception */ public function importFromString($string) { if ($string) { // Check to see if an AppsForYourDomainError exists // // track_errors is temporarily enabled so that if an error // occurs while parsing the XML we can append it to an // exception by referencing $php_errormsg @ini_set('track_errors', 1); $doc = new DOMDocument(); $doc = @Zend_Xml_Security::scan($string, $doc); @ini_restore('track_errors'); if (!$doc) { // require_once 'Zend/Gdata/App/Exception.php'; // $php_errormsg is automatically generated by PHP if // an error occurs while calling loadXML(), above. throw new Zend_Gdata_App_Exception("DOMDocument cannot parse XML: {$php_errormsg}"); } // Ensure that the outermost node is an AppsForYourDomain error. // If it isn't, something has gone horribly wrong. $rootElement = $doc->getElementsByTagName($this->_rootElement)->item(0); if (!$rootElement) { // require_once 'Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception('No root <' . $this->_rootElement . '> element found, cannot parse feed.'); } foreach ($rootElement->childNodes as $errorNode) { if (!$errorNode instanceof DOMText) { $error = new Zend_Gdata_Gapps_Error(); $error->transferFromDom($errorNode); $this->addError($error); } } return $this; } else { // require_once 'Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception('XML passed to transferFromXML cannot be null'); } }
/** * Packages a Windows Azure project structure. * * @command-name Create * @command-description Packages a Windows Azure project structure. * * @command-parameter-for $path Zend_Service_Console_Command_ParameterSource_Argv|Zend_Service_Console_Command_ParameterSource_ConfigFile --Path|-p Required. The path to package. * @command-parameter-for $runDevFabric Zend_Service_Console_Command_ParameterSource_Argv|Zend_Service_Console_Command_ParameterSource_ConfigFile --RunDevFabric|-dev Required. Switch. Run and deploy to the Windows Azure development fabric. * @command-parameter-for $outputPath Zend_Service_Console_Command_ParameterSource_Argv|Zend_Service_Console_Command_ParameterSource_ConfigFile --OutputPath|-out Optional. The output path for the resulting package. */ public function createPackageCommand($path, $runDevFabric, $outputPath) { // Create output paths if ($outputPath == '') { $outputPath = realpath($path . '/../'); } $packageOut = $outputPath . '/' . basename($path) . '.cspkg'; // Find Windows Azure SDK bin folder $windowsAzureSdkFolderCandidates = array_merge(isset($_SERVER['ProgramFiles']) ? glob($_SERVER['ProgramFiles'] . '\\Windows Azure SDK\\*\\bin', GLOB_NOSORT) : array(), isset($_SERVER['ProgramFiles']) ? glob($_SERVER['ProgramFiles(x86)'] . '\\Windows Azure SDK\\*\\bin', GLOB_NOSORT) : array(), isset($_SERVER['ProgramFiles']) ? glob($_SERVER['ProgramW6432'] . '\\Windows Azure SDK\\*\\bin', GLOB_NOSORT) : array()); if (count($windowsAzureSdkFolderCandidates) == 0) { throw new Zend_Service_Console_Exception('Could not locate Windows Azure SDK for PHP.'); } $cspack = '"' . $windowsAzureSdkFolderCandidates[0] . '\\cspack.exe' . '"'; $csrun = '"' . $windowsAzureSdkFolderCandidates[0] . '\\csrun.exe' . '"'; // Open the ServiceDefinition.csdef file and check for role paths $serviceDefinitionFile = $path . '/ServiceDefinition.csdef'; if (!file_exists($serviceDefinitionFile)) { require_once LIB_DIR . '/Zend/Service/Console/Exception.php'; throw new Zend_Service_Console_Exception('Could not locate ServiceDefinition.csdef at ' . $serviceDefinitionFile . '.'); } $serviceDefinition = Zend_Xml_Security::scanFile($serviceDefinitionFile); $xmlRoles = array(); if ($serviceDefinition->WebRole) { if (count($serviceDefinition->WebRole) > 1) { $xmlRoles = array_merge($xmlRoles, $serviceDefinition->WebRole); } else { $xmlRoles = array_merge($xmlRoles, array($serviceDefinition->WebRole)); } } if ($serviceDefinition->WorkerRole) { if (count($serviceDefinition->WorkerRole) > 1) { $xmlRoles = array_merge($xmlRoles, $serviceDefinition->WorkerRole); } else { $xmlRoles = array_merge($xmlRoles, array($serviceDefinition->WorkerRole)); } } // Build '/role:' command parameter $roleArgs = array(); foreach ($xmlRoles as $xmlRole) { if ($xmlRole["name"]) { $roleArgs[] = '/role:' . $xmlRole["name"] . ';' . realpath($path . '/' . $xmlRole["name"]); } } // Build command $command = $cspack; $args = array($path . '\\ServiceDefinition.csdef', implode(' ', $roleArgs), '/out:' . $packageOut); if ($runDevFabric) { $args[] = '/copyOnly'; } passthru($command . ' ' . implode(' ', $args)); // Can we copy a configuration file? $serviceConfigurationFile = $path . '/ServiceConfiguration.cscfg'; $serviceConfigurationFileOut = $outputPath . '/ServiceConfiguration.cscfg'; if (file_exists($serviceConfigurationFile) && !file_exists($serviceConfigurationFileOut)) { copy($serviceConfigurationFile, $serviceConfigurationFileOut); } // Do we have to start the development fabric? if ($runDevFabric) { passthru($csrun . ' /devstore:start /devfabric:start'); passthru($csrun . ' /removeAll'); passthru($csrun . ' /run:"' . $packageOut . ';' . $serviceConfigurationFileOut . '" /launchBrowser'); } }
/** * Parse result from Zend_Http_Response * * @param Zend_Http_Response $response Response from HTTP call * @return object * @throws Zend_Service_WindowsAzure_Exception */ protected function _parseResponse(Zend_Http_Response $response = null) { if (is_null($response)) { require_once 'Zend/Service/WindowsAzure/Exception.php'; throw new Zend_Service_WindowsAzure_Exception('Response should not be null.'); } $xml = Zend_Xml_Security::scan($response->getBody()); if ($xml !== false) { // Fetch all namespaces $namespaces = array_merge($xml->getNamespaces(true), $xml->getDocNamespaces(true)); // Register all namespace prefixes foreach ($namespaces as $prefix => $ns) { if ($prefix != '') { $xml->registerXPathNamespace($prefix, $ns); } } } return $xml; }
/** * Find possible routing to other path or locale * * @param string $locale * @param string $path * @param string $attribute * @param string $value * @param array $temp * @throws Zend_Locale_Exception * @access private */ private static function _findRoute($locale, $path, $attribute, $value, &$temp) { // load locale file if not already in cache // needed for alias tag when referring to other locale if (empty(self::$_ldml[(string) $locale])) { $filename = dirname(__FILE__) . '/Data/' . $locale . '.xml'; if (!file_exists($filename)) { //--//require_once 'Zend/Locale/Exception.php'; throw new Zend_Locale_Exception("Missing locale file '{$filename}' for '{$locale}' locale."); } self::$_ldml[(string) $locale] = Zend_Xml_Security::scanFile($filename); } // search for 'alias' tag in the search path for redirection $search = ''; $tok = strtok($path, '/'); // parse the complete path if (!empty(self::$_ldml[(string) $locale])) { while ($tok !== false) { $search .= '/' . $tok; if (strpos($search, '[@') !== false) { while (strrpos($search, '[@') > strrpos($search, ']')) { $tok = strtok('/'); if (empty($tok)) { $search .= '/'; } $search = $search . '/' . $tok; } } $result = self::$_ldml[(string) $locale]->xpath($search . '/alias'); // alias found if (!empty($result)) { $source = $result[0]['source']; $newpath = $result[0]['path']; // new path - path //ldml is to ignore if ($newpath != '//ldml') { // other path - parse to make real path while (substr($newpath, 0, 3) == '../') { $newpath = substr($newpath, 3); $search = substr($search, 0, strrpos($search, '/')); } // truncate ../ to realpath otherwise problems with alias $path = $search . '/' . $newpath; while (($tok = strtok('/')) !== false) { $path = $path . '/' . $tok; } } // reroute to other locale if ($source != 'locale') { $locale = $source; } $temp = self::_getFile($locale, $path, $attribute, $value, $temp); return false; } $tok = strtok('/'); } } return true; }
/** * Object constructor * * @param string $fileName * @param boolean $storeContent * @throws Zend_Search_Lucene_Exception */ private function __construct($fileName, $storeContent) { if (!class_exists('ZipArchive', false)) { // require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('MS Office documents processing functionality requires Zip extension to be loaded'); } // Document data holders $sharedStrings = array(); $worksheets = array(); $documentBody = array(); $coreProperties = array(); // Open OpenXML package $package = new ZipArchive(); $package->open($fileName); // Read relations and search for officeDocument $relationsXml = $package->getFromName('_rels/.rels'); if ($relationsXml === false) { // require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Invalid archive or corrupted .xlsx file.'); } $relations = Zend_Xml_Security::scan($relationsXml); foreach ($relations->Relationship as $rel) { if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_OFFICEDOCUMENT) { // Found office document! Read relations for workbook... $workbookRelations = Zend_Xml_Security::scan($package->getFromName($this->absoluteZipPath(dirname($rel["Target"]) . "/_rels/" . basename($rel["Target"]) . ".rels"))); $workbookRelations->registerXPathNamespace("rel", Zend_Search_Lucene_Document_OpenXml::SCHEMA_RELATIONSHIP); // Read shared strings $sharedStringsPath = $workbookRelations->xpath("rel:Relationship[@Type='" . Zend_Search_Lucene_Document_Xlsx::SCHEMA_SHAREDSTRINGS . "']"); $sharedStringsPath = (string) $sharedStringsPath[0]['Target']; $xmlStrings = Zend_Xml_Security::scan($package->getFromName($this->absoluteZipPath(dirname($rel["Target"]) . "/" . $sharedStringsPath))); if (isset($xmlStrings) && isset($xmlStrings->si)) { foreach ($xmlStrings->si as $val) { if (isset($val->t)) { $sharedStrings[] = (string) $val->t; } elseif (isset($val->r)) { $sharedStrings[] = $this->_parseRichText($val); } } } // Loop relations for workbook and extract worksheets... foreach ($workbookRelations->Relationship as $workbookRelation) { if ($workbookRelation["Type"] == Zend_Search_Lucene_Document_Xlsx::SCHEMA_WORKSHEETRELATION) { $worksheets[str_replace('rId', '', (string) $workbookRelation["Id"])] = Zend_Xml_Security::scan($package->getFromName($this->absoluteZipPath(dirname($rel["Target"]) . "/" . dirname($workbookRelation["Target"]) . "/" . basename($workbookRelation["Target"])))); } } break; } } // Sort worksheets ksort($worksheets); // Extract contents from worksheets foreach ($worksheets as $sheetKey => $worksheet) { foreach ($worksheet->sheetData->row as $row) { foreach ($row->c as $c) { // Determine data type $dataType = (string) $c["t"]; switch ($dataType) { case "s": // Value is a shared string if ((string) $c->v != '') { $value = $sharedStrings[intval($c->v)]; } else { $value = ''; } break; case "b": // Value is boolean $value = (string) $c->v; if ($value == '0') { $value = false; } else { if ($value == '1') { $value = true; } else { $value = (bool) $c->v; } } break; case "inlineStr": // Value is rich text inline $value = $this->_parseRichText($c->is); break; case "e": // Value is an error message if ((string) $c->v != '') { $value = (string) $c->v; } else { $value = ''; } break; default: // Value is a string $value = (string) $c->v; // Check for numeric values if (is_numeric($value) && $dataType != 's') { if ($value == (int) $value) { $value = (int) $value; } elseif ($value == (double) $value) { $value = (double) $value; } elseif ($value == (double) $value) { $value = (double) $value; } } } $documentBody[] = $value; } } } // Read core properties $coreProperties = $this->extractMetaData($package); // Close file $package->close(); // Store filename $this->addField(Zend_Search_Lucene_Field::Text('filename', $fileName, 'UTF-8')); // Store contents if ($storeContent) { $this->addField(Zend_Search_Lucene_Field::Text('body', implode(' ', $documentBody), 'UTF-8')); } else { $this->addField(Zend_Search_Lucene_Field::UnStored('body', implode(' ', $documentBody), 'UTF-8')); } // Store meta data properties foreach ($coreProperties as $key => $value) { $this->addField(Zend_Search_Lucene_Field::Text($key, $value, 'UTF-8')); } // Store title (if not present in meta data) if (!isset($coreProperties['title'])) { $this->addField(Zend_Search_Lucene_Field::Text('title', $fileName, 'UTF-8')); } }
/** * Handles all GET requests to a web service * * @param string $path Path * @param array $parms Array of GET parameters * @param string $type Type of a request ("xml"|"json") * @return mixed decoded response from web service * @throws Zend_Service_Delicious_Exception */ public function makeRequest($path, array $parms = array(), $type = 'xml') { // if previous request was made less then 1 sec ago // wait until we can make a new request $timeDiff = microtime(true) - self::$_lastRequestTime; if ($timeDiff < 1) { usleep((1 - $timeDiff) * 1000000); } $this->_rest->getHttpClient()->setAuth($this->_authUname, $this->_authPass); switch ($type) { case 'xml': $this->_rest->setUri(self::API_URI); break; case 'json': $parms['raw'] = true; $this->_rest->setUri(self::JSON_URI); break; default: /** * @see Zend_Service_Delicious_Exception */ require_once 'Zend/Service/Delicious/Exception.php'; throw new Zend_Service_Delicious_Exception('Unknown request type'); } self::$_lastRequestTime = microtime(true); $response = $this->_rest->restGet($path, $parms); if (!$response->isSuccessful()) { /** * @see Zend_Service_Delicious_Exception */ require_once 'Zend/Service/Delicious/Exception.php'; throw new Zend_Service_Delicious_Exception("Http client reported an error: '{$response->getMessage()}'"); } $responseBody = $response->getBody(); switch ($type) { case 'xml': $dom = new DOMDocument(); if (!($dom = @Zend_Xml_Security::scan($responseBody, $dom))) { /** * @see Zend_Service_Delicious_Exception */ require_once 'Zend/Service/Delicious/Exception.php'; throw new Zend_Service_Delicious_Exception('XML Error'); } return $dom; case 'json': return Zend_Json_Decoder::decode($responseBody); } }
/** * Helper function for parsing a YouTube token response * * @param string $response The service response * @throws Zend_Gdata_App_Exception * @return array An array containing the token and URL */ public static function parseFormUploadTokenResponse($response) { // Load the feed as an XML DOMDocument object @ini_set('track_errors', 1); $doc = new DOMDocument(); $doc = @Zend_Xml_Security::scan($response, $doc); @ini_restore('track_errors'); if (!$doc) { require_once LIB_DIR . '/Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception("Zend_Gdata_YouTube::parseFormUploadTokenResponse - " . "DOMDocument cannot parse XML: {$php_errormsg}"); } $responseElement = $doc->getElementsByTagName('response')->item(0); $urlText = null; $tokenText = null; if ($responseElement != null) { $urlElement = $responseElement->getElementsByTagName('url')->item(0); $tokenElement = $responseElement->getElementsByTagName('token')->item(0); if ($urlElement && $urlElement->hasChildNodes() && $tokenElement && $tokenElement->hasChildNodes()) { $urlText = $urlElement->firstChild->nodeValue; $tokenText = $tokenElement->firstChild->nodeValue; } } if ($tokenText != null && $urlText != null) { return array('token' => $tokenText, 'url' => $urlText); } else { require_once LIB_DIR . '/Zend/Gdata/App/Exception.php'; throw new Zend_Gdata_App_Exception('Form upload token not found in response'); } }
/** * Returns Flickr photo details by for the given photo ID * * @param string $id the NSID * @return array of Zend_Service_Flickr_Image, details for the specified image * @throws Zend_Service_Exception */ public function getImageDetails($id) { static $method = 'flickr.photos.getSizes'; if (empty($id)) { /** * @see Zend_Service_Exception */ #require_once 'Zend/Service/Exception.php'; throw new Zend_Service_Exception('You must supply a photo ID'); } $options = array('api_key' => $this->apiKey, 'method' => $method, 'photo_id' => $id); $restClient = $this->getRestClient(); $restClient->getHttpClient()->resetParameters(); $response = $restClient->restGet('/services/rest/', $options); $dom = new DOMDocument(); $dom = Zend_Xml_Security::scan($response->getBody(), $dom); $xpath = new DOMXPath($dom); self::_checkErrors($dom); $retval = array(); /** * @see Zend_Service_Flickr_Image */ #require_once 'Zend/Service/Flickr/Image.php'; foreach ($xpath->query('//size') as $size) { $label = (string) $size->getAttribute('label'); $retval[$label] = new Zend_Service_Flickr_Image($size); } return $retval; }