Continued:
[core.git] / inc / main / classes / class_BaseFrameworkSystem.php
index 7bee5ecac0fe15f427db47e30dbb4c57726dc67f..f306b320f5a12b3018de0e451bac5f14124265de 100644 (file)
@@ -1,11 +1,42 @@
 <?php
+// Own namespace
+namespace CoreFramework\Object;
+
+// Import framework stuff
+use CoreFramework\Compressor\Compressor;
+use CoreFramework\Configuration\FrameworkConfiguration;
+use CoreFramework\Connection\Database\DatabaseConnection;
+use CoreFramework\Controller\Controller;
+use CoreFramework\Criteria\Criteria;
+use CoreFramework\Criteria\Local\LocalSearchCriteria;
+use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
+use CoreFramework\Factory\ObjectFactory;
+use CoreFramework\Filesystem\FrameworkDirectory;
+use CoreFramework\Generic\FrameworkInterface;
+use CoreFramework\Generic\NullPointerException;
+use CoreFramework\Handler\Stream\IoHandler;
+use CoreFramework\Loader\ClassLoader;
+use CoreFramework\Manager\ManageableApplication;
+use CoreFramework\Middleware\Compressor\CompressorChannel;
+use CoreFramework\Middleware\Debug\DebugMiddleware;
+use CoreFramework\Registry\Register;
+use CoreFramework\Registry\Registry;
+use CoreFramework\Request\Requestable;
+use CoreFramework\Resolver\Resolver;
+use CoreFramework\Response\Responseable;
+use CoreFramework\Stream\Output\OutputStreamer;
+use CoreFramework\Template\CompileableTemplate;
+
+// Import SPL stuff
+use \stdClass;
+
 /**
  * The simulator system class is the super class of all other classes. This
  * class handles saving of games etc.
  *
  * @author             Roland Haeder <webmaster@shipsimu.org>
  * @version            0.0.0
- * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Core Developer Team
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
  * @license            GNU GPL 3.0 or any newer version
  * @link               http://www.shipsimu.org
  *
@@ -34,12 +65,12 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
        private $realClass = 'BaseFrameworkSystem';
 
        /**
-        * Instance of a request class
+        * Instance of a Requestable class
         */
        private $requestInstance = NULL;
 
        /**
-        * Instance of a response class
+        * Instance of a Responseable class
         */
        private $responseInstance = NULL;
 
@@ -458,7 +489,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                        $this->setRealClass('DestructedObject');
                } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
                        // Already destructed object
-                       self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
+                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
                                __CLASS__,
                                $this->__toString()
                        ));
