Пример #1
0
 /**
  * retrive stored value
  * @param string $name
  * @throws Exception when not available
  * @return mixed stored value
  */
 protected static function get($name = NULL)
 {
     self::_init();
     if (is_null($name)) {
         return self::$_singleton;
     }
     $request = is_array($name) ? $name : explode(':', $name);
     $facet = array_shift($request);
     if ('config' == $facet) {
         return self::_get('root:config', self::$_configuration);
         //#TODO #1.0.0 Saf_Config is not currently setup as a singleton...
     } else {
         try {
             if (array_key_exists($facet, self::$_configuration)) {
                 return self::_get($request, self::$_configuration[$facet]);
             } else {
                 array_unshift($request, $facet);
                 return self::_get($request, self::$_configuration['root']);
             }
         } catch (Exception $e) {
             throw new Exception(self::$_unavailableExceptionMessage . (Saf_Debug::isEnabled() ? "({$name})" : ''));
         }
     }
 }
Пример #2
0
 public function go($get = array(), $post = array(), $postContentType = '')
 {
     if ('' == trim($this->_serviceUrl)) {
         throw new Exception('Must specify a url before using the Http Client.');
     }
     $curl = curl_init();
     if (is_array($get)) {
         $query = $this->buildQuery($get);
     } else {
         if ('' != $get) {
             $cleanQuery = ltrim($get, '?');
             $query = '?' . $this->urlUnsafe($cleanQuery) ? urlencode($cleanQuery) : $cleanQuery;
         } else {
             $query = '';
         }
     }
     $fullUrl = $this->_serviceUrl . $this->_actionUrl . $query;
     $options = $this->_curlConfig;
     $options[CURLOPT_URL] = $fullUrl;
     if (is_array($post) && count($post) > 0) {
         $options[CURLOPT_POSTFIELDS] = $post;
         //#TODO the path reported by this client for any sent files will be fully qualified. if the server is too stupid to handle this, a work around will be needed, possibly chdir...
     } else {
         if (!is_array($post) && '' != trim($post)) {
             $options[CURLOPT_POST] = true;
             if ($postContentType === self::UNENCODED_POST_DATA) {
                 $post = urlencode($post);
             }
             $options[CURLOPT_POSTFIELDS] = $post;
             if ('' != $postContentType) {
                 $options[CURLOPT_HTTPHEADER] = array('Content-type: ' . $postContentType);
             }
         }
     }
     if ($this->_serviceAuthenticate) {
         $username = $this->_serviceUser;
         $password = $this->_servicePassword;
         $options[CURLOPT_USERPWD] = "{$username}:{$password}";
     }
     curl_setopt_array($curl, $options);
     if ($this->_antiqueServerMode) {
         curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));
     }
     try {
         $result = curl_exec($curl);
         $resultHeadEnd = strpos($result, "\r\n\r\n");
         $resultHead = $resultHeadEnd !== false ? substr($result, 0, $resultHeadEnd + 2) : $result;
         $resultBody = $resultHeadEnd !== false ? substr($result, $resultHeadEnd + 4) : '';
         $this->_lastError = curl_error($curl);
         $resultInfo = curl_getinfo($curl);
         $this->_lastStatus = $resultInfo['http_code'];
     } catch (Exception $e) {
         $this->_lastError = $e->getMessage();
         $this->_lastStatus = 'EXCEPTION';
         $return = array('url' => $fullUrl, 'status' => 500, 'error' => $this->_lastError, 'raw' => '', 'length' => 0, 'type' => '');
         if (Saf_Debug::isEnabled()) {
             $return['stack'] = $e->getTrace();
         }
         $this->_lastStatus = $return['status'];
         return $return;
     }
     curl_close($curl);
     $return = array('url' => $fullUrl, 'status' => $resultInfo['http_code'], 'length' => $resultInfo['download_content_length'], 'type' => $resultInfo['content_type'], 'redirectCount' => $resultInfo['redirect_count'], 'sentHeaders' => array_key_exists('request_header', $resultInfo) ? $resultInfo['request_header'] : '', 'receivedHeaders' => $resultHead, 'raw' => $resultBody);
     if ($fullUrl != $resultInfo['url']) {
         $return['effectiveUrl'] = $resultInfo['url'];
     }
     if (0 != $resultInfo['ssl_verify_result']) {
         $return['ssl_error_code'] = $return['ssl_error_code'] . ' ' . self::$_sslCodes[$resultInfo['ssl_error_code']];
     }
     return $return;
 }
