コード例 #1
0
ファイル: Acl.php プロジェクト: jthurteau/saf
 public function who($module, $controller = 'index', $action = 'index', $stack = array())
 {
     if ($this->isInList($this->_whiteList, $module, $controller, $action, $stack)) {
         $stackPart = implode('/', $stack);
         if ($stackPart) {
             $stackPart = "/{$stackPart}";
         }
         Saf_Debug::out("White-listed access for {$module}/{$controller}/{$action}{$stackPart}");
         return self::ACL_WHO_ANYONE;
     }
     if ($this->isInList($this->_blackList, $module, $controller, $action, $stack)) {
         $stackPart = implode('/', $stack);
         if ($stackPart) {
             $stackPart = "/{$stackPart}";
         }
         Saf_Debug::out("Black-listed access for {$module}/{$controller}/{$action}{$stackPart}");
         return self::ACL_WHO_NOONE;
     }
     if ($this->_authenticationEnabled && 'default' == $module && ('login' == $controller || 'index' == $controller && 'login' == $action)) {
         return self::ACL_WHO_ANYONE;
     }
     if ($this->_authenticationEnabled && 'default' == $module && ('logout' == $controller || 'index' == $controller && 'logout' == $action)) {
         return self::ACL_WHO_ANYUSER;
     }
     return self::ACL_WHO_UNKNOWN;
 }
コード例 #2
0
ファイル: RouteRules.php プロジェクト: jthurteau/saf
 public function routeShutdown(Zend_Controller_Request_Abstract $request)
 {
     try {
         $this->_statusRules($request->getModuleName(), $request->getControllerName(), $request->getActionName(), $request->getParam('resourceStack'));
         $this->_aclRules($request->getModuleName(), $request->getControllerName(), $request->getActionName(), $request->getParam('resourceStack'), $request->getQuery());
         $this->_workflowRules($request->getModuleName(), $request->getControllerName(), $request->getActionName(), $request->getParam('resourceStack'));
     } catch (Saf_Controller_Front_Plugin_RouteRules_Exception $e) {
         Saf_Debug::out('Enforcing Routing Rule: ' . $e->getMessage());
         $request->setModuleName($e->getModuleName());
         $request->setControllerName($e->getControllerName());
         $request->setActionName($e->getActionName());
         $request->setParam('resourceStack', $e->getResourceStack());
     }
 }
コード例 #3
0
ファイル: RestDetection.php プロジェクト: jthurteau/saf
 public function parseAccept($string, $table = self::ACCEPT_FORMAT)
 {
     $default = self::$_acceptTables[$table][0];
     if ('' == trim($string)) {
         Saf_Debug::out("No accept format specified, using default ({$default}).", 'NOTICE');
         return $default;
     }
     $array = explode(',', $string);
     foreach ($array as $option) {
         $format = strpos($option, ';') !== FALSE ? substr($option, 0, strpos($option, ';')) : $option;
         if (array_key_exists($format, self::$_acceptTables[$table])) {
             $notice = "Accept format ({$format}), using " . self::$_acceptTables[$table][$format] . '.';
             Saf_Debug::out($notice, 'NOTICE');
             return self::$_acceptTables[$table][$format];
         }
     }
     Saf_Debug::out("Unrecognized accept format ({$format}), using default ({$default}).", 'NOTICE');
     return $default;
 }
