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\Generic\UnsupportedOperationException;
26 use CoreFramework\Handler\Stream\IoHandler;
27 use CoreFramework\Index\Indexable;
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\State\Stateable;
41 use CoreFramework\Stream\Output\OutputStreamer;
42 use CoreFramework\Template\CompileableTemplate;
43 use CoreFramework\User\ManageableAccount;
44 use CoreFramework\Visitor\Visitor;
52 * The simulator system class is the super class of all other classes. This
53 * class handles saving of games etc.
55 * @author Roland Haeder <webmaster@shipsimu.org>
57 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
58 * @license GNU GPL 3.0 or any newer version
59 * @link http://www.shipsimu.org
61 * This program is free software: you can redistribute it and/or modify
62 * it under the terms of the GNU General Public License as published by
63 * the Free Software Foundation, either version 3 of the License, or
64 * (at your option) any later version.
66 * This program is distributed in the hope that it will be useful,
67 * but WITHOUT ANY WARRANTY; without even the implied warranty of
68 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
69 * GNU General Public License for more details.
71 * You should have received a copy of the GNU General Public License
72 * along with this program. If not, see <http://www.gnu.org/licenses/>.
74 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
76 * Length of output from hash()
78 private static $hashLength = NULL;
83 private $realClass = 'BaseFrameworkSystem';
86 * Search criteria instance
88 private $searchInstance = NULL;
91 * Update criteria instance
93 private $updateInstance = NULL;
96 * The file I/O instance for the template loader
98 private $fileIoInstance = NULL;
103 private $resolverInstance = NULL;
106 * Template engine instance
108 private $templateInstance = NULL;
111 * Database result instance
113 private $resultInstance = NULL;
116 * Instance for user class
118 private $userInstance = NULL;
121 * A controller instance
123 private $controllerInstance = NULL;
128 private $rngInstance = NULL;
131 * Instance of a crypto helper
133 private $cryptoInstance = NULL;
136 * Instance of an Iterator class
138 private $iteratorInstance = NULL;
141 * Instance of the list
143 private $listInstance = NULL;
148 private $menuInstance = NULL;
151 * Instance of the image
153 private $imageInstance = NULL;
156 * Instance of the stacker
158 private $stackInstance = NULL;
161 * A Compressor instance
163 private $compressorInstance = NULL;
166 * A Parseable instance
168 private $parserInstance = NULL;
171 * A HandleableProtocol instance
173 private $protocolInstance = NULL;
176 * A database wrapper instance
178 private $databaseInstance = NULL;
181 * A helper instance for the form
183 private $helperInstance = NULL;
186 * An instance of a Source class
188 private $sourceInstance = NULL;
191 * An instance of a UrlSource class
193 private $urlSourceInstance = NULL;
196 * An instance of a InputStream class
198 private $inputStreamInstance = NULL;
201 * An instance of a OutputStream class
203 private $outputStreamInstance = NULL;
206 * Networkable handler instance
208 private $handlerInstance = NULL;
211 * Visitor handler instance
213 private $visitorInstance = NULL;
218 private $dhtInstance = NULL;
221 * An instance of a database wrapper class
223 private $wrapperInstance = NULL;
226 * An instance of a file I/O pointer class (not handler)
228 private $pointerInstance = NULL;
231 * An instance of an Indexable class
233 private $indexInstance = NULL;
236 * An instance of a Block class
238 private $blockInstance = NULL;
243 private $minableInstance = NULL;
246 * A FrameworkDirectory instance
248 private $directoryInstance = NULL;
251 * An instance of a communicator
253 private $communicatorInstance = NULL;
256 * The concrete output instance
258 private $outputInstance = NULL;
263 private $stateInstance = NULL;
266 * Thousands separator
268 private $thousands = '.'; // German
273 private $decimals = ','; // German
278 private $socketResource = false;
281 * Regular expression to use for validation
283 private $regularExpression = '';
288 private $packageData = array();
293 private $genericArray = array();
298 private $commandName = '';
303 private $controllerName = '';
306 * Name of used protocol
308 private $protocolName = 'invalid';
311 * Array with bitmasks and such for pack/unpack methods to support both
312 * 32-bit and 64-bit systems
314 private $packingData = array(
317 'left' => 0xffff0000,
318 'right' => 0x0000ffff,
324 'left' => 0xffffffff00000000,
325 'right' => 0x00000000ffffffff,
332 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
334 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
336 private $archArrayElement = false;
338 /***********************
339 * Exception codes.... *
340 ***********************/
342 // @todo Try to clean these constants up
343 const EXCEPTION_IS_NULL_POINTER = 0x001;
344 const EXCEPTION_IS_NO_OBJECT = 0x002;
345 const EXCEPTION_IS_NO_ARRAY = 0x003;
346 const EXCEPTION_MISSING_METHOD = 0x004;
347 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
348 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
349 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
350 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
351 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
352 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
353 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
354 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
355 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
356 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
357 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
358 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
359 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
360 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
361 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
362 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
363 const EXCEPTION_PATH_NOT_FOUND = 0x015;
364 const EXCEPTION_INVALID_PATH_NAME = 0x016;
365 const EXCEPTION_READ_PROTECED_PATH = 0x017;
366 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
367 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
368 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
369 const EXCEPTION_INVALID_RESOURCE = 0x01b;
370 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
371 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
372 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
373 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
374 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
375 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
376 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
377 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
378 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
379 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
380 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
381 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
382 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
383 const EXCEPTION_INVALID_STRING = 0x029;
384 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
385 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
386 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
387 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
388 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
389 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
390 const EXCEPTION_MISSING_ELEMENT = 0x030;
391 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
392 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
393 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
394 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
395 const EXCEPTION_FATAL_ERROR = 0x035;
396 const EXCEPTION_FILE_NOT_FOUND = 0x036;
397 const EXCEPTION_ASSERTION_FAILED = 0x037;
398 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
399 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
400 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
401 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
402 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
403 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
406 * Hexadecimal->Decimal translation array
408 private static $hexdec = array(
428 * Decimal->hexadecimal translation array
430 private static $dechex = array(
450 * Startup time in miliseconds
452 private static $startupTime = 0;
455 * Protected super constructor
457 * @param $className Name of the class
460 protected function __construct ($className) {
462 $this->setRealClass($className);
464 // Set configuration instance if no registry ...
465 if (!$this instanceof Register) {
466 // ... because registries doesn't need to be configured
467 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
470 // Is the startup time set? (0 cannot be true anymore)
471 if (self::$startupTime == 0) {
473 self::$startupTime = microtime(true);
477 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
481 * Destructor for all classes. You should not call this method on your own.
485 public function __destruct () {
486 // Flush any updated entries to the database
487 $this->flushPendingUpdates();
489 // Is this object already destroyed?
490 if ($this->__toString() != 'DestructedObject') {
491 // Destroy all informations about this class but keep some text about it alive
492 $this->setRealClass('DestructedObject');
493 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
494 // Already destructed object
495 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
500 // Do not call this twice
501 trigger_error(__METHOD__ . ': Called twice.');
507 * The __call() method where all non-implemented methods end up
509 * @param $methodName Name of the missing method
510 * @args $args Arguments passed to the method
513 public final function __call ($methodName, $args) {
514 return self::__callStatic($methodName, $args);
518 * The __callStatic() method where all non-implemented static methods end up
520 * @param $methodName Name of the missing method
521 * @args $args Arguments passed to the method
524 public static final function __callStatic ($methodName, $args) {
526 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
528 // Init argument string
531 // Is it NULL, empty or an array?
532 if (is_null($args)) {
534 $argsString = 'NULL';
535 } elseif (is_array($args)) {
539 // Some arguments are there
540 foreach ($args as $arg) {
541 // Add data about the argument
542 $argsString .= gettype($arg) . ':';
545 // Found a NULL argument
546 $argsString .= 'NULL';
547 } elseif (is_string($arg)) {
548 // Add length for strings
549 $argsString .= strlen($arg);
550 } elseif ((is_int($arg)) || (is_float($arg))) {
553 } elseif (is_array($arg)) {
554 // .. or size if array
555 $argsString .= count($arg);
556 } elseif (is_object($arg)) {
558 $reflection = new ReflectionClass($arg);
560 // Is an other object, maybe no __toString() available
561 $argsString .= $reflection->getName();
562 } elseif ($arg === true) {
563 // ... is boolean 'true'
564 $argsString .= 'true';
565 } elseif ($arg === false) {
566 // ... is boolean 'false'
567 $argsString .= 'false';
570 // Comma for next one
575 if (substr($argsString, -2, 1) == ',') {
576 $argsString = substr($argsString, 0, -2);
582 // Invalid arguments!
583 $argsString = '!INVALID:' . gettype($args) . '!';
586 // Output stub message
587 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
588 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
598 * Getter for $realClass
600 * @return $realClass The name of the real class (not BaseFrameworkSystem)
602 public function __toString () {
603 return $this->realClass;
607 * Magic method to catch setting of missing but set class fields/attributes
609 * @param $name Name of the field/attribute
610 * @param $value Value to store
613 public final function __set ($name, $value) {
614 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
617 print_r($value, true)
622 * Magic method to catch getting of missing fields/attributes
624 * @param $name Name of the field/attribute
627 public final function __get ($name) {
628 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
634 * Magic method to catch unsetting of missing fields/attributes
636 * @param $name Name of the field/attribute
639 public final function __unset ($name) {
640 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
646 * Magic method to catch object serialization
648 * @return $unsupported Unsupported method
649 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
651 public final function __sleep () {
652 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
656 * Magic method to catch object deserialization
658 * @return $unsupported Unsupported method
659 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
661 public final function __wakeup () {
662 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
666 * Magic method to catch calls when an object instance is called
668 * @return $unsupported Unsupported method
669 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
671 public final function __invoke () {
672 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
676 * Setter for the real class name
678 * @param $realClass Class name (string)
681 public final function setRealClass ($realClass) {
683 $this->realClass = (string) $realClass;
687 * Setter for database result instance
689 * @param $resultInstance An instance of a database result class
691 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
693 protected final function setResultInstance (SearchableResult $resultInstance) {
694 $this->resultInstance = $resultInstance;
698 * Getter for database result instance
700 * @return $resultInstance An instance of a database result class
702 public final function getResultInstance () {
703 return $this->resultInstance;
707 * Setter for template engine instances
709 * @param $templateInstance An instance of a template engine class
712 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
713 $this->templateInstance = $templateInstance;
717 * Getter for template engine instances
719 * @return $templateInstance An instance of a template engine class
721 protected final function getTemplateInstance () {
722 return $this->templateInstance;
726 * Setter for search instance
728 * @param $searchInstance Searchable criteria instance
731 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
732 $this->searchInstance = $searchInstance;
736 * Getter for search instance
738 * @return $searchInstance Searchable criteria instance
740 public final function getSearchInstance () {
741 return $this->searchInstance;
745 * Setter for update instance
747 * @param $updateInstance An instance of a LocalUpdateCriteria clase
750 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
751 $this->updateInstance = $updateInstance;
755 * Getter for update instance
757 * @return $updateInstance Updateable criteria instance
759 public final function getUpdateInstance () {
760 return $this->updateInstance;
764 * Setter for resolver instance
766 * @param $resolverInstance Instance of a command resolver class
769 public final function setResolverInstance (Resolver $resolverInstance) {
770 $this->resolverInstance = $resolverInstance;
774 * Getter for resolver instance
776 * @return $resolverInstance Instance of a command resolver class
778 public final function getResolverInstance () {
779 return $this->resolverInstance;
783 * Setter for language instance
785 * @param $configInstance The configuration instance which shall
786 * be FrameworkConfiguration
789 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
790 Registry::getRegistry()->addInstance('config', $configInstance);
794 * Getter for configuration instance
796 * @return $configInstance Configuration instance
798 public final function getConfigInstance () {
799 $configInstance = Registry::getRegistry()->getInstance('config');
800 return $configInstance;
804 * Setter for debug instance
806 * @param $debugInstance The instance for debug output class
809 public final function setDebugInstance (DebugMiddleware $debugInstance) {
810 Registry::getRegistry()->addInstance('debug', $debugInstance);
814 * Getter for debug instance
816 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
818 public final function getDebugInstance () {
819 // Get debug instance
820 $debugInstance = Registry::getRegistry()->getInstance('debug');
823 return $debugInstance;
827 * Setter for web output instance
829 * @param $webInstance The instance for web output class
832 public final function setWebOutputInstance (OutputStreamer $webInstance) {
833 Registry::getRegistry()->addInstance('web_output', $webInstance);
837 * Getter for web output instance
839 * @return $webOutputInstance - Instance to class WebOutput
841 public final function getWebOutputInstance () {
842 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
843 return $webOutputInstance;
847 * Setter for database instance
849 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
852 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
853 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
857 * Getter for database layer
859 * @return $databaseInstance The database layer instance
861 public final function getDatabaseInstance () {
863 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
866 return $databaseInstance;
870 * Setter for compressor channel
872 * @param $compressorInstance An instance of CompressorChannel
875 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
876 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
880 * Getter for compressor channel
882 * @return $compressorInstance The compressor channel
884 public final function getCompressorChannel () {
885 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
886 return $compressorInstance;
890 * Protected getter for a manageable application helper class
892 * @return $applicationInstance An instance of a manageable application helper class
894 protected final function getApplicationInstance () {
895 $applicationInstance = Registry::getRegistry()->getInstance('app');
896 return $applicationInstance;
900 * Setter for a manageable application helper class
902 * @param $applicationInstance An instance of a manageable application helper class
905 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
906 Registry::getRegistry()->addInstance('application', $applicationInstance);
910 * Private getter for language instance
912 * @return $langInstance An instance to the language sub-system
914 protected final function getLanguageInstance () {
915 $langInstance = Registry::getRegistry()->getInstance('language');
916 return $langInstance;
920 * Setter for language instance
922 * @param $langInstance An instance to the language sub-system
924 * @see LanguageSystem
926 public final function setLanguageInstance (ManageableLanguage $langInstance) {
927 Registry::getRegistry()->addInstance('language', $langInstance);
931 * Private getter for file IO instance
933 * @return $fileIoInstance An instance to the file I/O sub-system
935 protected final function getFileIoInstance () {
936 return $this->fileIoInstance;
940 * Setter for file I/O instance
942 * @param $fileIoInstance An instance to the file I/O sub-system
945 public final function setFileIoInstance (IoHandler $fileIoInstance) {
946 $this->fileIoInstance = $fileIoInstance;
950 * Protected setter for user instance
952 * @param $userInstance An instance of a user class
955 protected final function setUserInstance (ManageableAccount $userInstance) {
956 $this->userInstance = $userInstance;
960 * Getter for user instance
962 * @return $userInstance An instance of a user class
964 public final function getUserInstance () {
965 return $this->userInstance;
969 * Setter for controller instance (this surely breaks a bit the MVC patterm)
971 * @param $controllerInstance An instance of the controller
974 public final function setControllerInstance (Controller $controllerInstance) {
975 $this->controllerInstance = $controllerInstance;
979 * Getter for controller instance (this surely breaks a bit the MVC patterm)
981 * @return $controllerInstance An instance of the controller
983 public final function getControllerInstance () {
984 return $this->controllerInstance;
988 * Setter for RNG instance
990 * @param $rngInstance An instance of a random number generator (RNG)
993 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
994 $this->rngInstance = $rngInstance;
998 * Getter for RNG instance
1000 * @return $rngInstance An instance of a random number generator (RNG)
1002 public final function getRngInstance () {
1003 return $this->rngInstance;
1007 * Setter for Cryptable instance
1009 * @param $cryptoInstance An instance of a Cryptable class
1012 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1013 $this->cryptoInstance = $cryptoInstance;
1017 * Getter for Cryptable instance
1019 * @return $cryptoInstance An instance of a Cryptable class
1021 public final function getCryptoInstance () {
1022 return $this->cryptoInstance;
1026 * Setter for the list instance
1028 * @param $listInstance A list of Listable
1031 protected final function setListInstance (Listable $listInstance) {
1032 $this->listInstance = $listInstance;
1036 * Getter for the list instance
1038 * @return $listInstance A list of Listable
1040 protected final function getListInstance () {
1041 return $this->listInstance;
1045 * Setter for the menu instance
1047 * @param $menuInstance A RenderableMenu instance
1050 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1051 $this->menuInstance = $menuInstance;
1055 * Getter for the menu instance
1057 * @return $menuInstance A RenderableMenu instance
1059 protected final function getMenuInstance () {
1060 return $this->menuInstance;
1064 * Setter for image instance
1066 * @param $imageInstance An instance of an image
1069 public final function setImageInstance (BaseImage $imageInstance) {
1070 $this->imageInstance = $imageInstance;
1074 * Getter for image instance
1076 * @return $imageInstance An instance of an image
1078 public final function getImageInstance () {
1079 return $this->imageInstance;
1083 * Setter for stacker instance
1085 * @param $stackInstance An instance of an stacker
1088 public final function setStackInstance (Stackable $stackInstance) {
1089 $this->stackInstance = $stackInstance;
1093 * Getter for stacker instance
1095 * @return $stackInstance An instance of an stacker
1097 public final function getStackInstance () {
1098 return $this->stackInstance;
1102 * Setter for compressor instance
1104 * @param $compressorInstance An instance of an compressor
1107 public final function setCompressorInstance (Compressor $compressorInstance) {
1108 $this->compressorInstance = $compressorInstance;
1112 * Getter for compressor instance
1114 * @return $compressorInstance An instance of an compressor
1116 public final function getCompressorInstance () {
1117 return $this->compressorInstance;
1121 * Setter for Parseable instance
1123 * @param $parserInstance An instance of an Parseable
1126 public final function setParserInstance (Parseable $parserInstance) {
1127 $this->parserInstance = $parserInstance;
1131 * Getter for Parseable instance
1133 * @return $parserInstance An instance of an Parseable
1135 public final function getParserInstance () {
1136 return $this->parserInstance;
1140 * Setter for HandleableProtocol instance
1142 * @param $protocolInstance An instance of an HandleableProtocol
1145 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1146 $this->protocolInstance = $protocolInstance;
1150 * Getter for HandleableProtocol instance
1152 * @return $protocolInstance An instance of an HandleableProtocol
1154 public final function getProtocolInstance () {
1155 return $this->protocolInstance;
1159 * Setter for DatabaseWrapper instance
1161 * @param $wrapperInstance An instance of an DatabaseWrapper
1164 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1165 $this->wrapperInstance = $wrapperInstance;
1169 * Getter for DatabaseWrapper instance
1171 * @return $wrapperInstance An instance of an DatabaseWrapper
1173 public final function getWrapperInstance () {
1174 return $this->wrapperInstance;
1178 * Setter for socket resource
1180 * @param $socketResource A valid socket resource
1183 public final function setSocketResource ($socketResource) {
1184 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1185 $this->socketResource = $socketResource;
1189 * Getter for socket resource
1191 * @return $socketResource A valid socket resource
1193 public final function getSocketResource () {
1194 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1195 return $this->socketResource;
1199 * Setter for regular expression
1201 * @param $regularExpression A valid regular expression
1204 public final function setRegularExpression ($regularExpression) {
1205 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1206 $this->regularExpression = $regularExpression;
1210 * Getter for regular expression
1212 * @return $regularExpression A valid regular expression
1214 public final function getRegularExpression () {
1215 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1216 return $this->regularExpression;
1220 * Setter for helper instance
1222 * @param $helperInstance An instance of a helper class
1225 protected final function setHelperInstance (Helper $helperInstance) {
1226 $this->helperInstance = $helperInstance;
1230 * Getter for helper instance
1232 * @return $helperInstance An instance of a helper class
1234 public final function getHelperInstance () {
1235 return $this->helperInstance;
1239 * Setter for a Source instance
1241 * @param $sourceInstance An instance of a Source class
1244 protected final function setSourceInstance (Source $sourceInstance) {
1245 $this->sourceInstance = $sourceInstance;
1249 * Getter for a Source instance
1251 * @return $sourceInstance An instance of a Source class
1253 protected final function getSourceInstance () {
1254 return $this->sourceInstance;
1258 * Setter for a UrlSource instance
1260 * @param $sourceInstance An instance of a UrlSource class
1263 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1264 $this->urlSourceInstance = $urlSourceInstance;
1268 * Getter for a UrlSource instance
1270 * @return $urlSourceInstance An instance of a UrlSource class
1272 protected final function getUrlSourceInstance () {
1273 return $this->urlSourceInstance;
1277 * Getter for a InputStream instance
1279 * @param $inputStreamInstance The InputStream instance
1281 protected final function getInputStreamInstance () {
1282 return $this->inputStreamInstance;
1286 * Setter for a InputStream instance
1288 * @param $inputStreamInstance The InputStream instance
1291 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1292 $this->inputStreamInstance = $inputStreamInstance;
1296 * Getter for a OutputStream instance
1298 * @param $outputStreamInstance The OutputStream instance
1300 protected final function getOutputStreamInstance () {
1301 return $this->outputStreamInstance;
1305 * Setter for a OutputStream instance
1307 * @param $outputStreamInstance The OutputStream instance
1310 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1311 $this->outputStreamInstance = $outputStreamInstance;
1315 * Setter for handler instance
1317 * @param $handlerInstance An instance of a Handleable class
1320 protected final function setHandlerInstance (Handleable $handlerInstance) {
1321 $this->handlerInstance = $handlerInstance;
1325 * Getter for handler instance
1327 * @return $handlerInstance A Networkable instance
1329 protected final function getHandlerInstance () {
1330 return $this->handlerInstance;
1334 * Setter for visitor instance
1336 * @param $visitorInstance A Visitor instance
1339 protected final function setVisitorInstance (Visitor $visitorInstance) {
1340 $this->visitorInstance = $visitorInstance;
1344 * Getter for visitor instance
1346 * @return $visitorInstance A Visitor instance
1348 protected final function getVisitorInstance () {
1349 return $this->visitorInstance;
1353 * Setter for DHT instance
1355 * @param $dhtInstance A Distributable instance
1358 protected final function setDhtInstance (Distributable $dhtInstance) {
1359 $this->dhtInstance = $dhtInstance;
1363 * Getter for DHT instance
1365 * @return $dhtInstance A Distributable instance
1367 protected final function getDhtInstance () {
1368 return $this->dhtInstance;
1372 * Setter for raw package Data
1374 * @param $packageData Raw package Data
1377 public final function setPackageData (array $packageData) {
1378 $this->packageData = $packageData;
1382 * Getter for raw package Data
1384 * @return $packageData Raw package Data
1386 public function getPackageData () {
1387 return $this->packageData;
1392 * Setter for Iterator instance
1394 * @param $iteratorInstance An instance of an Iterator
1397 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1398 $this->iteratorInstance = $iteratorInstance;
1402 * Getter for Iterator instance
1404 * @return $iteratorInstance An instance of an Iterator
1406 public final function getIteratorInstance () {
1407 return $this->iteratorInstance;
1411 * Setter for FilePointer instance
1413 * @param $pointerInstance An instance of an FilePointer class
1416 protected final function setPointerInstance (FilePointer $pointerInstance) {
1417 $this->pointerInstance = $pointerInstance;
1421 * Getter for FilePointer instance
1423 * @return $pointerInstance An instance of an FilePointer class
1425 public final function getPointerInstance () {
1426 return $this->pointerInstance;
1430 * Unsets pointer instance which triggers a call of __destruct() if the
1431 * instance is still there. This is surely not fatal on already "closed"
1432 * file pointer instances.
1434 * I don't want to mess around with above setter by giving it a default
1435 * value NULL as setter should always explicitly only set (existing) object
1436 * instances and NULL is NULL.
1440 protected final function unsetPointerInstance () {
1441 // Simply it to NULL
1442 $this->pointerInstance = NULL;
1446 * Setter for Indexable instance
1448 * @param $indexInstance An instance of an Indexable class
1451 protected final function setIndexInstance (Indexable $indexInstance) {
1452 $this->indexInstance = $indexInstance;
1456 * Getter for Indexable instance
1458 * @return $indexInstance An instance of an Indexable class
1460 public final function getIndexInstance () {
1461 return $this->indexInstance;
1465 * Setter for Block instance
1467 * @param $blockInstance An instance of an Block class
1470 protected final function setBlockInstance (Block $blockInstance) {
1471 $this->blockInstance = $blockInstance;
1475 * Getter for Block instance
1477 * @return $blockInstance An instance of an Block class
1479 public final function getBlockInstance () {
1480 return $this->blockInstance;
1484 * Setter for Minable instance
1486 * @param $minableInstance A Minable instance
1489 protected final function setMinableInstance (Minable $minableInstance) {
1490 $this->minableInstance = $minableInstance;
1494 * Getter for minable instance
1496 * @return $minableInstance A Minable instance
1498 protected final function getMinableInstance () {
1499 return $this->minableInstance;
1503 * Setter for FrameworkDirectory instance
1505 * @param $directoryInstance A FrameworkDirectory instance
1508 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1509 $this->directoryInstance = $directoryInstance;
1513 * Getter for FrameworkDirectory instance
1515 * @return $directoryInstance A FrameworkDirectory instance
1517 protected final function getDirectoryInstance () {
1518 return $this->directoryInstance;
1522 * Getter for communicator instance
1524 * @return $communicatorInstance An instance of a Communicator class
1526 public final function getCommunicatorInstance () {
1527 return $this->communicatorInstance;
1531 * Setter for communicator instance
1533 * @param $communicatorInstance An instance of a Communicator class
1536 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1537 $this->communicatorInstance = $communicatorInstance;
1541 * Setter for state instance
1543 * @param $stateInstance A Stateable instance
1546 public final function setStateInstance (Stateable $stateInstance) {
1547 $this->stateInstance = $stateInstance;
1551 * Getter for state instance
1553 * @return $stateInstance A Stateable instance
1555 public final function getStateInstance () {
1556 return $this->stateInstance;
1560 * Setter for output instance
1562 * @param $outputInstance The debug output instance
1565 public final function setOutputInstance (OutputStreamer $outputInstance) {
1566 $this->outputInstance = $outputInstance;
1570 * Getter for output instance
1572 * @return $outputInstance The debug output instance
1574 public final function getOutputInstance () {
1575 return $this->outputInstance;
1579 * Setter for command name
1581 * @param $commandName Last validated command name
1584 protected final function setCommandName ($commandName) {
1585 $this->commandName = $commandName;
1589 * Getter for command name
1591 * @return $commandName Last validated command name
1593 protected final function getCommandName () {
1594 return $this->commandName;
1598 * Setter for controller name
1600 * @param $controllerName Last validated controller name
1603 protected final function setControllerName ($controllerName) {
1604 $this->controllerName = $controllerName;
1608 * Getter for controller name
1610 * @return $controllerName Last validated controller name
1612 protected final function getControllerName () {
1613 return $this->controllerName;
1617 * Getter for protocol name
1619 * @return $protocolName Name of used protocol
1621 public final function getProtocolName () {
1622 return $this->protocolName;
1626 * Setter for protocol name
1628 * @param $protocolName Name of used protocol
1631 protected final function setProtocolName ($protocolName) {
1632 $this->protocolName = $protocolName;
1636 * Checks whether an object equals this object. You should overwrite this
1637 * method to implement own equality checks
1639 * @param $objectInstance An instance of a FrameworkInterface object
1640 * @return $equals Whether both objects equals
1642 public function equals (FrameworkInterface $objectInstance) {
1645 $this->__toString() == $objectInstance->__toString()
1647 $this->hashCode() == $objectInstance->hashCode()
1650 // Return the result
1655 * Generates a generic hash code of this class. You should really overwrite
1656 * this method with your own hash code generator code. But keep KISS in mind.
1658 * @return $hashCode A generic hash code respresenting this whole class
1660 public function hashCode () {
1662 return crc32($this->__toString());
1666 * Formats computer generated price values into human-understandable formats
1667 * with thousand and decimal separators.
1669 * @param $value The in computer format value for a price
1670 * @param $currency The currency symbol (use HTML-valid characters!)
1671 * @param $decNum Number of decimals after commata
1672 * @return $price The for the current language formated price string
1673 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1674 * thousands separator
1677 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1678 // Are all required attriutes set?
1679 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1680 // Throw an exception
1681 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1685 $value = (float) $value;
1687 // Reformat the US number
1688 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1690 // Return as string...
1695 * Appends a trailing slash to a string
1697 * @param $str A string (maybe) without trailing slash
1698 * @return $str A string with an auto-appended trailing slash
1700 public final function addMissingTrailingSlash ($str) {
1701 // Is there a trailing slash?
1702 if (substr($str, -1, 1) != '/') {
1706 // Return string with trailing slash
1711 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1712 * application helper instance (ApplicationHelper by default).
1714 * @param $applicationInstance An application helper instance or
1715 * null if we shall use the default
1716 * @return $templateInstance The template engine instance
1717 * @throws NullPointerException If the discovered application
1718 * instance is still null
1720 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1721 // Is the application instance set?
1722 if (is_null($applicationInstance)) {
1723 // Get the current instance
1724 $applicationInstance = Registry::getRegistry()->getInstance('app');
1727 if (is_null($applicationInstance)) {
1728 // Thrown an exception
1729 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1733 // Initialize the template engine
1734 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1736 // Return the prepared instance
1737 return $templateInstance;
1741 * Debugs this instance by putting out it's full content
1743 * @param $message Optional message to show in debug output
1746 public final function debugInstance ($message = '') {
1747 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1748 restore_error_handler();
1753 // Is a message set?
1754 if (!empty($message)) {
1755 // Construct message
1756 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1759 // Generate the output
1760 $content .= sprintf('<pre>%s</pre>',
1763 print_r($this, true)
1769 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>',
1770 $this->__toString(),
1772 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1777 * Replaces control characters with printable output
1779 * @param $str String with control characters
1780 * @return $str Replaced string
1782 protected function replaceControlCharacters ($str) {
1785 chr(13), '[r]', str_replace(
1786 chr(10), '[n]', str_replace(
1796 * Output a partial stub message for the caller method
1798 * @param $message An optional message to display
1801 protected function partialStub ($message = '') {
1802 // Get the backtrace
1803 $backtrace = debug_backtrace();
1805 // Generate the class::method string
1806 $methodName = 'UnknownClass->unknownMethod';
1807 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1808 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1811 // Construct the full message
1812 $stubMessage = sprintf('[%s:] Partial stub!',
1816 // Is the extra message given?
1817 if (!empty($message)) {
1818 // Then add it as well
1819 $stubMessage .= ' Message: ' . $message;
1822 // Debug instance is there?
1823 if (!is_null($this->getDebugInstance())) {
1824 // Output stub message
1825 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1828 trigger_error($stubMessage);
1834 * Outputs a debug backtrace and stops further script execution
1836 * @param $message An optional message to output
1837 * @param $doExit Whether exit the program (true is default)
1840 public function debugBackTrace ($message = '', $doExit = true) {
1841 // Sorry, there is no other way getting this nice backtrace
1842 if (!empty($message)) {
1844 printf('Message: %s<br />' . PHP_EOL, $message);
1848 debug_print_backtrace();
1852 if ($doExit === true) {
1858 * Creates an instance of a debugger instance
1860 * @param $className Name of the class (currently unsupported)
1861 * @param $lineNumber Line number where the call was made
1862 * @return $debugInstance An instance of a debugger class
1863 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1865 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1866 // Is the instance set?
1867 if (!Registry::getRegistry()->instanceExists('debug')) {
1868 // Init debug instance
1869 $debugInstance = NULL;
1873 // Get a debugger instance
1874 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1875 } catch (NullPointerException $e) {
1876 // Didn't work, no instance there
1877 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1880 // Empty string should be ignored and used for testing the middleware
1881 DebugMiddleware::getSelfInstance()->output('');
1883 // Set it in its own class. This will set it in the registry
1884 $debugInstance->setDebugInstance($debugInstance);
1886 // Get instance from registry
1887 $debugInstance = Registry::getRegistry()->getDebugInstance();
1891 return $debugInstance;
1895 * Simple output of a message with line-break
1897 * @param $message Message to output
1900 public function outputLine ($message) {
1902 print($message . PHP_EOL);
1906 * Outputs a debug message whether to debug instance (should be set!) or
1907 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1908 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1910 * @param $message Message we shall send out...
1911 * @param $doPrint Whether print or die here (default: print)
1912 * @paran $stripTags Whether to strip tags (default: false)
1915 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1916 // Set debug instance to NULL
1917 $debugInstance = NULL;
1921 // Get debug instance
1922 $debugInstance = $this->getDebugInstance();
1923 } catch (NullPointerException $e) {
1924 // The debug instance is not set (yet)
1927 // Is the debug instance there?
1928 if (is_object($debugInstance)) {
1929 // Use debug output handler
1930 $debugInstance->output($message, $stripTags);
1932 if ($doPrint === false) {
1933 // Die here if not printed
1937 // Are debug times enabled?
1938 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1940 $message = $this->getPrintableExecutionTime() . $message;
1944 if ($doPrint === true) {
1946 $this->outputLine($message);
1955 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1957 * @param $str The string, what ever it is needs to be converted
1958 * @return $className Generated class name
1960 public static final function convertToClassName ($str) {
1964 // Convert all dashes in underscores
1965 $str = self::convertDashesToUnderscores($str);
1967 // Now use that underscores to get classname parts for hungarian style
1968 foreach (explode('_', $str) as $strPart) {
1969 // Make the class name part lower case and first upper case
1970 $className .= ucfirst(strtolower($strPart));
1973 // Return class name
1978 * Converts dashes to underscores, e.g. useable for configuration entries
1980 * @param $str The string with maybe dashes inside
1981 * @return $str The converted string with no dashed, but underscores
1983 public static final function convertDashesToUnderscores ($str) {
1985 $str = str_replace('-', '_', $str);
1987 // Return converted string
1992 * Marks up the code by adding e.g. line numbers
1994 * @param $phpCode Unmarked PHP code
1995 * @return $markedCode Marked PHP code
1997 public function markupCode ($phpCode) {
2002 $errorArray = error_get_last();
2004 // Init the code with error message
2005 if (is_array($errorArray)) {
2007 $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>',
2008 basename($errorArray['file']),
2009 $errorArray['line'],
2010 $errorArray['message'],
2015 // Add line number to the code
2016 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2018 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2020 htmlentities($code, ENT_QUOTES)
2029 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2030 * beatiful for web-based front-ends. If null is given a message id
2031 * null_timestamp will be resolved and returned.
2033 * @param $timestamp Timestamp to prepare (filter) for display
2034 * @return $readable A readable timestamp
2036 public function doFilterFormatTimestamp ($timestamp) {
2037 // Default value to return
2040 // Is the timestamp null?
2041 if (is_null($timestamp)) {
2042 // Get a message string
2043 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2045 switch ($this->getLanguageInstance()->getLanguageCode()) {
2046 case 'de': // German format is a bit different to default
2047 // Split the GMT stamp up
2048 $dateTime = explode(' ', $timestamp );
2049 $dateArray = explode('-', $dateTime[0]);
2050 $timeArray = explode(':', $dateTime[1]);
2052 // Construct the timestamp
2053 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2063 default: // Default is pass-through
2064 $readable = $timestamp;
2074 * Filter a given number into a localized number
2076 * @param $value The raw value from e.g. database
2077 * @return $localized Localized value
2079 public function doFilterFormatNumber ($value) {
2080 // Generate it from config and localize dependencies
2081 switch ($this->getLanguageInstance()->getLanguageCode()) {
2082 case 'de': // German format is a bit different to default
2083 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2086 default: // US, etc.
2087 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2096 * "Getter" for databse entry
2098 * @return $entry An array with database entries
2099 * @throws NullPointerException If the database result is not found
2100 * @throws InvalidDatabaseResultException If the database result is invalid
2102 protected final function getDatabaseEntry () {
2103 // Is there an instance?
2104 if (!$this->getResultInstance() instanceof SearchableResult) {
2105 // Throw an exception here
2106 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2110 $this->getResultInstance()->rewind();
2112 // Do we have an entry?
2113 if ($this->getResultInstance()->valid() === false) {
2114 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2115 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2119 $this->getResultInstance()->next();
2122 $entry = $this->getResultInstance()->current();
2129 * Getter for field name
2131 * @param $fieldName Field name which we shall get
2132 * @return $fieldValue Field value from the user
2133 * @throws NullPointerException If the result instance is null
2135 public final function getField ($fieldName) {
2136 // Default field value
2139 // Get result instance
2140 $resultInstance = $this->getResultInstance();
2142 // Is this instance null?
2143 if (is_null($resultInstance)) {
2144 // Then the user instance is no longer valid (expired cookies?)
2145 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2148 // Get current array
2149 $fieldArray = $resultInstance->current();
2150 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2152 // Convert dashes to underscore
2153 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2155 // Does the field exist?
2156 if ($this->isFieldSet($fieldName)) {
2158 $fieldValue = $fieldArray[$fieldName2];
2159 } elseif (defined('DEVELOPER')) {
2160 // Missing field entry, may require debugging
2161 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2163 // Missing field entry, may require debugging
2164 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2172 * Checks if given field is set
2174 * @param $fieldName Field name to check
2175 * @return $isSet Whether the given field name is set
2176 * @throws NullPointerException If the result instance is null
2178 public function isFieldSet ($fieldName) {
2179 // Get result instance
2180 $resultInstance = $this->getResultInstance();
2182 // Is this instance null?
2183 if (is_null($resultInstance)) {
2184 // Then the user instance is no longer valid (expired cookies?)
2185 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2188 // Get current array
2189 $fieldArray = $resultInstance->current();
2190 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2192 // Convert dashes to underscore
2193 $fieldName = self::convertDashesToUnderscores($fieldName);
2196 $isSet = isset($fieldArray[$fieldName]);
2203 * Flushs all pending updates to the database layer
2207 public function flushPendingUpdates () {
2208 // Get result instance
2209 $resultInstance = $this->getResultInstance();
2211 // Do we have data to update?
2212 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2213 // Get wrapper class name config entry
2214 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2216 // Create object instance
2217 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2219 // Yes, then send the whole result to the database layer
2220 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2225 * Outputs a deprecation warning to the developer.
2227 * @param $message The message we shall output to the developer
2229 * @todo Write a logging mechanism for productive mode
2231 public function deprecationWarning ($message) {
2232 // Is developer mode active?
2233 if (defined('DEVELOPER')) {
2234 // Debug instance is there?
2235 if (!is_null($this->getDebugInstance())) {
2236 // Output stub message
2237 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2240 trigger_error($message . "<br />\n");
2244 // @TODO Finish this part!
2245 $this->partialStub('Developer mode inactive. Message:' . $message);
2250 * Checks whether the given PHP extension is loaded
2252 * @param $phpExtension The PHP extension we shall check
2253 * @return $isLoaded Whether the PHP extension is loaded
2255 public final function isPhpExtensionLoaded ($phpExtension) {
2257 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2264 * "Getter" as a time() replacement but with milliseconds. You should use this
2265 * method instead of the encapsulated getimeofday() function.
2267 * @return $milliTime Timestamp with milliseconds
2269 public function getMilliTime () {
2270 // Get the time of day as float
2271 $milliTime = gettimeofday(true);
2278 * Idles (sleeps) for given milliseconds
2280 * @return $hasSlept Whether it goes fine
2282 public function idle ($milliSeconds) {
2283 // Sleep is fine by default
2286 // Idle so long with found function
2287 if (function_exists('time_sleep_until')) {
2288 // Get current time and add idle time
2289 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2291 // New PHP 5.1.0 function found, ignore errors
2292 $hasSlept = @time_sleep_until($sleepUntil);
2295 * My Sun station doesn't have that function even with latest PHP
2298 usleep($milliSeconds * 1000);
2305 * Converts a hexadecimal string, even with negative sign as first string to
2306 * a decimal number using BC functions.
2308 * This work is based on comment #86673 on php.net documentation page at:
2309 * <http://de.php.net/manual/en/function.dechex.php#86673>
2311 * @param $hex Hexadecimal string
2312 * @return $dec Decimal number
2314 protected function hex2dec ($hex) {
2315 // Convert to all lower-case
2316 $hex = strtolower($hex);
2318 // Detect sign (negative/positive numbers)
2320 if (substr($hex, 0, 1) == '-') {
2322 $hex = substr($hex, 1);
2325 // Decode the hexadecimal string into a decimal number
2327 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2328 $factor = self::$hexdec[substr($hex, $i, 1)];
2329 $dec = bcadd($dec, bcmul($factor, $e));
2332 // Return the decimal number
2333 return $sign . $dec;
2337 * Converts even very large decimal numbers, also signed, to a hexadecimal
2340 * This work is based on comment #97756 on php.net documentation page at:
2341 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2343 * @param $dec Decimal number, even with negative sign
2344 * @param $maxLength Optional maximum length of the string
2345 * @return $hex Hexadecimal string
2347 protected function dec2hex ($dec, $maxLength = 0) {
2348 // maxLength can be zero or devideable by 2
2349 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2351 // Detect sign (negative/positive numbers)
2358 // Encode the decimal number into a hexadecimal string
2361 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2363 } while ($dec >= 1);
2366 * Leading zeros are required for hex-decimal "numbers". In some
2367 * situations more leading zeros are wanted, so check for both
2370 if ($maxLength > 0) {
2371 // Prepend more zeros
2372 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2373 } elseif ((strlen($hex) % 2) != 0) {
2374 // Only make string's length dividable by 2
2378 // Return the hexadecimal string
2379 return $sign . $hex;
2383 * Converts a ASCII string (0 to 255) into a decimal number.
2385 * @param $asc The ASCII string to be converted
2386 * @return $dec Decimal number
2388 protected function asc2dec ($asc) {
2389 // Convert it into a hexadecimal number
2390 $hex = bin2hex($asc);
2392 // And back into a decimal number
2393 $dec = $this->hex2dec($hex);
2400 * Converts a decimal number into an ASCII string.
2402 * @param $dec Decimal number
2403 * @return $asc An ASCII string
2405 protected function dec2asc ($dec) {
2406 // First convert the number into a hexadecimal string
2407 $hex = $this->dec2hex($dec);
2409 // Then convert it into the ASCII string
2410 $asc = $this->hex2asc($hex);
2417 * Converts a hexadecimal number into an ASCII string. Negative numbers
2420 * @param $hex Hexadecimal string
2421 * @return $asc An ASCII string
2423 protected function hex2asc ($hex) {
2424 // Check for length, it must be devideable by 2
2425 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2426 assert((strlen($hex) % 2) == 0);
2430 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2431 // Get the decimal number of the chunk
2432 $part = hexdec(substr($hex, $idx, 2));
2434 // Add it to the final string
2438 // Return the final string
2443 * Checks whether the given encoded data was encoded with Base64
2445 * @param $encodedData Encoded data we shall check
2446 * @return $isBase64 Whether the encoded data is Base64
2448 protected function isBase64Encoded ($encodedData) {
2450 $isBase64 = (@base64_decode($encodedData, true) !== false);
2457 * Gets a cache key from Criteria instance
2459 * @param $criteriaInstance An instance of a Criteria class
2460 * @param $onlyKeys Only use these keys for a cache key
2461 * @return $cacheKey A cache key suitable for lookup/storage purposes
2463 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2465 $cacheKey = sprintf('%s@%s',
2466 $this->__toString(),
2467 $criteriaInstance->getCacheKey($onlyKeys)
2471 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2476 * Getter for startup time in miliseconds
2478 * @return $startupTime Startup time in miliseconds
2480 protected function getStartupTime () {
2481 return self::$startupTime;
2485 * "Getter" for a printable currently execution time in nice braces
2487 * @return $executionTime Current execution time in nice braces
2489 protected function getPrintableExecutionTime () {
2490 // Caculate the execution time
2491 $executionTime = microtime(true) - $this->getStartupTime();
2493 // Pack it in nice braces
2494 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2497 return $executionTime;
2501 * Hashes a given string with a simple but stronger hash function (no salt)
2502 * and hex-encode it.
2504 * @param $str The string to be hashed
2505 * @return $hash The hash from string $str
2507 public static final function hash ($str) {
2508 // Hash given string with (better secure) hasher
2509 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2516 * "Getter" for length of hash() output. This will be "cached" to speed up
2519 * @return $length Length of hash() output
2521 public static final function getHashLength () {
2523 if (is_null(self::$hashLength)) {
2524 // No, then hash a string and save its length.
2525 self::$hashLength = strlen(self::hash('abc123'));
2529 return self::$hashLength;
2533 * Checks whether the given number is really a number (only chars 0-9).
2535 * @param $num A string consisting only chars between 0 and 9
2536 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2537 * @param $assertMismatch Whether to assert mismatches
2538 * @return $ret The (hopefully) secured numbered value
2540 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2541 // Filter all numbers out
2542 $ret = preg_replace('/[^0123456789]/', '', $num);
2545 if ($castValue === true) {
2546 // Cast to biggest numeric type
2547 $ret = (double) $ret;
2550 // Assert only if requested
2551 if ($assertMismatch === true) {
2552 // Has the whole value changed?
2553 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2561 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2563 * @param $num A string consisting only chars between 0 and 9
2564 * @param $assertMismatch Whether to assert mismatches
2565 * @return $ret The (hopefully) secured hext-numbered value
2567 public function hexval ($num, $assertMismatch = false) {
2568 // Filter all numbers out
2569 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2571 // Assert only if requested
2572 if ($assertMismatch === true) {
2573 // Has the whole value changed?
2574 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2582 * Checks whether start/end marker are set
2584 * @param $data Data to be checked
2585 * @return $isset Whether start/end marker are set
2587 public final function ifStartEndMarkersSet ($data) {
2589 $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));
2591 // ... and return it
2596 * Determines if an element is set in the generic array
2598 * @param $keyGroup Main group for the key
2599 * @param $subGroup Sub group for the key
2600 * @param $key Key to check
2601 * @param $element Element to check
2602 * @return $isset Whether the given key is set
2604 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2606 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2609 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2615 * Determines if a key is set in the generic array
2617 * @param $keyGroup Main group for the key
2618 * @param $subGroup Sub group for the key
2619 * @param $key Key to check
2620 * @return $isset Whether the given key is set
2622 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2624 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2627 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2635 * Determines if a group is set in the generic array
2637 * @param $keyGroup Main group
2638 * @param $subGroup Sub group
2639 * @return $isset Whether the given group is set
2641 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2643 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2646 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2653 * Getter for sub key group
2655 * @param $keyGroup Main key group
2656 * @param $subGroup Sub key group
2657 * @return $array An array with all array elements
2659 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2661 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2662 // No, then abort here
2663 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2668 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2671 return $this->genericArray[$keyGroup][$subGroup];
2675 * Unsets a given key in generic array
2677 * @param $keyGroup Main group for the key
2678 * @param $subGroup Sub group for the key
2679 * @param $key Key to unset
2682 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2684 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2687 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2691 * Unsets a given element in generic array
2693 * @param $keyGroup Main group for the key
2694 * @param $subGroup Sub group for the key
2695 * @param $key Key to unset
2696 * @param $element Element to unset
2699 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2701 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2704 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2708 * Append a string to a given generic array key
2710 * @param $keyGroup Main group for the key
2711 * @param $subGroup Sub group for the key
2712 * @param $key Key to unset
2713 * @param $value Value to add/append
2716 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2718 //* 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);
2720 // Is it already there?
2721 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2723 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2726 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2731 * Append a string to a given generic array element
2733 * @param $keyGroup Main group for the key
2734 * @param $subGroup Sub group for the key
2735 * @param $key Key to unset
2736 * @param $element Element to check
2737 * @param $value Value to add/append
2740 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2742 //* 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);
2744 // Is it already there?
2745 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2747 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2750 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2755 * Sets a string in a given generic array element
2757 * @param $keyGroup Main group for the key
2758 * @param $subGroup Sub group for the key
2759 * @param $key Key to unset
2760 * @param $element Element to check
2761 * @param $value Value to add/append
2764 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2766 //* 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);
2769 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2773 * Initializes given generic array group
2775 * @param $keyGroup Main group for the key
2776 * @param $subGroup Sub group for the key
2777 * @param $key Key to use
2778 * @param $forceInit Optionally force initialization
2781 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2783 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2785 // Is it already set?
2786 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2787 // Already initialized
2788 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2793 $this->genericArray[$keyGroup][$subGroup] = array();
2797 * Initializes given generic array key
2799 * @param $keyGroup Main group for the key
2800 * @param $subGroup Sub group for the key
2801 * @param $key Key to use
2802 * @param $forceInit Optionally force initialization
2805 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2807 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2809 // Is it already set?
2810 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2811 // Already initialized
2812 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2817 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2821 * Initializes given generic array element
2823 * @param $keyGroup Main group for the key
2824 * @param $subGroup Sub group for the key
2825 * @param $key Key to use
2826 * @param $element Element to use
2827 * @param $forceInit Optionally force initialization
2830 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2832 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2834 // Is it already set?
2835 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2836 // Already initialized
2837 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2842 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2846 * Pushes an element to a generic key
2848 * @param $keyGroup Main group for the key
2849 * @param $subGroup Sub group for the key
2850 * @param $key Key to use
2851 * @param $value Value to add/append
2852 * @return $count Number of array elements
2854 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2856 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2859 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2861 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2865 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2868 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2869 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2874 * Pushes an element to a generic array element
2876 * @param $keyGroup Main group for the key
2877 * @param $subGroup Sub group for the key
2878 * @param $key Key to use
2879 * @param $element Element to check
2880 * @param $value Value to add/append
2881 * @return $count Number of array elements
2883 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2885 //* 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));
2888 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2890 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2894 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2897 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2898 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2903 * Pops an element from a generic group
2905 * @param $keyGroup Main group for the key
2906 * @param $subGroup Sub group for the key
2907 * @param $key Key to unset
2908 * @return $value Last "popped" value
2910 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2912 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2915 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2917 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2922 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2925 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2926 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2931 * Shifts an element from a generic group
2933 * @param $keyGroup Main group for the key
2934 * @param $subGroup Sub group for the key
2935 * @param $key Key to unset
2936 * @return $value Last "popped" value
2938 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2940 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2943 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2945 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2950 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2953 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2954 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2959 * Count generic array group
2961 * @param $keyGroup Main group for the key
2962 * @return $count Count of given group
2964 protected final function countGenericArray ($keyGroup) {
2966 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2969 if (!isset($this->genericArray[$keyGroup])) {
2971 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2976 $count = count($this->genericArray[$keyGroup]);
2979 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2986 * Count generic array sub group
2988 * @param $keyGroup Main group for the key
2989 * @param $subGroup Sub group for the key
2990 * @return $count Count of given group
2992 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2994 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2997 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2999 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3004 $count = count($this->genericArray[$keyGroup][$subGroup]);
3007 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3014 * Count generic array elements
3016 * @param $keyGroup Main group for the key
3017 * @param $subGroup Sub group for the key
3018 * @para $key Key to count
3019 * @return $count Count of given key
3021 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3023 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3026 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3028 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3030 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3032 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3037 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3040 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3047 * Getter for whole generic group array
3049 * @param $keyGroup Key group to get
3050 * @return $array Whole generic array group
3052 protected final function getGenericArray ($keyGroup) {
3054 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3057 if (!isset($this->genericArray[$keyGroup])) {
3059 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3064 return $this->genericArray[$keyGroup];
3068 * Setter for generic array key
3070 * @param $keyGroup Key group to get
3071 * @param $subGroup Sub group for the key
3072 * @param $key Key to unset
3073 * @param $value Mixed value from generic array element
3076 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3078 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3081 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3085 * Getter for generic array key
3087 * @param $keyGroup Key group to get
3088 * @param $subGroup Sub group for the key
3089 * @param $key Key to unset
3090 * @return $value Mixed value from generic array element
3092 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3094 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3097 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3099 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3104 return $this->genericArray[$keyGroup][$subGroup][$key];
3108 * Sets a value in given generic array key/element
3110 * @param $keyGroup Main group for the key
3111 * @param $subGroup Sub group for the key
3112 * @param $key Key to set
3113 * @param $element Element to set
3114 * @param $value Value to set
3117 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3119 //* 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));
3122 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3126 * Getter for generic array element
3128 * @param $keyGroup Key group to get
3129 * @param $subGroup Sub group for the key
3130 * @param $key Key to look for
3131 * @param $element Element to look for
3132 * @return $value Mixed value from generic array element
3134 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3136 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3139 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3141 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3146 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3150 * Checks if a given sub group is valid (array)
3152 * @param $keyGroup Key group to get
3153 * @param $subGroup Sub group for the key
3154 * @return $isValid Whether given sub group is valid
3156 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3158 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3161 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3168 * Checks if a given key is valid (array)
3170 * @param $keyGroup Key group to get
3171 * @param $subGroup Sub group for the key
3172 * @param $key Key to check
3173 * @return $isValid Whether given sub group is valid
3175 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3177 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3180 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3187 * Initializes the web output instance
3191 protected function initWebOutputInstance () {
3192 // Get application instance
3193 $applicationInstance = Registry::getRegistry()->getInstance('app');
3195 // Init web output instance
3196 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3199 $this->setWebOutputInstance($outputInstance);
3203 * Translates boolean true to 'Y' and false to 'N'
3205 * @param $boolean Boolean value
3206 * @return $translated Translated boolean value
3208 public static final function translateBooleanToYesNo ($boolean) {
3209 // Make sure it is really boolean
3210 assert(is_bool($boolean));
3213 $translated = ($boolean === true) ? 'Y' : 'N';
3215 // ... and return it
3220 * Encodes raw data (almost any type) by "serializing" it and then pack it
3221 * into a "binary format".
3223 * @param $rawData Raw data (almost any type)
3224 * @return $encoded Encoded data
3226 protected function encodeData ($rawData) {
3227 // Make sure no objects or resources pass through
3228 assert(!is_object($rawData));
3229 assert(!is_resource($rawData));
3231 // First "serialize" it (json_encode() is faster than serialize())
3232 $encoded = $this->packString(json_encode($rawData));
3239 * Pack a string into a "binary format". Please execuse me that this is
3240 * widely undocumented. :-(
3242 * @param $str Unpacked string
3243 * @return $packed Packed string
3244 * @todo Improve documentation
3246 protected function packString ($str) {
3248 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3250 // First compress the string (gzcompress is okay)
3251 $str = gzcompress($str);
3256 // And start the "encoding" loop
3257 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3259 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3260 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3262 if (($idx + $i) <= strlen($str)) {
3263 $ord = ord(substr($str, ($idx + $i), 1));
3265 $add = $ord * pow(256, $factor);
3269 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3273 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3274 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3276 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3277 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3283 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3288 * Creates a full-qualified file name (FQFN) for given file name by adding
3289 * a configured temporary file path to it.
3291 * @param $fileName Name for temporary file
3292 * @return $fqfn Full-qualified file name
3293 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3294 * @throws FileIoException If the file cannot be written
3296 protected static function createTempPathForFile ($fileName) {
3298 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3300 // Is the path writeable?
3301 if (!is_writable($basePath)) {
3302 // Path is write-protected
3303 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3307 $fqfn = $basePath . '/' . $fileName;
3310 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3312 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3320 * "Getter" for a printable state name
3322 * @return $stateName Name of the node's state in a printable format
3324 public final function getPrintableState () {
3325 // Default is 'null'
3326 $stateName = 'null';
3328 // Get the state instance
3329 $stateInstance = $this->getStateInstance();
3331 // Is it an instance of Stateable?
3332 if ($stateInstance instanceof Stateable) {
3333 // Then use that state name
3334 $stateName = $stateInstance->getStateName();