Пример #3
0
 public static function autodetect($mode = NULL)
 {
     $originalActivePlugin = self::$_activePlugin;
     if (self::$_supportsInternal && self::$_activePlugin) {
         $simulatedLockOn = isset($_SESSION) && array_key_exists('simulated_login_lock', $_SESSION);
         $currentSimulatedUser = array_key_exists('simulated_user', $_SESSION) ? $_SESSION['simulated_user'] : '';
         if ($simulatedLockOn) {
             $mode = self::MODE_SIMULATED;
             Saf_Kickstart::defineLoad('AUTH_SIMULATED_USER', $currentSimulatedUser);
         }
         $userToLogin = $mode == self::MODE_SIMULATED && AUTH_SIMULATED_USER ? AUTH_SIMULATED_USER : self::USER_AUTODETECT;
         if (self::_login($userToLogin) && self::$_activePlugin->auth()) {
             if (self::$_authenticated && $mode == self::MODE_SIMULATED) {
                 $_SESSION['simulated_login_lock'] = TRUE;
                 $_SESSION['simulated_user'] = AUTH_SIMULATED_USER;
             }
             return self::$_authenticated;
         }
     }
     self::init();
     $plugins = !array_key_exists('loginRealm', $_GET) || !in_array(trim($_GET['loginRealm']), self::$_loadedPlugins) ? self::$_defaultPlugins : array(trim($_GET['loginRealm']));
     foreach ($plugins as $pluginName) {
         try {
             $plugin = self::_getPlugin($pluginName);
             self::$_activePlugin = $plugin;
             if ($plugin->auth()) {
                 return self::_login($plugin->getProvidedUsername(), TRUE);
             } else {
                 self::$_activePlugin = NULL;
             }
             /*
             				$pluginClass = self::$_classMap[$pluginName];
             				$plugin = new $pluginClass();
             				self::$_activePlugin = $plugin;
             				if($plugin->auth() && self::$_authenticated) { //#TODO #2.0.0 maybe too over zealous (artifact of old methods)
             					return self::_login(self::$_userObject, TRUE);
             				} else {
             					self::$_activePlugin = NULL;
             				}
             */
         } catch (Exception $e) {
             self::$_activePlugin = NULL;
             if (Saf_Debug::isEnabled()) {
                 self::$_errorMessages[] = "Exception in auth plugin {$pluginName} : " . $e->getMessage();
             }
         }
     }
     if (count(self::$_errorMessages) > 0) {
         count(self::$_errorMessages) == 1 ? Saf_Layout::setMessage('loginError', self::$_errorMessages[0]) : Saf_Layout::setMessage('loginError', 'Multiple errors: <ul><li>' . implode('</li><li>', self::$_errorMessages) . '</li></ul>');
         if (count($plugins) > 0 && $plugins[0] == 'Local' && self::$_credentialMissmatch) {
             Saf_Layout::setMessage('passwordResetPrompt', '<a href="?cmd=resetPasswordRequest">Forgotten/Lost Password</a>?');
         }
     }
     //$usersObject = new users();
     //Rd_Registry::set('root:userInterface',$usersObject->initUser('', ''));
     //Account_Rd::init();
     if (is_null(self::$_activePlugin)) {
         self::$_activePlugin = $originalActivePlugin;
     }
     return FALSE;
 }