コード例 #4
0
ファイル: Registry.php プロジェクト: jthurteau/saf
 /**
  * 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})" : ''));
         }
     }
 }
コード例 #5
0
ファイル: Application.php プロジェクト: jthurteau/saf
 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;
 }
コード例 #6
0
ファイル: Shib.php プロジェクト: jthurteau/saf
 public function fail()
 {
     if (Saf_Debug::isEnabled()) {
         Saf_Debug::out('Authentication Declined.');
     }
 }
コード例 #7
0
ファイル: Xml.php プロジェクト: jthurteau/saf
 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
 }
コード例 #8
0
ファイル: Layout.php プロジェクト: jthurteau/saf
    public static function debugFooter()
    {
        if (Saf_Debug::isEnabled()) {
            ?>
<!-- debug buffer -->
<?php 
            Saf_Debug::flushBuffer();
            Saf_Debug::printDebugExit();
        }
        if (Saf_Debug::isVerbose()) {
            Saf_Debug::printDebugEntry();
        }
    }
コード例 #9
0
ファイル: RouteResourceStack.php プロジェクト: jthurteau/saf
 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');
 }
コード例 #10
0
ファイル: Reflector.php プロジェクト: jthurteau/saf
 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);
             }
         }
     }
 }
コード例 #11
0
ファイル: Bootstrap.php プロジェクト: jthurteau/saf
 public function postSessionStart()
 {
     Saf_Debug::sessionReadyListner();
     return $this;
 }
コード例 #12
0
ファイル: Config.php プロジェクト: jthurteau/saf
 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);
         }
     }
 }
コード例 #13
0
ファイル: Kickstart.php プロジェクト: jthurteau/saf
 /**
  * Outputs in the case of complete and total failure during the
  * application bootstrap process.
  * @param Exception $e
  * @param string $caughtLevel
  * @param string $additionalError
  */
 public static function exceptionDisplay($e, $caughtLevel = 'BOOTSTRAP', $additionalError = '')
 {
     $rootUrl = defined('APPLICATION_BASE_URL') ? APPLICATION_BASE_URL : '';
     $title = 'Configuration Error';
     if (is_null(self::$_exceptionView)) {
         self::$_exceptionView = APPLICATION_PATH . '/views/scripts/error/error.php';
     }
     include self::$_exceptionView;
     if (class_exists('Saf_Debug', FALSE)) {
         Saf_Debug::dieSafe();
     }
 }
コード例 #14
0
ファイル: Cache.php プロジェクト: jthurteau/saf
 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);
 }
コード例 #15
0
ファイル: Http.php プロジェクト: jthurteau/saf
 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;
 }
コード例 #16
0
ファイル: Array.php プロジェクト: jthurteau/saf
 /**
  * Searches for string $key in array $array and returns true only if
  * it the key exists and the value it contains is an integer, boolean, or
  * non-empty. Optional third parameter can allow one or more falsy values:
  * NULL : Saf_Array::TYPE_NULL, 
  * empty array : Saf_Array::TYPE_ARRAY, 
  * empty string : Saf_Array::TYPE_STRING
  * 
  * $key may be an array, this method will return true if all are present.
  * 
  * @param string $key string array key to search for
  * @param array $array to be searched
  * @param int $allowedBlankTypes bitwise integer of blank types that are allowed
  * @return bool key exists and value is not blank
  */
 public static function keyExistsAndNotBlank($key, $array, $allowedBlankTypes = 0)
 {
     if (!is_array($array)) {
         Saf_Debug::out('Saf_Array::keyExistsAndNotBlank got a non-array operand.');
         return false;
     }
     if (!is_array($key)) {
         $key = array($key);
     }
     foreach ($key as $arrayKey) {
         if (!array_key_exists($arrayKey, $array) || !($allowedBlankTypes & self::TYPE_NULL || !is_null($array[$arrayKey])) || !(is_object($array[$arrayKey]) || is_array($array[$arrayKey]) && ($allowedBlankTypes & self::TYPE_ARRAY || count($array[$arrayKey]) > 0) || is_string($array[$arrayKey]) && ($allowedBlankTypes & self::TYPE_STRING || '' != trim($array[$arrayKey])) || is_bool($array[$arrayKey]) || is_numeric($array[$arrayKey]) && !is_string($array[$arrayKey]) || is_resource($array[$arrayKey]))) {
             return false;
         }
     }
     return true;
 }
コード例 #17
0
ファイル: Connection.php プロジェクト: jthurteau/saf
 public function addError($error)
 {
     $this->_errorMessage[] = $error;
     if ($this->_debugMode) {
         Saf_Debug::out($error);
     }
 }
