3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\Compressor\Compressor;
8 use CoreFramework\Configuration\FrameworkConfiguration;
9 use CoreFramework\Connection\Database\DatabaseConnection;
10 use CoreFramework\Controller\Controller;
11 use CoreFramework\Criteria\Criteria;
12 use CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use CoreFramework\Crypto\Cryptable;
15 use CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use CoreFramework\Database\Frontend\DatabaseWrapper;
17 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
18 use CoreFramework\Factory\ObjectFactory;
19 use CoreFramework\Filesystem\Block;
20 use CoreFramework\Filesystem\FilePointer;
21 use CoreFramework\Filesystem\FrameworkDirectory;
22 use CoreFramework\Filesystem\PathWriteProtectedException;
23 use CoreFramework\Generic\FrameworkInterface;
24 use CoreFramework\Generic\NullPointerException;
25 use CoreFramework\Handler\Stream\IoHandler;
26 use CoreFramework\Index\Indexable;
27 use CoreFramework\Listener\Listenable;
28 use CoreFramework\Lists\Listable;
29 use CoreFramework\Loader\ClassLoader;
30 use CoreFramework\Manager\ManageableApplication;
31 use CoreFramework\Middleware\Compressor\CompressorChannel;
32 use CoreFramework\Middleware\Debug\DebugMiddleware;
33 use CoreFramework\Parser\Parseable;
34 use CoreFramework\Registry\Register;
35 use CoreFramework\Registry\Registry;
36 use CoreFramework\Resolver\Resolver;
37 use CoreFramework\Result\Database\CachedDatabaseResult;
38 use CoreFramework\Result\Search\SearchableResult;
39 use CoreFramework\Stacker\Stackable;
40 use CoreFramework\Stream\Output\OutputStreamer;
41 use CoreFramework\Template\CompileableTemplate;
42 use CoreFramework\User\ManageableAccount;
43 use CoreFramework\Visitor\Visitor;
51 * The simulator system class is the super class of all other classes. This
52 * class handles saving of games etc.
54 * @author Roland Haeder <webmaster@shipsimu.org>
56 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
57 * @license GNU GPL 3.0 or any newer version
58 * @link http://www.shipsimu.org
60 * This program is free software: you can redistribute it and/or modify
61 * it under the terms of the GNU General Public License as published by
62 * the Free Software Foundation, either version 3 of the License, or
63 * (at your option) any later version.
65 * This program is distributed in the hope that it will be useful,
66 * but WITHOUT ANY WARRANTY; without even the implied warranty of
67 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
68 * GNU General Public License for more details.
70 * You should have received a copy of the GNU General Public License
71 * along with this program. If not, see <http://www.gnu.org/licenses/>.
73 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
75 * Length of output from hash()
77 private static $hashLength = NULL;
82 private $realClass = 'BaseFrameworkSystem';
85 * Search criteria instance
87 private $searchInstance = NULL;
90 * Update criteria instance
92 private $updateInstance = NULL;
95 * The file I/O instance for the template loader
97 private $fileIoInstance = NULL;
102 private $resolverInstance = NULL;
105 * Template engine instance
107 private $templateInstance = NULL;
110 * Database result instance
112 private $resultInstance = NULL;
115 * Instance for user class
117 private $userInstance = NULL;
120 * A controller instance
122 private $controllerInstance = NULL;
127 private $rngInstance = NULL;
130 * Instance of a crypto helper
132 private $cryptoInstance = NULL;
135 * Instance of an Iterator class
137 private $iteratorInstance = NULL;
140 * Instance of the list
142 private $listInstance = NULL;
147 private $menuInstance = NULL;
150 * Instance of the image
152 private $imageInstance = NULL;
155 * Instance of the stacker
157 private $stackInstance = NULL;
160 * A Compressor instance
162 private $compressorInstance = NULL;
165 * A Parseable instance
167 private $parserInstance = NULL;
170 * A HandleableProtocol instance
172 private $protocolInstance = NULL;
175 * A database wrapper instance
177 private $databaseInstance = NULL;
180 * A helper instance for the form
182 private $helperInstance = NULL;
185 * An instance of a Source class
187 private $sourceInstance = NULL;
190 * An instance of a UrlSource class
192 private $urlSourceInstance = NULL;
195 * An instance of a InputStream class
197 private $inputStreamInstance = NULL;
200 * An instance of a OutputStream class
202 private $outputStreamInstance = NULL;
205 * Networkable handler instance
207 private $handlerInstance = NULL;
210 * Visitor handler instance
212 private $visitorInstance = NULL;
217 private $dhtInstance = NULL;
220 * An instance of a database wrapper class
222 private $wrapperInstance = NULL;
225 * An instance of a file I/O pointer class (not handler)
227 private $pointerInstance = NULL;
230 * An instance of an Indexable class
232 private $indexInstance = NULL;
235 * An instance of a Block class
237 private $blockInstance = NULL;
242 private $minableInstance = NULL;
245 * A FrameworkDirectory instance
247 private $directoryInstance = NULL;
252 private $listenerInstance = NULL;
255 * An instance of a communicator
257 private $communicatorInstance = NULL;
260 * The concrete output instance
262 private $outputInstance = NULL;
267 private $stateInstance = NULL;
270 * Thousands separator
272 private $thousands = '.'; // German
277 private $decimals = ','; // German
282 private $socketResource = false;
285 * Regular expression to use for validation
287 private $regularExpression = '';
292 private $packageData = array();
297 private $genericArray = array();
302 private $commandName = '';
307 private $controllerName = '';
310 * Name of used protocol
312 private $protocolName = 'invalid';
315 * Array with bitmasks and such for pack/unpack methods to support both
316 * 32-bit and 64-bit systems
318 private $packingData = array(
321 'left' => 0xffff0000,
322 'right' => 0x0000ffff,
328 'left' => 0xffffffff00000000,
329 'right' => 0x00000000ffffffff,
336 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
338 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
340 private $archArrayElement = false;
342 /***********************
343 * Exception codes.... *
344 ***********************/
346 // @todo Try to clean these constants up
347 const EXCEPTION_IS_NULL_POINTER = 0x001;
348 const EXCEPTION_IS_NO_OBJECT = 0x002;
349 const EXCEPTION_IS_NO_ARRAY = 0x003;
350 const EXCEPTION_MISSING_METHOD = 0x004;
351 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
352 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
353 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
354 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
355 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
356 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
357 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
358 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
359 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
360 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
361 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
362 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
363 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
364 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
365 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
366 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
367 const EXCEPTION_PATH_NOT_FOUND = 0x015;
368 const EXCEPTION_INVALID_PATH_NAME = 0x016;
369 const EXCEPTION_READ_PROTECED_PATH = 0x017;
370 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
371 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
372 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
373 const EXCEPTION_INVALID_RESOURCE = 0x01b;
374 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
375 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
376 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
377 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
378 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
379 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
380 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
381 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
382 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
383 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
384 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
385 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
386 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
387 const EXCEPTION_INVALID_STRING = 0x029;
388 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
389 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
390 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
391 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
392 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
393 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
394 const EXCEPTION_MISSING_ELEMENT = 0x030;
395 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
396 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
397 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
398 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
399 const EXCEPTION_FATAL_ERROR = 0x035;
400 const EXCEPTION_FILE_NOT_FOUND = 0x036;
401 const EXCEPTION_ASSERTION_FAILED = 0x037;
402 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
403 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
404 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
405 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
406 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
407 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
410 * Hexadecimal->Decimal translation array
412 private static $hexdec = array(
432 * Decimal->hexadecimal translation array
434 private static $dechex = array(
454 * Startup time in miliseconds
456 private static $startupTime = 0;
459 * Protected super constructor
461 * @param $className Name of the class
464 protected function __construct ($className) {
466 $this->setRealClass($className);
468 // Set configuration instance if no registry ...
469 if (!$this instanceof Register) {
470 // ... because registries doesn't need to be configured
471 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
474 // Is the startup time set? (0 cannot be true anymore)
475 if (self::$startupTime == 0) {
477 self::$startupTime = microtime(true);
481 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
485 * Destructor for all classes. You should not call this method on your own.
489 public function __destruct () {
490 // Flush any updated entries to the database
491 $this->flushPendingUpdates();
493 // Is this object already destroyed?
494 if ($this->__toString() != 'DestructedObject') {
495 // Destroy all informations about this class but keep some text about it alive
496 $this->setRealClass('DestructedObject');
497 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
498 // Already destructed object
499 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
504 // Do not call this twice
505 trigger_error(__METHOD__ . ': Called twice.');
511 * The __call() method where all non-implemented methods end up
513 * @param $methodName Name of the missing method
514 * @args $args Arguments passed to the method
517 public final function __call ($methodName, $args) {
518 return self::__callStatic($methodName, $args);
522 * The __callStatic() method where all non-implemented static methods end up
524 * @param $methodName Name of the missing method
525 * @args $args Arguments passed to the method
528 public static final function __callStatic ($methodName, $args) {
530 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
532 // Init argument string
535 // Is it NULL, empty or an array?
536 if (is_null($args)) {
538 $argsString = 'NULL';
539 } elseif (is_array($args)) {
543 // Some arguments are there
544 foreach ($args as $arg) {
545 // Add data about the argument
546 $argsString .= gettype($arg) . ':';
549 // Found a NULL argument
550 $argsString .= 'NULL';
551 } elseif (is_string($arg)) {
552 // Add length for strings
553 $argsString .= strlen($arg);
554 } elseif ((is_int($arg)) || (is_float($arg))) {
557 } elseif (is_array($arg)) {
558 // .. or size if array
559 $argsString .= count($arg);
560 } elseif (is_object($arg)) {
562 $reflection = new ReflectionClass($arg);
564 // Is an other object, maybe no __toString() available
565 $argsString .= $reflection->getName();
566 } elseif ($arg === true) {
567 // ... is boolean 'true'
568 $argsString .= 'true';
569 } elseif ($arg === false) {
570 // ... is boolean 'false'
571 $argsString .= 'false';
574 // Comma for next one
579 if (substr($argsString, -2, 1) == ',') {
580 $argsString = substr($argsString, 0, -2);
586 // Invalid arguments!
587 $argsString = '!INVALID:' . gettype($args) . '!';
590 // Output stub message
591 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
592 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
602 * Getter for $realClass
604 * @return $realClass The name of the real class (not BaseFrameworkSystem)
606 public function __toString () {
607 return $this->realClass;
611 * Magic method to catch setting of missing but set class fields/attributes
613 * @param $name Name of the field/attribute
614 * @param $value Value to store
617 public final function __set ($name, $value) {
618 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
621 print_r($value, true)
626 * Magic method to catch getting of missing fields/attributes
628 * @param $name Name of the field/attribute
631 public final function __get ($name) {
632 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
638 * Magic method to catch unsetting of missing fields/attributes
640 * @param $name Name of the field/attribute
643 public final function __unset ($name) {
644 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
650 * Magic method to catch object serialization
652 * @return $unsupported Unsupported method
653 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
655 public final function __sleep () {
656 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
660 * Magic method to catch object deserialization
662 * @return $unsupported Unsupported method
663 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
665 public final function __wakeup () {
666 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
670 * Magic method to catch calls when an object instance is called
672 * @return $unsupported Unsupported method
673 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
675 public final function __invoke () {
676 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
680 * Setter for the real class name
682 * @param $realClass Class name (string)
685 public final function setRealClass ($realClass) {
687 $this->realClass = (string) $realClass;
691 * Setter for database result instance
693 * @param $resultInstance An instance of a database result class
695 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
697 protected final function setResultInstance (SearchableResult $resultInstance) {
698 $this->resultInstance = $resultInstance;
702 * Getter for database result instance
704 * @return $resultInstance An instance of a database result class
706 public final function getResultInstance () {
707 return $this->resultInstance;
711 * Setter for template engine instances
713 * @param $templateInstance An instance of a template engine class
716 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
717 $this->templateInstance = $templateInstance;
721 * Getter for template engine instances
723 * @return $templateInstance An instance of a template engine class
725 protected final function getTemplateInstance () {
726 return $this->templateInstance;
730 * Setter for search instance
732 * @param $searchInstance Searchable criteria instance
735 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
736 $this->searchInstance = $searchInstance;
740 * Getter for search instance
742 * @return $searchInstance Searchable criteria instance
744 public final function getSearchInstance () {
745 return $this->searchInstance;
749 * Setter for update instance
751 * @param $updateInstance An instance of a LocalUpdateCriteria clase
754 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
755 $this->updateInstance = $updateInstance;
759 * Getter for update instance
761 * @return $updateInstance Updateable criteria instance
763 public final function getUpdateInstance () {
764 return $this->updateInstance;
768 * Setter for resolver instance
770 * @param $resolverInstance Instance of a command resolver class
773 public final function setResolverInstance (Resolver $resolverInstance) {
774 $this->resolverInstance = $resolverInstance;
778 * Getter for resolver instance
780 * @return $resolverInstance Instance of a command resolver class
782 public final function getResolverInstance () {
783 return $this->resolverInstance;
787 * Setter for language instance
789 * @param $configInstance The configuration instance which shall
790 * be FrameworkConfiguration
793 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
794 Registry::getRegistry()->addInstance('config', $configInstance);
798 * Getter for configuration instance
800 * @return $configInstance Configuration instance
802 public final function getConfigInstance () {
803 $configInstance = Registry::getRegistry()->getInstance('config');
804 return $configInstance;
808 * Setter for debug instance
810 * @param $debugInstance The instance for debug output class
813 public final function setDebugInstance (DebugMiddleware $debugInstance) {
814 Registry::getRegistry()->addInstance('debug', $debugInstance);
818 * Getter for debug instance
820 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
822 public final function getDebugInstance () {
823 // Get debug instance
824 $debugInstance = Registry::getRegistry()->getInstance('debug');
827 return $debugInstance;
831 * Setter for web output instance
833 * @param $webInstance The instance for web output class
836 public final function setWebOutputInstance (OutputStreamer $webInstance) {
837 Registry::getRegistry()->addInstance('web_output', $webInstance);
841 * Getter for web output instance
843 * @return $webOutputInstance - Instance to class WebOutput
845 public final function getWebOutputInstance () {
846 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
847 return $webOutputInstance;
851 * Setter for database instance
853 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
856 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
857 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
861 * Getter for database layer
863 * @return $databaseInstance The database layer instance
865 public final function getDatabaseInstance () {
867 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
870 return $databaseInstance;
874 * Setter for compressor channel
876 * @param $compressorInstance An instance of CompressorChannel
879 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
880 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
884 * Getter for compressor channel
886 * @return $compressorInstance The compressor channel
888 public final function getCompressorChannel () {
889 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
890 return $compressorInstance;
894 * Protected getter for a manageable application helper class
896 * @return $applicationInstance An instance of a manageable application helper class
898 protected final function getApplicationInstance () {
899 $applicationInstance = Registry::getRegistry()->getInstance('app');
900 return $applicationInstance;
904 * Setter for a manageable application helper class
906 * @param $applicationInstance An instance of a manageable application helper class
909 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
910 Registry::getRegistry()->addInstance('application', $applicationInstance);
914 * Private getter for language instance
916 * @return $langInstance An instance to the language sub-system
918 protected final function getLanguageInstance () {
919 $langInstance = Registry::getRegistry()->getInstance('language');
920 return $langInstance;
924 * Setter for language instance
926 * @param $langInstance An instance to the language sub-system
928 * @see LanguageSystem
930 public final function setLanguageInstance (ManageableLanguage $langInstance) {
931 Registry::getRegistry()->addInstance('language', $langInstance);
935 * Private getter for file IO instance
937 * @return $fileIoInstance An instance to the file I/O sub-system
939 protected final function getFileIoInstance () {
940 return $this->fileIoInstance;
944 * Setter for file I/O instance
946 * @param $fileIoInstance An instance to the file I/O sub-system
949 public final function setFileIoInstance (IoHandler $fileIoInstance) {
950 $this->fileIoInstance = $fileIoInstance;
954 * Protected setter for user instance
956 * @param $userInstance An instance of a user class
959 protected final function setUserInstance (ManageableAccount $userInstance) {
960 $this->userInstance = $userInstance;
964 * Getter for user instance
966 * @return $userInstance An instance of a user class
968 public final function getUserInstance () {
969 return $this->userInstance;
973 * Setter for controller instance (this surely breaks a bit the MVC patterm)
975 * @param $controllerInstance An instance of the controller
978 public final function setControllerInstance (Controller $controllerInstance) {
979 $this->controllerInstance = $controllerInstance;
983 * Getter for controller instance (this surely breaks a bit the MVC patterm)
985 * @return $controllerInstance An instance of the controller
987 public final function getControllerInstance () {
988 return $this->controllerInstance;
992 * Setter for RNG instance
994 * @param $rngInstance An instance of a random number generator (RNG)
997 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
998 $this->rngInstance = $rngInstance;
1002 * Getter for RNG instance
1004 * @return $rngInstance An instance of a random number generator (RNG)
1006 public final function getRngInstance () {
1007 return $this->rngInstance;
1011 * Setter for Cryptable instance
1013 * @param $cryptoInstance An instance of a Cryptable class
1016 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1017 $this->cryptoInstance = $cryptoInstance;
1021 * Getter for Cryptable instance
1023 * @return $cryptoInstance An instance of a Cryptable class
1025 public final function getCryptoInstance () {
1026 return $this->cryptoInstance;
1030 * Setter for the list instance
1032 * @param $listInstance A list of Listable
1035 protected final function setListInstance (Listable $listInstance) {
1036 $this->listInstance = $listInstance;
1040 * Getter for the list instance
1042 * @return $listInstance A list of Listable
1044 protected final function getListInstance () {
1045 return $this->listInstance;
1049 * Setter for the menu instance
1051 * @param $menuInstance A RenderableMenu instance
1054 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1055 $this->menuInstance = $menuInstance;
1059 * Getter for the menu instance
1061 * @return $menuInstance A RenderableMenu instance
1063 protected final function getMenuInstance () {
1064 return $this->menuInstance;
1068 * Setter for image instance
1070 * @param $imageInstance An instance of an image
1073 public final function setImageInstance (BaseImage $imageInstance) {
1074 $this->imageInstance = $imageInstance;
1078 * Getter for image instance
1080 * @return $imageInstance An instance of an image
1082 public final function getImageInstance () {
1083 return $this->imageInstance;
1087 * Setter for stacker instance
1089 * @param $stackInstance An instance of an stacker
1092 public final function setStackInstance (Stackable $stackInstance) {
1093 $this->stackInstance = $stackInstance;
1097 * Getter for stacker instance
1099 * @return $stackInstance An instance of an stacker
1101 public final function getStackInstance () {
1102 return $this->stackInstance;
1106 * Setter for compressor instance
1108 * @param $compressorInstance An instance of an compressor
1111 public final function setCompressorInstance (Compressor $compressorInstance) {
1112 $this->compressorInstance = $compressorInstance;
1116 * Getter for compressor instance
1118 * @return $compressorInstance An instance of an compressor
1120 public final function getCompressorInstance () {
1121 return $this->compressorInstance;
1125 * Setter for Parseable instance
1127 * @param $parserInstance An instance of an Parseable
1130 public final function setParserInstance (Parseable $parserInstance) {
1131 $this->parserInstance = $parserInstance;
1135 * Getter for Parseable instance
1137 * @return $parserInstance An instance of an Parseable
1139 public final function getParserInstance () {
1140 return $this->parserInstance;
1144 * Setter for HandleableProtocol instance
1146 * @param $protocolInstance An instance of an HandleableProtocol
1149 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1150 $this->protocolInstance = $protocolInstance;
1154 * Getter for HandleableProtocol instance
1156 * @return $protocolInstance An instance of an HandleableProtocol
1158 public final function getProtocolInstance () {
1159 return $this->protocolInstance;
1163 * Setter for DatabaseWrapper instance
1165 * @param $wrapperInstance An instance of an DatabaseWrapper
1168 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1169 $this->wrapperInstance = $wrapperInstance;
1173 * Getter for DatabaseWrapper instance
1175 * @return $wrapperInstance An instance of an DatabaseWrapper
1177 public final function getWrapperInstance () {
1178 return $this->wrapperInstance;
1182 * Setter for socket resource
1184 * @param $socketResource A valid socket resource
1187 public final function setSocketResource ($socketResource) {
1188 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1189 $this->socketResource = $socketResource;
1193 * Getter for socket resource
1195 * @return $socketResource A valid socket resource
1197 public final function getSocketResource () {
1198 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1199 return $this->socketResource;
1203 * Setter for regular expression
1205 * @param $regularExpression A valid regular expression
1208 public final function setRegularExpression ($regularExpression) {
1209 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1210 $this->regularExpression = $regularExpression;
1214 * Getter for regular expression
1216 * @return $regularExpression A valid regular expression
1218 public final function getRegularExpression () {
1219 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1220 return $this->regularExpression;
1224 * Setter for helper instance
1226 * @param $helperInstance An instance of a helper class
1229 protected final function setHelperInstance (Helper $helperInstance) {
1230 $this->helperInstance = $helperInstance;
1234 * Getter for helper instance
1236 * @return $helperInstance An instance of a helper class
1238 public final function getHelperInstance () {
1239 return $this->helperInstance;
1243 * Setter for a Source instance
1245 * @param $sourceInstance An instance of a Source class
1248 protected final function setSourceInstance (Source $sourceInstance) {
1249 $this->sourceInstance = $sourceInstance;
1253 * Getter for a Source instance
1255 * @return $sourceInstance An instance of a Source class
1257 protected final function getSourceInstance () {
1258 return $this->sourceInstance;
1262 * Setter for a UrlSource instance
1264 * @param $sourceInstance An instance of a UrlSource class
1267 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1268 $this->urlSourceInstance = $urlSourceInstance;
1272 * Getter for a UrlSource instance
1274 * @return $urlSourceInstance An instance of a UrlSource class
1276 protected final function getUrlSourceInstance () {
1277 return $this->urlSourceInstance;
1281 * Getter for a InputStream instance
1283 * @param $inputStreamInstance The InputStream instance
1285 protected final function getInputStreamInstance () {
1286 return $this->inputStreamInstance;
1290 * Setter for a InputStream instance
1292 * @param $inputStreamInstance The InputStream instance
1295 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1296 $this->inputStreamInstance = $inputStreamInstance;
1300 * Getter for a OutputStream instance
1302 * @param $outputStreamInstance The OutputStream instance
1304 protected final function getOutputStreamInstance () {
1305 return $this->outputStreamInstance;
1309 * Setter for a OutputStream instance
1311 * @param $outputStreamInstance The OutputStream instance
1314 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1315 $this->outputStreamInstance = $outputStreamInstance;
1319 * Setter for handler instance
1321 * @param $handlerInstance An instance of a Handleable class
1324 protected final function setHandlerInstance (Handleable $handlerInstance) {
1325 $this->handlerInstance = $handlerInstance;
1329 * Getter for handler instance
1331 * @return $handlerInstance A Networkable instance
1333 protected final function getHandlerInstance () {
1334 return $this->handlerInstance;
1338 * Setter for visitor instance
1340 * @param $visitorInstance A Visitor instance
1343 protected final function setVisitorInstance (Visitor $visitorInstance) {
1344 $this->visitorInstance = $visitorInstance;
1348 * Getter for visitor instance
1350 * @return $visitorInstance A Visitor instance
1352 protected final function getVisitorInstance () {
1353 return $this->visitorInstance;
1357 * Setter for DHT instance
1359 * @param $dhtInstance A Distributable instance
1362 protected final function setDhtInstance (Distributable $dhtInstance) {
1363 $this->dhtInstance = $dhtInstance;
1367 * Getter for DHT instance
1369 * @return $dhtInstance A Distributable instance
1371 protected final function getDhtInstance () {
1372 return $this->dhtInstance;
1376 * Setter for raw package Data
1378 * @param $packageData Raw package Data
1381 public final function setPackageData (array $packageData) {
1382 $this->packageData = $packageData;
1386 * Getter for raw package Data
1388 * @return $packageData Raw package Data
1390 public function getPackageData () {
1391 return $this->packageData;
1396 * Setter for Iterator instance
1398 * @param $iteratorInstance An instance of an Iterator
1401 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1402 $this->iteratorInstance = $iteratorInstance;
1406 * Getter for Iterator instance
1408 * @return $iteratorInstance An instance of an Iterator
1410 public final function getIteratorInstance () {
1411 return $this->iteratorInstance;
1415 * Setter for FilePointer instance
1417 * @param $pointerInstance An instance of an FilePointer class
1420 protected final function setPointerInstance (FilePointer $pointerInstance) {
1421 $this->pointerInstance = $pointerInstance;
1425 * Getter for FilePointer instance
1427 * @return $pointerInstance An instance of an FilePointer class
1429 public final function getPointerInstance () {
1430 return $this->pointerInstance;
1434 * Unsets pointer instance which triggers a call of __destruct() if the
1435 * instance is still there. This is surely not fatal on already "closed"
1436 * file pointer instances.
1438 * I don't want to mess around with above setter by giving it a default
1439 * value NULL as setter should always explicitly only set (existing) object
1440 * instances and NULL is NULL.
1444 protected final function unsetPointerInstance () {
1445 // Simply it to NULL
1446 $this->pointerInstance = NULL;
1450 * Setter for Indexable instance
1452 * @param $indexInstance An instance of an Indexable class
1455 protected final function setIndexInstance (Indexable $indexInstance) {
1456 $this->indexInstance = $indexInstance;
1460 * Getter for Indexable instance
1462 * @return $indexInstance An instance of an Indexable class
1464 public final function getIndexInstance () {
1465 return $this->indexInstance;
1469 * Setter for Block instance
1471 * @param $blockInstance An instance of an Block class
1474 protected final function setBlockInstance (Block $blockInstance) {
1475 $this->blockInstance = $blockInstance;
1479 * Getter for Block instance
1481 * @return $blockInstance An instance of an Block class
1483 public final function getBlockInstance () {
1484 return $this->blockInstance;
1488 * Setter for Minable instance
1490 * @param $minableInstance A Minable instance
1493 protected final function setMinableInstance (Minable $minableInstance) {
1494 $this->minableInstance = $minableInstance;
1498 * Getter for minable instance
1500 * @return $minableInstance A Minable instance
1502 protected final function getMinableInstance () {
1503 return $this->minableInstance;
1507 * Setter for FrameworkDirectory instance
1509 * @param $directoryInstance A FrameworkDirectory instance
1512 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1513 $this->directoryInstance = $directoryInstance;
1517 * Getter for FrameworkDirectory instance
1519 * @return $directoryInstance A FrameworkDirectory instance
1521 protected final function getDirectoryInstance () {
1522 return $this->directoryInstance;
1526 * Setter for listener instance
1528 * @param $listenerInstance A Listenable instance
1531 protected final function setListenerInstance (Listenable $listenerInstance) {
1532 $this->listenerInstance = $listenerInstance;
1536 * Getter for listener instance
1538 * @return $listenerInstance A Listenable instance
1540 protected final function getListenerInstance () {
1541 return $this->listenerInstance;
1545 * Getter for communicator instance
1547 * @return $communicatorInstance An instance of a Communicator class
1549 public final function getCommunicatorInstance () {
1550 return $this->communicatorInstance;
1554 * Setter for communicator instance
1556 * @param $communicatorInstance An instance of a Communicator class
1559 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1560 $this->communicatorInstance = $communicatorInstance;
1564 * Setter for state instance
1566 * @param $stateInstance A Stateable instance
1569 public final function setStateInstance (Stateable $stateInstance) {
1570 $this->stateInstance = $stateInstance;
1574 * Getter for state instance
1576 * @return $stateInstance A Stateable instance
1578 public final function getStateInstance () {
1579 return $this->stateInstance;
1583 * Setter for output instance
1585 * @param $outputInstance The debug output instance
1588 public final function setOutputInstance (OutputStreamer $outputInstance) {
1589 $this->outputInstance = $outputInstance;
1593 * Getter for output instance
1595 * @return $outputInstance The debug output instance
1597 public final function getOutputInstance () {
1598 return $this->outputInstance;
1602 * Setter for command name
1604 * @param $commandName Last validated command name
1607 protected final function setCommandName ($commandName) {
1608 $this->commandName = $commandName;
1612 * Getter for command name
1614 * @return $commandName Last validated command name
1616 protected final function getCommandName () {
1617 return $this->commandName;
1621 * Setter for controller name
1623 * @param $controllerName Last validated controller name
1626 protected final function setControllerName ($controllerName) {
1627 $this->controllerName = $controllerName;
1631 * Getter for controller name
1633 * @return $controllerName Last validated controller name
1635 protected final function getControllerName () {
1636 return $this->controllerName;
1640 * Getter for protocol name
1642 * @return $protocolName Name of used protocol
1644 public final function getProtocolName () {
1645 return $this->protocolName;
1649 * Setter for protocol name
1651 * @param $protocolName Name of used protocol
1654 protected final function setProtocolName ($protocolName) {
1655 $this->protocolName = $protocolName;
1659 * Checks whether an object equals this object. You should overwrite this
1660 * method to implement own equality checks
1662 * @param $objectInstance An instance of a FrameworkInterface object
1663 * @return $equals Whether both objects equals
1665 public function equals (FrameworkInterface $objectInstance) {
1668 $this->__toString() == $objectInstance->__toString()
1670 $this->hashCode() == $objectInstance->hashCode()
1673 // Return the result
1678 * Generates a generic hash code of this class. You should really overwrite
1679 * this method with your own hash code generator code. But keep KISS in mind.
1681 * @return $hashCode A generic hash code respresenting this whole class
1683 public function hashCode () {
1685 return crc32($this->__toString());
1689 * Formats computer generated price values into human-understandable formats
1690 * with thousand and decimal separators.
1692 * @param $value The in computer format value for a price
1693 * @param $currency The currency symbol (use HTML-valid characters!)
1694 * @param $decNum Number of decimals after commata
1695 * @return $price The for the current language formated price string
1696 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1697 * thousands separator
1700 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1701 // Are all required attriutes set?
1702 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1703 // Throw an exception
1704 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1708 $value = (float) $value;
1710 // Reformat the US number
1711 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1713 // Return as string...
1718 * Appends a trailing slash to a string
1720 * @param $str A string (maybe) without trailing slash
1721 * @return $str A string with an auto-appended trailing slash
1723 public final function addMissingTrailingSlash ($str) {
1724 // Is there a trailing slash?
1725 if (substr($str, -1, 1) != '/') {
1729 // Return string with trailing slash
1734 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1735 * application helper instance (ApplicationHelper by default).
1737 * @param $applicationInstance An application helper instance or
1738 * null if we shall use the default
1739 * @return $templateInstance The template engine instance
1740 * @throws NullPointerException If the discovered application
1741 * instance is still null
1743 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1744 // Is the application instance set?
1745 if (is_null($applicationInstance)) {
1746 // Get the current instance
1747 $applicationInstance = Registry::getRegistry()->getInstance('app');
1750 if (is_null($applicationInstance)) {
1751 // Thrown an exception
1752 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1756 // Initialize the template engine
1757 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1759 // Return the prepared instance
1760 return $templateInstance;
1764 * Debugs this instance by putting out it's full content
1766 * @param $message Optional message to show in debug output
1769 public final function debugInstance ($message = '') {
1770 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1771 restore_error_handler();
1776 // Is a message set?
1777 if (!empty($message)) {
1778 // Construct message
1779 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1782 // Generate the output
1783 $content .= sprintf('<pre>%s</pre>',
1786 print_r($this, true)
1792 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>',
1793 $this->__toString(),
1795 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1800 * Replaces control characters with printable output
1802 * @param $str String with control characters
1803 * @return $str Replaced string
1805 protected function replaceControlCharacters ($str) {
1808 chr(13), '[r]', str_replace(
1809 chr(10), '[n]', str_replace(
1819 * Output a partial stub message for the caller method
1821 * @param $message An optional message to display
1824 protected function partialStub ($message = '') {
1825 // Get the backtrace
1826 $backtrace = debug_backtrace();
1828 // Generate the class::method string
1829 $methodName = 'UnknownClass->unknownMethod';
1830 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1831 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1834 // Construct the full message
1835 $stubMessage = sprintf('[%s:] Partial stub!',
1839 // Is the extra message given?
1840 if (!empty($message)) {
1841 // Then add it as well
1842 $stubMessage .= ' Message: ' . $message;
1845 // Debug instance is there?
1846 if (!is_null($this->getDebugInstance())) {
1847 // Output stub message
1848 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1851 trigger_error($stubMessage);
1857 * Outputs a debug backtrace and stops further script execution
1859 * @param $message An optional message to output
1860 * @param $doExit Whether exit the program (true is default)
1863 public function debugBackTrace ($message = '', $doExit = true) {
1864 // Sorry, there is no other way getting this nice backtrace
1865 if (!empty($message)) {
1867 printf('Message: %s<br />' . PHP_EOL, $message);
1871 debug_print_backtrace();
1875 if ($doExit === true) {
1881 * Creates an instance of a debugger instance
1883 * @param $className Name of the class (currently unsupported)
1884 * @param $lineNumber Line number where the call was made
1885 * @return $debugInstance An instance of a debugger class
1886 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1888 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1889 // Is the instance set?
1890 if (!Registry::getRegistry()->instanceExists('debug')) {
1891 // Init debug instance
1892 $debugInstance = NULL;
1896 // Get a debugger instance
1897 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1898 } catch (NullPointerException $e) {
1899 // Didn't work, no instance there
1900 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1903 // Empty string should be ignored and used for testing the middleware
1904 DebugMiddleware::getSelfInstance()->output('');
1906 // Set it in its own class. This will set it in the registry
1907 $debugInstance->setDebugInstance($debugInstance);
1909 // Get instance from registry
1910 $debugInstance = Registry::getRegistry()->getDebugInstance();
1914 return $debugInstance;
1918 * Simple output of a message with line-break
1920 * @param $message Message to output
1923 public function outputLine ($message) {
1925 print($message . PHP_EOL);
1929 * Outputs a debug message whether to debug instance (should be set!) or
1930 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1931 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1933 * @param $message Message we shall send out...
1934 * @param $doPrint Whether print or die here (default: print)
1935 * @paran $stripTags Whether to strip tags (default: false)
1938 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1939 // Set debug instance to NULL
1940 $debugInstance = NULL;
1944 // Get debug instance
1945 $debugInstance = $this->getDebugInstance();
1946 } catch (NullPointerException $e) {
1947 // The debug instance is not set (yet)
1950 // Is the debug instance there?
1951 if (is_object($debugInstance)) {
1952 // Use debug output handler
1953 $debugInstance->output($message, $stripTags);
1955 if ($doPrint === false) {
1956 // Die here if not printed
1960 // Are debug times enabled?
1961 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1963 $message = $this->getPrintableExecutionTime() . $message;
1967 if ($doPrint === true) {
1969 $this->outputLine($message);
1978 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1980 * @param $str The string, what ever it is needs to be converted
1981 * @return $className Generated class name
1983 public static final function convertToClassName ($str) {
1987 // Convert all dashes in underscores
1988 $str = self::convertDashesToUnderscores($str);
1990 // Now use that underscores to get classname parts for hungarian style
1991 foreach (explode('_', $str) as $strPart) {
1992 // Make the class name part lower case and first upper case
1993 $className .= ucfirst(strtolower($strPart));
1996 // Return class name
2001 * Converts dashes to underscores, e.g. useable for configuration entries
2003 * @param $str The string with maybe dashes inside
2004 * @return $str The converted string with no dashed, but underscores
2006 public static final function convertDashesToUnderscores ($str) {
2008 $str = str_replace('-', '_', $str);
2010 // Return converted string
2015 * Marks up the code by adding e.g. line numbers
2017 * @param $phpCode Unmarked PHP code
2018 * @return $markedCode Marked PHP code
2020 public function markupCode ($phpCode) {
2025 $errorArray = error_get_last();
2027 // Init the code with error message
2028 if (is_array($errorArray)) {
2030 $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>',
2031 basename($errorArray['file']),
2032 $errorArray['line'],
2033 $errorArray['message'],
2038 // Add line number to the code
2039 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2041 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2043 htmlentities($code, ENT_QUOTES)
2052 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2053 * beatiful for web-based front-ends. If null is given a message id
2054 * null_timestamp will be resolved and returned.
2056 * @param $timestamp Timestamp to prepare (filter) for display
2057 * @return $readable A readable timestamp
2059 public function doFilterFormatTimestamp ($timestamp) {
2060 // Default value to return
2063 // Is the timestamp null?
2064 if (is_null($timestamp)) {
2065 // Get a message string
2066 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2068 switch ($this->getLanguageInstance()->getLanguageCode()) {
2069 case 'de': // German format is a bit different to default
2070 // Split the GMT stamp up
2071 $dateTime = explode(' ', $timestamp );
2072 $dateArray = explode('-', $dateTime[0]);
2073 $timeArray = explode(':', $dateTime[1]);
2075 // Construct the timestamp
2076 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2086 default: // Default is pass-through
2087 $readable = $timestamp;
2097 * Filter a given number into a localized number
2099 * @param $value The raw value from e.g. database
2100 * @return $localized Localized value
2102 public function doFilterFormatNumber ($value) {
2103 // Generate it from config and localize dependencies
2104 switch ($this->getLanguageInstance()->getLanguageCode()) {
2105 case 'de': // German format is a bit different to default
2106 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2109 default: // US, etc.
2110 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2119 * "Getter" for databse entry
2121 * @return $entry An array with database entries
2122 * @throws NullPointerException If the database result is not found
2123 * @throws InvalidDatabaseResultException If the database result is invalid
2125 protected final function getDatabaseEntry () {
2126 // Is there an instance?
2127 if (!$this->getResultInstance() instanceof SearchableResult) {
2128 // Throw an exception here
2129 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2133 $this->getResultInstance()->rewind();
2135 // Do we have an entry?
2136 if ($this->getResultInstance()->valid() === false) {
2137 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2138 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2142 $this->getResultInstance()->next();
2145 $entry = $this->getResultInstance()->current();
2152 * Getter for field name
2154 * @param $fieldName Field name which we shall get
2155 * @return $fieldValue Field value from the user
2156 * @throws NullPointerException If the result instance is null
2158 public final function getField ($fieldName) {
2159 // Default field value
2162 // Get result instance
2163 $resultInstance = $this->getResultInstance();
2165 // Is this instance null?
2166 if (is_null($resultInstance)) {
2167 // Then the user instance is no longer valid (expired cookies?)
2168 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2171 // Get current array
2172 $fieldArray = $resultInstance->current();
2173 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2175 // Convert dashes to underscore
2176 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2178 // Does the field exist?
2179 if ($this->isFieldSet($fieldName)) {
2181 $fieldValue = $fieldArray[$fieldName2];
2182 } elseif (defined('DEVELOPER')) {
2183 // Missing field entry, may require debugging
2184 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2186 // Missing field entry, may require debugging
2187 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2195 * Checks if given field is set
2197 * @param $fieldName Field name to check
2198 * @return $isSet Whether the given field name is set
2199 * @throws NullPointerException If the result instance is null
2201 public function isFieldSet ($fieldName) {
2202 // Get result instance
2203 $resultInstance = $this->getResultInstance();
2205 // Is this instance null?
2206 if (is_null($resultInstance)) {
2207 // Then the user instance is no longer valid (expired cookies?)
2208 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2211 // Get current array
2212 $fieldArray = $resultInstance->current();
2213 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2215 // Convert dashes to underscore
2216 $fieldName = self::convertDashesToUnderscores($fieldName);
2219 $isSet = isset($fieldArray[$fieldName]);
2226 * Flushs all pending updates to the database layer
2230 public function flushPendingUpdates () {
2231 // Get result instance
2232 $resultInstance = $this->getResultInstance();
2234 // Do we have data to update?
2235 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2236 // Get wrapper class name config entry
2237 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2239 // Create object instance
2240 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2242 // Yes, then send the whole result to the database layer
2243 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2248 * Outputs a deprecation warning to the developer.
2250 * @param $message The message we shall output to the developer
2252 * @todo Write a logging mechanism for productive mode
2254 public function deprecationWarning ($message) {
2255 // Is developer mode active?
2256 if (defined('DEVELOPER')) {
2257 // Debug instance is there?
2258 if (!is_null($this->getDebugInstance())) {
2259 // Output stub message
2260 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2263 trigger_error($message . "<br />\n");
2267 // @TODO Finish this part!
2268 $this->partialStub('Developer mode inactive. Message:' . $message);
2273 * Checks whether the given PHP extension is loaded
2275 * @param $phpExtension The PHP extension we shall check
2276 * @return $isLoaded Whether the PHP extension is loaded
2278 public final function isPhpExtensionLoaded ($phpExtension) {
2280 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2287 * "Getter" as a time() replacement but with milliseconds. You should use this
2288 * method instead of the encapsulated getimeofday() function.
2290 * @return $milliTime Timestamp with milliseconds
2292 public function getMilliTime () {
2293 // Get the time of day as float
2294 $milliTime = gettimeofday(true);
2301 * Idles (sleeps) for given milliseconds
2303 * @return $hasSlept Whether it goes fine
2305 public function idle ($milliSeconds) {
2306 // Sleep is fine by default
2309 // Idle so long with found function
2310 if (function_exists('time_sleep_until')) {
2311 // Get current time and add idle time
2312 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2314 // New PHP 5.1.0 function found, ignore errors
2315 $hasSlept = @time_sleep_until($sleepUntil);
2318 * My Sun station doesn't have that function even with latest PHP
2321 usleep($milliSeconds * 1000);
2328 * Converts a hexadecimal string, even with negative sign as first string to
2329 * a decimal number using BC functions.
2331 * This work is based on comment #86673 on php.net documentation page at:
2332 * <http://de.php.net/manual/en/function.dechex.php#86673>
2334 * @param $hex Hexadecimal string
2335 * @return $dec Decimal number
2337 protected function hex2dec ($hex) {
2338 // Convert to all lower-case
2339 $hex = strtolower($hex);
2341 // Detect sign (negative/positive numbers)
2343 if (substr($hex, 0, 1) == '-') {
2345 $hex = substr($hex, 1);
2348 // Decode the hexadecimal string into a decimal number
2350 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2351 $factor = self::$hexdec[substr($hex, $i, 1)];
2352 $dec = bcadd($dec, bcmul($factor, $e));
2355 // Return the decimal number
2356 return $sign . $dec;
2360 * Converts even very large decimal numbers, also signed, to a hexadecimal
2363 * This work is based on comment #97756 on php.net documentation page at:
2364 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2366 * @param $dec Decimal number, even with negative sign
2367 * @param $maxLength Optional maximum length of the string
2368 * @return $hex Hexadecimal string
2370 protected function dec2hex ($dec, $maxLength = 0) {
2371 // maxLength can be zero or devideable by 2
2372 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2374 // Detect sign (negative/positive numbers)
2381 // Encode the decimal number into a hexadecimal string
2384 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2386 } while ($dec >= 1);
2389 * Leading zeros are required for hex-decimal "numbers". In some
2390 * situations more leading zeros are wanted, so check for both
2393 if ($maxLength > 0) {
2394 // Prepend more zeros
2395 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2396 } elseif ((strlen($hex) % 2) != 0) {
2397 // Only make string's length dividable by 2
2401 // Return the hexadecimal string
2402 return $sign . $hex;
2406 * Converts a ASCII string (0 to 255) into a decimal number.
2408 * @param $asc The ASCII string to be converted
2409 * @return $dec Decimal number
2411 protected function asc2dec ($asc) {
2412 // Convert it into a hexadecimal number
2413 $hex = bin2hex($asc);
2415 // And back into a decimal number
2416 $dec = $this->hex2dec($hex);
2423 * Converts a decimal number into an ASCII string.
2425 * @param $dec Decimal number
2426 * @return $asc An ASCII string
2428 protected function dec2asc ($dec) {
2429 // First convert the number into a hexadecimal string
2430 $hex = $this->dec2hex($dec);
2432 // Then convert it into the ASCII string
2433 $asc = $this->hex2asc($hex);
2440 * Converts a hexadecimal number into an ASCII string. Negative numbers
2443 * @param $hex Hexadecimal string
2444 * @return $asc An ASCII string
2446 protected function hex2asc ($hex) {
2447 // Check for length, it must be devideable by 2
2448 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2449 assert((strlen($hex) % 2) == 0);
2453 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2454 // Get the decimal number of the chunk
2455 $part = hexdec(substr($hex, $idx, 2));
2457 // Add it to the final string
2461 // Return the final string
2466 * Checks whether the given encoded data was encoded with Base64
2468 * @param $encodedData Encoded data we shall check
2469 * @return $isBase64 Whether the encoded data is Base64
2471 protected function isBase64Encoded ($encodedData) {
2473 $isBase64 = (@base64_decode($encodedData, true) !== false);
2480 * Gets a cache key from Criteria instance
2482 * @param $criteriaInstance An instance of a Criteria class
2483 * @param $onlyKeys Only use these keys for a cache key
2484 * @return $cacheKey A cache key suitable for lookup/storage purposes
2486 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2488 $cacheKey = sprintf('%s@%s',
2489 $this->__toString(),
2490 $criteriaInstance->getCacheKey($onlyKeys)
2494 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2499 * Getter for startup time in miliseconds
2501 * @return $startupTime Startup time in miliseconds
2503 protected function getStartupTime () {
2504 return self::$startupTime;
2508 * "Getter" for a printable currently execution time in nice braces
2510 * @return $executionTime Current execution time in nice braces
2512 protected function getPrintableExecutionTime () {
2513 // Caculate the execution time
2514 $executionTime = microtime(true) - $this->getStartupTime();
2516 // Pack it in nice braces
2517 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2520 return $executionTime;
2524 * Hashes a given string with a simple but stronger hash function (no salt)
2525 * and hex-encode it.
2527 * @param $str The string to be hashed
2528 * @return $hash The hash from string $str
2530 public static final function hash ($str) {
2531 // Hash given string with (better secure) hasher
2532 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2539 * "Getter" for length of hash() output. This will be "cached" to speed up
2542 * @return $length Length of hash() output
2544 public static final function getHashLength () {
2546 if (is_null(self::$hashLength)) {
2547 // No, then hash a string and save its length.
2548 self::$hashLength = strlen(self::hash('abc123'));
2552 return self::$hashLength;
2556 * Checks whether the given number is really a number (only chars 0-9).
2558 * @param $num A string consisting only chars between 0 and 9
2559 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2560 * @param $assertMismatch Whether to assert mismatches
2561 * @return $ret The (hopefully) secured numbered value
2563 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2564 // Filter all numbers out
2565 $ret = preg_replace('/[^0123456789]/', '', $num);
2568 if ($castValue === true) {
2569 // Cast to biggest numeric type
2570 $ret = (double) $ret;
2573 // Assert only if requested
2574 if ($assertMismatch === true) {
2575 // Has the whole value changed?
2576 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2584 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2586 * @param $num A string consisting only chars between 0 and 9
2587 * @param $assertMismatch Whether to assert mismatches
2588 * @return $ret The (hopefully) secured hext-numbered value
2590 public function hexval ($num, $assertMismatch = false) {
2591 // Filter all numbers out
2592 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2594 // Assert only if requested
2595 if ($assertMismatch === true) {
2596 // Has the whole value changed?
2597 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2605 * Checks whether start/end marker are set
2607 * @param $data Data to be checked
2608 * @return $isset Whether start/end marker are set
2610 public final function ifStartEndMarkersSet ($data) {
2612 $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));
2614 // ... and return it
2619 * Determines if an element is set in the generic array
2621 * @param $keyGroup Main group for the key
2622 * @param $subGroup Sub group for the key
2623 * @param $key Key to check
2624 * @param $element Element to check
2625 * @return $isset Whether the given key is set
2627 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2629 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2632 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2638 * Determines if a key is set in the generic array
2640 * @param $keyGroup Main group for the key
2641 * @param $subGroup Sub group for the key
2642 * @param $key Key to check
2643 * @return $isset Whether the given key is set
2645 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2647 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2650 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2658 * Determines if a group is set in the generic array
2660 * @param $keyGroup Main group
2661 * @param $subGroup Sub group
2662 * @return $isset Whether the given group is set
2664 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2666 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2669 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2676 * Getter for sub key group
2678 * @param $keyGroup Main key group
2679 * @param $subGroup Sub key group
2680 * @return $array An array with all array elements
2682 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2684 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2685 // No, then abort here
2686 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2691 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2694 return $this->genericArray[$keyGroup][$subGroup];
2698 * Unsets a given key in generic array
2700 * @param $keyGroup Main group for the key
2701 * @param $subGroup Sub group for the key
2702 * @param $key Key to unset
2705 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2707 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2710 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2714 * Unsets a given element in generic array
2716 * @param $keyGroup Main group for the key
2717 * @param $subGroup Sub group for the key
2718 * @param $key Key to unset
2719 * @param $element Element to unset
2722 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2724 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2727 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2731 * Append a string to a given generic array key
2733 * @param $keyGroup Main group for the key
2734 * @param $subGroup Sub group for the key
2735 * @param $key Key to unset
2736 * @param $value Value to add/append
2739 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2741 //* 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);
2743 // Is it already there?
2744 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2746 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2749 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2754 * Append a string to a given generic array element
2756 * @param $keyGroup Main group for the key
2757 * @param $subGroup Sub group for the key
2758 * @param $key Key to unset
2759 * @param $element Element to check
2760 * @param $value Value to add/append
2763 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2765 //* 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);
2767 // Is it already there?
2768 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2770 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2773 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2778 * Sets a string in a given generic array element
2780 * @param $keyGroup Main group for the key
2781 * @param $subGroup Sub group for the key
2782 * @param $key Key to unset
2783 * @param $element Element to check
2784 * @param $value Value to add/append
2787 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2789 //* 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);
2792 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2796 * Initializes given generic array group
2798 * @param $keyGroup Main group for the key
2799 * @param $subGroup Sub group for the key
2800 * @param $key Key to use
2801 * @param $forceInit Optionally force initialization
2804 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2806 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2808 // Is it already set?
2809 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2810 // Already initialized
2811 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2816 $this->genericArray[$keyGroup][$subGroup] = array();
2820 * Initializes given generic array key
2822 * @param $keyGroup Main group for the key
2823 * @param $subGroup Sub group for the key
2824 * @param $key Key to use
2825 * @param $forceInit Optionally force initialization
2828 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2830 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2832 // Is it already set?
2833 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2834 // Already initialized
2835 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2840 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2844 * Initializes given generic array element
2846 * @param $keyGroup Main group for the key
2847 * @param $subGroup Sub group for the key
2848 * @param $key Key to use
2849 * @param $element Element to use
2850 * @param $forceInit Optionally force initialization
2853 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2855 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2857 // Is it already set?
2858 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2859 // Already initialized
2860 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2865 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2869 * Pushes an element to a generic key
2871 * @param $keyGroup Main group for the key
2872 * @param $subGroup Sub group for the key
2873 * @param $key Key to use
2874 * @param $value Value to add/append
2875 * @return $count Number of array elements
2877 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2879 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2882 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2884 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2888 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2891 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2892 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2897 * Pushes an element to a generic array element
2899 * @param $keyGroup Main group for the key
2900 * @param $subGroup Sub group for the key
2901 * @param $key Key to use
2902 * @param $element Element to check
2903 * @param $value Value to add/append
2904 * @return $count Number of array elements
2906 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2908 //* 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));
2911 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2913 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2917 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2920 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2921 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2926 * Pops an element from a generic group
2928 * @param $keyGroup Main group for the key
2929 * @param $subGroup Sub group for the key
2930 * @param $key Key to unset
2931 * @return $value Last "popped" value
2933 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2935 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2938 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2940 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2945 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2948 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2949 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2954 * Shifts an element from a generic group
2956 * @param $keyGroup Main group for the key
2957 * @param $subGroup Sub group for the key
2958 * @param $key Key to unset
2959 * @return $value Last "popped" value
2961 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2963 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2966 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2968 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2973 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2976 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2977 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2982 * Count generic array group
2984 * @param $keyGroup Main group for the key
2985 * @return $count Count of given group
2987 protected final function countGenericArray ($keyGroup) {
2989 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2992 if (!isset($this->genericArray[$keyGroup])) {
2994 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2999 $count = count($this->genericArray[$keyGroup]);
3002 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3009 * Count generic array sub group
3011 * @param $keyGroup Main group for the key
3012 * @param $subGroup Sub group for the key
3013 * @return $count Count of given group
3015 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3017 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3020 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3022 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3027 $count = count($this->genericArray[$keyGroup][$subGroup]);
3030 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3037 * Count generic array elements
3039 * @param $keyGroup Main group for the key
3040 * @param $subGroup Sub group for the key
3041 * @para $key Key to count
3042 * @return $count Count of given key
3044 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3046 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3049 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3051 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3053 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3055 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3060 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3063 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3070 * Getter for whole generic group array
3072 * @param $keyGroup Key group to get
3073 * @return $array Whole generic array group
3075 protected final function getGenericArray ($keyGroup) {
3077 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3080 if (!isset($this->genericArray[$keyGroup])) {
3082 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3087 return $this->genericArray[$keyGroup];
3091 * Setter for generic array key
3093 * @param $keyGroup Key group to get
3094 * @param $subGroup Sub group for the key
3095 * @param $key Key to unset
3096 * @param $value Mixed value from generic array element
3099 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3101 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3104 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3108 * Getter for generic array key
3110 * @param $keyGroup Key group to get
3111 * @param $subGroup Sub group for the key
3112 * @param $key Key to unset
3113 * @return $value Mixed value from generic array element
3115 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3117 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3120 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3122 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3127 return $this->genericArray[$keyGroup][$subGroup][$key];
3131 * Sets a value in given generic array key/element
3133 * @param $keyGroup Main group for the key
3134 * @param $subGroup Sub group for the key
3135 * @param $key Key to set
3136 * @param $element Element to set
3137 * @param $value Value to set
3140 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3142 //* 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));
3145 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3149 * Getter for generic array element
3151 * @param $keyGroup Key group to get
3152 * @param $subGroup Sub group for the key
3153 * @param $key Key to look for
3154 * @param $element Element to look for
3155 * @return $value Mixed value from generic array element
3157 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3159 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3162 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3164 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3169 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3173 * Checks if a given sub group is valid (array)
3175 * @param $keyGroup Key group to get
3176 * @param $subGroup Sub group for the key
3177 * @return $isValid Whether given sub group is valid
3179 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3181 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3184 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3191 * Checks if a given key is valid (array)
3193 * @param $keyGroup Key group to get
3194 * @param $subGroup Sub group for the key
3195 * @param $key Key to check
3196 * @return $isValid Whether given sub group is valid
3198 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3200 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3203 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3210 * Initializes the web output instance
3214 protected function initWebOutputInstance () {
3215 // Get application instance
3216 $applicationInstance = Registry::getRegistry()->getInstance('app');
3218 // Init web output instance
3219 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3222 $this->setWebOutputInstance($outputInstance);
3226 * Translates boolean true to 'Y' and false to 'N'
3228 * @param $boolean Boolean value
3229 * @return $translated Translated boolean value
3231 public static final function translateBooleanToYesNo ($boolean) {
3232 // Make sure it is really boolean
3233 assert(is_bool($boolean));
3236 $translated = ($boolean === true) ? 'Y' : 'N';
3238 // ... and return it
3243 * Encodes raw data (almost any type) by "serializing" it and then pack it
3244 * into a "binary format".
3246 * @param $rawData Raw data (almost any type)
3247 * @return $encoded Encoded data
3249 protected function encodeData ($rawData) {
3250 // Make sure no objects or resources pass through
3251 assert(!is_object($rawData));
3252 assert(!is_resource($rawData));
3254 // First "serialize" it (json_encode() is faster than serialize())
3255 $encoded = $this->packString(json_encode($rawData));
3262 * Pack a string into a "binary format". Please execuse me that this is
3263 * widely undocumented. :-(
3265 * @param $str Unpacked string
3266 * @return $packed Packed string
3267 * @todo Improve documentation
3269 protected function packString ($str) {
3271 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3273 // First compress the string (gzcompress is okay)
3274 $str = gzcompress($str);
3279 // And start the "encoding" loop
3280 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3282 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3283 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3285 if (($idx + $i) <= strlen($str)) {
3286 $ord = ord(substr($str, ($idx + $i), 1));
3288 $add = $ord * pow(256, $factor);
3292 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3296 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3297 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3299 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3300 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3306 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3311 * Creates a full-qualified file name (FQFN) for given file name by adding
3312 * a configured temporary file path to it.
3314 * @param $fileName Name for temporary file
3315 * @return $fqfn Full-qualified file name
3316 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3317 * @throws FileIoException If the file cannot be written
3319 protected static function createTempPathForFile ($fileName) {
3321 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3323 // Is the path writeable?
3324 if (!is_writable($basePath)) {
3325 // Path is write-protected
3326 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3330 $fqfn = $basePath . '/' . $fileName;
3333 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3335 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3343 * "Getter" for a printable state name
3345 * @return $stateName Name of the node's state in a printable format
3347 public final function getPrintableState () {
3348 // Default is 'null'
3349 $stateName = 'null';
3351 // Get the state instance
3352 $stateInstance = $this->getStateInstance();
3354 // Is it an instance of Stateable?
3355 if ($stateInstance instanceof Stateable) {
3356 // Then use that state name
3357 $stateName = $stateInstance->getStateName();
3365 * Handles socket error for given socket resource and peer data. This method
3366 * validates $socketResource if it is a valid resource (see is_resource())
3367 * but assumes valid data in array $recipientData, except that
3368 * count($recipientData) is always 2.
3370 * @param $method Value of __METHOD__ from calling method
3371 * @param $line Value of __LINE__ from calling method
3372 * @param $socketResource A valid socket resource
3373 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3375 * @throws InvalidSocketException If $socketResource is no socket resource
3376 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3377 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3379 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3380 // This method handles only socket resources
3381 if (!is_resource($socketResource)) {
3382 // No resource, abort here
3383 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3386 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3387 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, true));
3388 assert(isset($socketData[0]));
3389 assert(isset($socketData[1]));
3391 // Get error code for first validation (0 is not an error)
3392 $errorCode = socket_last_error($socketResource);
3394 // If the error code is zero, someone called this method without an error
3395 if ($errorCode == 0) {
3396 // No error detected (or previously cleared outside this method)
3397 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3400 // Get handler (method) name
3401 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3403 // Call-back the error handler method
3404 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3406 // Finally clear the error because it has been handled
3407 socket_clear_error($socketResource);