Пример #4
0
 public function bootstrap($type = NULL)
 {
     if ($type === TRUE || $type === FALSE) {
         $type = NULL;
         //#TODO #2.0.0 allow valid class names and bootstrapObjects
     }
     if (is_null($type) && !is_null($this->_bootstrap)) {
         return $this->_bootstrap;
     } else {
         if (!is_null($this->_bootstrap)) {
             $bootstrapClass = get_class($this->_bootstrap);
             if ("Saf_Bootstrap_{$type}" == $bootstrapClass) {
                 return $this->_bootstrap;
             }
         }
     }
     if (is_null($type)) {
         $type = defined('APPLICATION_PROTOCOL') ? APPLICATION_PROTOCOL != 'commandline' ? 'Http' : 'Commandline' : 'Http';
     }
     try {
         $bootstrapClass = "Saf_Bootstrap_{$type}";
         if (!$this->_autoLoad && !class_exists($bootstrapClass)) {
             Saf_Kickstart::autoload($bootstrapClass);
         }
         $this->_bootstrap = new $bootstrapClass($this, $this->_bootstrapConfig);
     } catch (Exception $e) {
         if (!class_exists($bootstrapClass, FALSE)) {
             //!in_array($bootstrapClass, get_declared_classes())) { //also seems to fail
             //#TODO #RAINYDAY for some reason if spl_autoload throws an exception for a class,
             //PHPseems to refuse try again, or even load the class manually...
             if ($this->_autoLoad) {
                 throw new Exception('Unable to load the requested Bootstrap' . (Saf_Debug::isEnabled() ? " ({$bootstrapClass}) " : '') . '. Autoloading is enabled, but unable to find the bootstrap.', 0, $e);
             } else {
                 throw new Exception('Unable to load the requested Bootstrap' . (Saf_Debug::isEnabled() ? " ({$bootstrapClass}) " : '') . '. Manually require this class, or enable autoloading.', 0, $e);
             }
         } else {
             throw $e;
         }
     }
     return $this->_bootstrap;
 }
Пример #5
0
    public static function debugFooter()
    {
        if (Saf_Debug::isEnabled()) {
            ?>
<!-- debug buffer -->
<?php 
            Saf_Debug::flushBuffer();
            Saf_Debug::printDebugExit();
        }
        if (Saf_Debug::isVerbose()) {
            Saf_Debug::printDebugEntry();
        }
    }
Пример #6
0
 public function parseResponse($rawResponseArray, $finalPattern = self::API_PARSE_PATTERN_NONE, $levelsDeep = 2)
 {
     if (is_null($finalPattern)) {
         $finalPattern = self::API_PARSE_PATTERN_NONE;
     }
     if (!array_key_exists('failedConnectionInfo', $rawResponseArray)) {
         if ($rawResponseArray['status'] > 200) {
             ob_start();
             print_r($rawResponseArray['failedConnectionInfo']);
             $rawFail = ob_get_contents();
             ob_end_clean();
             $prev = Saf_Debug::isEnabled() ? new Exception(htmlentities($rawFail)) : NULL;
             throw new Saf_Exception_BadGateway('The scheduling system failed. ', $rawResponseArray['status'], $prev);
         }
         $xmlResult = simplexml_load_string($rawResponseArray['raw'], 'SimpleXMLElement', 0, 'http://www.w3.org/2003/05/soap-envelope', FALSE);
         if ($xmlResult) {
             $envelope = $xmlResult->children('http://www.w3.org/2003/05/soap-envelope');
             $current = $envelope;
             for ($i = 0; $i < $levelsDeep; $i++) {
                 $current = $current->children();
             }
             $payloadXml = (string) $current;
             $data = simplexml_load_string($payloadXml);
             $parsedData = Saf_Config::arrayMap($data);
             if (is_array($parsedData) && array_key_exists('Error', $parsedData)) {
                 if (is_array($parsedData['Error']) && array_key_exists('Message', $parsedData['Error'])) {
                     $message = $parsedData['Error']['Message'];
                     $userMessage = Saf_Debug::isEnabled() ? $message : 'Server returned an error message that has been logged';
                     //#TODO #1.1.0 decide how to handle error logging
                     throw new Saf_Exception_Upstream($message, 0);
                 } else {
                     Saf_Debug::outData(array("XML Client Error Message " => $parsedData['Error']));
                     throw new Saf_Exception_Upstream('Server returned error with no message', 0);
                 }
             }
             return $parsedData ? $finalPattern == self::API_PARSE_PATTERN_NONE ? $parsedData : current($parsedData) : NULL;
         } else {
             $head = str_replace("\r\n", "\\r\\n<br/>", $rawResponseArray['receivedHeaders']);
             $body = str_replace("\r\n", "\\r\\n<br/>", $rawResponseArray['raw']);
             $libXmlErrors = libxml_get_errors();
             $xmlErrors = array();
             $errorMap = array(LIBXML_ERR_WARNING => 'LIBXML_ERR_WARNING', LIBXML_ERR_ERROR => 'LIBXML_ERR_ERROR', LIBXML_ERR_FATAL => 'LIBXML_ERR_FATAL');
             foreach ($libXmlErrors as $error) {
                 $xmlErrors[] = "{$error->level} {$error->code}" . ($error->file ? " in {$error->file}" : "") . " on line {$error->line},{$error->column}" . ($error->message ? ": {$error->message}" : '');
             }
             $libXmlErrors = 'LIB_XML_ERRORS: <br/>' . implode('<br/>', $xmlErrors) . '<br/>BAD_XML: ' . htmlentities($rawResponseArray['raw']) . '<br/>SERVER_HEADERS: ' . htmlentities($head) . '<br/>SERVER_BODY: ' . htmlentities($body);
             throw new Exception('Unable to parse response XML', 0, Saf_Debug::isEnabled() ? new Exception($libXmlErrors) : NULL);
         }
     } else {
         ob_start();
         print_r($rawResponseArray['failedConnectionInfo']);
         $rawFail = ob_get_contents();
         ob_end_clean();
         if ($rawResponseArray['status'] == 0) {
             if ($rawResponseArray['failedConnectionInfo']['connect_time'] > $this->_client->getConnectionTimeout()) {
                 throw new Saf_Exception_GatewayTimeout('Connection to the remote system timed out.');
             } else {
                 if ($rawResponseArray['failedConnectionInfo']['total_time'] > $this->_client->getTimeout()) {
                     throw new Saf_Exception_GatewayTimeout('Response from the remote system timed out.');
                 }
             }
             $prev = new Exception(htmlentities($rawFail));
             throw new Saf_Exception_BadGateway('Unable to contact the remote system.', $rawResponseArray['status'], $prev);
         }
         $rawRequest = array_key_exists('request', $rawResponseArray) ? 'RAW_REQUEST ' . (array_key_exists('request', $rawResponseArray) ? htmlentities($rawResponseArray['request']) : '') : '';
         $prev = Saf_Debug::isEnabled() ? new Exception('RAW_FAIL ' . htmlentities($rawFail) . '<br/>' . ($rawRequest ? htmlentities($rawRequest) . '<br/>' : '') . ('RAW_RESPONSE ' . htmlentities(htmlentities($rawResponseArray['raw'])))) : NULL;
         throw new Saf_Exception_BadGateway('Communication with the remote system failed.', $rawResponseArray['status'], $prev);
     }
 }
