public function open($filePath, $section = '', $merge = self::LOAD_MERGE) { self::assertFile($filePath); $this->_loadedSources[] = array($filePath, $section, $merge); $newXml = simplexml_load_file($filePath); if (!$newXml) { Saf_Debug::outData(array('failedXMLConfigLoad' => libxml_get_errors())); //#TODO #1.1.0 utlilitize this see Ems_Api->parseResponse //if(!Saf_Debug::isEnabled()){ //#TODO #1.1.0 not for production... //Saf_Debug::flushBuffer(TRUE); //} } $newConfiguration = self::parse($newXml, $section); if (!$newConfiguration) { $debugData = Saf_Debug::isEnabled() ? " Loading file: {$filePath}." : ''; throw new Exception(self::$_corruptedExceptionMessage . $debugData); } if ($merge == self::LOAD_QUARANTINED) { return new Saf_Config($newConfiguration); } else { if (is_null($this->_configuration) || $merge == self::LOAD_REPLACE) { $this->_configuration = $newConfiguration; } else { $this->_configuration = self::merge($this->_configuration, $newConfiguration); } } return $this; }
public function count($result = NULL) { if (is_null($result)) { $result = $this->_lastResult; } if ($this->_debugMode) { Saf_Debug::outData(array('count', $result, $result->rowCount())); } return $result ? $result->rowCount() : NULL; }
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); } }
/** * Attempt to bind after connecting. If no login and password are supplied, * the most recently provided login and password are used. Binding is normally * handled by the adapter, but this method makes it possible to manually * bind. Functions that require a binding will only attempt to bind if there * is not already an existing binding. */ public function bind($login = '', $password = '') { if (!$this->_connected) { $this->_error[] = "Attempting to bind when not connected"; return false; } if ($login != '') { $this->_remoteLogin = $login; $this->remotePassword = $password; } if ($this->_remoteLogin != '' && ($this->_connectedSecurely || $this->_allowInsecureAuth)) { if ($this->_allowInsecureAuth) { $this->_error[] = "Sent login and password over clear text because it was explicitly requested. "; } $this->_bound = ldap_bind($this->_connection, $this->_remoteLogin, $this->_remotePassword); Saf_Debug::outData(array($this->_remoteLogin, $this->_remotePassword, $this->_context, $this->_bound)); } else { if ($this->_remoteLogin != '') { $this->_error[] = 'Attempted to login with authentication via ' . $this->_remoteProtocol . $this->_remoteAddress . $this->_remotePort . "with login {$this->_remoteLogin} but was not connected securely so " . 'anonymous access was used instead. '; } $this->_bound = ldap_bind($this->_connection); } if ($this->_bound) { //#TODO #2.0.0 it seems as if sometimes AD will return true for bind even when it fails. Not sure how to detect this pre-search return true; } $errorMessage = ''; ldap_get_option($this->_connection, LDAP_OPT_ERROR_STRING, $errorMessage); $this->_error[] = "Unable to bind to LDAP {$this->_remoteProtocol}{$this->_remoteAddress}{$this->_remotePort} : " . $errorMessage . ", " . ldap_error($this->_connection); $this->close(); return false; }
public function routeShutdown(Zend_Controller_Request_Abstract $request) { $stack = explode('/', $request->getPathInfo()); $newStack = array(); $preRouter = array(); if ('' == $stack[count($stack) - 1]) { array_pop($stack); } if (count($stack) && '' == $stack[0]) { array_shift($stack); } $pathParts = explode('/', ROUTER_PATH); if ('' == $pathParts[count($pathParts) - 1]) { array_pop($pathParts); } if (count($pathParts) && '' == $pathParts[0]) { array_shift($pathParts); } if ($pathParts) { if (array_key_exists(0, $pathParts)) { $request->setModuleName($pathParts[0]); } if (array_key_exists(1, $pathParts)) { $request->setControllerName($pathParts[1]); } if (array_key_exists(2, $pathParts)) { $request->setActionName($pathParts[2]); } if (array_key_exists(3, $pathParts)) { $newStack = array_merge(array_splice($pathParts, 3), $stack); } } else { $routerFound = FALSE; $moduleFound = 'default' == $request->getModuleName(); $controllerFound = $moduleFound && 'index' == $request->getControllerName(); $actionFound = $controllerFound && 'index' == $request->getActionName(); $router = ROUTER_NAME; $controllerReflector = NULL; foreach ($stack as $part) { //Saf_Debug::outData(array($part)); $routerFound = $routerFound || TRUE; //#TODO #2.0.0 is this still needed for non Zend Routing? if (!$moduleFound && $request->getModuleName() == $part) { $moduleFound = TRUE; array_shift($stack); } else { if (!$controllerFound && $request->getControllerName() == $part) { $controllerFound = TRUE; //#TODO #9.9.9 handle bug with routing with path #¯\_(ツ)_/¯ $controllerName = ucfirst($request->getControllerName()); $front = Zend_Controller_Front::getInstance(); $paths = $front->getControllerDirectory(); $controllerClass = "{$controllerName}Controller"; foreach ($paths as $path) { if (file_exists("{$path}/{$controllerClass}.php")) { include_once "{$path}/{$controllerClass}.php"; } } $controllerReflector = new ReflectionClass($controllerClass); //#TODO #2.0.0 handle the case where class is non-existant (i.e. module/[index/index/]resourcestack) array_shift($stack); continue; } else { if (!$actionFound && $request->getActionName() == $part) { $actionFound = TRUE; $actionName = ucfirst($request->getActionName()); $controllerHasAction = $controllerReflector && $controllerReflector->hasMethod("{$actionName}Action"); if ($controllerHasAction) { array_shift($stack); } else { $request->setActionName(''); } continue; } } } if ($routerFound && $moduleFound && $controllerFound && $actionFound) { //Saf_Debug::outData(array('stacking...', $routerFound, $moduleFound, $controllerFound, $request->getActionName(), $actionFound, $part)); $newStack[] = array_shift($stack); } else { //Saf_Debug::outData(array('prerouting...', $routerFound, $moduleFound, $controllerFound, $request->getActionName(), $actionFound, $part)); $preRouter[] = array_shift($stack); } } //Saf_Debug::outData(array('preparts',$pathParts,$newStack)); if (count($stack)) { $newStack = array_merge($newStack, $stack); } //Saf_Debug::outData(array('postparts',$newStack)); if ($preRouter && !$newStack) { $newStack = $preRouter; $preRouter = array(); } } if ($preRouter) { Saf_Debug::outData(array('preRouter' => $preRouter)); } $request->setParam('resourceStack', $newStack); $stackString = implode('/', $newStack); $module = $request->getModuleName(); $controller = $request->getControllerName(); $action = $request->getActionName(); Saf_Debug::out("Resolved to path: {$module} {$controller} {$action} {$stackString}", 'NOTICE'); }
public static function saveHash($file, $uname, $value) { if (is_null($value)) { Saf_Debug::outData(array("saving null value to hash, {$file}:{$uname}")); } if (!array_key_exists($file, self::$_hashMemory)) { self::$_hashMemory[$file] = array(); } self::$_hashMemory[$file][$uname] = $value; if (strpos($file, 'hash/') === 0) { try { $fileUnhash = substr($file, 5); self::_initHash($fileUnhash); } catch (Exception $e) { Saf_Debug::out("unable to prepare hash for {$file} : {$uname}. " . $e->getMessage()); } } $path = self::$_path . '/' . $file; $mode = file_exists($path) ? 'r+' : 'w'; //#NOTE could use c+, but $mode is overloaded $pointer = fopen($path, $mode); $fileLock = flock($pointer, LOCK_EX); if (!$fileLock) { Saf_Debug::out("write blocking {$file}"); $fileLock = flock($pointer, LOCK_EX | LOCK_NB); } if ($fileLock) { $hashValue = 'r+' == $mode ? json_decode(fread($pointer, filesize($path)), TRUE) : array(); if (is_null($hashValue)) { Saf_Debug::out("cache invalid, resetting {$file}"); $hashValue = array(); } ftruncate($pointer, 0); rewind($pointer); $time = time(); $hashValue[$uname] = array('stamp' => $time, 'payload' => $value); fwrite($pointer, json_encode($hashValue, JSON_FORCE_OBJECT)); //Saf_Debug::out("cached {$file} : {$uname}"); } else { Saf_Debug::out("unable to save {$file} : {$uname}"); } flock($pointer, LOCK_UN); fclose($pointer); }
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; }