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;
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;
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('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
501 // Do not call this twice
502 trigger_error(__METHOD__ . ': Called twice.');
508 * The __call() method where all non-implemented methods end up
510 * @param $methodName Name of the missing method
511 * @args $args Arguments passed to the method
514 public final function __call ($methodName, $args) {
515 return self::__callStatic($methodName, $args);
519 * The __callStatic() method where all non-implemented static methods end up
521 * @param $methodName Name of the missing method
522 * @args $args Arguments passed to the method
525 public static final function __callStatic ($methodName, $args) {
527 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
529 // Init argument string
532 // Is it NULL, empty or an array?
533 if (is_null($args)) {
535 $argsString = 'NULL';
536 } elseif (is_array($args)) {
540 // Some arguments are there
541 foreach ($args as $arg) {
542 // Add data about the argument
543 $argsString .= gettype($arg) . ':';
546 // Found a NULL argument
547 $argsString .= 'NULL';
548 } elseif (is_string($arg)) {
549 // Add length for strings
550 $argsString .= strlen($arg);
551 } elseif ((is_int($arg)) || (is_float($arg))) {
554 } elseif (is_array($arg)) {
555 // .. or size if array
556 $argsString .= count($arg);
557 } elseif (is_object($arg)) {
559 $reflection = new ReflectionClass($arg);
561 // Is an other object, maybe no __toString() available
562 $argsString .= $reflection->getName();
563 } elseif ($arg === true) {
564 // ... is boolean 'true'
565 $argsString .= 'true';
566 } elseif ($arg === false) {
567 // ... is boolean 'false'
568 $argsString .= 'false';
571 // Comma for next one
576 if (substr($argsString, -2, 1) == ',') {
577 $argsString = substr($argsString, 0, -2);
583 // Invalid arguments!
584 $argsString = '!INVALID:' . gettype($args) . '!';
587 // Output stub message
588 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
589 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
599 * Getter for $realClass
601 * @return $realClass The name of the real class (not BaseFrameworkSystem)
603 public function __toString () {
604 return $this->realClass;
608 * Magic method to catch setting of missing but set class fields/attributes
610 * @param $name Name of the field/attribute
611 * @param $value Value to store
614 public final function __set ($name, $value) {
615 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
618 print_r($value, true)
623 * Magic method to catch getting of missing fields/attributes
625 * @param $name Name of the field/attribute
628 public final function __get ($name) {
629 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
635 * Magic method to catch unsetting of missing fields/attributes
637 * @param $name Name of the field/attribute
640 public final function __unset ($name) {
641 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
647 * Magic method to catch object serialization
649 * @return $unsupported Unsupported method
650 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
652 public final function __sleep () {
653 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
657 * Magic method to catch object deserialization
659 * @return $unsupported Unsupported method
660 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
662 public final function __wakeup () {
663 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
667 * Magic method to catch calls when an object instance is called
669 * @return $unsupported Unsupported method
670 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
672 public final function __invoke () {
673 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
677 * Setter for the real class name
679 * @param $realClass Class name (string)
682 public final function setRealClass ($realClass) {
684 $this->realClass = (string) $realClass;
688 * Setter for database result instance
690 * @param $resultInstance An instance of a database result class
692 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
694 protected final function setResultInstance (SearchableResult $resultInstance) {
695 $this->resultInstance = $resultInstance;
699 * Getter for database result instance
701 * @return $resultInstance An instance of a database result class
703 public final function getResultInstance () {
704 return $this->resultInstance;
708 * Setter for template engine instances
710 * @param $templateInstance An instance of a template engine class
713 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
714 $this->templateInstance = $templateInstance;
718 * Getter for template engine instances
720 * @return $templateInstance An instance of a template engine class
722 protected final function getTemplateInstance () {
723 return $this->templateInstance;
727 * Setter for search instance
729 * @param $searchInstance Searchable criteria instance
732 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
733 $this->searchInstance = $searchInstance;
737 * Getter for search instance
739 * @return $searchInstance Searchable criteria instance
741 public final function getSearchInstance () {
742 return $this->searchInstance;
746 * Setter for update instance
748 * @param $updateInstance An instance of a LocalUpdateCriteria clase
751 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
752 $this->updateInstance = $updateInstance;
756 * Getter for update instance
758 * @return $updateInstance Updateable criteria instance
760 public final function getUpdateInstance () {
761 return $this->updateInstance;
765 * Setter for resolver instance
767 * @param $resolverInstance Instance of a command resolver class
770 public final function setResolverInstance (Resolver $resolverInstance) {
771 $this->resolverInstance = $resolverInstance;
775 * Getter for resolver instance
777 * @return $resolverInstance Instance of a command resolver class
779 public final function getResolverInstance () {
780 return $this->resolverInstance;
784 * Setter for language instance
786 * @param $configInstance The configuration instance which shall
787 * be FrameworkConfiguration
790 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
791 Registry::getRegistry()->addInstance('config', $configInstance);
795 * Getter for configuration instance
797 * @return $configInstance Configuration instance
799 public final function getConfigInstance () {
800 $configInstance = Registry::getRegistry()->getInstance('config');
801 return $configInstance;
805 * Setter for debug instance
807 * @param $debugInstance The instance for debug output class
810 public final function setDebugInstance (DebugMiddleware $debugInstance) {
811 Registry::getRegistry()->addInstance('debug', $debugInstance);
815 * Getter for debug instance
817 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
819 public final function getDebugInstance () {
820 // Get debug instance
821 $debugInstance = Registry::getRegistry()->getInstance('debug');
824 return $debugInstance;
828 * Setter for web output instance
830 * @param $webInstance The instance for web output class
833 public final function setWebOutputInstance (OutputStreamer $webInstance) {
834 Registry::getRegistry()->addInstance('web_output', $webInstance);
838 * Getter for web output instance
840 * @return $webOutputInstance - Instance to class WebOutput
842 public final function getWebOutputInstance () {
843 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
844 return $webOutputInstance;
848 * Setter for database instance
850 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
853 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
854 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
858 * Getter for database layer
860 * @return $databaseInstance The database layer instance
862 public final function getDatabaseInstance () {
864 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
867 return $databaseInstance;
871 * Setter for compressor channel
873 * @param $compressorInstance An instance of CompressorChannel
876 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
877 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
881 * Getter for compressor channel
883 * @return $compressorInstance The compressor channel
885 public final function getCompressorChannel () {
886 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
887 return $compressorInstance;
891 * Protected getter for a manageable application helper class
893 * @return $applicationInstance An instance of a manageable application helper class
895 protected final function getApplicationInstance () {
896 $applicationInstance = Registry::getRegistry()->getInstance('app');
897 return $applicationInstance;
901 * Setter for a manageable application helper class
903 * @param $applicationInstance An instance of a manageable application helper class
906 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
907 Registry::getRegistry()->addInstance('application', $applicationInstance);
911 * Private getter for language instance
913 * @return $langInstance An instance to the language sub-system
915 protected final function getLanguageInstance () {
916 $langInstance = Registry::getRegistry()->getInstance('language');
917 return $langInstance;
921 * Setter for language instance
923 * @param $langInstance An instance to the language sub-system
925 * @see LanguageSystem
927 public final function setLanguageInstance (ManageableLanguage $langInstance) {
928 Registry::getRegistry()->addInstance('language', $langInstance);
932 * Private getter for file IO instance
934 * @return $fileIoInstance An instance to the file I/O sub-system
936 protected final function getFileIoInstance () {
937 return $this->fileIoInstance;
941 * Setter for file I/O instance
943 * @param $fileIoInstance An instance to the file I/O sub-system
946 public final function setFileIoInstance (IoHandler $fileIoInstance) {
947 $this->fileIoInstance = $fileIoInstance;
951 * Protected setter for user instance
953 * @param $userInstance An instance of a user class
956 protected final function setUserInstance (ManageableAccount $userInstance) {
957 $this->userInstance = $userInstance;
961 * Getter for user instance
963 * @return $userInstance An instance of a user class
965 public final function getUserInstance () {
966 return $this->userInstance;
970 * Setter for controller instance (this surely breaks a bit the MVC patterm)
972 * @param $controllerInstance An instance of the controller
975 public final function setControllerInstance (Controller $controllerInstance) {
976 $this->controllerInstance = $controllerInstance;
980 * Getter for controller instance (this surely breaks a bit the MVC patterm)
982 * @return $controllerInstance An instance of the controller
984 public final function getControllerInstance () {
985 return $this->controllerInstance;
989 * Setter for RNG instance
991 * @param $rngInstance An instance of a random number generator (RNG)
994 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
995 $this->rngInstance = $rngInstance;
999 * Getter for RNG instance
1001 * @return $rngInstance An instance of a random number generator (RNG)
1003 public final function getRngInstance () {
1004 return $this->rngInstance;
1008 * Setter for Cryptable instance
1010 * @param $cryptoInstance An instance of a Cryptable class
1013 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1014 $this->cryptoInstance = $cryptoInstance;
1018 * Getter for Cryptable instance
1020 * @return $cryptoInstance An instance of a Cryptable class
1022 public final function getCryptoInstance () {
1023 return $this->cryptoInstance;
1027 * Setter for the list instance
1029 * @param $listInstance A list of Listable
1032 protected final function setListInstance (Listable $listInstance) {
1033 $this->listInstance = $listInstance;
1037 * Getter for the list instance
1039 * @return $listInstance A list of Listable
1041 protected final function getListInstance () {
1042 return $this->listInstance;
1046 * Setter for the menu instance
1048 * @param $menuInstance A RenderableMenu instance
1051 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1052 $this->menuInstance = $menuInstance;
1056 * Getter for the menu instance
1058 * @return $menuInstance A RenderableMenu instance
1060 protected final function getMenuInstance () {
1061 return $this->menuInstance;
1065 * Setter for image instance
1067 * @param $imageInstance An instance of an image
1070 public final function setImageInstance (BaseImage $imageInstance) {
1071 $this->imageInstance = $imageInstance;
1075 * Getter for image instance
1077 * @return $imageInstance An instance of an image
1079 public final function getImageInstance () {
1080 return $this->imageInstance;
1084 * Setter for stacker instance
1086 * @param $stackInstance An instance of an stacker
1089 public final function setStackInstance (Stackable $stackInstance) {
1090 $this->stackInstance = $stackInstance;
1094 * Getter for stacker instance
1096 * @return $stackInstance An instance of an stacker
1098 public final function getStackInstance () {
1099 return $this->stackInstance;
1103 * Setter for compressor instance
1105 * @param $compressorInstance An instance of an compressor
1108 public final function setCompressorInstance (Compressor $compressorInstance) {
1109 $this->compressorInstance = $compressorInstance;
1113 * Getter for compressor instance
1115 * @return $compressorInstance An instance of an compressor
1117 public final function getCompressorInstance () {
1118 return $this->compressorInstance;
1122 * Setter for Parseable instance
1124 * @param $parserInstance An instance of an Parseable
1127 public final function setParserInstance (Parseable $parserInstance) {
1128 $this->parserInstance = $parserInstance;
1132 * Getter for Parseable instance
1134 * @return $parserInstance An instance of an Parseable
1136 public final function getParserInstance () {
1137 return $this->parserInstance;
1141 * Setter for HandleableProtocol instance
1143 * @param $protocolInstance An instance of an HandleableProtocol
1146 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1147 $this->protocolInstance = $protocolInstance;
1151 * Getter for HandleableProtocol instance
1153 * @return $protocolInstance An instance of an HandleableProtocol
1155 public final function getProtocolInstance () {
1156 return $this->protocolInstance;
1160 * Setter for DatabaseWrapper instance
1162 * @param $wrapperInstance An instance of an DatabaseWrapper
1165 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1166 $this->wrapperInstance = $wrapperInstance;
1170 * Getter for DatabaseWrapper instance
1172 * @return $wrapperInstance An instance of an DatabaseWrapper
1174 public final function getWrapperInstance () {
1175 return $this->wrapperInstance;
1179 * Setter for socket resource
1181 * @param $socketResource A valid socket resource
1184 public final function setSocketResource ($socketResource) {
1185 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1186 $this->socketResource = $socketResource;
1190 * Getter for socket resource
1192 * @return $socketResource A valid socket resource
1194 public final function getSocketResource () {
1195 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1196 return $this->socketResource;
1200 * Setter for regular expression
1202 * @param $regularExpression A valid regular expression
1205 public final function setRegularExpression ($regularExpression) {
1206 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1207 $this->regularExpression = $regularExpression;
1211 * Getter for regular expression
1213 * @return $regularExpression A valid regular expression
1215 public final function getRegularExpression () {
1216 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1217 return $this->regularExpression;
1221 * Setter for helper instance
1223 * @param $helperInstance An instance of a helper class
1226 protected final function setHelperInstance (Helper $helperInstance) {
1227 $this->helperInstance = $helperInstance;
1231 * Getter for helper instance
1233 * @return $helperInstance An instance of a helper class
1235 public final function getHelperInstance () {
1236 return $this->helperInstance;
1240 * Setter for a Source instance
1242 * @param $sourceInstance An instance of a Source class
1245 protected final function setSourceInstance (Source $sourceInstance) {
1246 $this->sourceInstance = $sourceInstance;
1250 * Getter for a Source instance
1252 * @return $sourceInstance An instance of a Source class
1254 protected final function getSourceInstance () {
1255 return $this->sourceInstance;
1259 * Setter for a UrlSource instance
1261 * @param $sourceInstance An instance of a UrlSource class
1264 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1265 $this->urlSourceInstance = $urlSourceInstance;
1269 * Getter for a UrlSource instance
1271 * @return $urlSourceInstance An instance of a UrlSource class
1273 protected final function getUrlSourceInstance () {
1274 return $this->urlSourceInstance;
1278 * Getter for a InputStream instance
1280 * @param $inputStreamInstance The InputStream instance
1282 protected final function getInputStreamInstance () {
1283 return $this->inputStreamInstance;
1287 * Setter for a InputStream instance
1289 * @param $inputStreamInstance The InputStream instance
1292 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1293 $this->inputStreamInstance = $inputStreamInstance;
1297 * Getter for a OutputStream instance
1299 * @param $outputStreamInstance The OutputStream instance
1301 protected final function getOutputStreamInstance () {
1302 return $this->outputStreamInstance;
1306 * Setter for a OutputStream instance
1308 * @param $outputStreamInstance The OutputStream instance
1311 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1312 $this->outputStreamInstance = $outputStreamInstance;
1316 * Setter for handler instance
1318 * @param $handlerInstance An instance of a Handleable class
1321 protected final function setHandlerInstance (Handleable $handlerInstance) {
1322 $this->handlerInstance = $handlerInstance;
1326 * Getter for handler instance
1328 * @return $handlerInstance A Handleable instance
1330 protected final function getHandlerInstance () {
1331 return $this->handlerInstance;
1335 * Setter for visitor instance
1337 * @param $visitorInstance A Visitor instance
1340 protected final function setVisitorInstance (Visitor $visitorInstance) {
1341 $this->visitorInstance = $visitorInstance;
1345 * Getter for visitor instance
1347 * @return $visitorInstance A Visitor instance
1349 protected final function getVisitorInstance () {
1350 return $this->visitorInstance;
1354 * Setter for DHT instance
1356 * @param $dhtInstance A Distributable instance
1359 protected final function setDhtInstance (Distributable $dhtInstance) {
1360 $this->dhtInstance = $dhtInstance;
1364 * Getter for DHT instance
1366 * @return $dhtInstance A Distributable instance
1368 protected final function getDhtInstance () {
1369 return $this->dhtInstance;
1373 * Setter for raw package Data
1375 * @param $packageData Raw package Data
1378 public final function setPackageData (array $packageData) {
1379 $this->packageData = $packageData;
1383 * Getter for raw package Data
1385 * @return $packageData Raw package Data
1387 public function getPackageData () {
1388 return $this->packageData;
1393 * Setter for Iterator instance
1395 * @param $iteratorInstance An instance of an Iterator
1398 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1399 $this->iteratorInstance = $iteratorInstance;
1403 * Getter for Iterator instance
1405 * @return $iteratorInstance An instance of an Iterator
1407 public final function getIteratorInstance () {
1408 return $this->iteratorInstance;
1412 * Setter for FilePointer instance
1414 * @param $pointerInstance An instance of an FilePointer class
1417 protected final function setPointerInstance (FilePointer $pointerInstance) {
1418 $this->pointerInstance = $pointerInstance;
1422 * Getter for FilePointer instance
1424 * @return $pointerInstance An instance of an FilePointer class
1426 public final function getPointerInstance () {
1427 return $this->pointerInstance;
1431 * Unsets pointer instance which triggers a call of __destruct() if the
1432 * instance is still there. This is surely not fatal on already "closed"
1433 * file pointer instances.
1435 * I don't want to mess around with above setter by giving it a default
1436 * value NULL as setter should always explicitly only set (existing) object
1437 * instances and NULL is NULL.
1441 protected final function unsetPointerInstance () {
1442 // Simply it to NULL
1443 $this->pointerInstance = NULL;
1447 * Setter for Indexable instance
1449 * @param $indexInstance An instance of an Indexable class
1452 protected final function setIndexInstance (Indexable $indexInstance) {
1453 $this->indexInstance = $indexInstance;
1457 * Getter for Indexable instance
1459 * @return $indexInstance An instance of an Indexable class
1461 public final function getIndexInstance () {
1462 return $this->indexInstance;
1466 * Setter for Block instance
1468 * @param $blockInstance An instance of an Block class
1471 protected final function setBlockInstance (Block $blockInstance) {
1472 $this->blockInstance = $blockInstance;
1476 * Getter for Block instance
1478 * @return $blockInstance An instance of an Block class
1480 public final function getBlockInstance () {
1481 return $this->blockInstance;
1485 * Setter for Minable instance
1487 * @param $minableInstance A Minable instance
1490 protected final function setMinableInstance (Minable $minableInstance) {
1491 $this->minableInstance = $minableInstance;
1495 * Getter for minable instance
1497 * @return $minableInstance A Minable instance
1499 protected final function getMinableInstance () {
1500 return $this->minableInstance;
1504 * Setter for FrameworkDirectory instance
1506 * @param $directoryInstance A FrameworkDirectory instance
1509 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1510 $this->directoryInstance = $directoryInstance;
1514 * Getter for FrameworkDirectory instance
1516 * @return $directoryInstance A FrameworkDirectory instance
1518 protected final function getDirectoryInstance () {
1519 return $this->directoryInstance;
1523 * Getter for communicator instance
1525 * @return $communicatorInstance An instance of a Communicator class
1527 public final function getCommunicatorInstance () {
1528 return $this->communicatorInstance;
1532 * Setter for communicator instance
1534 * @param $communicatorInstance An instance of a Communicator class
1537 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1538 $this->communicatorInstance = $communicatorInstance;
1542 * Setter for state instance
1544 * @param $stateInstance A Stateable instance
1547 public final function setStateInstance (Stateable $stateInstance) {
1548 $this->stateInstance = $stateInstance;
1552 * Getter for state instance
1554 * @return $stateInstance A Stateable instance
1556 public final function getStateInstance () {
1557 return $this->stateInstance;
1561 * Setter for output instance
1563 * @param $outputInstance The debug output instance
1566 public final function setOutputInstance (OutputStreamer $outputInstance) {
1567 $this->outputInstance = $outputInstance;
1571 * Getter for output instance
1573 * @return $outputInstance The debug output instance
1575 public final function getOutputInstance () {
1576 return $this->outputInstance;
1580 * Setter for command name
1582 * @param $commandName Last validated command name
1585 protected final function setCommandName ($commandName) {
1586 $this->commandName = $commandName;
1590 * Getter for command name
1592 * @return $commandName Last validated command name
1594 protected final function getCommandName () {
1595 return $this->commandName;
1599 * Setter for controller name
1601 * @param $controllerName Last validated controller name
1604 protected final function setControllerName ($controllerName) {
1605 $this->controllerName = $controllerName;
1609 * Getter for controller name
1611 * @return $controllerName Last validated controller name
1613 protected final function getControllerName () {
1614 return $this->controllerName;
1618 * Getter for protocol name
1620 * @return $protocolName Name of used protocol
1622 public final function getProtocolName () {
1623 return $this->protocolName;
1627 * Setter for protocol name
1629 * @param $protocolName Name of used protocol
1632 protected final function setProtocolName ($protocolName) {
1633 $this->protocolName = $protocolName;
1637 * Checks whether an object equals this object. You should overwrite this
1638 * method to implement own equality checks
1640 * @param $objectInstance An instance of a FrameworkInterface object
1641 * @return $equals Whether both objects equals
1643 public function equals (FrameworkInterface $objectInstance) {
1646 $this->__toString() == $objectInstance->__toString()
1648 $this->hashCode() == $objectInstance->hashCode()
1651 // Return the result
1656 * Generates a generic hash code of this class. You should really overwrite
1657 * this method with your own hash code generator code. But keep KISS in mind.
1659 * @return $hashCode A generic hash code respresenting this whole class
1661 public function hashCode () {
1663 return crc32($this->__toString());
1667 * Formats computer generated price values into human-understandable formats
1668 * with thousand and decimal separators.
1670 * @param $value The in computer format value for a price
1671 * @param $currency The currency symbol (use HTML-valid characters!)
1672 * @param $decNum Number of decimals after commata
1673 * @return $price The for the current language formated price string
1674 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1675 * thousands separator
1678 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1679 // Are all required attriutes set?
1680 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1681 // Throw an exception
1682 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1686 $value = (float) $value;
1688 // Reformat the US number
1689 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1691 // Return as string...
1696 * Appends a trailing slash to a string
1698 * @param $str A string (maybe) without trailing slash
1699 * @return $str A string with an auto-appended trailing slash
1701 public final function addMissingTrailingSlash ($str) {
1702 // Is there a trailing slash?
1703 if (substr($str, -1, 1) != '/') {
1707 // Return string with trailing slash
1712 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1713 * application helper instance (ApplicationHelper by default).
1715 * @param $applicationInstance An application helper instance or
1716 * null if we shall use the default
1717 * @return $templateInstance The template engine instance
1718 * @throws NullPointerException If the discovered application
1719 * instance is still null
1721 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1722 // Is the application instance set?
1723 if (is_null($applicationInstance)) {
1724 // Get the current instance
1725 $applicationInstance = Registry::getRegistry()->getInstance('app');
1728 if (is_null($applicationInstance)) {
1729 // Thrown an exception
1730 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1734 // Initialize the template engine
1735 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1737 // Return the prepared instance
1738 return $templateInstance;
1742 * Debugs this instance by putting out it's full content
1744 * @param $message Optional message to show in debug output
1747 public final function debugInstance ($message = '') {
1748 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1749 restore_error_handler();
1754 // Is a message set?
1755 if (!empty($message)) {
1756 // Construct message
1757 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1760 // Generate the output
1761 $content .= sprintf('<pre>%s</pre>',
1764 print_r($this, true)
1770 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>',
1771 $this->__toString(),
1773 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1778 * Replaces control characters with printable output
1780 * @param $str String with control characters
1781 * @return $str Replaced string
1783 protected function replaceControlCharacters ($str) {
1786 chr(13), '[r]', str_replace(
1787 chr(10), '[n]', str_replace(
1797 * Output a partial stub message for the caller method
1799 * @param $message An optional message to display
1802 protected function partialStub ($message = '') {
1803 // Get the backtrace
1804 $backtrace = debug_backtrace();
1806 // Generate the class::method string
1807 $methodName = 'UnknownClass->unknownMethod';
1808 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1809 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1812 // Construct the full message
1813 $stubMessage = sprintf('[%s:] Partial stub!',
1817 // Is the extra message given?
1818 if (!empty($message)) {
1819 // Then add it as well
1820 $stubMessage .= ' Message: ' . $message;
1823 // Debug instance is there?
1824 if (!is_null($this->getDebugInstance())) {
1825 // Output stub message
1826 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1829 trigger_error($stubMessage);
1835 * Outputs a debug backtrace and stops further script execution
1837 * @param $message An optional message to output
1838 * @param $doExit Whether exit the program (true is default)
1841 public function debugBackTrace ($message = '', $doExit = true) {
1842 // Sorry, there is no other way getting this nice backtrace
1843 if (!empty($message)) {
1845 printf('Message: %s<br />' . PHP_EOL, $message);
1849 debug_print_backtrace();
1853 if ($doExit === true) {
1859 * Creates an instance of a debugger instance
1861 * @param $className Name of the class (currently unsupported)
1862 * @param $lineNumber Line number where the call was made
1863 * @return $debugInstance An instance of a debugger class
1864 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1866 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1867 // Is the instance set?
1868 if (!Registry::getRegistry()->instanceExists('debug')) {
1869 // Init debug instance
1870 $debugInstance = NULL;
1874 // Get a debugger instance
1875 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1876 } catch (NullPointerException $e) {
1877 // Didn't work, no instance there
1878 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1881 // Empty string should be ignored and used for testing the middleware
1882 DebugMiddleware::getSelfInstance()->output('');
1884 // Set it in its own class. This will set it in the registry
1885 $debugInstance->setDebugInstance($debugInstance);
1887 // Get instance from registry
1888 $debugInstance = Registry::getRegistry()->getDebugInstance();
1892 return $debugInstance;
1896 * Simple output of a message with line-break
1898 * @param $message Message to output
1901 public function outputLine ($message) {
1903 print($message . PHP_EOL);
1907 * Outputs a debug message whether to debug instance (should be set!) or
1908 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1909 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1911 * @param $message Message we shall send out...
1912 * @param $doPrint Whether print or die here (default: print)
1913 * @paran $stripTags Whether to strip tags (default: false)
1916 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1917 // Set debug instance to NULL
1918 $debugInstance = NULL;
1922 // Get debug instance
1923 $debugInstance = $this->getDebugInstance();
1924 } catch (NullPointerException $e) {
1925 // The debug instance is not set (yet)
1928 // Is the debug instance there?
1929 if (is_object($debugInstance)) {
1930 // Use debug output handler
1931 $debugInstance->output($message, $stripTags);
1933 if ($doPrint === false) {
1934 // Die here if not printed
1938 // Are debug times enabled?
1939 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1941 $message = $this->getPrintableExecutionTime() . $message;
1945 if ($doPrint === true) {
1947 $this->outputLine($message);
1956 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1958 * @param $str The string, what ever it is needs to be converted
1959 * @return $className Generated class name
1961 public static final function convertToClassName ($str) {
1965 // Convert all dashes in underscores
1966 $str = self::convertDashesToUnderscores($str);
1968 // Now use that underscores to get classname parts for hungarian style
1969 foreach (explode('_', $str) as $strPart) {
1970 // Make the class name part lower case and first upper case
1971 $className .= ucfirst(strtolower($strPart));
1974 // Return class name
1979 * Converts dashes to underscores, e.g. useable for configuration entries
1981 * @param $str The string with maybe dashes inside
1982 * @return $str The converted string with no dashed, but underscores
1984 public static final function convertDashesToUnderscores ($str) {
1986 $str = str_replace('-', '_', $str);
1988 // Return converted string
1993 * Marks up the code by adding e.g. line numbers
1995 * @param $phpCode Unmarked PHP code
1996 * @return $markedCode Marked PHP code
1998 public function markupCode ($phpCode) {
2003 $errorArray = error_get_last();
2005 // Init the code with error message
2006 if (is_array($errorArray)) {
2008 $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>',
2009 basename($errorArray['file']),
2010 $errorArray['line'],
2011 $errorArray['message'],
2016 // Add line number to the code
2017 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2019 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2021 htmlentities($code, ENT_QUOTES)
2030 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2031 * beatiful for web-based front-ends. If null is given a message id
2032 * null_timestamp will be resolved and returned.
2034 * @param $timestamp Timestamp to prepare (filter) for display
2035 * @return $readable A readable timestamp
2037 public function doFilterFormatTimestamp ($timestamp) {
2038 // Default value to return
2041 // Is the timestamp null?
2042 if (is_null($timestamp)) {
2043 // Get a message string
2044 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2046 switch ($this->getLanguageInstance()->getLanguageCode()) {
2047 case 'de': // German format is a bit different to default
2048 // Split the GMT stamp up
2049 $dateTime = explode(' ', $timestamp );
2050 $dateArray = explode('-', $dateTime[0]);
2051 $timeArray = explode(':', $dateTime[1]);
2053 // Construct the timestamp
2054 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2064 default: // Default is pass-through
2065 $readable = $timestamp;
2075 * Filter a given number into a localized number
2077 * @param $value The raw value from e.g. database
2078 * @return $localized Localized value
2080 public function doFilterFormatNumber ($value) {
2081 // Generate it from config and localize dependencies
2082 switch ($this->getLanguageInstance()->getLanguageCode()) {
2083 case 'de': // German format is a bit different to default
2084 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2087 default: // US, etc.
2088 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2097 * "Getter" for databse entry
2099 * @return $entry An array with database entries
2100 * @throws NullPointerException If the database result is not found
2101 * @throws InvalidDatabaseResultException If the database result is invalid
2103 protected final function getDatabaseEntry () {
2104 // Is there an instance?
2105 if (!$this->getResultInstance() instanceof SearchableResult) {
2106 // Throw an exception here
2107 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2111 $this->getResultInstance()->rewind();
2113 // Do we have an entry?
2114 if ($this->getResultInstance()->valid() === false) {
2115 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2116 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2120 $this->getResultInstance()->next();
2123 $entry = $this->getResultInstance()->current();
2130 * Getter for field name
2132 * @param $fieldName Field name which we shall get
2133 * @return $fieldValue Field value from the user
2134 * @throws NullPointerException If the result instance is null
2136 public final function getField ($fieldName) {
2137 // Default field value
2140 // Get result instance
2141 $resultInstance = $this->getResultInstance();
2143 // Is this instance null?
2144 if (is_null($resultInstance)) {
2145 // Then the user instance is no longer valid (expired cookies?)
2146 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2149 // Get current array
2150 $fieldArray = $resultInstance->current();
2151 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2153 // Convert dashes to underscore
2154 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2156 // Does the field exist?
2157 if ($this->isFieldSet($fieldName)) {
2159 $fieldValue = $fieldArray[$fieldName2];
2160 } elseif (defined('DEVELOPER')) {
2161 // Missing field entry, may require debugging
2162 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2164 // Missing field entry, may require debugging
2165 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2173 * Checks if given field is set
2175 * @param $fieldName Field name to check
2176 * @return $isSet Whether the given field name is set
2177 * @throws NullPointerException If the result instance is null
2179 public function isFieldSet ($fieldName) {
2180 // Get result instance
2181 $resultInstance = $this->getResultInstance();
2183 // Is this instance null?
2184 if (is_null($resultInstance)) {
2185 // Then the user instance is no longer valid (expired cookies?)
2186 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2189 // Get current array
2190 $fieldArray = $resultInstance->current();
2191 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2193 // Convert dashes to underscore
2194 $fieldName = self::convertDashesToUnderscores($fieldName);
2197 $isSet = isset($fieldArray[$fieldName]);
2204 * Flushs all pending updates to the database layer
2208 public function flushPendingUpdates () {
2209 // Get result instance
2210 $resultInstance = $this->getResultInstance();
2212 // Do we have data to update?
2213 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2214 // Get wrapper class name config entry
2215 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2217 // Create object instance
2218 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2220 // Yes, then send the whole result to the database layer
2221 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2226 * Outputs a deprecation warning to the developer.
2228 * @param $message The message we shall output to the developer
2230 * @todo Write a logging mechanism for productive mode
2232 public function deprecationWarning ($message) {
2233 // Is developer mode active?
2234 if (defined('DEVELOPER')) {
2235 // Debug instance is there?
2236 if (!is_null($this->getDebugInstance())) {
2237 // Output stub message
2238 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2241 trigger_error($message . "<br />\n");
2245 // @TODO Finish this part!
2246 $this->partialStub('Developer mode inactive. Message:' . $message);
2251 * Checks whether the given PHP extension is loaded
2253 * @param $phpExtension The PHP extension we shall check
2254 * @return $isLoaded Whether the PHP extension is loaded
2256 public final function isPhpExtensionLoaded ($phpExtension) {
2258 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2265 * "Getter" as a time() replacement but with milliseconds. You should use this
2266 * method instead of the encapsulated getimeofday() function.
2268 * @return $milliTime Timestamp with milliseconds
2270 public function getMilliTime () {
2271 // Get the time of day as float
2272 $milliTime = gettimeofday(true);
2279 * Idles (sleeps) for given milliseconds
2281 * @return $hasSlept Whether it goes fine
2283 public function idle ($milliSeconds) {
2284 // Sleep is fine by default
2287 // Idle so long with found function
2288 if (function_exists('time_sleep_until')) {
2289 // Get current time and add idle time
2290 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2292 // New PHP 5.1.0 function found, ignore errors
2293 $hasSlept = @time_sleep_until($sleepUntil);
2296 * My Sun station doesn't have that function even with latest PHP
2299 usleep($milliSeconds * 1000);
2306 * Converts a hexadecimal string, even with negative sign as first string to
2307 * a decimal number using BC functions.
2309 * This work is based on comment #86673 on php.net documentation page at:
2310 * <http://de.php.net/manual/en/function.dechex.php#86673>
2312 * @param $hex Hexadecimal string
2313 * @return $dec Decimal number
2315 protected function hex2dec ($hex) {
2316 // Convert to all lower-case
2317 $hex = strtolower($hex);
2319 // Detect sign (negative/positive numbers)
2321 if (substr($hex, 0, 1) == '-') {
2323 $hex = substr($hex, 1);
2326 // Decode the hexadecimal string into a decimal number
2328 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2329 $factor = self::$hexdec[substr($hex, $i, 1)];
2330 $dec = bcadd($dec, bcmul($factor, $e));
2333 // Return the decimal number
2334 return $sign . $dec;
2338 * Converts even very large decimal numbers, also signed, to a hexadecimal
2341 * This work is based on comment #97756 on php.net documentation page at:
2342 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2344 * @param $dec Decimal number, even with negative sign
2345 * @param $maxLength Optional maximum length of the string
2346 * @return $hex Hexadecimal string
2348 protected function dec2hex ($dec, $maxLength = 0) {
2349 // maxLength can be zero or devideable by 2
2350 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2352 // Detect sign (negative/positive numbers)
2359 // Encode the decimal number into a hexadecimal string
2362 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2364 } while ($dec >= 1);
2367 * Leading zeros are required for hex-decimal "numbers". In some
2368 * situations more leading zeros are wanted, so check for both
2371 if ($maxLength > 0) {
2372 // Prepend more zeros
2373 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2374 } elseif ((strlen($hex) % 2) != 0) {
2375 // Only make string's length dividable by 2
2379 // Return the hexadecimal string
2380 return $sign . $hex;
2384 * Converts a ASCII string (0 to 255) into a decimal number.
2386 * @param $asc The ASCII string to be converted
2387 * @return $dec Decimal number
2389 protected function asc2dec ($asc) {
2390 // Convert it into a hexadecimal number
2391 $hex = bin2hex($asc);
2393 // And back into a decimal number
2394 $dec = $this->hex2dec($hex);
2401 * Converts a decimal number into an ASCII string.
2403 * @param $dec Decimal number
2404 * @return $asc An ASCII string
2406 protected function dec2asc ($dec) {
2407 // First convert the number into a hexadecimal string
2408 $hex = $this->dec2hex($dec);
2410 // Then convert it into the ASCII string
2411 $asc = $this->hex2asc($hex);
2418 * Converts a hexadecimal number into an ASCII string. Negative numbers
2421 * @param $hex Hexadecimal string
2422 * @return $asc An ASCII string
2424 protected function hex2asc ($hex) {
2425 // Check for length, it must be devideable by 2
2426 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2427 assert((strlen($hex) % 2) == 0);
2431 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2432 // Get the decimal number of the chunk
2433 $part = hexdec(substr($hex, $idx, 2));
2435 // Add it to the final string
2439 // Return the final string
2444 * Checks whether the given encoded data was encoded with Base64
2446 * @param $encodedData Encoded data we shall check
2447 * @return $isBase64 Whether the encoded data is Base64
2449 protected function isBase64Encoded ($encodedData) {
2451 $isBase64 = (@base64_decode($encodedData, true) !== false);
2458 * Gets a cache key from Criteria instance
2460 * @param $criteriaInstance An instance of a Criteria class
2461 * @param $onlyKeys Only use these keys for a cache key
2462 * @return $cacheKey A cache key suitable for lookup/storage purposes
2464 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2466 $cacheKey = sprintf('%s@%s',
2467 $this->__toString(),
2468 $criteriaInstance->getCacheKey($onlyKeys)
2472 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2477 * Getter for startup time in miliseconds
2479 * @return $startupTime Startup time in miliseconds
2481 protected function getStartupTime () {
2482 return self::$startupTime;
2486 * "Getter" for a printable currently execution time in nice braces
2488 * @return $executionTime Current execution time in nice braces
2490 protected function getPrintableExecutionTime () {
2491 // Caculate the execution time
2492 $executionTime = microtime(true) - $this->getStartupTime();
2494 // Pack it in nice braces
2495 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2498 return $executionTime;
2502 * Hashes a given string with a simple but stronger hash function (no salt)
2503 * and hex-encode it.
2505 * @param $str The string to be hashed
2506 * @return $hash The hash from string $str
2508 public static final function hash ($str) {
2509 // Hash given string with (better secure) hasher
2510 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2517 * "Getter" for length of hash() output. This will be "cached" to speed up
2520 * @return $length Length of hash() output
2522 public static final function getHashLength () {
2524 if (is_null(self::$hashLength)) {
2525 // No, then hash a string and save its length.
2526 self::$hashLength = strlen(self::hash('abc123'));
2530 return self::$hashLength;
2534 * Checks whether the given number is really a number (only chars 0-9).
2536 * @param $num A string consisting only chars between 0 and 9
2537 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2538 * @param $assertMismatch Whether to assert mismatches
2539 * @return $ret The (hopefully) secured numbered value
2541 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2542 // Filter all numbers out
2543 $ret = preg_replace('/[^0123456789]/', '', $num);
2546 if ($castValue === true) {
2547 // Cast to biggest numeric type
2548 $ret = (double) $ret;
2551 // Assert only if requested
2552 if ($assertMismatch === true) {
2553 // Has the whole value changed?
2554 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2562 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2564 * @param $num A string consisting only chars between 0 and 9
2565 * @param $assertMismatch Whether to assert mismatches
2566 * @return $ret The (hopefully) secured hext-numbered value
2568 public function hexval ($num, $assertMismatch = false) {
2569 // Filter all numbers out
2570 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2572 // Assert only if requested
2573 if ($assertMismatch === true) {
2574 // Has the whole value changed?
2575 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2583 * Checks whether start/end marker are set
2585 * @param $data Data to be checked
2586 * @return $isset Whether start/end marker are set
2588 public final function ifStartEndMarkersSet ($data) {
2590 $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));
2592 // ... and return it
2597 * Determines if an element is set in the generic array
2599 * @param $keyGroup Main group for the key
2600 * @param $subGroup Sub group for the key
2601 * @param $key Key to check
2602 * @param $element Element to check
2603 * @return $isset Whether the given key is set
2605 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2607 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2610 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2616 * Determines if a key is set in the generic array
2618 * @param $keyGroup Main group for the key
2619 * @param $subGroup Sub group for the key
2620 * @param $key Key to check
2621 * @return $isset Whether the given key is set
2623 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2625 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2628 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2636 * Determines if a group is set in the generic array
2638 * @param $keyGroup Main group
2639 * @param $subGroup Sub group
2640 * @return $isset Whether the given group is set
2642 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2644 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2647 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2654 * Getter for sub key group
2656 * @param $keyGroup Main key group
2657 * @param $subGroup Sub key group
2658 * @return $array An array with all array elements
2660 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2662 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2663 // No, then abort here
2664 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2669 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2672 return $this->genericArray[$keyGroup][$subGroup];
2676 * Unsets a given key in generic array
2678 * @param $keyGroup Main group for the key
2679 * @param $subGroup Sub group for the key
2680 * @param $key Key to unset
2683 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2685 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2688 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2692 * Unsets a given element in generic array
2694 * @param $keyGroup Main group for the key
2695 * @param $subGroup Sub group for the key
2696 * @param $key Key to unset
2697 * @param $element Element to unset
2700 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2702 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2705 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2709 * Append a string to a given generic array key
2711 * @param $keyGroup Main group for the key
2712 * @param $subGroup Sub group for the key
2713 * @param $key Key to unset
2714 * @param $value Value to add/append
2717 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2719 //* 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);
2721 // Is it already there?
2722 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2724 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2727 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2732 * Append a string to a given generic array element
2734 * @param $keyGroup Main group for the key
2735 * @param $subGroup Sub group for the key
2736 * @param $key Key to unset
2737 * @param $element Element to check
2738 * @param $value Value to add/append
2741 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2743 //* 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);
2745 // Is it already there?
2746 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2748 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2751 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2756 * Sets a string in a given generic array element
2758 * @param $keyGroup Main group for the key
2759 * @param $subGroup Sub group for the key
2760 * @param $key Key to unset
2761 * @param $element Element to check
2762 * @param $value Value to add/append
2765 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2767 //* 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);
2770 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2774 * Initializes given generic array group
2776 * @param $keyGroup Main group for the key
2777 * @param $subGroup Sub group for the key
2778 * @param $key Key to use
2779 * @param $forceInit Optionally force initialization
2782 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2784 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2786 // Is it already set?
2787 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2788 // Already initialized
2789 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2794 $this->genericArray[$keyGroup][$subGroup] = array();
2798 * Initializes given generic array key
2800 * @param $keyGroup Main group for the key
2801 * @param $subGroup Sub group for the key
2802 * @param $key Key to use
2803 * @param $forceInit Optionally force initialization
2806 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2808 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2810 // Is it already set?
2811 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2812 // Already initialized
2813 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2818 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2822 * Initializes given generic array element
2824 * @param $keyGroup Main group for the key
2825 * @param $subGroup Sub group for the key
2826 * @param $key Key to use
2827 * @param $element Element to use
2828 * @param $forceInit Optionally force initialization
2831 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2833 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2835 // Is it already set?
2836 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2837 // Already initialized
2838 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2843 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2847 * Pushes an element to a generic key
2849 * @param $keyGroup Main group for the key
2850 * @param $subGroup Sub group for the key
2851 * @param $key Key to use
2852 * @param $value Value to add/append
2853 * @return $count Number of array elements
2855 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2857 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2860 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2862 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2866 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2869 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2870 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2875 * Pushes an element to a generic array element
2877 * @param $keyGroup Main group for the key
2878 * @param $subGroup Sub group for the key
2879 * @param $key Key to use
2880 * @param $element Element to check
2881 * @param $value Value to add/append
2882 * @return $count Number of array elements
2884 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2886 //* 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));
2889 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2891 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2895 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2898 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2899 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2904 * Pops an element from a generic group
2906 * @param $keyGroup Main group for the key
2907 * @param $subGroup Sub group for the key
2908 * @param $key Key to unset
2909 * @return $value Last "popped" value
2911 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2913 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2916 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2918 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2923 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2926 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2927 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2932 * Shifts an element from a generic group
2934 * @param $keyGroup Main group for the key
2935 * @param $subGroup Sub group for the key
2936 * @param $key Key to unset
2937 * @return $value Last "popped" value
2939 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2941 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2944 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2946 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2951 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2954 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2955 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2960 * Count generic array group
2962 * @param $keyGroup Main group for the key
2963 * @return $count Count of given group
2965 protected final function countGenericArray ($keyGroup) {
2967 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2970 if (!isset($this->genericArray[$keyGroup])) {
2972 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2977 $count = count($this->genericArray[$keyGroup]);
2980 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2987 * Count generic array sub group
2989 * @param $keyGroup Main group for the key
2990 * @param $subGroup Sub group for the key
2991 * @return $count Count of given group
2993 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2995 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2998 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3000 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3005 $count = count($this->genericArray[$keyGroup][$subGroup]);
3008 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3015 * Count generic array elements
3017 * @param $keyGroup Main group for the key
3018 * @param $subGroup Sub group for the key
3019 * @para $key Key to count
3020 * @return $count Count of given key
3022 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3024 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3027 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3029 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3031 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3033 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3038 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3041 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3048 * Getter for whole generic group array
3050 * @param $keyGroup Key group to get
3051 * @return $array Whole generic array group
3053 protected final function getGenericArray ($keyGroup) {
3055 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3058 if (!isset($this->genericArray[$keyGroup])) {
3060 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3065 return $this->genericArray[$keyGroup];
3069 * Setter for generic array key
3071 * @param $keyGroup Key group to get
3072 * @param $subGroup Sub group for the key
3073 * @param $key Key to unset
3074 * @param $value Mixed value from generic array element
3077 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3079 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3082 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3086 * Getter for generic array key
3088 * @param $keyGroup Key group to get
3089 * @param $subGroup Sub group for the key
3090 * @param $key Key to unset
3091 * @return $value Mixed value from generic array element
3093 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3095 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3098 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3100 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3105 return $this->genericArray[$keyGroup][$subGroup][$key];
3109 * Sets a value in given generic array key/element
3111 * @param $keyGroup Main group for the key
3112 * @param $subGroup Sub group for the key
3113 * @param $key Key to set
3114 * @param $element Element to set
3115 * @param $value Value to set
3118 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3120 //* 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));
3123 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3127 * Getter for generic array element
3129 * @param $keyGroup Key group to get
3130 * @param $subGroup Sub group for the key
3131 * @param $key Key to look for
3132 * @param $element Element to look for
3133 * @return $value Mixed value from generic array element
3135 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3137 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3140 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3142 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3147 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3151 * Checks if a given sub group is valid (array)
3153 * @param $keyGroup Key group to get
3154 * @param $subGroup Sub group for the key
3155 * @return $isValid Whether given sub group is valid
3157 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3159 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3162 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3169 * Checks if a given key is valid (array)
3171 * @param $keyGroup Key group to get
3172 * @param $subGroup Sub group for the key
3173 * @param $key Key to check
3174 * @return $isValid Whether given sub group is valid
3176 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3178 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3181 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3188 * Initializes the web output instance
3192 protected function initWebOutputInstance () {
3193 // Get application instance
3194 $applicationInstance = Registry::getRegistry()->getInstance('app');
3196 // Init web output instance
3197 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3200 $this->setWebOutputInstance($outputInstance);
3204 * Translates boolean true to 'Y' and false to 'N'
3206 * @param $boolean Boolean value
3207 * @return $translated Translated boolean value
3209 public static final function translateBooleanToYesNo ($boolean) {
3210 // Make sure it is really boolean
3211 assert(is_bool($boolean));
3214 $translated = ($boolean === true) ? 'Y' : 'N';
3216 // ... and return it
3221 * Encodes raw data (almost any type) by "serializing" it and then pack it
3222 * into a "binary format".
3224 * @param $rawData Raw data (almost any type)
3225 * @return $encoded Encoded data
3227 protected function encodeData ($rawData) {
3228 // Make sure no objects or resources pass through
3229 assert(!is_object($rawData));
3230 assert(!is_resource($rawData));
3232 // First "serialize" it (json_encode() is faster than serialize())
3233 $encoded = $this->packString(json_encode($rawData));
3240 * Pack a string into a "binary format". Please execuse me that this is
3241 * widely undocumented. :-(
3243 * @param $str Unpacked string
3244 * @return $packed Packed string
3245 * @todo Improve documentation
3247 protected function packString ($str) {
3249 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3251 // First compress the string (gzcompress is okay)
3252 $str = gzcompress($str);
3257 // And start the "encoding" loop
3258 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3260 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3261 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3263 if (($idx + $i) <= strlen($str)) {
3264 $ord = ord(substr($str, ($idx + $i), 1));
3266 $add = $ord * pow(256, $factor);
3270 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3274 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3275 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3277 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3278 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3284 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3289 * Creates a full-qualified file name (FQFN) for given file name by adding
3290 * a configured temporary file path to it.
3292 * @param $fileName Name for temporary file
3293 * @return $fqfn Full-qualified file name
3294 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3295 * @throws FileIoException If the file cannot be written
3297 protected static function createTempPathForFile ($fileName) {
3299 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3301 // Is the path writeable?
3302 if (!is_writable($basePath)) {
3303 // Path is write-protected
3304 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3308 $fqfn = $basePath . '/' . $fileName;
3311 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3313 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3321 * "Getter" for a printable state name
3323 * @return $stateName Name of the node's state in a printable format
3325 public final function getPrintableState () {
3326 // Default is 'null'
3327 $stateName = 'null';
3329 // Get the state instance
3330 $stateInstance = $this->getStateInstance();
3332 // Is it an instance of Stateable?
3333 if ($stateInstance instanceof Stateable) {
3334 // Then use that state name
3335 $stateName = $stateInstance->getStateName();