Пример #7
0
 public function fail()
 {
     if (Saf_Debug::isEnabled()) {
         Saf_Debug::out('Authentication Declined.');
     }
 }
Пример #8
0
 protected static function _translateClass($class, $term, $conditional, &$config, $depth = 0)
 {
     if ($depth > self::MAX_DEREF_DEPTH) {
         throw new Exepction('Model Reflection error: translated class too deeply.');
     }
     if (!is_object($class) && !self::_validClassName($class)) {
         throw new Exception('Model Reflection error: invalid class name' . (Saf_Debug::isEnabled() ? " {$class} {$term}." : '.'));
     }
     $nextObjectRef = strpos($term, '->');
     $nextParamRef = strpos($term, '(');
     $reflector = new ReflectionClass($class);
     $allowsNonString = array_key_exists('allowNonStrings', $config) && $config['allowNonStrings'];
     if ($nextParamRef != FALSE && ($nextObjectRef === FALSE || $nextParamRef < $nextObjectRef)) {
         $termMethod = trim(substr($term, 0, strpos($term, '(')));
         $termRest = substr($currentTerm, strpos($currentTerm, '(') + 1);
         $endParam = strpos($termRest, ')');
         // #TODO #2.0.0 this needs to scan for the matching close
         if ($endParam !== FALSE) {
             $termParam = trim(substr($term, 0, $endParam));
             $termRest = trim(substr($currentTerm, $endParam + 1));
         } else {
             $termParam = trim($termRest);
             $termRest = '';
         }
         $params = explode(',', $termParam);
         $paramConfig = array_merge($config, array('allowNonStrings' => TRUE));
         foreach ($params as $paramIndex => $param) {
             $param = trim($param);
             if (strpos($param, '`') === 0 && strrpos($param, '`') == strlen($param) - 1) {
                 $params[$paramIndex] = substr($param, 1, strlen($param) - 2);
             } else {
                 $params[$paramIndex] = self::translate($param, $paramConfig, $depth + 1);
                 //#TODO #2.0.0 flag in config to indivate returning a non-string
             }
         }
         $allowsNonString ? $reflector->getMethod($termMethod)->invokeArgs(NULL, $params) : (string) $reflector->getMethod($termMethod)->invokeArgs(NULL, $params);
     } else {
         if ($nextObjectRef !== FALSE && ($nextClassRef === FALSE || $nextObjectRef < $nextClassRef)) {
             $currentTerm = substr($term, 0, strpos($term, '->'));
             $termRest = trim(substr($term, strpos($term, '->') + 2));
             if (isset($class::${$currentTerm})) {
                 $nextObject = $class::${$currentTerm};
                 print_r(array('TBR' => 'check allows non string'));
                 die;
                 return $allowsNonString ? self::_translateObject($nextObject, $termRest, $conditional, $config, $depth + 1) : (string) self::_translateObject($nextObject, $termRest, $conditional, $config, $depth + 1);
             }
         } else {
             if ($reflector->hasMethod($term)) {
                 $method = $reflector->getMethod($term);
                 return $allowsNonString ? $method->invoke(NULL) : (string) $method->invoke(NULL);
             }
             if (FALSE) {
                 print_r(array('TBR' => 'support constants'));
                 die;
                 //#TODO #2.0.0 support constants
             } else {
                 return $allowsNonString ? $reflector->getStaticPropertyValue($term) : (string) $reflector->getStaticPropertyValue($term);
             }
         }
     }
 }