コード例 #18
0
ファイル: Ldap.php プロジェクト: jthurteau/saf
 /**
  * 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;
 }
コード例 #19
0
ファイル: Auth.php プロジェクト: jthurteau/saf
 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;
 }
コード例 #20
0
ファイル: Status.php プロジェクト: jthurteau/saf
 public static function set($status)
 {
     switch ($status) {
         case 200:
         case '200':
             self::_header('200 OK');
             break;
         case 201:
         case '201':
             self::_header('201 Created');
             break;
         case 202:
         case '202':
             self::_header('202 Accepted');
             break;
         case 203:
         case '203':
             self::_header('203 Non-Authoritative Information');
             break;
         case 204:
         case '204':
             self::_header('204 No Content');
             break;
         case 205:
         case '205':
             self::_header('205 Reset Content');
             break;
         case 300:
         case '300':
             self::_header('300 Multiple Choices');
             break;
         case 301:
         case '301':
             self::_header('301 Moved Permanently');
             //don't keep using the request-uri
             break;
         case 302:
         case '302':
             self::_header('302 Found');
             //temporary, keep using the request-uri
             break;
         case 303:
         case '303':
             self::_header('303 See Other');
             //context specific, keep using the request-uri POST safe redirect option
             //#TODO #2.0.0 use this for redirect exception, with 302 as the non-default antique browser option
             break;
         case 304:
         case '304':
             self::_header('304 Not Modified');
             break;
         case 307:
         case '307':
             self::_header('307 Temporary Redirect');
             //temporary, keep using the request-uri stricter alternative to 302
             //which may incorrectly auto-redirect
             break;
         case 400:
         case '400':
             self::_header('400 Bad Request');
             break;
         case 401:
         case '401':
             self::_header('401 Unauthorized');
             break;
         case 403:
         case '403':
             self::_header('403 Forbidden');
             break;
         case 404:
         case '404':
             self::_header('404 Not Found');
             break;
         case 405:
         case '405':
             self::_header('405 Method Not Allowed');
             break;
         case 406:
         case '406':
             self::_header('406 Not Acceptable');
             //cannot formulate a response that would conform to the client's
             //expectations.
             break;
         case 408:
         case '408':
             self::_header('408 Request Timeout');
             break;
         case 409:
         case '409':
             self::_header('409 Conflict');
             break;
         case 410:
         case '410':
             self::_header('410 Gone');
             break;
         case 412:
         case '412':
             self::header('412 Precondition Failed');
             break;
         case 413:
         case '413':
             self::_header('413 Request Entity Too Large');
             break;
         case 415:
         case '415':
             self::_header('415 Unsupported Media Type');
             break;
         case 416:
         case '416':
             self::_header('416 Expectation Failed');
             break;
         case 500:
         case '500':
             self::_header('500 Internal Server Error');
             break;
         case 501:
         case '501':
             self::_header('501 Not Implemented');
             break;
         case 502:
         case '502':
             self::_header('502 Bad Gateway');
             break;
         case 503:
         case '503':
             self::_header('503 Service Unavailable');
             break;
         case 504:
         case '504':
             self::_header('504 Gateway Timeout');
             break;
         default:
             if (class_exists('Saf_Debug')) {
                 Saf_Debug::out('Unrecognized HTTP Status Set Request: ' . $status);
             }
             return FALSE;
     }
     return TRUE;
 }
コード例 #21
0
ファイル: Http.php プロジェクト: jthurteau/saf
 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;
 }
コード例 #22
0
ファイル: Xml.php プロジェクト: jthurteau/saf
 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);
     }
 }
コード例 #23
0
ファイル: Debug.php プロジェクト: jthurteau/saf
 public static function clearMessages()
 {
     self::$_debugStack = array();
 }
コード例 #24
0
ファイル: Bootstrap.php プロジェクト: jthurteau/saf
 protected function _postRun()
 {
     if ($this == self::$_rootStrap) {
         Saf_Debug::dieSafe();
     }
 }