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\EntryPoint\ApplicationEntryPoint;
18 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
19 use CoreFramework\Factory\ObjectFactory;
20 use CoreFramework\Filesystem\Block;
21 use CoreFramework\Filesystem\FilePointer;
22 use CoreFramework\Filesystem\FrameworkDirectory;
23 use CoreFramework\Filesystem\PathWriteProtectedException;
24 use CoreFramework\Generic\FrameworkInterface;
25 use CoreFramework\Generic\NullPointerException;
26 use CoreFramework\Generic\UnsupportedOperationException;
27 use CoreFramework\Handler\Handleable;
28 use CoreFramework\Handler\Stream\IoHandler;
29 use CoreFramework\Helper\Helper;
30 use CoreFramework\Index\Indexable;
31 use CoreFramework\Lists\Listable;
32 use CoreFramework\Loader\ClassLoader;
33 use CoreFramework\Manager\ManageableApplication;
34 use CoreFramework\Middleware\Compressor\CompressorChannel;
35 use CoreFramework\Middleware\Debug\DebugMiddleware;
36 use CoreFramework\Parser\Parseable;
37 use CoreFramework\Registry\Register;
38 use CoreFramework\Registry\Registry;
39 use CoreFramework\Resolver\Resolver;
40 use CoreFramework\Result\Database\CachedDatabaseResult;
41 use CoreFramework\Result\Search\SearchableResult;
42 use CoreFramework\Stacker\Stackable;
43 use CoreFramework\State\Stateable;
44 use CoreFramework\Stream\Input\InputStream;
45 use CoreFramework\Stream\Output\OutputStreamer;
46 use CoreFramework\Stream\Output\OutputStream;
47 use CoreFramework\Template\CompileableTemplate;
48 use CoreFramework\User\ManageableAccount;
49 use CoreFramework\Visitor\Visitor;
57 * The simulator system class is the super class of all other classes. This
58 * class handles saving of games etc.
60 * @author Roland Haeder <webmaster@shipsimu.org>
62 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
63 * @license GNU GPL 3.0 or any newer version
64 * @link http://www.shipsimu.org
66 * This program is free software: you can redistribute it and/or modify
67 * it under the terms of the GNU General Public License as published by
68 * the Free Software Foundation, either version 3 of the License, or
69 * (at your option) any later version.
71 * This program is distributed in the hope that it will be useful,
72 * but WITHOUT ANY WARRANTY; without even the implied warranty of
73 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
74 * GNU General Public License for more details.
76 * You should have received a copy of the GNU General Public License
77 * along with this program. If not, see <http://www.gnu.org/licenses/>.
79 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
81 * Length of output from hash()
83 private static $hashLength = NULL;
88 private $realClass = 'BaseFrameworkSystem';
91 * Search criteria instance
93 private $searchInstance = NULL;
96 * Update criteria instance
98 private $updateInstance = NULL;
101 * The file I/O instance for the template loader
103 private $fileIoInstance = NULL;
108 private $resolverInstance = NULL;
111 * Template engine instance
113 private $templateInstance = NULL;
116 * Database result instance
118 private $resultInstance = NULL;
121 * Instance for user class
123 private $userInstance = NULL;
126 * A controller instance
128 private $controllerInstance = NULL;
133 private $rngInstance = NULL;
136 * Instance of a crypto helper
138 private $cryptoInstance = NULL;
141 * Instance of an Iterator class
143 private $iteratorInstance = NULL;
146 * Instance of the list
148 private $listInstance = NULL;
153 private $menuInstance = NULL;
156 * Instance of the image
158 private $imageInstance = NULL;
161 * Instance of the stacker
163 private $stackInstance = NULL;
166 * A Compressor instance
168 private $compressorInstance = NULL;
171 * A Parseable instance
173 private $parserInstance = 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;
208 private $handlerInstance = NULL;
211 * Visitor handler instance
213 private $visitorInstance = NULL;
216 * An instance of a database wrapper class
218 private $wrapperInstance = NULL;
221 * An instance of a file I/O pointer class (not handler)
223 private $pointerInstance = NULL;
226 * An instance of an Indexable class
228 private $indexInstance = NULL;
231 * An instance of a Block class
233 private $blockInstance = NULL;
238 private $minableInstance = NULL;
241 * A FrameworkDirectory instance
243 private $directoryInstance = NULL;
246 * An instance of a communicator
248 private $communicatorInstance = NULL;
251 * The concrete output instance
253 private $outputInstance = NULL;
258 private $stateInstance = NULL;
261 * Registry instance (implementing Register)
263 private $registryInstance = NULL;
268 private $callbackInstance = NULL;
271 * Thousands separator
273 private $thousands = '.'; // German
278 private $decimals = ','; // German
283 private $socketResource = false;
286 * Regular expression to use for validation
288 private $regularExpression = '';
293 private $packageData = array();
298 private $genericArray = array();
303 private $commandName = '';
308 private $controllerName = '';
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;
404 const EXCEPTION_INVALID_SOCKET = 0x03e;
407 * Hexadecimal->Decimal translation array
409 private static $hexdec = array(
429 * Decimal->hexadecimal translation array
431 private static $dechex = array(
451 * Startup time in miliseconds
453 private static $startupTime = 0;
456 * Protected super constructor
458 * @param $className Name of the class
461 protected function __construct ($className) {
463 $this->setRealClass($className);
465 // Set configuration instance if no registry ...
466 if (!$this instanceof Register) {
467 // ... because registries doesn't need to be configured
468 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
471 // Is the startup time set? (0 cannot be true anymore)
472 if (self::$startupTime == 0) {
474 self::$startupTime = microtime(true);
478 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
482 * Destructor for all classes. You should not call this method on your own.
486 public function __destruct () {
487 // Flush any updated entries to the database
488 $this->flushPendingUpdates();
490 // Is this object already destroyed?
491 if ($this->__toString() != 'DestructedObject') {
492 // Destroy all informations about this class but keep some text about it alive
493 $this->setRealClass('DestructedObject');
494 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
495 // Already destructed object
496 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('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 DatabaseWrapper instance
1142 * @param $wrapperInstance An instance of an DatabaseWrapper
1145 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1146 $this->wrapperInstance = $wrapperInstance;
1150 * Getter for DatabaseWrapper instance
1152 * @return $wrapperInstance An instance of an DatabaseWrapper
1154 public final function getWrapperInstance () {
1155 return $this->wrapperInstance;
1159 * Setter for socket resource
1161 * @param $socketResource A valid socket resource
1164 public final function setSocketResource ($socketResource) {
1165 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1166 $this->socketResource = $socketResource;
1170 * Getter for socket resource
1172 * @return $socketResource A valid socket resource
1174 public final function getSocketResource () {
1175 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1176 return $this->socketResource;
1180 * Setter for regular expression
1182 * @param $regularExpression A valid regular expression
1185 public final function setRegularExpression ($regularExpression) {
1186 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1187 $this->regularExpression = $regularExpression;
1191 * Getter for regular expression
1193 * @return $regularExpression A valid regular expression
1195 public final function getRegularExpression () {
1196 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1197 return $this->regularExpression;
1201 * Setter for helper instance
1203 * @param $helperInstance An instance of a helper class
1206 protected final function setHelperInstance (Helper $helperInstance) {
1207 $this->helperInstance = $helperInstance;
1211 * Getter for helper instance
1213 * @return $helperInstance An instance of a helper class
1215 public final function getHelperInstance () {
1216 return $this->helperInstance;
1220 * Setter for a Source instance
1222 * @param $sourceInstance An instance of a Source class
1225 protected final function setSourceInstance (Source $sourceInstance) {
1226 $this->sourceInstance = $sourceInstance;
1230 * Getter for a Source instance
1232 * @return $sourceInstance An instance of a Source class
1234 protected final function getSourceInstance () {
1235 return $this->sourceInstance;
1239 * Setter for a UrlSource instance
1241 * @param $sourceInstance An instance of a UrlSource class
1244 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1245 $this->urlSourceInstance = $urlSourceInstance;
1249 * Getter for a UrlSource instance
1251 * @return $urlSourceInstance An instance of a UrlSource class
1253 protected final function getUrlSourceInstance () {
1254 return $this->urlSourceInstance;
1258 * Getter for a InputStream instance
1260 * @param $inputStreamInstance The InputStream instance
1262 protected final function getInputStreamInstance () {
1263 return $this->inputStreamInstance;
1267 * Setter for a InputStream instance
1269 * @param $inputStreamInstance The InputStream instance
1272 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1273 $this->inputStreamInstance = $inputStreamInstance;
1277 * Getter for a OutputStream instance
1279 * @param $outputStreamInstance The OutputStream instance
1281 protected final function getOutputStreamInstance () {
1282 return $this->outputStreamInstance;
1286 * Setter for a OutputStream instance
1288 * @param $outputStreamInstance The OutputStream instance
1291 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1292 $this->outputStreamInstance = $outputStreamInstance;
1296 * Setter for handler instance
1298 * @param $handlerInstance An instance of a Handleable class
1301 protected final function setHandlerInstance (Handleable $handlerInstance) {
1302 $this->handlerInstance = $handlerInstance;
1306 * Getter for handler instance
1308 * @return $handlerInstance A Handleable instance
1310 protected final function getHandlerInstance () {
1311 return $this->handlerInstance;
1315 * Setter for visitor instance
1317 * @param $visitorInstance A Visitor instance
1320 protected final function setVisitorInstance (Visitor $visitorInstance) {
1321 $this->visitorInstance = $visitorInstance;
1325 * Getter for visitor instance
1327 * @return $visitorInstance A Visitor instance
1329 protected final function getVisitorInstance () {
1330 return $this->visitorInstance;
1334 * Setter for raw package Data
1336 * @param $packageData Raw package Data
1339 public final function setPackageData (array $packageData) {
1340 $this->packageData = $packageData;
1344 * Getter for raw package Data
1346 * @return $packageData Raw package Data
1348 public function getPackageData () {
1349 return $this->packageData;
1354 * Setter for Iterator instance
1356 * @param $iteratorInstance An instance of an Iterator
1359 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1360 $this->iteratorInstance = $iteratorInstance;
1364 * Getter for Iterator instance
1366 * @return $iteratorInstance An instance of an Iterator
1368 public final function getIteratorInstance () {
1369 return $this->iteratorInstance;
1373 * Setter for FilePointer instance
1375 * @param $pointerInstance An instance of an FilePointer class
1378 protected final function setPointerInstance (FilePointer $pointerInstance) {
1379 $this->pointerInstance = $pointerInstance;
1383 * Getter for FilePointer instance
1385 * @return $pointerInstance An instance of an FilePointer class
1387 public final function getPointerInstance () {
1388 return $this->pointerInstance;
1392 * Unsets pointer instance which triggers a call of __destruct() if the
1393 * instance is still there. This is surely not fatal on already "closed"
1394 * file pointer instances.
1396 * I don't want to mess around with above setter by giving it a default
1397 * value NULL as setter should always explicitly only set (existing) object
1398 * instances and NULL is NULL.
1402 protected final function unsetPointerInstance () {
1403 // Simply it to NULL
1404 $this->pointerInstance = NULL;
1408 * Setter for Indexable instance
1410 * @param $indexInstance An instance of an Indexable class
1413 protected final function setIndexInstance (Indexable $indexInstance) {
1414 $this->indexInstance = $indexInstance;
1418 * Getter for Indexable instance
1420 * @return $indexInstance An instance of an Indexable class
1422 public final function getIndexInstance () {
1423 return $this->indexInstance;
1427 * Setter for Block instance
1429 * @param $blockInstance An instance of an Block class
1432 protected final function setBlockInstance (Block $blockInstance) {
1433 $this->blockInstance = $blockInstance;
1437 * Getter for Block instance
1439 * @return $blockInstance An instance of an Block class
1441 public final function getBlockInstance () {
1442 return $this->blockInstance;
1446 * Setter for Minable instance
1448 * @param $minableInstance A Minable instance
1451 protected final function setMinableInstance (Minable $minableInstance) {
1452 $this->minableInstance = $minableInstance;
1456 * Getter for minable instance
1458 * @return $minableInstance A Minable instance
1460 protected final function getMinableInstance () {
1461 return $this->minableInstance;
1465 * Setter for FrameworkDirectory instance
1467 * @param $directoryInstance A FrameworkDirectory instance
1470 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1471 $this->directoryInstance = $directoryInstance;
1475 * Getter for FrameworkDirectory instance
1477 * @return $directoryInstance A FrameworkDirectory instance
1479 protected final function getDirectoryInstance () {
1480 return $this->directoryInstance;
1484 * Getter for communicator instance
1486 * @return $communicatorInstance An instance of a Communicator class
1488 public final function getCommunicatorInstance () {
1489 return $this->communicatorInstance;
1493 * Setter for communicator instance
1495 * @param $communicatorInstance An instance of a Communicator class
1498 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1499 $this->communicatorInstance = $communicatorInstance;
1503 * Setter for state instance
1505 * @param $stateInstance A Stateable instance
1508 public final function setStateInstance (Stateable $stateInstance) {
1509 $this->stateInstance = $stateInstance;
1513 * Getter for state instance
1515 * @return $stateInstance A Stateable instance
1517 public final function getStateInstance () {
1518 return $this->stateInstance;
1522 * Setter for output instance
1524 * @param $outputInstance The debug output instance
1527 public final function setOutputInstance (OutputStreamer $outputInstance) {
1528 $this->outputInstance = $outputInstance;
1532 * Getter for output instance
1534 * @return $outputInstance The debug output instance
1536 public final function getOutputInstance () {
1537 return $this->outputInstance;
1541 * Setter for registry instance
1543 * @param $registryInstance An instance of a Register class
1546 protected final function setRegistryInstance (Register $registryInstance) {
1547 $this->registryInstance = $registryInstance;
1551 * Getter for registry instance
1553 * @return $registryInstance The debug registry instance
1555 public final function getRegistryInstance () {
1556 return $this->registryInstance;
1560 * Setter for call-back instance
1562 * @param $callbackInstance An instance of a FrameworkInterface class
1565 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1566 $this->callbackInstance = $callbackInstance;
1570 * Getter for call-back instance
1572 * @return $callbackInstance An instance of a FrameworkInterface class
1574 protected final function getCallbackInstance () {
1575 return $this->callbackInstance;
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 * Checks whether an object equals this object. You should overwrite this
1618 * method to implement own equality checks
1620 * @param $objectInstance An instance of a FrameworkInterface object
1621 * @return $equals Whether both objects equals
1623 public function equals (FrameworkInterface $objectInstance) {
1626 $this->__toString() == $objectInstance->__toString()
1628 $this->hashCode() == $objectInstance->hashCode()
1631 // Return the result
1636 * Generates a generic hash code of this class. You should really overwrite
1637 * this method with your own hash code generator code. But keep KISS in mind.
1639 * @return $hashCode A generic hash code respresenting this whole class
1641 public function hashCode () {
1643 return crc32($this->__toString());
1647 * Formats computer generated price values into human-understandable formats
1648 * with thousand and decimal separators.
1650 * @param $value The in computer format value for a price
1651 * @param $currency The currency symbol (use HTML-valid characters!)
1652 * @param $decNum Number of decimals after commata
1653 * @return $price The for the current language formated price string
1654 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1655 * thousands separator
1658 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1659 // Are all required attriutes set?
1660 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1661 // Throw an exception
1662 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1666 $value = (float) $value;
1668 // Reformat the US number
1669 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1671 // Return as string...
1676 * Appends a trailing slash to a string
1678 * @param $str A string (maybe) without trailing slash
1679 * @return $str A string with an auto-appended trailing slash
1681 public final function addMissingTrailingSlash ($str) {
1682 // Is there a trailing slash?
1683 if (substr($str, -1, 1) != '/') {
1687 // Return string with trailing slash
1692 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1693 * application helper instance (ApplicationHelper by default).
1695 * @param $applicationInstance An application helper instance or
1696 * null if we shall use the default
1697 * @return $templateInstance The template engine instance
1698 * @throws NullPointerException If the discovered application
1699 * instance is still null
1701 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1702 // Is the application instance set?
1703 if (is_null($applicationInstance)) {
1704 // Get the current instance
1705 $applicationInstance = Registry::getRegistry()->getInstance('app');
1708 if (is_null($applicationInstance)) {
1709 // Thrown an exception
1710 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1714 // Initialize the template engine
1715 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1717 // Return the prepared instance
1718 return $templateInstance;
1722 * Debugs this instance by putting out it's full content
1724 * @param $message Optional message to show in debug output
1727 public final function debugInstance ($message = '') {
1728 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1729 restore_error_handler();
1734 // Is a message set?
1735 if (!empty($message)) {
1736 // Construct message
1737 $content = sprintf('<div class="debug_message">
1739 </div>' . PHP_EOL, $message);
1742 // Generate the output
1743 $content .= sprintf('<pre>%s</pre>',
1746 print_r($this, true)
1752 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1755 <div class="debug_content">
1759 <div class="debug_include_list">
1762 $this->__toString(),
1764 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1769 * Replaces control characters with printable output
1771 * @param $str String with control characters
1772 * @return $str Replaced string
1774 protected function replaceControlCharacters ($str) {
1777 chr(13), '[r]', str_replace(
1778 chr(10), '[n]', str_replace(
1788 * Output a partial stub message for the caller method
1790 * @param $message An optional message to display
1793 protected function partialStub ($message = '') {
1795 $stubMessage = 'Partial Stub!';
1797 // Is the extra message given?
1798 if (!empty($message)) {
1799 // Then add it as well
1800 $stubMessage .= ' Message: ' . $message;
1803 // Debug instance is there?
1804 if (!is_null($this->getDebugInstance())) {
1805 // Output stub message
1806 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1809 trigger_error($stubMessage);
1815 * Outputs a debug backtrace and stops further script execution
1817 * @param $message An optional message to output
1818 * @param $doExit Whether exit the program (true is default)
1821 public function debugBackTrace ($message = '', $doExit = true) {
1822 // Sorry, there is no other way getting this nice backtrace
1823 if (!empty($message)) {
1825 printf('Message: %s<br />' . PHP_EOL, $message);
1829 debug_print_backtrace();
1833 if ($doExit === true) {
1839 * Creates an instance of a debugger instance
1841 * @param $className Name of the class (currently unsupported)
1842 * @param $lineNumber Line number where the call was made
1843 * @return $debugInstance An instance of a debugger class
1844 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1846 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1847 // Is the instance set?
1848 if (!Registry::getRegistry()->instanceExists('debug')) {
1849 // Init debug instance
1850 $debugInstance = NULL;
1854 // Get a debugger instance
1855 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1856 } catch (NullPointerException $e) {
1857 // Didn't work, no instance there
1858 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1861 // Empty string should be ignored and used for testing the middleware
1862 DebugMiddleware::getSelfInstance()->output('');
1864 // Set it in registry
1865 Registry::getRegistry()->addInstance('debug', $debugInstance);
1867 // Get instance from registry
1868 $debugInstance = Registry::getRegistry()->getInstance('debug');
1872 return $debugInstance;
1876 * Simple output of a message with line-break
1878 * @param $message Message to output
1881 public function outputLine ($message) {
1883 print($message . PHP_EOL);
1887 * Outputs a debug message whether to debug instance (should be set!) or
1888 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1889 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1891 * @param $message Message we shall send out...
1892 * @param $doPrint Whether print or die here (default: print)
1893 * @paran $stripTags Whether to strip tags (default: false)
1896 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1897 // Set debug instance to NULL
1898 $debugInstance = NULL;
1901 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1903 // Is function partialStub/__callStatic ?
1904 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1905 // Prepend class::function:line from 3rd element
1906 $message = sprintf('[%s::%s:%d]: %s',
1907 $backtrace[2]['class'],
1908 $backtrace[2]['function'],
1909 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1913 // Prepend class::function:line from 2nd element
1914 $message = sprintf('[%s::%s:%d]: %s',
1915 $backtrace[1]['class'],
1916 $backtrace[1]['function'],
1917 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1924 // Get debug instance
1925 $debugInstance = $this->getDebugInstance();
1926 } catch (NullPointerException $e) {
1927 // The debug instance is not set (yet)
1930 // Is the debug instance there?
1931 if (is_object($debugInstance)) {
1932 // Use debug output handler
1933 $debugInstance->output($message, $stripTags);
1935 if ($doPrint === false) {
1936 // Die here if not printed
1940 // Are debug times enabled?
1941 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1943 $message = $this->getPrintableExecutionTime() . $message;
1947 if ($doPrint === true) {
1949 $this->outputLine($message);
1958 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1960 * @param $str The string, what ever it is needs to be converted
1961 * @return $className Generated class name
1963 public static final function convertToClassName ($str) {
1967 // Convert all dashes in underscores
1968 $str = self::convertDashesToUnderscores($str);
1970 // Now use that underscores to get classname parts for hungarian style
1971 foreach (explode('_', $str) as $strPart) {
1972 // Make the class name part lower case and first upper case
1973 $className .= ucfirst(strtolower($strPart));
1976 // Return class name
1981 * Converts dashes to underscores, e.g. useable for configuration entries
1983 * @param $str The string with maybe dashes inside
1984 * @return $str The converted string with no dashed, but underscores
1986 public static final function convertDashesToUnderscores ($str) {
1988 $str = str_replace('-', '_', $str);
1990 // Return converted string
1995 * Marks up the code by adding e.g. line numbers
1997 * @param $phpCode Unmarked PHP code
1998 * @return $markedCode Marked PHP code
2000 public function markupCode ($phpCode) {
2005 $errorArray = error_get_last();
2007 // Init the code with error message
2008 if (is_array($errorArray)) {
2010 $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>',
2011 basename($errorArray['file']),
2012 $errorArray['line'],
2013 $errorArray['message'],
2018 // Add line number to the code
2019 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2021 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2023 htmlentities($code, ENT_QUOTES)
2032 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2033 * beatiful for web-based front-ends. If null is given a message id
2034 * null_timestamp will be resolved and returned.
2036 * @param $timestamp Timestamp to prepare (filter) for display
2037 * @return $readable A readable timestamp
2039 public function doFilterFormatTimestamp ($timestamp) {
2040 // Default value to return
2043 // Is the timestamp null?
2044 if (is_null($timestamp)) {
2045 // Get a message string
2046 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2048 switch ($this->getLanguageInstance()->getLanguageCode()) {
2049 case 'de': // German format is a bit different to default
2050 // Split the GMT stamp up
2051 $dateTime = explode(' ', $timestamp );
2052 $dateArray = explode('-', $dateTime[0]);
2053 $timeArray = explode(':', $dateTime[1]);
2055 // Construct the timestamp
2056 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2066 default: // Default is pass-through
2067 $readable = $timestamp;
2077 * Filter a given number into a localized number
2079 * @param $value The raw value from e.g. database
2080 * @return $localized Localized value
2082 public function doFilterFormatNumber ($value) {
2083 // Generate it from config and localize dependencies
2084 switch ($this->getLanguageInstance()->getLanguageCode()) {
2085 case 'de': // German format is a bit different to default
2086 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2089 default: // US, etc.
2090 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2099 * "Getter" for databse entry
2101 * @return $entry An array with database entries
2102 * @throws NullPointerException If the database result is not found
2103 * @throws InvalidDatabaseResultException If the database result is invalid
2105 protected final function getDatabaseEntry () {
2106 // Is there an instance?
2107 if (!$this->getResultInstance() instanceof SearchableResult) {
2108 // Throw an exception here
2109 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2113 $this->getResultInstance()->rewind();
2115 // Do we have an entry?
2116 if ($this->getResultInstance()->valid() === false) {
2117 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2118 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2122 $this->getResultInstance()->next();
2125 $entry = $this->getResultInstance()->current();
2132 * Getter for field name
2134 * @param $fieldName Field name which we shall get
2135 * @return $fieldValue Field value from the user
2136 * @throws NullPointerException If the result instance is null
2138 public final function getField ($fieldName) {
2139 // Default field value
2142 // Get result instance
2143 $resultInstance = $this->getResultInstance();
2145 // Is this instance null?
2146 if (is_null($resultInstance)) {
2147 // Then the user instance is no longer valid (expired cookies?)
2148 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2151 // Get current array
2152 $fieldArray = $resultInstance->current();
2153 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2155 // Convert dashes to underscore
2156 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2158 // Does the field exist?
2159 if ($this->isFieldSet($fieldName)) {
2161 $fieldValue = $fieldArray[$fieldName2];
2162 } elseif (defined('DEVELOPER')) {
2163 // Missing field entry, may require debugging
2164 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2166 // Missing field entry, may require debugging
2167 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2175 * Checks if given field is set
2177 * @param $fieldName Field name to check
2178 * @return $isSet Whether the given field name is set
2179 * @throws NullPointerException If the result instance is null
2181 public function isFieldSet ($fieldName) {
2182 // Get result instance
2183 $resultInstance = $this->getResultInstance();
2185 // Is this instance null?
2186 if (is_null($resultInstance)) {
2187 // Then the user instance is no longer valid (expired cookies?)
2188 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2191 // Get current array
2192 $fieldArray = $resultInstance->current();
2193 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2195 // Convert dashes to underscore
2196 $fieldName = self::convertDashesToUnderscores($fieldName);
2199 $isSet = isset($fieldArray[$fieldName]);
2206 * Flushs all pending updates to the database layer
2210 public function flushPendingUpdates () {
2211 // Get result instance
2212 $resultInstance = $this->getResultInstance();
2214 // Do we have data to update?
2215 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2216 // Get wrapper class name config entry
2217 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2219 // Create object instance
2220 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2222 // Yes, then send the whole result to the database layer
2223 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2228 * Outputs a deprecation warning to the developer.
2230 * @param $message The message we shall output to the developer
2232 * @todo Write a logging mechanism for productive mode
2234 public function deprecationWarning ($message) {
2235 // Is developer mode active?
2236 if (defined('DEVELOPER')) {
2237 // Debug instance is there?
2238 if (!is_null($this->getDebugInstance())) {
2239 // Output stub message
2240 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2243 trigger_error($message . "<br />\n");
2247 // @TODO Finish this part!
2248 $this->partialStub('Developer mode inactive. Message:' . $message);
2253 * Checks whether the given PHP extension is loaded
2255 * @param $phpExtension The PHP extension we shall check
2256 * @return $isLoaded Whether the PHP extension is loaded
2258 public final function isPhpExtensionLoaded ($phpExtension) {
2260 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2267 * "Getter" as a time() replacement but with milliseconds. You should use this
2268 * method instead of the encapsulated getimeofday() function.
2270 * @return $milliTime Timestamp with milliseconds
2272 public function getMilliTime () {
2273 // Get the time of day as float
2274 $milliTime = gettimeofday(true);
2281 * Idles (sleeps) for given milliseconds
2283 * @return $hasSlept Whether it goes fine
2285 public function idle ($milliSeconds) {
2286 // Sleep is fine by default
2289 // Idle so long with found function
2290 if (function_exists('time_sleep_until')) {
2291 // Get current time and add idle time
2292 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2294 // New PHP 5.1.0 function found, ignore errors
2295 $hasSlept = @time_sleep_until($sleepUntil);
2298 * My Sun station doesn't have that function even with latest PHP
2301 usleep($milliSeconds * 1000);
2308 * Converts a hexadecimal string, even with negative sign as first string to
2309 * a decimal number using BC functions.
2311 * This work is based on comment #86673 on php.net documentation page at:
2312 * <http://de.php.net/manual/en/function.dechex.php#86673>
2314 * @param $hex Hexadecimal string
2315 * @return $dec Decimal number
2317 protected function hex2dec ($hex) {
2318 // Convert to all lower-case
2319 $hex = strtolower($hex);
2321 // Detect sign (negative/positive numbers)
2323 if (substr($hex, 0, 1) == '-') {
2325 $hex = substr($hex, 1);
2328 // Decode the hexadecimal string into a decimal number
2330 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2331 $factor = self::$hexdec[substr($hex, $i, 1)];
2332 $dec = bcadd($dec, bcmul($factor, $e));
2335 // Return the decimal number
2336 return $sign . $dec;
2340 * Converts even very large decimal numbers, also signed, to a hexadecimal
2343 * This work is based on comment #97756 on php.net documentation page at:
2344 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2346 * @param $dec Decimal number, even with negative sign
2347 * @param $maxLength Optional maximum length of the string
2348 * @return $hex Hexadecimal string
2350 protected function dec2hex ($dec, $maxLength = 0) {
2351 // maxLength can be zero or devideable by 2
2352 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2354 // Detect sign (negative/positive numbers)
2361 // Encode the decimal number into a hexadecimal string
2364 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2366 } while ($dec >= 1);
2369 * Leading zeros are required for hex-decimal "numbers". In some
2370 * situations more leading zeros are wanted, so check for both
2373 if ($maxLength > 0) {
2374 // Prepend more zeros
2375 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2376 } elseif ((strlen($hex) % 2) != 0) {
2377 // Only make string's length dividable by 2
2381 // Return the hexadecimal string
2382 return $sign . $hex;
2386 * Converts a ASCII string (0 to 255) into a decimal number.
2388 * @param $asc The ASCII string to be converted
2389 * @return $dec Decimal number
2391 protected function asc2dec ($asc) {
2392 // Convert it into a hexadecimal number
2393 $hex = bin2hex($asc);
2395 // And back into a decimal number
2396 $dec = $this->hex2dec($hex);
2403 * Converts a decimal number into an ASCII string.
2405 * @param $dec Decimal number
2406 * @return $asc An ASCII string
2408 protected function dec2asc ($dec) {
2409 // First convert the number into a hexadecimal string
2410 $hex = $this->dec2hex($dec);
2412 // Then convert it into the ASCII string
2413 $asc = $this->hex2asc($hex);
2420 * Converts a hexadecimal number into an ASCII string. Negative numbers
2423 * @param $hex Hexadecimal string
2424 * @return $asc An ASCII string
2426 protected function hex2asc ($hex) {
2427 // Check for length, it must be devideable by 2
2428 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2429 assert((strlen($hex) % 2) == 0);
2433 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2434 // Get the decimal number of the chunk
2435 $part = hexdec(substr($hex, $idx, 2));
2437 // Add it to the final string
2441 // Return the final string
2446 * Checks whether the given encoded data was encoded with Base64
2448 * @param $encodedData Encoded data we shall check
2449 * @return $isBase64 Whether the encoded data is Base64
2451 protected function isBase64Encoded ($encodedData) {
2453 $isBase64 = (@base64_decode($encodedData, true) !== false);
2460 * Gets a cache key from Criteria instance
2462 * @param $criteriaInstance An instance of a Criteria class
2463 * @param $onlyKeys Only use these keys for a cache key
2464 * @return $cacheKey A cache key suitable for lookup/storage purposes
2466 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2468 $cacheKey = sprintf('%s@%s',
2469 $this->__toString(),
2470 $criteriaInstance->getCacheKey($onlyKeys)
2474 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2479 * Getter for startup time in miliseconds
2481 * @return $startupTime Startup time in miliseconds
2483 protected function getStartupTime () {
2484 return self::$startupTime;
2488 * "Getter" for a printable currently execution time in nice braces
2490 * @return $executionTime Current execution time in nice braces
2492 protected function getPrintableExecutionTime () {
2493 // Caculate the execution time
2494 $executionTime = microtime(true) - $this->getStartupTime();
2496 // Pack it in nice braces
2497 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2500 return $executionTime;
2504 * Hashes a given string with a simple but stronger hash function (no salt)
2505 * and hex-encode it.
2507 * @param $str The string to be hashed
2508 * @return $hash The hash from string $str
2510 public static final function hash ($str) {
2511 // Hash given string with (better secure) hasher
2512 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2519 * "Getter" for length of hash() output. This will be "cached" to speed up
2522 * @return $length Length of hash() output
2524 public static final function getHashLength () {
2526 if (is_null(self::$hashLength)) {
2527 // No, then hash a string and save its length.
2528 self::$hashLength = strlen(self::hash('abc123'));
2532 return self::$hashLength;
2536 * Checks whether the given number is really a number (only chars 0-9).
2538 * @param $num A string consisting only chars between 0 and 9
2539 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2540 * @param $assertMismatch Whether to assert mismatches
2541 * @return $ret The (hopefully) secured numbered value
2543 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2544 // Filter all numbers out
2545 $ret = preg_replace('/[^0123456789]/', '', $num);
2548 if ($castValue === true) {
2549 // Cast to biggest numeric type
2550 $ret = (double) $ret;
2553 // Assert only if requested
2554 if ($assertMismatch === true) {
2555 // Has the whole value changed?
2556 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2564 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2566 * @param $num A string consisting only chars between 0 and 9
2567 * @param $assertMismatch Whether to assert mismatches
2568 * @return $ret The (hopefully) secured hext-numbered value
2570 public function hexval ($num, $assertMismatch = false) {
2571 // Filter all numbers out
2572 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2574 // Assert only if requested
2575 if ($assertMismatch === true) {
2576 // Has the whole value changed?
2577 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2585 * Determines if an element is set in the generic array
2587 * @param $keyGroup Main group for the key
2588 * @param $subGroup Sub group for the key
2589 * @param $key Key to check
2590 * @param $element Element to check
2591 * @return $isset Whether the given key is set
2593 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2595 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2598 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2604 * Determines if a key is set in the generic array
2606 * @param $keyGroup Main group for the key
2607 * @param $subGroup Sub group for the key
2608 * @param $key Key to check
2609 * @return $isset Whether the given key is set
2611 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2613 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2616 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2624 * Determines if a group is set in the generic array
2626 * @param $keyGroup Main group
2627 * @param $subGroup Sub group
2628 * @return $isset Whether the given group is set
2630 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2632 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2635 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2642 * Getter for sub key group
2644 * @param $keyGroup Main key group
2645 * @param $subGroup Sub key group
2646 * @return $array An array with all array elements
2648 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2650 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2651 // No, then abort here
2652 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2657 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2660 return $this->genericArray[$keyGroup][$subGroup];
2664 * Unsets a given key in generic array
2666 * @param $keyGroup Main group for the key
2667 * @param $subGroup Sub group for the key
2668 * @param $key Key to unset
2671 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2673 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2676 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2680 * Unsets a given element in generic array
2682 * @param $keyGroup Main group for the key
2683 * @param $subGroup Sub group for the key
2684 * @param $key Key to unset
2685 * @param $element Element to unset
2688 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2690 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2693 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2697 * Append a string to a given generic array key
2699 * @param $keyGroup Main group for the key
2700 * @param $subGroup Sub group for the key
2701 * @param $key Key to unset
2702 * @param $value Value to add/append
2705 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2707 //* 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);
2709 // Is it already there?
2710 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2712 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2715 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2720 * Append a string to a given generic array element
2722 * @param $keyGroup Main group for the key
2723 * @param $subGroup Sub group for the key
2724 * @param $key Key to unset
2725 * @param $element Element to check
2726 * @param $value Value to add/append
2729 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2731 //* 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);
2733 // Is it already there?
2734 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2736 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2739 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2744 * Sets a string in a given generic array element
2746 * @param $keyGroup Main group for the key
2747 * @param $subGroup Sub group for the key
2748 * @param $key Key to unset
2749 * @param $element Element to check
2750 * @param $value Value to add/append
2753 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2755 //* 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);
2758 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2762 * Initializes given generic array group
2764 * @param $keyGroup Main group for the key
2765 * @param $subGroup Sub group for the key
2766 * @param $key Key to use
2767 * @param $forceInit Optionally force initialization
2770 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2772 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2774 // Is it already set?
2775 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2776 // Already initialized
2777 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2782 $this->genericArray[$keyGroup][$subGroup] = array();
2786 * Initializes given generic array key
2788 * @param $keyGroup Main group for the key
2789 * @param $subGroup Sub group for the key
2790 * @param $key Key to use
2791 * @param $forceInit Optionally force initialization
2794 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2796 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2798 // Is it already set?
2799 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2800 // Already initialized
2801 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2806 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2810 * Initializes given generic array element
2812 * @param $keyGroup Main group for the key
2813 * @param $subGroup Sub group for the key
2814 * @param $key Key to use
2815 * @param $element Element to use
2816 * @param $forceInit Optionally force initialization
2819 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2821 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2823 // Is it already set?
2824 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2825 // Already initialized
2826 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2831 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2835 * Pushes an element to a generic key
2837 * @param $keyGroup Main group for the key
2838 * @param $subGroup Sub group for the key
2839 * @param $key Key to use
2840 * @param $value Value to add/append
2841 * @return $count Number of array elements
2843 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2845 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2848 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2850 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2854 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2857 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2858 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2863 * Pushes an element to a generic array element
2865 * @param $keyGroup Main group for the key
2866 * @param $subGroup Sub group for the key
2867 * @param $key Key to use
2868 * @param $element Element to check
2869 * @param $value Value to add/append
2870 * @return $count Number of array elements
2872 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2874 //* 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));
2877 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2879 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2883 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2886 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2887 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2892 * Pops an element from a generic group
2894 * @param $keyGroup Main group for the key
2895 * @param $subGroup Sub group for the key
2896 * @param $key Key to unset
2897 * @return $value Last "popped" value
2899 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2901 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2904 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2906 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2911 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2914 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2915 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2920 * Shifts an element from a generic group
2922 * @param $keyGroup Main group for the key
2923 * @param $subGroup Sub group for the key
2924 * @param $key Key to unset
2925 * @return $value Last "popped" value
2927 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2929 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2932 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2934 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2939 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2942 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2943 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2948 * Count generic array group
2950 * @param $keyGroup Main group for the key
2951 * @return $count Count of given group
2953 protected final function countGenericArray ($keyGroup) {
2955 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2958 if (!isset($this->genericArray[$keyGroup])) {
2960 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2965 $count = count($this->genericArray[$keyGroup]);
2968 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2975 * Count generic array sub group
2977 * @param $keyGroup Main group for the key
2978 * @param $subGroup Sub group for the key
2979 * @return $count Count of given group
2981 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2983 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2986 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2988 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2993 $count = count($this->genericArray[$keyGroup][$subGroup]);
2996 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3003 * Count generic array elements
3005 * @param $keyGroup Main group for the key
3006 * @param $subGroup Sub group for the key
3007 * @para $key Key to count
3008 * @return $count Count of given key
3010 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3012 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3015 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3017 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3019 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3021 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3026 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3029 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3036 * Getter for whole generic group array
3038 * @param $keyGroup Key group to get
3039 * @return $array Whole generic array group
3041 protected final function getGenericArray ($keyGroup) {
3043 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3046 if (!isset($this->genericArray[$keyGroup])) {
3048 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3053 return $this->genericArray[$keyGroup];
3057 * Setter for generic array key
3059 * @param $keyGroup Key group to get
3060 * @param $subGroup Sub group for the key
3061 * @param $key Key to unset
3062 * @param $value Mixed value from generic array element
3065 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3067 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3070 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3074 * Getter for generic array key
3076 * @param $keyGroup Key group to get
3077 * @param $subGroup Sub group for the key
3078 * @param $key Key to unset
3079 * @return $value Mixed value from generic array element
3081 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3083 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3086 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3088 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3093 return $this->genericArray[$keyGroup][$subGroup][$key];
3097 * Sets a value in given generic array key/element
3099 * @param $keyGroup Main group for the key
3100 * @param $subGroup Sub group for the key
3101 * @param $key Key to set
3102 * @param $element Element to set
3103 * @param $value Value to set
3106 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3108 //* 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));
3111 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3115 * Getter for generic array element
3117 * @param $keyGroup Key group to get
3118 * @param $subGroup Sub group for the key
3119 * @param $key Key to look for
3120 * @param $element Element to look for
3121 * @return $value Mixed value from generic array element
3123 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3125 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3128 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3130 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3135 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3139 * Checks if a given sub group is valid (array)
3141 * @param $keyGroup Key group to get
3142 * @param $subGroup Sub group for the key
3143 * @return $isValid Whether given sub group is valid
3145 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3147 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3150 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3157 * Checks if a given key is valid (array)
3159 * @param $keyGroup Key group to get
3160 * @param $subGroup Sub group for the key
3161 * @param $key Key to check
3162 * @return $isValid Whether given sub group is valid
3164 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3166 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3169 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3176 * Initializes the web output instance
3180 protected function initWebOutputInstance () {
3181 // Get application instance
3182 $applicationInstance = Registry::getRegistry()->getInstance('app');
3184 // Init web output instance
3185 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3188 $this->setWebOutputInstance($outputInstance);
3192 * Translates boolean true to 'Y' and false to 'N'
3194 * @param $boolean Boolean value
3195 * @return $translated Translated boolean value
3197 public static final function translateBooleanToYesNo ($boolean) {
3198 // Make sure it is really boolean
3199 assert(is_bool($boolean));
3202 $translated = ($boolean === true) ? 'Y' : 'N';
3204 // ... and return it
3209 * Encodes raw data (almost any type) by "serializing" it and then pack it
3210 * into a "binary format".
3212 * @param $rawData Raw data (almost any type)
3213 * @return $encoded Encoded data
3215 protected function encodeData ($rawData) {
3216 // Make sure no objects or resources pass through
3217 assert(!is_object($rawData));
3218 assert(!is_resource($rawData));
3220 // First "serialize" it (json_encode() is faster than serialize())
3221 $encoded = $this->packString(json_encode($rawData));
3228 * Pack a string into a "binary format". Please execuse me that this is
3229 * widely undocumented. :-(
3231 * @param $str Unpacked string
3232 * @return $packed Packed string
3233 * @todo Improve documentation
3235 protected function packString ($str) {
3237 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3239 // First compress the string (gzcompress is okay)
3240 $str = gzcompress($str);
3245 // And start the "encoding" loop
3246 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3248 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3249 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3251 if (($idx + $i) <= strlen($str)) {
3252 $ord = ord(substr($str, ($idx + $i), 1));
3254 $add = $ord * pow(256, $factor);
3258 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3262 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3263 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3265 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3266 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3272 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3277 * Creates a full-qualified file name (FQFN) for given file name by adding
3278 * a configured temporary file path to it.
3280 * @param $fileName Name for temporary file
3281 * @return $fqfn Full-qualified file name
3282 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3283 * @throws FileIoException If the file cannot be written
3285 protected static function createTempPathForFile ($fileName) {
3287 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3289 // Is the path writeable?
3290 if (!is_writable($basePath)) {
3291 // Path is write-protected
3292 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3296 $fqfn = $basePath . DIRECTORY_SEPARATOR . $fileName;
3299 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3301 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3309 * "Getter" for a printable state name
3311 * @return $stateName Name of the node's state in a printable format
3313 public final function getPrintableState () {
3314 // Default is 'null'
3315 $stateName = 'null';
3317 // Get the state instance
3318 $stateInstance = $this->getStateInstance();
3320 // Is it an instance of Stateable?
3321 if ($stateInstance instanceof Stateable) {
3322 // Then use that state name
3323 $stateName = $stateInstance->getStateName();