Пример #9
0
 protected static function _get($name, $currentPosition)
 {
     foreach ($name as $index => $subName) {
         if ($currentPosition && array_key_exists($subName, $currentPosition)) {
             if ($index == count($name) - 1) {
                 if (is_array($currentPosition[$subName])) {
                     $copy = array();
                     foreach ($currentPosition[$subName] as $copyIndex => $copyValue) {
                         if (!is_numeric($copyIndex)) {
                             $copy[$copyIndex] = $copyValue;
                         }
                     }
                     return count($copy) > 0 ? $copy : (array_key_exists(0, $currentPosition[$subName]) ? $currentPosition[$subName][0] : NULL);
                 } else {
                     return $currentPosition[$subName];
                 }
             } else {
                 if (array_key_exists($index + 1, $name) && '+' == $name[$index + 1]) {
                     return $currentPosition[$subName];
                 } else {
                     $currentPosition = $currentPosition[$subName];
                 }
             }
         } else {
             $debugData = Saf_Debug::isEnabled() ? ' Requested option named: ' . implode(':', $name) : '';
             throw new Exception(self::$_unavailableExceptionMessage . $debugData);
         }
     }
 }
Пример #10
0
 /**
  * Attempts to autoload a class by name, checking it against known class
  * name prefixes for libraries (using an optional user provided path 
  * resolution method), or for other files using the Zend Framework naming 
  * conventions in one or more registered paths.
  * Autoloading come preconfigured to look in the APPLICATION_PATH/models/
  * (matching any class), and LIBRARY_PATH/Saf/ (matching prefix 'Saf_') paths.
  * Libraries alway take precidence over other matching rules.
  * The first existing match file will be included.
  * If a $specialLoader is specified, only that loader is searched.
  * Special loaders are only searched when specified.
  * @param string $className name of class to be found/loaded
  * @param string $specialLoader limits the search to a specific special loader
  *
  */
 public static function autoload($className, $specialLoader = '')
 {
     if (class_exists($className, FALSE)) {
         return TRUE;
     }
     if (!self::$_autoloadingInstalled && class_exists('Zend_Loader_Autoloader', FALSE)) {
         $zendAutoloader = Zend_Loader_Autoloader::getInstance();
         $currentSetting = $zendAutoloader->suppressNotFoundWarnings();
         $zendAutoloader->suppressNotFoundWarnings(TRUE);
         $zendResult = Zend_Loader_Autoloader::autoload($className);
         $zendAutoloader->suppressNotFoundWarnings($currentSetting);
         return $zendResult;
     }
     if (!self::$_initialized) {
         self::initializeAutoloader(FALSE);
     }
     if ($specialLoader) {
         if (!is_array($specialLoader)) {
             $specialLoader = array();
         }
         foreach ($specialLoader as $loader) {
             if (array_key_exists($specialLoader, self::$_specialAutoloaders)) {
                 foreach (self::$_specialAutoloaders[$specialLoader] as $callableList) {
                     foreach ($callableList as $callableSet) {
                         if (is_array($callableSet)) {
                             $callableInstance = $callableSet[0];
                             $callableReflector = $callableSet[1];
                         } else {
                             $callableInstance = NULL;
                             $callableReflector = $callableSet;
                         }
                         $classFile = $callableReflector->invoke($callableInstance, $className);
                         if ($classFile && self::fileExistsInPath($classFile)) {
                             require_once $classFile;
                             if (!class_exists($className, FALSE)) {
                                 throw new Exception('Failed to special autoload class' . (class_exists('Saf_Debug', FALSE) && Saf_Debug::isEnabled() ? " {$className}" : '') . '. Found class file, but no definition inside.');
                             }
                             return TRUE;
                         }
                     }
                 }
             } else {
                 throw new Exception('Failed to special autoload class' . (class_exists('Saf_Debug', FALSE) && Saf_Debug::isEnabled() ? " {$className}" : '') . '. invalid loader specified.');
             }
         }
         return FALSE;
     }
     foreach (self::$_libraries as $classPrefix => $callableList) {
         if (strpos($className, $classPrefix) === 0) {
             foreach ($callableList as $callableSet) {
                 if (is_array($callableSet)) {
                     $callableInstance = $callableSet[0];
                     $callableReflector = $callableSet[1];
                 } else {
                     $callableInstance = NULL;
                     $callableReflector = $callableSet;
                 }
                 // 					if (!is_object($callableReflector)) {
                 // 						print_r(array($className,$classPrefix,$callableList));
                 // 						throw new Exception('huh');
                 // 					}
                 $classFile = $callableReflector->invoke($callableInstance, $className);
                 if ($classFile && self::fileExistsInPath($classFile)) {
                     require_once $classFile;
                     if (!class_exists($className, FALSE)) {
                         throw new Exception('Failed to autoload class' . (class_exists('Saf_Debug', FALSE) && Saf_Debug::isEnabled() ? " {$className}" : '') . '. Found a library, but no definition inside.');
                     }
                     return TRUE;
                 }
             }
         }
     }
     foreach (self::$_autoloaders as $classPrefix => $pathList) {
         if ('' == $classPrefix || strpos($className, $classPrefix) === 0) {
             foreach ($pathList as $path) {
                 $classFile = self::resolveClassPath($className, $path);
                 if ($classFile && self::fileExistsInPath($classFile)) {
                     require_once $classFile;
                     if (!class_exists($className, FALSE)) {
                         throw new Exception('Failed to autoload class' . (class_exists('Saf_Debug', FALSE) && Saf_Debug::isEnabled() ? " {$className}" : '') . '. Found a file, but no definition inside.');
                     }
                     return TRUE;
                 }
             }
         }
     }
     if (!class_exists($className, FALSE)) {
         throw new Exception('Failed resolving file to autoload class' . (class_exists('Saf_Debug', FALSE) && Saf_Debug::isEnabled() ? " {$className}" : '') . '.');
     }
     return TRUE;
 }