@@ -488,6 +519,9 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      void
         */
        public static final function __callStatic ($methodName, $args) {
+               // Trace message
+               //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
+
                // Init argument string
                $argsString = '';
 
@@ -495,44 +529,52 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                if (is_null($args)) {
                        // No arguments
                        $argsString = 'NULL';
-               } elseif (empty($args)) {
-                       // Empty arguments
-                       $argsString = '(empty)';
                } elseif (is_array($args)) {
+                       // Start braces
+                       $argsString = '(';
+
                        // Some arguments are there
                        foreach ($args as $arg) {
-                               // Add the value itself if not array. This prevents 'array to string conversion' message
-                               if (is_array($arg)) {
-                                       $argsString .= 'Array';
-                               } else {
-                                       $argsString .= $arg;
-                               }
-
                                // Add data about the argument
-                               $argsString .= ' (' . gettype($arg);
+                               $argsString .= gettype($arg) . ':';
 
-                               if (is_string($arg)) {
+                               if (is_null($arg)) {
+                                       // Found a NULL argument
+                                       $argsString .= 'NULL';
+                               } elseif (is_string($arg)) {
                                        // Add length for strings
-                                       $argsString .= ', ' . strlen($arg);
+                                       $argsString .= strlen($arg);
+                               } elseif ((is_int($arg)) || (is_float($arg))) {
+                                       // ... integer/float
+                                       $argsString .= $arg;
                                } elseif (is_array($arg)) {
                                        // .. or size if array
-                                       $argsString .= ', ' . count($arg);
+                                       $argsString .= count($arg);
+                               } elseif (is_object($arg)) {
+                                       // Get reflection
+                                       $reflection = new ReflectionClass($arg);
+
+                                       // Is an other object, maybe no __toString() available
+                                       $argsString .= $reflection->getName();
                                } elseif ($arg === TRUE) {
                                        // ... is boolean 'TRUE'
-                                       $argsString .= 'TRUE';
+                                       $argsString .= 'TRUE';
                                } elseif ($arg === FALSE) {
                                        // ... is boolean 'FALSE'
-                                       $argsString .= 'FALSE';
+                                       $argsString .= 'FALSE';
                                }
 
-                               // Closing bracket
-                               $argsString .= '), ';
+                               // Comma for next one
+                               $argsString .= ', ';
                        } // END - foreach
 
                        // Remove last comma
                        if (substr($argsString, -2, 1) == ',') {
                                $argsString = substr($argsString, 0, -2);
                        } // END - if
+
+                       // Close braces
+                       $argsString .= ')';
                } else {
                        // Invalid arguments!
                        $argsString = '!INVALID:' . gettype($args) . '!';
@@ -540,7 +582,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
 
                // Output stub message
                // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
-               self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
+               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
                        $methodName,
                        $argsString
                ));
@@ -1174,7 +1216,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      void
         */
        public final function setSocketResource ($socketResource) {
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
                $this->socketResource = $socketResource;
        }
 
@@ -1184,7 +1226,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      $socketResource         A valid socket resource
         */
        public final function getSocketResource () {
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
                return $this->socketResource;
        }
 
@@ -1195,7 +1237,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      void
         */
        public final function setRegularExpression ($regularExpression) {
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
                $this->regularExpression = $regularExpression;
        }
 
@@ -1205,7 +1247,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      $regularExpression      A valid regular expression
         */
        public final function getRegularExpression () {
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
                return $this->regularExpression;
        }
 
@@ -1495,7 +1537,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
        /**
         * Setter for FrameworkDirectory instance
         *
-        * @param       $directoryInstance      A FrameworkDirectoryPointer instance
+        * @param       $directoryInstance      A FrameworkDirectory instance
         * @return      void
         */
        protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
@@ -1834,7 +1876,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                // Debug instance is there?
                if (!is_null($this->getDebugInstance())) {
                        // Output stub message
-                       self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
+                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
                } else {
                        // Trigger an error
                        trigger_error($stubMessage);
@@ -1853,7 +1895,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                // Sorry, there is no other way getting this nice backtrace
                if (!empty($message)) {
                        // Output message
-                       printf('Message: %s<br />' . chr(10), $message);
+                       printf('Message: %s<br />' . PHP_EOL, $message);
                } // END - if
 
                print('<pre>');
@@ -1870,10 +1912,11 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * Creates an instance of a debugger instance
         *
         * @param       $className              Name of the class (currently unsupported)
+        * @param       $lineNumber             Line number where the call was made
         * @return      $debugInstance  An instance of a debugger class
         * @deprecated  Not fully, as the new Logger facilities are not finished yet.
         */
-       public final static function createDebugInstance ($className) {
+       public final static function createDebugInstance ($className, $lineNumber = NULL) {
                // Is the instance set?
                if (!Registry::getRegistry()->instanceExists('debug')) {
                        // Init debug instance
@@ -1885,7 +1928,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                                $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
                        } catch (NullPointerException $e) {
                                // Didn't work, no instance there
-                               exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
+                               exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
                        }
 
                        // Empty string should be ignored and used for testing the middleware
@@ -2026,7 +2069,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                // Add line number to the code
                foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
                        // Add line numbers
-                       $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
+                       $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
                                ($lineNo + 1),
                                htmlentities($code, ENT_QUOTES)
                        );
@@ -2158,7 +2201,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
 
                // Get current array
                $fieldArray = $resultInstance->current();
-               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
+               //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
 
                // Convert dashes to underscore
                $fieldName2 = self::convertDashesToUnderscores($fieldName);
@@ -2169,10 +2212,10 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                        $fieldValue = $fieldArray[$fieldName2];
                } elseif (defined('DEVELOPER')) {
                        // Missing field entry, may require debugging
-                       self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
+                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
                } else {
                        // Missing field entry, may require debugging
-                       self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
+                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
                }
 
                // Return it
@@ -2198,7 +2241,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
 
                // Get current array
                $fieldArray = $resultInstance->current();
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
 
                // Convert dashes to underscore
                $fieldName = self::convertDashesToUnderscores($fieldName);
@@ -2245,7 +2288,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                        // Debug instance is there?
                        if (!is_null($this->getDebugInstance())) {
                                // Output stub message
-                               self::createDebugInstance(__CLASS__)->debugOutput($message);
+                               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
                        } else {
                                // Trigger an error
                                trigger_error($message . "<br />\n");
@@ -2433,7 +2476,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         */
        protected function hex2asc ($hex) {
                // Check for length, it must be devideable by 2
-               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
+               //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
                assert((strlen($hex) % 2) == 0);
 
                // Walk the string
@@ -2501,7 +2544,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                );
 
                // And return it
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
                return $cacheKey;
        }
 
@@ -3284,7 +3327,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         */
        protected function packString ($str) {
                // Debug message
-               //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
+               //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
 
                // First compress the string (gzcompress is okay)
                $str = gzcompress($str);
@@ -3319,7 +3362,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                } // END - for
 
                // Return it
-               //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
+               //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
                return $packed;
        }
 
@@ -3331,7 +3374,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @param       $filePathName   Name of the file/path to be checked
         * @return      $isReachable    Whether it is within open_basedir()
         */
-       public static function isReachableFilePath ($filePathName) {
+       protected static function isReachableFilePath ($filePathName) {
                // Is not reachable by default
                $isReachable = FALSE;
 
@@ -3374,7 +3417,105 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                // Return status
                return $isReadable;
        }
-}
 
-// [EOF]
-?>
+       /**
+        * Creates a full-qualified file name (FQFN) for given file name by adding
+        * a configured temporary file path to it.
+        *
+        * @param       $fileName       Name for temporary file
+        * @return      $fqfn   Full-qualified file name
+        * @throw       PathWriteProtectedException If the path in 'temp_file_path' is write-protected
+        * @throws      FileIoException If the file cannot be written
+        */
+        protected static function createTempPathForFile ($fileName) {
+               // Get config entry
+               $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
+
+               // Is the path writeable?
+               if (!is_writable($basePath)) {
+                       // Path is write-protected
+                       throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
+               } // END - if
+
+               // Add it
+               $fqfn = $basePath . '/' . $fileName;
+
+               // Is it reachable?
+               if (!self::isReachableFilePath($fqfn)) {
+                       // Not reachable
+                       throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
+               } // END - if
+
+               // Return it
+               return $fqfn;
+        }
+
+       /**
+        * "Getter" for a printable state name
+        *
+        * @return      $stateName      Name of the node's state in a printable format
+        */
+       public final function getPrintableState () {
+               // Default is 'null'
+               $stateName = 'null';
+
+               // Get the state instance
+               $stateInstance = $this->getStateInstance();
+
+               // Is it an instance of Stateable?
+               if ($stateInstance instanceof Stateable) {
+                       // Then use that state name
+                       $stateName = $stateInstance->getStateName();
+               } // END - if
+
+               // Return result
+               return $stateName;
+       }
+
+       /**
+        * Handles socket error for given socket resource and peer data. This method
+        * validates $socketResource if it is a valid resource (see is_resource())
+        * but assumes valid data in array $recipientData, except that
+        * count($recipientData) is always 2.
+        *
+        * @param       $method                         Value of __METHOD__ from calling method
+        * @param       $line                           Value of __LINE__ from calling method
+        * @param       $socketResource         A valid socket resource
+        * @param       $socketData                     A valid socket data array (0 = IP/file name, 1 = port)
+        * @return      void
+        * @throws      InvalidSocketException  If $socketResource is no socket resource
+        * @throws      NoSocketErrorDetectedException  If socket_last_error() gives zero back
+        * @todo        Move all this socket-related stuff into own class, most of it resides in BaseListener
+        */
+       protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
+               // This method handles only socket resources
+               if (!is_resource($socketResource)) {
+                       // No resource, abort here
+                       throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
+               } // END - if
+
+               // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
+               //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
+               assert(isset($socketData[0]));
+               assert(isset($socketData[1]));
+
+               // Get error code for first validation (0 is not an error)
+               $errorCode = socket_last_error($socketResource);
+
+               // If the error code is zero, someone called this method without an error
+               if ($errorCode == 0) {
+                       // No error detected (or previously cleared outside this method)
+                       throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
+               } // END - if
+
+               // Get handler (method) name
+               $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
+
+               // Call-back the error handler method
+               call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
+
+               // Finally clear the error because it has been handled
+               socket_clear_error($socketResource);
+       }
+
+}