3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Compressor\Compressor;
7 use CoreFramework\Configuration\FrameworkConfiguration;
8 use CoreFramework\Connection\Database\DatabaseConnection;
9 use CoreFramework\Controller\Controller;
10 use CoreFramework\Criteria\Criteria;
11 use CoreFramework\Criteria\Local\LocalSearchCriteria;
12 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
13 use CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
14 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
15 use CoreFramework\Factory\ObjectFactory;
16 use CoreFramework\Filesystem\Block;
17 use CoreFramework\Filesystem\FilePointer;
18 use CoreFramework\Filesystem\FrameworkDirectory;
19 use CoreFramework\Generic\FrameworkInterface;
20 use CoreFramework\Generic\NullPointerException;
21 use CoreFramework\Handler\Stream\IoHandler;
22 use CoreFramework\Index\Indexable;
23 use CoreFramework\Listener\Listenable;
24 use CoreFramework\Lists\Listable;
25 use CoreFramework\Loader\ClassLoader;
26 use CoreFramework\Manager\ManageableApplication;
27 use CoreFramework\Middleware\Compressor\CompressorChannel;
28 use CoreFramework\Middleware\Debug\DebugMiddleware;
29 use CoreFramework\Parser\Parseable;
30 use CoreFramework\Registry\Register;
31 use CoreFramework\Registry\Registry;
32 use CoreFramework\Request\Requestable;
33 use CoreFramework\Resolver\Resolver;
34 use CoreFramework\Result\Database\CachedDatabaseResult;
35 use CoreFramework\Result\Search\SearchableResult;
36 use CoreFramework\Response\Responseable;
37 use CoreFramework\Stacker\Stackable;
38 use CoreFramework\Stream\Output\OutputStreamer;
39 use CoreFramework\Template\CompileableTemplate;
40 use CoreFramework\User\ManageableAccount;
41 use CoreFramework\Visitor\Visitor;
42 use CoreFramework\Wrapper\Database\DatabaseWrapper;
49 * The simulator system class is the super class of all other classes. This
50 * class handles saving of games etc.
52 * @author Roland Haeder <webmaster@shipsimu.org>
54 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
55 * @license GNU GPL 3.0 or any newer version
56 * @link http://www.shipsimu.org
58 * This program is free software: you can redistribute it and/or modify
59 * it under the terms of the GNU General Public License as published by
60 * the Free Software Foundation, either version 3 of the License, or
61 * (at your option) any later version.
63 * This program is distributed in the hope that it will be useful,
64 * but WITHOUT ANY WARRANTY; without even the implied warranty of
65 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
66 * GNU General Public License for more details.
68 * You should have received a copy of the GNU General Public License
69 * along with this program. If not, see <http://www.gnu.org/licenses/>.
71 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
73 * Length of output from hash()
75 private static $hashLength = NULL;
80 private $realClass = 'BaseFrameworkSystem';
83 * Instance of a Requestable class
85 private $requestInstance = NULL;
88 * Instance of a Responseable class
90 private $responseInstance = NULL;
93 * Search criteria instance
95 private $searchInstance = NULL;
98 * Update criteria instance
100 private $updateInstance = NULL;
103 * The file I/O instance for the template loader
105 private $fileIoInstance = NULL;
110 private $resolverInstance = NULL;
113 * Template engine instance
115 private $templateInstance = NULL;
118 * Database result instance
120 private $resultInstance = NULL;
123 * Instance for user class
125 private $userInstance = NULL;
128 * A controller instance
130 private $controllerInstance = NULL;
135 private $rngInstance = NULL;
138 * Instance of a crypto helper
140 private $cryptoInstance = NULL;
143 * Instance of an Iterator class
145 private $iteratorInstance = NULL;
148 * Instance of the list
150 private $listInstance = NULL;
155 private $menuInstance = NULL;
158 * Instance of the image
160 private $imageInstance = NULL;
163 * Instance of the stacker
165 private $stackInstance = NULL;
168 * A Compressor instance
170 private $compressorInstance = NULL;
173 * A Parseable instance
175 private $parserInstance = NULL;
178 * A HandleableProtocol instance
180 private $protocolInstance = NULL;
183 * A database wrapper instance
185 private $databaseInstance = NULL;
188 * A helper instance for the form
190 private $helperInstance = NULL;
193 * An instance of a Source class
195 private $sourceInstance = NULL;
198 * An instance of a UrlSource class
200 private $urlSourceInstance = NULL;
203 * An instance of a InputStream class
205 private $inputStreamInstance = NULL;
208 * An instance of a OutputStream class
210 private $outputStreamInstance = NULL;
213 * Networkable handler instance
215 private $handlerInstance = NULL;
218 * Visitor handler instance
220 private $visitorInstance = NULL;
225 private $dhtInstance = NULL;
228 * An instance of a database wrapper class
230 private $wrapperInstance = NULL;
233 * An instance of a file I/O pointer class (not handler)
235 private $pointerInstance = NULL;
238 * An instance of an Indexable class
240 private $indexInstance = NULL;
243 * An instance of a Block class
245 private $blockInstance = NULL;
250 private $minableInstance = NULL;
253 * A FrameworkDirectory instance
255 private $directoryInstance = NULL;
260 private $listenerInstance = NULL;
263 * An instance of a communicator
265 private $communicatorInstance = NULL;
268 * The concrete output instance
270 private $outputInstance = NULL;
275 private $stateInstance = NULL;
278 * Thousands separator
280 private $thousands = '.'; // German
285 private $decimals = ','; // German
290 private $socketResource = FALSE;
293 * Regular expression to use for validation
295 private $regularExpression = '';
300 private $packageData = array();
305 private $genericArray = array();
310 private $commandName = '';
315 private $controllerName = '';
318 * Name of used protocol
320 private $protocolName = 'invalid';
323 * Array with bitmasks and such for pack/unpack methods to support both
324 * 32-bit and 64-bit systems
326 private $packingData = array(
329 'left' => 0xffff0000,
330 'right' => 0x0000ffff,
336 'left' => 0xffffffff00000000,
337 'right' => 0x00000000ffffffff,
344 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
346 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
348 private $archArrayElement = FALSE;
350 /***********************
351 * Exception codes.... *
352 ***********************/
354 // @todo Try to clean these constants up
355 const EXCEPTION_IS_NULL_POINTER = 0x001;
356 const EXCEPTION_IS_NO_OBJECT = 0x002;
357 const EXCEPTION_IS_NO_ARRAY = 0x003;
358 const EXCEPTION_MISSING_METHOD = 0x004;
359 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
360 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
361 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
362 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
363 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
364 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
365 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
366 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
367 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
368 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
369 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
370 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
371 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
372 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
373 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
374 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
375 const EXCEPTION_PATH_NOT_FOUND = 0x015;
376 const EXCEPTION_INVALID_PATH_NAME = 0x016;
377 const EXCEPTION_READ_PROTECED_PATH = 0x017;
378 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
379 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
380 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
381 const EXCEPTION_INVALID_RESOURCE = 0x01b;
382 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
383 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
384 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
385 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
386 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
387 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
388 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
389 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
390 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
391 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
392 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
393 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
394 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
395 const EXCEPTION_INVALID_STRING = 0x029;
396 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
397 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
398 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
399 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
400 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
401 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
402 const EXCEPTION_MISSING_ELEMENT = 0x030;
403 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
404 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
405 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
406 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
407 const EXCEPTION_FATAL_ERROR = 0x035;
408 const EXCEPTION_FILE_NOT_FOUND = 0x036;
409 const EXCEPTION_ASSERTION_FAILED = 0x037;
410 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
411 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
412 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
413 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
414 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
415 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
418 * Hexadecimal->Decimal translation array
420 private static $hexdec = array(
440 * Decimal->hexadecimal translation array
442 private static $dechex = array(
462 * Startup time in miliseconds
464 private static $startupTime = 0;
467 * Protected super constructor
469 * @param $className Name of the class
472 protected function __construct ($className) {
474 $this->setRealClass($className);
476 // Set configuration instance if no registry ...
477 if (!$this instanceof Register) {
478 // ... because registries doesn't need to be configured
479 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
482 // Is the startup time set? (0 cannot be TRUE anymore)
483 if (self::$startupTime == 0) {
485 self::$startupTime = microtime(TRUE);
489 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
493 * Destructor for all classes. You should not call this method on your own.
497 public function __destruct () {
498 // Flush any updated entries to the database
499 $this->flushPendingUpdates();
501 // Is this object already destroyed?
502 if ($this->__toString() != 'DestructedObject') {
503 // Destroy all informations about this class but keep some text about it alive
504 $this->setRealClass('DestructedObject');
505 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
506 // Already destructed object
507 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
512 // Do not call this twice
513 trigger_error(__METHOD__ . ': Called twice.');
519 * The __call() method where all non-implemented methods end up
521 * @param $methodName Name of the missing method
522 * @args $args Arguments passed to the method
525 public final function __call ($methodName, $args) {
526 return self::__callStatic($methodName, $args);
530 * The __callStatic() method where all non-implemented static methods end up
532 * @param $methodName Name of the missing method
533 * @args $args Arguments passed to the method
536 public static final function __callStatic ($methodName, $args) {
538 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
540 // Init argument string
543 // Is it NULL, empty or an array?
544 if (is_null($args)) {
546 $argsString = 'NULL';
547 } elseif (is_array($args)) {
551 // Some arguments are there
552 foreach ($args as $arg) {
553 // Add data about the argument
554 $argsString .= gettype($arg) . ':';
557 // Found a NULL argument
558 $argsString .= 'NULL';
559 } elseif (is_string($arg)) {
560 // Add length for strings
561 $argsString .= strlen($arg);
562 } elseif ((is_int($arg)) || (is_float($arg))) {
565 } elseif (is_array($arg)) {
566 // .. or size if array
567 $argsString .= count($arg);
568 } elseif (is_object($arg)) {
570 $reflection = new ReflectionClass($arg);
572 // Is an other object, maybe no __toString() available
573 $argsString .= $reflection->getName();
574 } elseif ($arg === TRUE) {
575 // ... is boolean 'TRUE'
576 $argsString .= 'TRUE';
577 } elseif ($arg === FALSE) {
578 // ... is boolean 'FALSE'
579 $argsString .= 'FALSE';
582 // Comma for next one
587 if (substr($argsString, -2, 1) == ',') {
588 $argsString = substr($argsString, 0, -2);
594 // Invalid arguments!
595 $argsString = '!INVALID:' . gettype($args) . '!';
598 // Output stub message
599 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
600 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
610 * Getter for $realClass
612 * @return $realClass The name of the real class (not BaseFrameworkSystem)
614 public function __toString () {
615 return $this->realClass;
619 * Magic method to catch setting of missing but set class fields/attributes
621 * @param $name Name of the field/attribute
622 * @param $value Value to store
625 public final function __set ($name, $value) {
626 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
629 print_r($value, TRUE)
634 * Magic method to catch getting of missing fields/attributes
636 * @param $name Name of the field/attribute
639 public final function __get ($name) {
640 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
646 * Magic method to catch unsetting of missing fields/attributes
648 * @param $name Name of the field/attribute
651 public final function __unset ($name) {
652 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
658 * Magic method to catch object serialization
660 * @return $unsupported Unsupported method
661 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
663 public final function __sleep () {
664 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
668 * Magic method to catch object deserialization
670 * @return $unsupported Unsupported method
671 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
673 public final function __wakeup () {
674 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
678 * Magic method to catch calls when an object instance is called
680 * @return $unsupported Unsupported method
681 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
683 public final function __invoke () {
684 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
688 * Setter for the real class name
690 * @param $realClass Class name (string)
693 public final function setRealClass ($realClass) {
695 $this->realClass = (string) $realClass;
699 * Setter for database result instance
701 * @param $resultInstance An instance of a database result class
703 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
705 protected final function setResultInstance (SearchableResult $resultInstance) {
706 $this->resultInstance = $resultInstance;
710 * Getter for database result instance
712 * @return $resultInstance An instance of a database result class
714 public final function getResultInstance () {
715 return $this->resultInstance;
719 * Setter for template engine instances
721 * @param $templateInstance An instance of a template engine class
724 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
725 $this->templateInstance = $templateInstance;
729 * Getter for template engine instances
731 * @return $templateInstance An instance of a template engine class
733 protected final function getTemplateInstance () {
734 return $this->templateInstance;
738 * Setter for search instance
740 * @param $searchInstance Searchable criteria instance
743 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
744 $this->searchInstance = $searchInstance;
748 * Getter for search instance
750 * @return $searchInstance Searchable criteria instance
752 public final function getSearchInstance () {
753 return $this->searchInstance;
757 * Setter for update instance
759 * @param $updateInstance An instance of a LocalUpdateCriteria clase
762 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
763 $this->updateInstance = $updateInstance;
767 * Getter for update instance
769 * @return $updateInstance Updateable criteria instance
771 public final function getUpdateInstance () {
772 return $this->updateInstance;
776 * Setter for resolver instance
778 * @param $resolverInstance Instance of a command resolver class
781 public final function setResolverInstance (Resolver $resolverInstance) {
782 $this->resolverInstance = $resolverInstance;
786 * Getter for resolver instance
788 * @return $resolverInstance Instance of a command resolver class
790 public final function getResolverInstance () {
791 return $this->resolverInstance;
795 * Setter for language instance
797 * @param $configInstance The configuration instance which shall
798 * be FrameworkConfiguration
801 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
802 Registry::getRegistry()->addInstance('config', $configInstance);
806 * Getter for configuration instance
808 * @return $configInstance Configuration instance
810 public final function getConfigInstance () {
811 $configInstance = Registry::getRegistry()->getInstance('config');
812 return $configInstance;
816 * Setter for debug instance
818 * @param $debugInstance The instance for debug output class
821 public final function setDebugInstance (DebugMiddleware $debugInstance) {
822 Registry::getRegistry()->addInstance('debug', $debugInstance);
826 * Getter for debug instance
828 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
830 public final function getDebugInstance () {
831 // Get debug instance
832 $debugInstance = Registry::getRegistry()->getInstance('debug');
835 return $debugInstance;
839 * Setter for web output instance
841 * @param $webInstance The instance for web output class
844 public final function setWebOutputInstance (OutputStreamer $webInstance) {
845 Registry::getRegistry()->addInstance('web_output', $webInstance);
849 * Getter for web output instance
851 * @return $webOutputInstance - Instance to class WebOutput
853 public final function getWebOutputInstance () {
854 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
855 return $webOutputInstance;
859 * Setter for database instance
861 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
864 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
865 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
869 * Getter for database layer
871 * @return $databaseInstance The database layer instance
873 public final function getDatabaseInstance () {
875 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
878 return $databaseInstance;
882 * Setter for compressor channel
884 * @param $compressorInstance An instance of CompressorChannel
887 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
888 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
892 * Getter for compressor channel
894 * @return $compressorInstance The compressor channel
896 public final function getCompressorChannel () {
897 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
898 return $compressorInstance;
902 * Protected getter for a manageable application helper class
904 * @return $applicationInstance An instance of a manageable application helper class
906 protected final function getApplicationInstance () {
907 $applicationInstance = Registry::getRegistry()->getInstance('application');
908 return $applicationInstance;
912 * Setter for a manageable application helper class
914 * @param $applicationInstance An instance of a manageable application helper class
917 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
918 Registry::getRegistry()->addInstance('application', $applicationInstance);
922 * Setter for request instance
924 * @param $requestInstance An instance of a Requestable class
927 public final function setRequestInstance (Requestable $requestInstance) {
928 $this->requestInstance = $requestInstance;
932 * Getter for request instance
934 * @return $requestInstance An instance of a Requestable class
936 public final function getRequestInstance () {
937 return $this->requestInstance;
941 * Setter for response instance
943 * @param $responseInstance An instance of a Responseable class
946 public final function setResponseInstance (Responseable $responseInstance) {
947 $this->responseInstance = $responseInstance;
951 * Getter for response instance
953 * @return $responseInstance An instance of a Responseable class
955 public final function getResponseInstance () {
956 return $this->responseInstance;
960 * Private getter for language instance
962 * @return $langInstance An instance to the language sub-system
964 protected final function getLanguageInstance () {
965 $langInstance = Registry::getRegistry()->getInstance('language');
966 return $langInstance;
970 * Setter for language instance
972 * @param $langInstance An instance to the language sub-system
974 * @see LanguageSystem
976 public final function setLanguageInstance (ManageableLanguage $langInstance) {
977 Registry::getRegistry()->addInstance('language', $langInstance);
981 * Private getter for file IO instance
983 * @return $fileIoInstance An instance to the file I/O sub-system
985 protected final function getFileIoInstance () {
986 return $this->fileIoInstance;
990 * Setter for file I/O instance
992 * @param $fileIoInstance An instance to the file I/O sub-system
995 public final function setFileIoInstance (IoHandler $fileIoInstance) {
996 $this->fileIoInstance = $fileIoInstance;
1000 * Protected setter for user instance
1002 * @param $userInstance An instance of a user class
1005 protected final function setUserInstance (ManageableAccount $userInstance) {
1006 $this->userInstance = $userInstance;
1010 * Getter for user instance
1012 * @return $userInstance An instance of a user class
1014 public final function getUserInstance () {
1015 return $this->userInstance;
1019 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1021 * @param $controllerInstance An instance of the controller
1024 public final function setControllerInstance (Controller $controllerInstance) {
1025 $this->controllerInstance = $controllerInstance;
1029 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1031 * @return $controllerInstance An instance of the controller
1033 public final function getControllerInstance () {
1034 return $this->controllerInstance;
1038 * Setter for RNG instance
1040 * @param $rngInstance An instance of a random number generator (RNG)
1043 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1044 $this->rngInstance = $rngInstance;
1048 * Getter for RNG instance
1050 * @return $rngInstance An instance of a random number generator (RNG)
1052 public final function getRngInstance () {
1053 return $this->rngInstance;
1057 * Setter for Cryptable instance
1059 * @param $cryptoInstance An instance of a Cryptable class
1062 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1063 $this->cryptoInstance = $cryptoInstance;
1067 * Getter for Cryptable instance
1069 * @return $cryptoInstance An instance of a Cryptable class
1071 public final function getCryptoInstance () {
1072 return $this->cryptoInstance;
1076 * Setter for the list instance
1078 * @param $listInstance A list of Listable
1081 protected final function setListInstance (Listable $listInstance) {
1082 $this->listInstance = $listInstance;
1086 * Getter for the list instance
1088 * @return $listInstance A list of Listable
1090 protected final function getListInstance () {
1091 return $this->listInstance;
1095 * Setter for the menu instance
1097 * @param $menuInstance A RenderableMenu instance
1100 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1101 $this->menuInstance = $menuInstance;
1105 * Getter for the menu instance
1107 * @return $menuInstance A RenderableMenu instance
1109 protected final function getMenuInstance () {
1110 return $this->menuInstance;
1114 * Setter for image instance
1116 * @param $imageInstance An instance of an image
1119 public final function setImageInstance (BaseImage $imageInstance) {
1120 $this->imageInstance = $imageInstance;
1124 * Getter for image instance
1126 * @return $imageInstance An instance of an image
1128 public final function getImageInstance () {
1129 return $this->imageInstance;
1133 * Setter for stacker instance
1135 * @param $stackInstance An instance of an stacker
1138 public final function setStackInstance (Stackable $stackInstance) {
1139 $this->stackInstance = $stackInstance;
1143 * Getter for stacker instance
1145 * @return $stackInstance An instance of an stacker
1147 public final function getStackInstance () {
1148 return $this->stackInstance;
1152 * Setter for compressor instance
1154 * @param $compressorInstance An instance of an compressor
1157 public final function setCompressorInstance (Compressor $compressorInstance) {
1158 $this->compressorInstance = $compressorInstance;
1162 * Getter for compressor instance
1164 * @return $compressorInstance An instance of an compressor
1166 public final function getCompressorInstance () {
1167 return $this->compressorInstance;
1171 * Setter for Parseable instance
1173 * @param $parserInstance An instance of an Parseable
1176 public final function setParserInstance (Parseable $parserInstance) {
1177 $this->parserInstance = $parserInstance;
1181 * Getter for Parseable instance
1183 * @return $parserInstance An instance of an Parseable
1185 public final function getParserInstance () {
1186 return $this->parserInstance;
1190 * Setter for HandleableProtocol instance
1192 * @param $protocolInstance An instance of an HandleableProtocol
1195 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1196 $this->protocolInstance = $protocolInstance;
1200 * Getter for HandleableProtocol instance
1202 * @return $protocolInstance An instance of an HandleableProtocol
1204 public final function getProtocolInstance () {
1205 return $this->protocolInstance;
1209 * Setter for DatabaseWrapper instance
1211 * @param $wrapperInstance An instance of an DatabaseWrapper
1214 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1215 $this->wrapperInstance = $wrapperInstance;
1219 * Getter for DatabaseWrapper instance
1221 * @return $wrapperInstance An instance of an DatabaseWrapper
1223 public final function getWrapperInstance () {
1224 return $this->wrapperInstance;
1228 * Setter for socket resource
1230 * @param $socketResource A valid socket resource
1233 public final function setSocketResource ($socketResource) {
1234 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1235 $this->socketResource = $socketResource;
1239 * Getter for socket resource
1241 * @return $socketResource A valid socket resource
1243 public final function getSocketResource () {
1244 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1245 return $this->socketResource;
1249 * Setter for regular expression
1251 * @param $regularExpression A valid regular expression
1254 public final function setRegularExpression ($regularExpression) {
1255 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1256 $this->regularExpression = $regularExpression;
1260 * Getter for regular expression
1262 * @return $regularExpression A valid regular expression
1264 public final function getRegularExpression () {
1265 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1266 return $this->regularExpression;
1270 * Setter for helper instance
1272 * @param $helperInstance An instance of a helper class
1275 protected final function setHelperInstance (Helper $helperInstance) {
1276 $this->helperInstance = $helperInstance;
1280 * Getter for helper instance
1282 * @return $helperInstance An instance of a helper class
1284 public final function getHelperInstance () {
1285 return $this->helperInstance;
1289 * Setter for a Source instance
1291 * @param $sourceInstance An instance of a Source class
1294 protected final function setSourceInstance (Source $sourceInstance) {
1295 $this->sourceInstance = $sourceInstance;
1299 * Getter for a Source instance
1301 * @return $sourceInstance An instance of a Source class
1303 protected final function getSourceInstance () {
1304 return $this->sourceInstance;
1308 * Setter for a UrlSource instance
1310 * @param $sourceInstance An instance of a UrlSource class
1313 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1314 $this->urlSourceInstance = $urlSourceInstance;
1318 * Getter for a UrlSource instance
1320 * @return $urlSourceInstance An instance of a UrlSource class
1322 protected final function getUrlSourceInstance () {
1323 return $this->urlSourceInstance;
1327 * Getter for a InputStream instance
1329 * @param $inputStreamInstance The InputStream instance
1331 protected final function getInputStreamInstance () {
1332 return $this->inputStreamInstance;
1336 * Setter for a InputStream instance
1338 * @param $inputStreamInstance The InputStream instance
1341 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1342 $this->inputStreamInstance = $inputStreamInstance;
1346 * Getter for a OutputStream instance
1348 * @param $outputStreamInstance The OutputStream instance
1350 protected final function getOutputStreamInstance () {
1351 return $this->outputStreamInstance;
1355 * Setter for a OutputStream instance
1357 * @param $outputStreamInstance The OutputStream instance
1360 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1361 $this->outputStreamInstance = $outputStreamInstance;
1365 * Setter for handler instance
1367 * @param $handlerInstance An instance of a Handleable class
1370 protected final function setHandlerInstance (Handleable $handlerInstance) {
1371 $this->handlerInstance = $handlerInstance;
1375 * Getter for handler instance
1377 * @return $handlerInstance A Networkable instance
1379 protected final function getHandlerInstance () {
1380 return $this->handlerInstance;
1384 * Setter for visitor instance
1386 * @param $visitorInstance A Visitor instance
1389 protected final function setVisitorInstance (Visitor $visitorInstance) {
1390 $this->visitorInstance = $visitorInstance;
1394 * Getter for visitor instance
1396 * @return $visitorInstance A Visitor instance
1398 protected final function getVisitorInstance () {
1399 return $this->visitorInstance;
1403 * Setter for DHT instance
1405 * @param $dhtInstance A Distributable instance
1408 protected final function setDhtInstance (Distributable $dhtInstance) {
1409 $this->dhtInstance = $dhtInstance;
1413 * Getter for DHT instance
1415 * @return $dhtInstance A Distributable instance
1417 protected final function getDhtInstance () {
1418 return $this->dhtInstance;
1422 * Setter for raw package Data
1424 * @param $packageData Raw package Data
1427 public final function setPackageData (array $packageData) {
1428 $this->packageData = $packageData;
1432 * Getter for raw package Data
1434 * @return $packageData Raw package Data
1436 public function getPackageData () {
1437 return $this->packageData;
1442 * Setter for Iterator instance
1444 * @param $iteratorInstance An instance of an Iterator
1447 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1448 $this->iteratorInstance = $iteratorInstance;
1452 * Getter for Iterator instance
1454 * @return $iteratorInstance An instance of an Iterator
1456 public final function getIteratorInstance () {
1457 return $this->iteratorInstance;
1461 * Setter for FilePointer instance
1463 * @param $pointerInstance An instance of an FilePointer class
1466 protected final function setPointerInstance (FilePointer $pointerInstance) {
1467 $this->pointerInstance = $pointerInstance;
1471 * Getter for FilePointer instance
1473 * @return $pointerInstance An instance of an FilePointer class
1475 public final function getPointerInstance () {
1476 return $this->pointerInstance;
1480 * Unsets pointer instance which triggers a call of __destruct() if the
1481 * instance is still there. This is surely not fatal on already "closed"
1482 * file pointer instances.
1484 * I don't want to mess around with above setter by giving it a default
1485 * value NULL as setter should always explicitly only set (existing) object
1486 * instances and NULL is NULL.
1490 protected final function unsetPointerInstance () {
1491 // Simply it to NULL
1492 $this->pointerInstance = NULL;
1496 * Setter for Indexable instance
1498 * @param $indexInstance An instance of an Indexable class
1501 protected final function setIndexInstance (Indexable $indexInstance) {
1502 $this->indexInstance = $indexInstance;
1506 * Getter for Indexable instance
1508 * @return $indexInstance An instance of an Indexable class
1510 public final function getIndexInstance () {
1511 return $this->indexInstance;
1515 * Setter for Block instance
1517 * @param $blockInstance An instance of an Block class
1520 protected final function setBlockInstance (Block $blockInstance) {
1521 $this->blockInstance = $blockInstance;
1525 * Getter for Block instance
1527 * @return $blockInstance An instance of an Block class
1529 public final function getBlockInstance () {
1530 return $this->blockInstance;
1534 * Setter for Minable instance
1536 * @param $minableInstance A Minable instance
1539 protected final function setMinableInstance (Minable $minableInstance) {
1540 $this->minableInstance = $minableInstance;
1544 * Getter for minable instance
1546 * @return $minableInstance A Minable instance
1548 protected final function getMinableInstance () {
1549 return $this->minableInstance;
1553 * Setter for FrameworkDirectory instance
1555 * @param $directoryInstance A FrameworkDirectory instance
1558 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1559 $this->directoryInstance = $directoryInstance;
1563 * Getter for FrameworkDirectory instance
1565 * @return $directoryInstance A FrameworkDirectory instance
1567 protected final function getDirectoryInstance () {
1568 return $this->directoryInstance;
1572 * Setter for listener instance
1574 * @param $listenerInstance A Listenable instance
1577 protected final function setListenerInstance (Listenable $listenerInstance) {
1578 $this->listenerInstance = $listenerInstance;
1582 * Getter for listener instance
1584 * @return $listenerInstance A Listenable instance
1586 protected final function getListenerInstance () {
1587 return $this->listenerInstance;
1591 * Getter for communicator instance
1593 * @return $communicatorInstance An instance of a Communicator class
1595 public final function getCommunicatorInstance () {
1596 return $this->communicatorInstance;
1600 * Setter for communicator instance
1602 * @param $communicatorInstance An instance of a Communicator class
1605 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1606 $this->communicatorInstance = $communicatorInstance;
1610 * Setter for state instance
1612 * @param $stateInstance A Stateable instance
1615 public final function setStateInstance (Stateable $stateInstance) {
1616 $this->stateInstance = $stateInstance;
1620 * Getter for state instance
1622 * @return $stateInstance A Stateable instance
1624 public final function getStateInstance () {
1625 return $this->stateInstance;
1629 * Setter for output instance
1631 * @param $outputInstance The debug output instance
1634 public final function setOutputInstance (OutputStreamer $outputInstance) {
1635 $this->outputInstance = $outputInstance;
1639 * Getter for output instance
1641 * @return $outputInstance The debug output instance
1643 public final function getOutputInstance () {
1644 return $this->outputInstance;
1648 * Setter for command name
1650 * @param $commandName Last validated command name
1653 protected final function setCommandName ($commandName) {
1654 $this->commandName = $commandName;
1658 * Getter for command name
1660 * @return $commandName Last validated command name
1662 protected final function getCommandName () {
1663 return $this->commandName;
1667 * Setter for controller name
1669 * @param $controllerName Last validated controller name
1672 protected final function setControllerName ($controllerName) {
1673 $this->controllerName = $controllerName;
1677 * Getter for controller name
1679 * @return $controllerName Last validated controller name
1681 protected final function getControllerName () {
1682 return $this->controllerName;
1686 * Getter for protocol name
1688 * @return $protocolName Name of used protocol
1690 public final function getProtocolName () {
1691 return $this->protocolName;
1695 * Setter for protocol name
1697 * @param $protocolName Name of used protocol
1700 protected final function setProtocolName ($protocolName) {
1701 $this->protocolName = $protocolName;
1705 * Checks whether an object equals this object. You should overwrite this
1706 * method to implement own equality checks
1708 * @param $objectInstance An instance of a FrameworkInterface object
1709 * @return $equals Whether both objects equals
1711 public function equals (FrameworkInterface $objectInstance) {
1714 $this->__toString() == $objectInstance->__toString()
1716 $this->hashCode() == $objectInstance->hashCode()
1719 // Return the result
1724 * Generates a generic hash code of this class. You should really overwrite
1725 * this method with your own hash code generator code. But keep KISS in mind.
1727 * @return $hashCode A generic hash code respresenting this whole class
1729 public function hashCode () {
1731 return crc32($this->__toString());
1735 * Formats computer generated price values into human-understandable formats
1736 * with thousand and decimal separators.
1738 * @param $value The in computer format value for a price
1739 * @param $currency The currency symbol (use HTML-valid characters!)
1740 * @param $decNum Number of decimals after commata
1741 * @return $price The for the current language formated price string
1742 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1743 * thousands separator
1746 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1747 // Are all required attriutes set?
1748 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1749 // Throw an exception
1750 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1754 $value = (float) $value;
1756 // Reformat the US number
1757 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1759 // Return as string...
1764 * Appends a trailing slash to a string
1766 * @param $str A string (maybe) without trailing slash
1767 * @return $str A string with an auto-appended trailing slash
1769 public final function addMissingTrailingSlash ($str) {
1770 // Is there a trailing slash?
1771 if (substr($str, -1, 1) != '/') {
1775 // Return string with trailing slash
1780 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1781 * application helper instance (ApplicationHelper by default).
1783 * @param $applicationInstance An application helper instance or
1784 * null if we shall use the default
1785 * @return $templateInstance The template engine instance
1786 * @throws NullPointerException If the discovered application
1787 * instance is still null
1789 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1790 // Is the application instance set?
1791 if (is_null($applicationInstance)) {
1792 // Get the current instance
1793 $applicationInstance = $this->getApplicationInstance();
1796 if (is_null($applicationInstance)) {
1797 // Thrown an exception
1798 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1802 // Initialize the template engine
1803 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1805 // Return the prepared instance
1806 return $templateInstance;
1810 * Debugs this instance by putting out it's full content
1812 * @param $message Optional message to show in debug output
1815 public final function debugInstance ($message = '') {
1816 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1817 restore_error_handler();
1822 // Is a message set?
1823 if (!empty($message)) {
1824 // Construct message
1825 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1828 // Generate the output
1829 $content .= sprintf('<pre>%s</pre>',
1832 print_r($this, TRUE)
1838 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">%s debug output:</div><div class="debug_content">%s</div>Loaded includes: <div class="debug_include_list">%s</div>',
1839 $this->__toString(),
1841 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1846 * Replaces control characters with printable output
1848 * @param $str String with control characters
1849 * @return $str Replaced string
1851 protected function replaceControlCharacters ($str) {
1854 chr(13), '[r]', str_replace(
1855 chr(10), '[n]', str_replace(
1865 * Output a partial stub message for the caller method
1867 * @param $message An optional message to display
1870 protected function partialStub ($message = '') {
1871 // Get the backtrace
1872 $backtrace = debug_backtrace();
1874 // Generate the class::method string
1875 $methodName = 'UnknownClass->unknownMethod';
1876 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1877 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1880 // Construct the full message
1881 $stubMessage = sprintf('[%s:] Partial stub!',
1885 // Is the extra message given?
1886 if (!empty($message)) {
1887 // Then add it as well
1888 $stubMessage .= ' Message: ' . $message;
1891 // Debug instance is there?
1892 if (!is_null($this->getDebugInstance())) {
1893 // Output stub message
1894 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1897 trigger_error($stubMessage);
1903 * Outputs a debug backtrace and stops further script execution
1905 * @param $message An optional message to output
1906 * @param $doExit Whether exit the program (TRUE is default)
1909 public function debugBackTrace ($message = '', $doExit = TRUE) {
1910 // Sorry, there is no other way getting this nice backtrace
1911 if (!empty($message)) {
1913 printf('Message: %s<br />' . PHP_EOL, $message);
1917 debug_print_backtrace();
1921 if ($doExit === TRUE) {
1927 * Creates an instance of a debugger instance
1929 * @param $className Name of the class (currently unsupported)
1930 * @param $lineNumber Line number where the call was made
1931 * @return $debugInstance An instance of a debugger class
1932 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1934 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1935 // Is the instance set?
1936 if (!Registry::getRegistry()->instanceExists('debug')) {
1937 // Init debug instance
1938 $debugInstance = NULL;
1942 // Get a debugger instance
1943 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1944 } catch (NullPointerException $e) {
1945 // Didn't work, no instance there
1946 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1949 // Empty string should be ignored and used for testing the middleware
1950 DebugMiddleware::getSelfInstance()->output('');
1952 // Set it in its own class. This will set it in the registry
1953 $debugInstance->setDebugInstance($debugInstance);
1955 // Get instance from registry
1956 $debugInstance = Registry::getRegistry()->getDebugInstance();
1960 return $debugInstance;
1964 * Simple output of a message with line-break
1966 * @param $message Message to output
1969 public function outputLine ($message) {
1971 print($message . PHP_EOL);
1975 * Outputs a debug message whether to debug instance (should be set!) or
1976 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1977 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1979 * @param $message Message we shall send out...
1980 * @param $doPrint Whether print or die here (default: print)
1981 * @paran $stripTags Whether to strip tags (default: FALSE)
1984 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1985 // Set debug instance to NULL
1986 $debugInstance = NULL;
1990 // Get debug instance
1991 $debugInstance = $this->getDebugInstance();
1992 } catch (NullPointerException $e) {
1993 // The debug instance is not set (yet)
1996 // Is the debug instance there?
1997 if (is_object($debugInstance)) {
1998 // Use debug output handler
1999 $debugInstance->output($message, $stripTags);
2001 if ($doPrint === FALSE) {
2002 // Die here if not printed
2006 // Are debug times enabled?
2007 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
2009 $message = $this->getPrintableExecutionTime() . $message;
2013 if ($doPrint === TRUE) {
2015 $this->outputLine($message);
2024 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2026 * @param $str The string, what ever it is needs to be converted
2027 * @return $className Generated class name
2029 public static final function convertToClassName ($str) {
2033 // Convert all dashes in underscores
2034 $str = self::convertDashesToUnderscores($str);
2036 // Now use that underscores to get classname parts for hungarian style
2037 foreach (explode('_', $str) as $strPart) {
2038 // Make the class name part lower case and first upper case
2039 $className .= ucfirst(strtolower($strPart));
2042 // Return class name
2047 * Converts dashes to underscores, e.g. useable for configuration entries
2049 * @param $str The string with maybe dashes inside
2050 * @return $str The converted string with no dashed, but underscores
2052 public static final function convertDashesToUnderscores ($str) {
2054 $str = str_replace('-', '_', $str);
2056 // Return converted string
2061 * Marks up the code by adding e.g. line numbers
2063 * @param $phpCode Unmarked PHP code
2064 * @return $markedCode Marked PHP code
2066 public function markupCode ($phpCode) {
2071 $errorArray = error_get_last();
2073 // Init the code with error message
2074 if (is_array($errorArray)) {
2076 $markedCode = sprintf('<div id="error_header">File: <span id="error_data">%s</span>, Line: <span id="error_data">%s</span>, Message: <span id="error_data">%s</span>, Type: <span id="error_data">%s</span></div>',
2077 basename($errorArray['file']),
2078 $errorArray['line'],
2079 $errorArray['message'],
2084 // Add line number to the code
2085 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2087 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2089 htmlentities($code, ENT_QUOTES)
2098 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2099 * beatiful for web-based front-ends. If null is given a message id
2100 * null_timestamp will be resolved and returned.
2102 * @param $timestamp Timestamp to prepare (filter) for display
2103 * @return $readable A readable timestamp
2105 public function doFilterFormatTimestamp ($timestamp) {
2106 // Default value to return
2109 // Is the timestamp null?
2110 if (is_null($timestamp)) {
2111 // Get a message string
2112 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2114 switch ($this->getLanguageInstance()->getLanguageCode()) {
2115 case 'de': // German format is a bit different to default
2116 // Split the GMT stamp up
2117 $dateTime = explode(' ', $timestamp );
2118 $dateArray = explode('-', $dateTime[0]);
2119 $timeArray = explode(':', $dateTime[1]);
2121 // Construct the timestamp
2122 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2132 default: // Default is pass-through
2133 $readable = $timestamp;
2143 * Filter a given number into a localized number
2145 * @param $value The raw value from e.g. database
2146 * @return $localized Localized value
2148 public function doFilterFormatNumber ($value) {
2149 // Generate it from config and localize dependencies
2150 switch ($this->getLanguageInstance()->getLanguageCode()) {
2151 case 'de': // German format is a bit different to default
2152 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2155 default: // US, etc.
2156 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2165 * "Getter" for databse entry
2167 * @return $entry An array with database entries
2168 * @throws NullPointerException If the database result is not found
2169 * @throws InvalidDatabaseResultException If the database result is invalid
2171 protected final function getDatabaseEntry () {
2172 // Is there an instance?
2173 if (!$this->getResultInstance() instanceof SearchableResult) {
2174 // Throw an exception here
2175 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2179 $this->getResultInstance()->rewind();
2181 // Do we have an entry?
2182 if ($this->getResultInstance()->valid() === FALSE) {
2183 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2184 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2188 $this->getResultInstance()->next();
2191 $entry = $this->getResultInstance()->current();
2198 * Getter for field name
2200 * @param $fieldName Field name which we shall get
2201 * @return $fieldValue Field value from the user
2202 * @throws NullPointerException If the result instance is null
2204 public final function getField ($fieldName) {
2205 // Default field value
2208 // Get result instance
2209 $resultInstance = $this->getResultInstance();
2211 // Is this instance null?
2212 if (is_null($resultInstance)) {
2213 // Then the user instance is no longer valid (expired cookies?)
2214 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2217 // Get current array
2218 $fieldArray = $resultInstance->current();
2219 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2221 // Convert dashes to underscore
2222 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2224 // Does the field exist?
2225 if ($this->isFieldSet($fieldName)) {
2227 $fieldValue = $fieldArray[$fieldName2];
2228 } elseif (defined('DEVELOPER')) {
2229 // Missing field entry, may require debugging
2230 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2232 // Missing field entry, may require debugging
2233 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2241 * Checks if given field is set
2243 * @param $fieldName Field name to check
2244 * @return $isSet Whether the given field name is set
2245 * @throws NullPointerException If the result instance is null
2247 public function isFieldSet ($fieldName) {
2248 // Get result instance
2249 $resultInstance = $this->getResultInstance();
2251 // Is this instance null?
2252 if (is_null($resultInstance)) {
2253 // Then the user instance is no longer valid (expired cookies?)
2254 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2257 // Get current array
2258 $fieldArray = $resultInstance->current();
2259 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2261 // Convert dashes to underscore
2262 $fieldName = self::convertDashesToUnderscores($fieldName);
2265 $isSet = isset($fieldArray[$fieldName]);
2272 * Flushs all pending updates to the database layer
2276 public function flushPendingUpdates () {
2277 // Get result instance
2278 $resultInstance = $this->getResultInstance();
2280 // Do we have data to update?
2281 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2282 // Get wrapper class name config entry
2283 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2285 // Create object instance
2286 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2288 // Yes, then send the whole result to the database layer
2289 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2294 * Outputs a deprecation warning to the developer.
2296 * @param $message The message we shall output to the developer
2298 * @todo Write a logging mechanism for productive mode
2300 public function deprecationWarning ($message) {
2301 // Is developer mode active?
2302 if (defined('DEVELOPER')) {
2303 // Debug instance is there?
2304 if (!is_null($this->getDebugInstance())) {
2305 // Output stub message
2306 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2309 trigger_error($message . "<br />\n");
2313 // @TODO Finish this part!
2314 $this->partialStub('Developer mode inactive. Message:' . $message);
2319 * Checks whether the given PHP extension is loaded
2321 * @param $phpExtension The PHP extension we shall check
2322 * @return $isLoaded Whether the PHP extension is loaded
2324 public final function isPhpExtensionLoaded ($phpExtension) {
2326 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2333 * "Getter" as a time() replacement but with milliseconds. You should use this
2334 * method instead of the encapsulated getimeofday() function.
2336 * @return $milliTime Timestamp with milliseconds
2338 public function getMilliTime () {
2339 // Get the time of day as float
2340 $milliTime = gettimeofday(TRUE);
2347 * Idles (sleeps) for given milliseconds
2349 * @return $hasSlept Whether it goes fine
2351 public function idle ($milliSeconds) {
2352 // Sleep is fine by default
2355 // Idle so long with found function
2356 if (function_exists('time_sleep_until')) {
2357 // Get current time and add idle time
2358 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2360 // New PHP 5.1.0 function found, ignore errors
2361 $hasSlept = @time_sleep_until($sleepUntil);
2364 * My Sun station doesn't have that function even with latest PHP
2367 usleep($milliSeconds * 1000);
2374 * Converts a hexadecimal string, even with negative sign as first string to
2375 * a decimal number using BC functions.
2377 * This work is based on comment #86673 on php.net documentation page at:
2378 * <http://de.php.net/manual/en/function.dechex.php#86673>
2380 * @param $hex Hexadecimal string
2381 * @return $dec Decimal number
2383 protected function hex2dec ($hex) {
2384 // Convert to all lower-case
2385 $hex = strtolower($hex);
2387 // Detect sign (negative/positive numbers)
2389 if (substr($hex, 0, 1) == '-') {
2391 $hex = substr($hex, 1);
2394 // Decode the hexadecimal string into a decimal number
2396 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2397 $factor = self::$hexdec[substr($hex, $i, 1)];
2398 $dec = bcadd($dec, bcmul($factor, $e));
2401 // Return the decimal number
2402 return $sign . $dec;
2406 * Converts even very large decimal numbers, also signed, to a hexadecimal
2409 * This work is based on comment #97756 on php.net documentation page at:
2410 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2412 * @param $dec Decimal number, even with negative sign
2413 * @param $maxLength Optional maximum length of the string
2414 * @return $hex Hexadecimal string
2416 protected function dec2hex ($dec, $maxLength = 0) {
2417 // maxLength can be zero or devideable by 2
2418 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2420 // Detect sign (negative/positive numbers)
2427 // Encode the decimal number into a hexadecimal string
2430 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2432 } while ($dec >= 1);
2435 * Leading zeros are required for hex-decimal "numbers". In some
2436 * situations more leading zeros are wanted, so check for both
2439 if ($maxLength > 0) {
2440 // Prepend more zeros
2441 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2442 } elseif ((strlen($hex) % 2) != 0) {
2443 // Only make string's length dividable by 2
2447 // Return the hexadecimal string
2448 return $sign . $hex;
2452 * Converts a ASCII string (0 to 255) into a decimal number.
2454 * @param $asc The ASCII string to be converted
2455 * @return $dec Decimal number
2457 protected function asc2dec ($asc) {
2458 // Convert it into a hexadecimal number
2459 $hex = bin2hex($asc);
2461 // And back into a decimal number
2462 $dec = $this->hex2dec($hex);
2469 * Converts a decimal number into an ASCII string.
2471 * @param $dec Decimal number
2472 * @return $asc An ASCII string
2474 protected function dec2asc ($dec) {
2475 // First convert the number into a hexadecimal string
2476 $hex = $this->dec2hex($dec);
2478 // Then convert it into the ASCII string
2479 $asc = $this->hex2asc($hex);
2486 * Converts a hexadecimal number into an ASCII string. Negative numbers
2489 * @param $hex Hexadecimal string
2490 * @return $asc An ASCII string
2492 protected function hex2asc ($hex) {
2493 // Check for length, it must be devideable by 2
2494 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2495 assert((strlen($hex) % 2) == 0);
2499 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2500 // Get the decimal number of the chunk
2501 $part = hexdec(substr($hex, $idx, 2));
2503 // Add it to the final string
2507 // Return the final string
2512 * Checks whether the given encoded data was encoded with Base64
2514 * @param $encodedData Encoded data we shall check
2515 * @return $isBase64 Whether the encoded data is Base64
2517 protected function isBase64Encoded ($encodedData) {
2519 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2526 * "Getter" to get response/request type from analysis of the system.
2528 * @return $responseType Analyzed response type
2530 protected static function getResponseTypeFromSystem () {
2531 // Default is console
2532 $responseType = 'console';
2534 // Is 'HTTP_HOST' set?
2535 if (isset($_SERVER['HTTP_HOST'])) {
2537 * Then it is a HTML response/request as RSS and so on may be
2538 * transfered over HTTP as well.
2540 $responseType = 'html';
2544 return $responseType;
2548 * Gets a cache key from Criteria instance
2550 * @param $criteriaInstance An instance of a Criteria class
2551 * @param $onlyKeys Only use these keys for a cache key
2552 * @return $cacheKey A cache key suitable for lookup/storage purposes
2554 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2556 $cacheKey = sprintf('%s@%s',
2557 $this->__toString(),
2558 $criteriaInstance->getCacheKey($onlyKeys)
2562 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2567 * Getter for startup time in miliseconds
2569 * @return $startupTime Startup time in miliseconds
2571 protected function getStartupTime () {
2572 return self::$startupTime;
2576 * "Getter" for a printable currently execution time in nice braces
2578 * @return $executionTime Current execution time in nice braces
2580 protected function getPrintableExecutionTime () {
2581 // Caculate the execution time
2582 $executionTime = microtime(TRUE) - $this->getStartupTime();
2584 // Pack it in nice braces
2585 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2588 return $executionTime;
2592 * Hashes a given string with a simple but stronger hash function (no salt)
2593 * and hex-encode it.
2595 * @param $str The string to be hashed
2596 * @return $hash The hash from string $str
2598 public static final function hash ($str) {
2599 // Hash given string with (better secure) hasher
2600 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2607 * "Getter" for length of hash() output. This will be "cached" to speed up
2610 * @return $length Length of hash() output
2612 public static final function getHashLength () {
2614 if (is_null(self::$hashLength)) {
2615 // No, then hash a string and save its length.
2616 self::$hashLength = strlen(self::hash('abc123'));
2620 return self::$hashLength;
2624 * Checks whether the given number is really a number (only chars 0-9).
2626 * @param $num A string consisting only chars between 0 and 9
2627 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2628 * @param $assertMismatch Whether to assert mismatches
2629 * @return $ret The (hopefully) secured numbered value
2631 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2632 // Filter all numbers out
2633 $ret = preg_replace('/[^0123456789]/', '', $num);
2636 if ($castValue === TRUE) {
2637 // Cast to biggest numeric type
2638 $ret = (double) $ret;
2641 // Assert only if requested
2642 if ($assertMismatch === TRUE) {
2643 // Has the whole value changed?
2644 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2652 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2654 * @param $num A string consisting only chars between 0 and 9
2655 * @param $assertMismatch Whether to assert mismatches
2656 * @return $ret The (hopefully) secured hext-numbered value
2658 public function hexval ($num, $assertMismatch = FALSE) {
2659 // Filter all numbers out
2660 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2662 // Assert only if requested
2663 if ($assertMismatch === TRUE) {
2664 // Has the whole value changed?
2665 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2673 * Checks whether start/end marker are set
2675 * @param $data Data to be checked
2676 * @return $isset Whether start/end marker are set
2678 public final function ifStartEndMarkersSet ($data) {
2680 $isset = ((substr($data, 0, strlen(BaseRawDataHandler::STREAM_START_MARKER)) == BaseRawDataHandler::STREAM_START_MARKER) && (substr($data, -1 * strlen(BaseRawDataHandler::STREAM_END_MARKER), strlen(BaseRawDataHandler::STREAM_END_MARKER)) == BaseRawDataHandler::STREAM_END_MARKER));
2682 // ... and return it
2687 * Determines if an element is set in the generic array
2689 * @param $keyGroup Main group for the key
2690 * @param $subGroup Sub group for the key
2691 * @param $key Key to check
2692 * @param $element Element to check
2693 * @return $isset Whether the given key is set
2695 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2697 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2700 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2706 * Determines if a key is set in the generic array
2708 * @param $keyGroup Main group for the key
2709 * @param $subGroup Sub group for the key
2710 * @param $key Key to check
2711 * @return $isset Whether the given key is set
2713 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2715 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2718 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2726 * Determines if a group is set in the generic array
2728 * @param $keyGroup Main group
2729 * @param $subGroup Sub group
2730 * @return $isset Whether the given group is set
2732 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2734 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2737 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2744 * Getter for sub key group
2746 * @param $keyGroup Main key group
2747 * @param $subGroup Sub key group
2748 * @return $array An array with all array elements
2750 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2752 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2753 // No, then abort here
2754 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2759 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2762 return $this->genericArray[$keyGroup][$subGroup];
2766 * Unsets a given key in generic array
2768 * @param $keyGroup Main group for the key
2769 * @param $subGroup Sub group for the key
2770 * @param $key Key to unset
2773 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2775 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2778 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2782 * Unsets a given element in generic array
2784 * @param $keyGroup Main group for the key
2785 * @param $subGroup Sub group for the key
2786 * @param $key Key to unset
2787 * @param $element Element to unset
2790 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2792 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2795 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2799 * Append a string to a given generic array key
2801 * @param $keyGroup Main group for the key
2802 * @param $subGroup Sub group for the key
2803 * @param $key Key to unset
2804 * @param $value Value to add/append
2807 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2809 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE) . ',appendGlue=' . $appendGlue);
2811 // Is it already there?
2812 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2814 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2817 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2822 * Append a string to a given generic array element
2824 * @param $keyGroup Main group for the key
2825 * @param $subGroup Sub group for the key
2826 * @param $key Key to unset
2827 * @param $element Element to check
2828 * @param $value Value to add/append
2831 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2833 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE) . ',appendGlue=' . $appendGlue);
2835 // Is it already there?
2836 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2838 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2841 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2846 * Sets a string in a given generic array element
2848 * @param $keyGroup Main group for the key
2849 * @param $subGroup Sub group for the key
2850 * @param $key Key to unset
2851 * @param $element Element to check
2852 * @param $value Value to add/append
2855 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2857 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE) . ',appendGlue=' . $appendGlue);
2860 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2864 * Initializes given generic array group
2866 * @param $keyGroup Main group for the key
2867 * @param $subGroup Sub group for the key
2868 * @param $key Key to use
2869 * @param $forceInit Optionally force initialization
2872 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2874 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2876 // Is it already set?
2877 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2878 // Already initialized
2879 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2884 $this->genericArray[$keyGroup][$subGroup] = array();
2888 * Initializes given generic array key
2890 * @param $keyGroup Main group for the key
2891 * @param $subGroup Sub group for the key
2892 * @param $key Key to use
2893 * @param $forceInit Optionally force initialization
2896 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2898 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2900 // Is it already set?
2901 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2902 // Already initialized
2903 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2908 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2912 * Initializes given generic array element
2914 * @param $keyGroup Main group for the key
2915 * @param $subGroup Sub group for the key
2916 * @param $key Key to use
2917 * @param $element Element to use
2918 * @param $forceInit Optionally force initialization
2921 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2923 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2925 // Is it already set?
2926 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2927 // Already initialized
2928 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2933 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2937 * Pushes an element to a generic key
2939 * @param $keyGroup Main group for the key
2940 * @param $subGroup Sub group for the key
2941 * @param $key Key to use
2942 * @param $value Value to add/append
2943 * @return $count Number of array elements
2945 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2947 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2950 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2952 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2956 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2959 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2960 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2965 * Pushes an element to a generic array element
2967 * @param $keyGroup Main group for the key
2968 * @param $subGroup Sub group for the key
2969 * @param $key Key to use
2970 * @param $element Element to check
2971 * @param $value Value to add/append
2972 * @return $count Number of array elements
2974 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2976 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2979 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2981 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2985 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2988 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2989 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2994 * Pops an element from a generic group
2996 * @param $keyGroup Main group for the key
2997 * @param $subGroup Sub group for the key
2998 * @param $key Key to unset
2999 * @return $value Last "popped" value
3001 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
3003 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3006 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3008 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3013 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3016 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3017 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3022 * Shifts an element from a generic group
3024 * @param $keyGroup Main group for the key
3025 * @param $subGroup Sub group for the key
3026 * @param $key Key to unset
3027 * @return $value Last "popped" value
3029 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3031 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3034 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3036 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3041 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3044 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3045 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3050 * Count generic array group
3052 * @param $keyGroup Main group for the key
3053 * @return $count Count of given group
3055 protected final function countGenericArray ($keyGroup) {
3057 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3060 if (!isset($this->genericArray[$keyGroup])) {
3062 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3067 $count = count($this->genericArray[$keyGroup]);
3070 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3077 * Count generic array sub group
3079 * @param $keyGroup Main group for the key
3080 * @param $subGroup Sub group for the key
3081 * @return $count Count of given group
3083 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3085 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3088 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3090 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3095 $count = count($this->genericArray[$keyGroup][$subGroup]);
3098 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3105 * Count generic array elements
3107 * @param $keyGroup Main group for the key
3108 * @param $subGroup Sub group for the key
3109 * @para $key Key to count
3110 * @return $count Count of given key
3112 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3114 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3117 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3119 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3121 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3123 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3128 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3131 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3138 * Getter for whole generic group array
3140 * @param $keyGroup Key group to get
3141 * @return $array Whole generic array group
3143 protected final function getGenericArray ($keyGroup) {
3145 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3148 if (!isset($this->genericArray[$keyGroup])) {
3150 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3155 return $this->genericArray[$keyGroup];
3159 * Setter for generic array key
3161 * @param $keyGroup Key group to get
3162 * @param $subGroup Sub group for the key
3163 * @param $key Key to unset
3164 * @param $value Mixed value from generic array element
3167 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3169 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3172 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3176 * Getter for generic array key
3178 * @param $keyGroup Key group to get
3179 * @param $subGroup Sub group for the key
3180 * @param $key Key to unset
3181 * @return $value Mixed value from generic array element
3183 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3185 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3188 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3190 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3195 return $this->genericArray[$keyGroup][$subGroup][$key];
3199 * Sets a value in given generic array key/element
3201 * @param $keyGroup Main group for the key
3202 * @param $subGroup Sub group for the key
3203 * @param $key Key to set
3204 * @param $element Element to set
3205 * @param $value Value to set
3208 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3210 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3213 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3217 * Getter for generic array element
3219 * @param $keyGroup Key group to get
3220 * @param $subGroup Sub group for the key
3221 * @param $key Key to look for
3222 * @param $element Element to look for
3223 * @return $value Mixed value from generic array element
3225 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3227 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3230 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3232 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3237 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3241 * Checks if a given sub group is valid (array)
3243 * @param $keyGroup Key group to get
3244 * @param $subGroup Sub group for the key
3245 * @return $isValid Whether given sub group is valid
3247 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3249 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3252 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3259 * Checks if a given key is valid (array)
3261 * @param $keyGroup Key group to get
3262 * @param $subGroup Sub group for the key
3263 * @param $key Key to check
3264 * @return $isValid Whether given sub group is valid
3266 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3268 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3271 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3278 * Initializes the web output instance
3282 protected function initWebOutputInstance () {
3283 // Get application instance
3284 $applicationInstance = Registry::getRegistry()->getInstance('app');
3286 // Is this a response instance?
3287 if ($this instanceof Responseable) {
3288 // Then set it in application instance
3289 $applicationInstance->setResponseInstance($this);
3292 // Init web output instance
3293 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3296 $this->setWebOutputInstance($outputInstance);
3300 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3302 * @param $boolean Boolean value
3303 * @return $translated Translated boolean value
3305 public static final function translateBooleanToYesNo ($boolean) {
3306 // Make sure it is really boolean
3307 assert(is_bool($boolean));
3310 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3312 // ... and return it
3317 * Encodes raw data (almost any type) by "serializing" it and then pack it
3318 * into a "binary format".
3320 * @param $rawData Raw data (almost any type)
3321 * @return $encoded Encoded data
3323 protected function encodeData ($rawData) {
3324 // Make sure no objects or resources pass through
3325 assert(!is_object($rawData));
3326 assert(!is_resource($rawData));
3328 // First "serialize" it (json_encode() is faster than serialize())
3329 $encoded = $this->packString(json_encode($rawData));
3336 * Pack a string into a "binary format". Please execuse me that this is
3337 * widely undocumented. :-(
3339 * @param $str Unpacked string
3340 * @return $packed Packed string
3341 * @todo Improve documentation
3343 protected function packString ($str) {
3345 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3347 // First compress the string (gzcompress is okay)
3348 $str = gzcompress($str);
3353 // And start the "encoding" loop
3354 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3356 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3357 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3359 if (($idx + $i) <= strlen($str)) {
3360 $ord = ord(substr($str, ($idx + $i), 1));
3362 $add = $ord * pow(256, $factor);
3366 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3370 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3371 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3373 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3374 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3380 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3385 * Checks whether the given file/path is in open_basedir(). This does not
3386 * gurantee that the file is actually readable and/or writeable. If you need
3387 * such gurantee then please use isReadableFile() instead.
3389 * @param $filePathName Name of the file/path to be checked
3390 * @return $isReachable Whether it is within open_basedir()
3392 protected static function isReachableFilePath ($filePathName) {
3393 // Is not reachable by default
3394 $isReachable = FALSE;
3396 // Get open_basedir parameter
3397 $openBaseDir = ini_get('open_basedir');
3400 if (!empty($openBaseDir)) {
3401 // Check all entries
3402 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3403 // Check on existence
3404 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3406 $isReachable = TRUE;
3410 // If open_basedir is not set, all is allowed
3411 $isReachable = TRUE;
3415 return $isReachable;
3419 * Checks whether the give file is within open_basedir() (done by
3420 * isReachableFilePath()), is actually a file and is readable.
3422 * @param $fileName Name of the file to be checked
3423 * @return $isReadable Whether the file is readable (and therefor exists)
3425 public static function isReadableFile ($fileName) {
3426 // Default is not readable
3427 $isReadable = FALSE;
3429 // Is within parameters, so check if it is a file and readable
3430 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3437 * Creates a full-qualified file name (FQFN) for given file name by adding
3438 * a configured temporary file path to it.
3440 * @param $fileName Name for temporary file
3441 * @return $fqfn Full-qualified file name
3442 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3443 * @throws FileIoException If the file cannot be written
3445 protected static function createTempPathForFile ($fileName) {
3447 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3449 // Is the path writeable?
3450 if (!is_writable($basePath)) {
3451 // Path is write-protected
3452 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3456 $fqfn = $basePath . '/' . $fileName;
3459 if (!self::isReachableFilePath($fqfn)) {
3461 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3469 * "Getter" for a printable state name
3471 * @return $stateName Name of the node's state in a printable format
3473 public final function getPrintableState () {
3474 // Default is 'null'
3475 $stateName = 'null';
3477 // Get the state instance
3478 $stateInstance = $this->getStateInstance();
3480 // Is it an instance of Stateable?
3481 if ($stateInstance instanceof Stateable) {
3482 // Then use that state name
3483 $stateName = $stateInstance->getStateName();
3491 * Handles socket error for given socket resource and peer data. This method
3492 * validates $socketResource if it is a valid resource (see is_resource())
3493 * but assumes valid data in array $recipientData, except that
3494 * count($recipientData) is always 2.
3496 * @param $method Value of __METHOD__ from calling method
3497 * @param $line Value of __LINE__ from calling method
3498 * @param $socketResource A valid socket resource
3499 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3501 * @throws InvalidSocketException If $socketResource is no socket resource
3502 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3503 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3505 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3506 // This method handles only socket resources
3507 if (!is_resource($socketResource)) {
3508 // No resource, abort here
3509 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3512 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3513 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3514 assert(isset($socketData[0]));
3515 assert(isset($socketData[1]));
3517 // Get error code for first validation (0 is not an error)
3518 $errorCode = socket_last_error($socketResource);
3520 // If the error code is zero, someone called this method without an error
3521 if ($errorCode == 0) {
3522 // No error detected (or previously cleared outside this method)
3523 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3526 // Get handler (method) name
3527 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3529 // Call-back the error handler method
3530 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3532 // Finally clear the error because it has been handled
3533 socket_clear_error($socketResource);