Пример #11
0
 public function go($get = array(), $post = array(), $postContentType = '')
 {
     if ('' == trim($this->_url)) {
         throw new Exception('Must specify a url before using the Http Client.');
     }
     $persist = $this->_connection;
     if (!$persist) {
         $this->pickup();
     }
     if (is_array($get)) {
         $query = $this->buildQuery($get);
     } else {
         if (!is_null($get) && '' != trim($get)) {
             $cleanQuery = ltrim($get, '?');
             $query = '?' . Saf_UrlRewrite::makeUrlSafe($cleanQuery);
         } else {
             $query = '';
         }
     }
     $headers = array_merge($this->_headers, $this->_tempHeaders);
     $this->clearTempHeaders();
     $fullUrl = $this->_url . $this->_actionUrl . $query;
     $options = array();
     $options[CURLOPT_URL] = $fullUrl;
     $debugPost = '';
     if (is_array($post) && count($post) > 0) {
         $debugPost = json_encode($debugPost, JSON_FORCE_OBJECT);
         $options[CURLOPT_POSTFIELDS] = $post;
         //#TODO #2.0.0 the path reported by this client for any sent files will be fully qualified. if the server is too stupid to handle this, a work around will be needed, possibly chdir...
     } else {
         if (!is_array($post) && '' != trim($post)) {
             $debugPost = $post;
             $options[CURLOPT_POST] = TRUE;
             if ($postContentType === self::UNENCODED_POST_DATA) {
                 $post = urlencode($post);
             }
             $options[CURLOPT_POSTFIELDS] = $post;
             if ('' != $postContentType && $postContentType !== self::UNENCODED_POST_DATA) {
                 $headers[] = 'Content-type: ' . $postContentType;
             }
         } else {
             #TODO #2.0.0 make sure switching back to GET mode when persisting works properly
             if (array_key_exists(CURLOPT_POST, $options)) {
                 $options[CURLOPT_POST] = FALSE;
                 //or unset?
             }
         }
     }
     if ($this->_authenticate) {
         $username = $this->_user;
         $password = $this->_password;
         $options[CURLOPT_USERPWD] = "{$username}:{$password}";
     }
     $options[CURLOPT_HTTPHEADER] = $headers;
     if ($this->_antiqueServerMode) {
         $options[CURLOPT_HTTPHEADER] = array('Expect:');
     }
     curl_setopt_array($this->_connection, $options);
     try {
         $result = curl_exec($this->_connection);
         $resultHead = '';
         $resultRest = $result;
         $resultHeadEnd = strpos($resultRest, "\r\n\r\n");
         //			$count = 0;
         //			$head = str_replace("\r\n", "\\r\\n<br/>", $resultHead);
         //			$body = str_replace("\r\n", "\\r\\n<br/>", $resultRest);
         while ($resultHeadEnd !== FALSE) {
             //				$count++;
             $resultHead .= substr($resultRest, 0, $resultHeadEnd + 4);
             $resultRest = substr($resultRest, $resultHeadEnd + 4);
             $resultHeadEnd = strpos($resultRest, "\r\n\r\n");
             // 				if (
             // 					strpos($resultRest, 'HTTP') === 0
             // 					|| strpos($resultRest, '\r\n\r\n') !== FALSE
             // 				) {
             // 				} else {
             // 					$resultHeadEnd = FALSE;
             // 				}
             // 				$resultHeadEnd =
             // 					(
             // 						strpos($resultRest,'HTTP') !== 0
             // 					//	&& strpos($resultRest,'Content-Length:') !== 0
             // 					) ? FALSE
             // 					: strpos($resultRest,"\r\n\r\n");
             // 				if (strpos($resultRest,'\r\n') === 0) {
             // 					$resultHead .= (
             // 							substr($result, 0, 2)
             // 					);
             // 					$resultRest = substr($result, 2);
             // 					$resultHeadEnd +=2;
             // 				}
             $head = str_replace("\r\n", "\\r\\n<br/>", $resultHead);
             $body = str_replace("\r\n", "\\r\\n<br/>", $resultRest);
             //Saf_Debug::outData(array($resultHeadEnd,$head,$body));
         }
         //			if ($count > 2) {
         //				die('server sent too many continues'); //#TODO #1.1.0
         //			}
         if ($this->_debugEnabled) {
             Saf_Debug::outData(array($fullUrl, htmlentities($debugPost), htmlentities($head), htmlentities($body)));
         }
         $resultBody = $resultRest;
         $this->_lastError = curl_error($this->_connection);
         $resultInfo = curl_getinfo($this->_connection);
         $this->_lastResult = array('response' => $result, 'status' => $resultInfo, 'error' => $this->_lastError);
         $this->_lastStatus = $resultInfo['http_code'];
     } catch (Exception $e) {
         $this->_lastError = $e->getMessage();
         $this->_lastStatus = 'EXCEPTION';
         $return = array('url' => $fullUrl, 'status' => 500, 'error' => $this->_lastError, 'raw' => '', 'length' => 0, 'type' => '');
         if (Saf_Debug::isEnabled()) {
             $return['stack'] = $e->getTrace();
         }
         $this->_lastStatus = $return['status'];
         return $return;
     }
     if (!$persist) {
         $this->putdown();
     }
     $status = (int) $resultInfo['http_code'];
     $return = array('url' => $fullUrl, 'status' => $status, 'status_label' => array_key_exists($status, self::$_httpCodes) ? self::$_httpCodes[$status] : 'UNKNOWN', 'length' => $resultInfo['download_content_length'], 'type' => $resultInfo['content_type'], 'redirectCount' => $resultInfo['redirect_count'], 'sentHeaders' => array_key_exists('request_header', $resultInfo) ? $resultInfo['request_header'] : '', 'receivedHeaders' => $resultHead, 'raw' => $resultBody);
     if ($resultInfo['size_upload'] < $resultInfo['upload_content_length']) {
         $return['up'] = floor($resultInfo['size_upload'] / $resultInfo['upload_content_length'] * 100);
     }
     if ($resultInfo['size_download'] < $resultInfo['download_content_length']) {
         $return['down'] = floor($resultInfo['size_download'] / $resultInfo['download_content_length'] * 100);
     }
     if ($fullUrl != $resultInfo['url']) {
         $return['effectiveUrl'] = $resultInfo['url'];
     }
     if (array_key_exists('ssl_verify_result', $resultInfo) && 0 != $resultInfo['ssl_verify_result']) {
         $return['ssl_error_code'] = $resultInfo['ssl_verify_result'] . (array_key_exists($resultInfo['ssl_verify_result'], self::$_sslCodes) ? ' ' . self::$_sslCodes[$resultInfo['ssl_verify_result']] : ' unknown SSL connection error');
     }
     if ($status < 200 || $status >= 300) {
         $return['failedConnectionInfo'] = curl_getinfo($this->_connection);
         if ($post && Saf_Debug::isEnabled()) {
             if (is_array($post) && count($post) > 0) {
                 ob_start();
                 print_r($post);
                 $rawRequest = ob_get_contents();
                 ob_end_clean();
                 $return['request'] = $rawRequest;
             } else {
                 $return['request'] = $post;
             }
         }
     }
     return $return;
 }
Пример #12
0
 public static function parse($xmlObject, $section = '', $existingConfigs = array())
 {
     //#TODO #2.0.0 do we need to pass existing for some reason? i.e. reflective/nesting issues?
     $newConfig = array();
     $extensionMap = array();
     $sourceMap = array();
     if (!is_object($xmlObject)) {
         throw new Exception(self::$_corruptedExceptionMessage);
     }
     $rootName = $xmlObject->getName();
     if ('' == $section || $section == $rootName) {
         return self::_xmlToArray($xmlObject);
     } else {
         $childNodes = $xmlObject->children();
         foreach ($childNodes as $child) {
             $childName = $child->getName();
             if ($childName == $section) {
                 if (array_key_exists($childName, $sourceMap)) {
                     $debugData = Saf_Debug::isEnabled() ? " Section name: {$childName}." : '';
                     throw new Exception(self::$_duplicateSectionExceptionMessage . $debugData);
                 }
             }
             $attributes = $child->attributes();
             $extends = '';
             $sourceMap[$childName] = array();
             foreach ($attributes as $attributeName => $attributeNode) {
                 $attributeValue = (string) $attributeNode;
                 if ('src' == $attributeName) {
                     $sourceMap[$childName][] = $attributeValue;
                     //#TODO #2.0.0 check and throw a _warning_ if the file does not exist, even if not needed for this source
                 }
                 if ('extends' == $attributeName) {
                     $extends = $attributeValue;
                 }
             }
             $extensionMap[$childName] = $extends;
             $sourceMap[$childName][] = $child;
         }
         if (!array_key_exists($childName, $sourceMap)) {
             $debugData = Saf_Debug::isEnabled() ? " Section name: {$section}." : '';
             throw new Exception(self::$_missingSectionExceptionMessage . $debugData);
         }
         $extending = self::_generateRequirements($section, $extensionMap);
         foreach ($sourceMap as $targetSection => $sourceList) {
             if ($targetSection == $section || in_array($targetSection, $extending)) {
                 foreach ($sourceList as $currentIndex => $currentSource) {
                     if (is_string($currentSource)) {
                         //#TODO #2.0.0 load external XML
                     }
                     $sourceMap[$targetSection][$currentIndex] = self::_xmlToArray($currentSource, $sourceMap, $targetSection);
                 }
                 $sourceMap[$targetSection] = count($sourceMap[$targetSection]) > 1 ? self::merge($sourceMap[$targetSection][0], $sourceMap[$targetSection][1]) : $sourceMap[$targetSection][0];
             }
         }
         $return = array_key_exists($section, $sourceMap) && !is_null($sourceMap[$section]) ? $sourceMap[$section] : array();
         $inherit = array_shift($extending);
         while ($inherit) {
             $return = self::merge($sourceMap[$inherit], $return);
             $inherit = array_shift($extending);
         }
         return $return;
     }
     //#TODO #2.0.0 iterate through $source to populate $newConfig
 }