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\Handleable;
27 use CoreFramework\Handler\Stream\IoHandler;
28 use CoreFramework\Index\Indexable;
29 use CoreFramework\Lists\Listable;
30 use CoreFramework\Loader\ClassLoader;
31 use CoreFramework\Manager\ManageableApplication;
32 use CoreFramework\Middleware\Compressor\CompressorChannel;
33 use CoreFramework\Middleware\Debug\DebugMiddleware;
34 use CoreFramework\Parser\Parseable;
35 use CoreFramework\Registry\Register;
36 use CoreFramework\Registry\Registry;
37 use CoreFramework\Resolver\Resolver;
38 use CoreFramework\Result\Database\CachedDatabaseResult;
39 use CoreFramework\Result\Search\SearchableResult;
40 use CoreFramework\Stacker\Stackable;
41 use CoreFramework\State\Stateable;
42 use CoreFramework\Stream\Input\InputStream;
43 use CoreFramework\Stream\Output\OutputStreamer;
44 use CoreFramework\Template\CompileableTemplate;
45 use CoreFramework\User\ManageableAccount;
46 use CoreFramework\Visitor\Visitor;
54 * The simulator system class is the super class of all other classes. This
55 * class handles saving of games etc.
57 * @author Roland Haeder <webmaster@shipsimu.org>
59 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
60 * @license GNU GPL 3.0 or any newer version
61 * @link http://www.shipsimu.org
63 * This program is free software: you can redistribute it and/or modify
64 * it under the terms of the GNU General Public License as published by
65 * the Free Software Foundation, either version 3 of the License, or
66 * (at your option) any later version.
68 * This program is distributed in the hope that it will be useful,
69 * but WITHOUT ANY WARRANTY; without even the implied warranty of
70 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
71 * GNU General Public License for more details.
73 * You should have received a copy of the GNU General Public License
74 * along with this program. If not, see <http://www.gnu.org/licenses/>.
76 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
78 * Length of output from hash()
80 private static $hashLength = NULL;
85 private $realClass = 'BaseFrameworkSystem';
88 * Search criteria instance
90 private $searchInstance = NULL;
93 * Update criteria instance
95 private $updateInstance = NULL;
98 * The file I/O instance for the template loader
100 private $fileIoInstance = NULL;
105 private $resolverInstance = NULL;
108 * Template engine instance
110 private $templateInstance = NULL;
113 * Database result instance
115 private $resultInstance = NULL;
118 * Instance for user class
120 private $userInstance = NULL;
123 * A controller instance
125 private $controllerInstance = NULL;
130 private $rngInstance = NULL;
133 * Instance of a crypto helper
135 private $cryptoInstance = NULL;
138 * Instance of an Iterator class
140 private $iteratorInstance = NULL;
143 * Instance of the list
145 private $listInstance = NULL;
150 private $menuInstance = NULL;
153 * Instance of the image
155 private $imageInstance = NULL;
158 * Instance of the stacker
160 private $stackInstance = NULL;
163 * A Compressor instance
165 private $compressorInstance = NULL;
168 * A Parseable instance
170 private $parserInstance = NULL;
173 * A database wrapper instance
175 private $databaseInstance = NULL;
178 * A helper instance for the form
180 private $helperInstance = NULL;
183 * An instance of a Source class
185 private $sourceInstance = NULL;
188 * An instance of a UrlSource class
190 private $urlSourceInstance = NULL;
193 * An instance of a InputStream class
195 private $inputStreamInstance = NULL;
198 * An instance of a OutputStream class
200 private $outputStreamInstance = NULL;
205 private $handlerInstance = NULL;
208 * Visitor handler instance
210 private $visitorInstance = NULL;
213 * An instance of a database wrapper class
215 private $wrapperInstance = NULL;
218 * An instance of a file I/O pointer class (not handler)
220 private $pointerInstance = NULL;
223 * An instance of an Indexable class
225 private $indexInstance = NULL;
228 * An instance of a Block class
230 private $blockInstance = NULL;
235 private $minableInstance = NULL;
238 * A FrameworkDirectory instance
240 private $directoryInstance = NULL;
243 * An instance of a communicator
245 private $communicatorInstance = NULL;
248 * The concrete output instance
250 private $outputInstance = NULL;
255 private $stateInstance = NULL;
258 * Thousands separator
260 private $thousands = '.'; // German
265 private $decimals = ','; // German
270 private $socketResource = false;
273 * Regular expression to use for validation
275 private $regularExpression = '';
280 private $packageData = array();
285 private $genericArray = array();
290 private $commandName = '';
295 private $controllerName = '';
298 * Array with bitmasks and such for pack/unpack methods to support both
299 * 32-bit and 64-bit systems
301 private $packingData = array(
304 'left' => 0xffff0000,
305 'right' => 0x0000ffff,
311 'left' => 0xffffffff00000000,
312 'right' => 0x00000000ffffffff,
319 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
321 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
323 private $archArrayElement = false;
325 /***********************
326 * Exception codes.... *
327 ***********************/
329 // @todo Try to clean these constants up
330 const EXCEPTION_IS_NULL_POINTER = 0x001;
331 const EXCEPTION_IS_NO_OBJECT = 0x002;
332 const EXCEPTION_IS_NO_ARRAY = 0x003;
333 const EXCEPTION_MISSING_METHOD = 0x004;
334 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
335 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
336 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
337 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
338 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
339 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
340 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
341 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
342 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
343 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
344 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
345 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
346 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
347 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
348 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
349 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
350 const EXCEPTION_PATH_NOT_FOUND = 0x015;
351 const EXCEPTION_INVALID_PATH_NAME = 0x016;
352 const EXCEPTION_READ_PROTECED_PATH = 0x017;
353 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
354 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
355 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
356 const EXCEPTION_INVALID_RESOURCE = 0x01b;
357 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
358 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
359 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
360 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
361 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
362 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
363 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
364 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
365 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
366 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
367 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
368 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
369 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
370 const EXCEPTION_INVALID_STRING = 0x029;
371 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
372 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
373 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
374 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
375 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
376 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
377 const EXCEPTION_MISSING_ELEMENT = 0x030;
378 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
379 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
380 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
381 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
382 const EXCEPTION_FATAL_ERROR = 0x035;
383 const EXCEPTION_FILE_NOT_FOUND = 0x036;
384 const EXCEPTION_ASSERTION_FAILED = 0x037;
385 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
386 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
387 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
388 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
389 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
390 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
391 const EXCEPTION_INVALID_SOCKET = 0x03e;
394 * Hexadecimal->Decimal translation array
396 private static $hexdec = array(
416 * Decimal->hexadecimal translation array
418 private static $dechex = array(
438 * Startup time in miliseconds
440 private static $startupTime = 0;
443 * Protected super constructor
445 * @param $className Name of the class
448 protected function __construct ($className) {
450 $this->setRealClass($className);
452 // Set configuration instance if no registry ...
453 if (!$this instanceof Register) {
454 // ... because registries doesn't need to be configured
455 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
458 // Is the startup time set? (0 cannot be true anymore)
459 if (self::$startupTime == 0) {
461 self::$startupTime = microtime(true);
465 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
469 * Destructor for all classes. You should not call this method on your own.
473 public function __destruct () {
474 // Flush any updated entries to the database
475 $this->flushPendingUpdates();
477 // Is this object already destroyed?
478 if ($this->__toString() != 'DestructedObject') {
479 // Destroy all informations about this class but keep some text about it alive
480 $this->setRealClass('DestructedObject');
481 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
482 // Already destructed object
483 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
487 // Do not call this twice
488 trigger_error(__METHOD__ . ': Called twice.');
494 * The __call() method where all non-implemented methods end up
496 * @param $methodName Name of the missing method
497 * @args $args Arguments passed to the method
500 public final function __call ($methodName, $args) {
501 return self::__callStatic($methodName, $args);
505 * The __callStatic() method where all non-implemented static methods end up
507 * @param $methodName Name of the missing method
508 * @args $args Arguments passed to the method
511 public static final function __callStatic ($methodName, $args) {
513 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
515 // Init argument string
518 // Is it NULL, empty or an array?
519 if (is_null($args)) {
521 $argsString = 'NULL';
522 } elseif (is_array($args)) {
526 // Some arguments are there
527 foreach ($args as $arg) {
528 // Add data about the argument
529 $argsString .= gettype($arg) . ':';
532 // Found a NULL argument
533 $argsString .= 'NULL';
534 } elseif (is_string($arg)) {
535 // Add length for strings
536 $argsString .= strlen($arg);
537 } elseif ((is_int($arg)) || (is_float($arg))) {
540 } elseif (is_array($arg)) {
541 // .. or size if array
542 $argsString .= count($arg);
543 } elseif (is_object($arg)) {
545 $reflection = new ReflectionClass($arg);
547 // Is an other object, maybe no __toString() available
548 $argsString .= $reflection->getName();
549 } elseif ($arg === true) {
550 // ... is boolean 'true'
551 $argsString .= 'true';
552 } elseif ($arg === false) {
553 // ... is boolean 'false'
554 $argsString .= 'false';
557 // Comma for next one
562 if (substr($argsString, -2, 1) == ',') {
563 $argsString = substr($argsString, 0, -2);
569 // Invalid arguments!
570 $argsString = '!INVALID:' . gettype($args) . '!';
573 // Output stub message
574 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
575 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
585 * Getter for $realClass
587 * @return $realClass The name of the real class (not BaseFrameworkSystem)
589 public function __toString () {
590 return $this->realClass;
594 * Magic method to catch setting of missing but set class fields/attributes
596 * @param $name Name of the field/attribute
597 * @param $value Value to store
600 public final function __set ($name, $value) {
601 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
604 print_r($value, true)
609 * Magic method to catch getting of missing fields/attributes
611 * @param $name Name of the field/attribute
614 public final function __get ($name) {
615 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
621 * Magic method to catch unsetting of missing fields/attributes
623 * @param $name Name of the field/attribute
626 public final function __unset ($name) {
627 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
633 * Magic method to catch object serialization
635 * @return $unsupported Unsupported method
636 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
638 public final function __sleep () {
639 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
643 * Magic method to catch object deserialization
645 * @return $unsupported Unsupported method
646 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
648 public final function __wakeup () {
649 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
653 * Magic method to catch calls when an object instance is called
655 * @return $unsupported Unsupported method
656 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
658 public final function __invoke () {
659 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
663 * Setter for the real class name
665 * @param $realClass Class name (string)
668 public final function setRealClass ($realClass) {
670 $this->realClass = (string) $realClass;
674 * Setter for database result instance
676 * @param $resultInstance An instance of a database result class
678 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
680 protected final function setResultInstance (SearchableResult $resultInstance) {
681 $this->resultInstance = $resultInstance;
685 * Getter for database result instance
687 * @return $resultInstance An instance of a database result class
689 public final function getResultInstance () {
690 return $this->resultInstance;
694 * Setter for template engine instances
696 * @param $templateInstance An instance of a template engine class
699 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
700 $this->templateInstance = $templateInstance;
704 * Getter for template engine instances
706 * @return $templateInstance An instance of a template engine class
708 protected final function getTemplateInstance () {
709 return $this->templateInstance;
713 * Setter for search instance
715 * @param $searchInstance Searchable criteria instance
718 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
719 $this->searchInstance = $searchInstance;
723 * Getter for search instance
725 * @return $searchInstance Searchable criteria instance
727 public final function getSearchInstance () {
728 return $this->searchInstance;
732 * Setter for update instance
734 * @param $updateInstance An instance of a LocalUpdateCriteria clase
737 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
738 $this->updateInstance = $updateInstance;
742 * Getter for update instance
744 * @return $updateInstance Updateable criteria instance
746 public final function getUpdateInstance () {
747 return $this->updateInstance;
751 * Setter for resolver instance
753 * @param $resolverInstance Instance of a command resolver class
756 public final function setResolverInstance (Resolver $resolverInstance) {
757 $this->resolverInstance = $resolverInstance;
761 * Getter for resolver instance
763 * @return $resolverInstance Instance of a command resolver class
765 public final function getResolverInstance () {
766 return $this->resolverInstance;
770 * Setter for language instance
772 * @param $configInstance The configuration instance which shall
773 * be FrameworkConfiguration
776 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
777 Registry::getRegistry()->addInstance('config', $configInstance);
781 * Getter for configuration instance
783 * @return $configInstance Configuration instance
785 public final function getConfigInstance () {
786 $configInstance = Registry::getRegistry()->getInstance('config');
787 return $configInstance;
791 * Setter for debug instance
793 * @param $debugInstance The instance for debug output class
796 public final function setDebugInstance (DebugMiddleware $debugInstance) {
797 Registry::getRegistry()->addInstance('debug', $debugInstance);
801 * Getter for debug instance
803 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
805 public final function getDebugInstance () {
806 // Get debug instance
807 $debugInstance = Registry::getRegistry()->getInstance('debug');
810 return $debugInstance;
814 * Setter for web output instance
816 * @param $webInstance The instance for web output class
819 public final function setWebOutputInstance (OutputStreamer $webInstance) {
820 Registry::getRegistry()->addInstance('web_output', $webInstance);
824 * Getter for web output instance
826 * @return $webOutputInstance - Instance to class WebOutput
828 public final function getWebOutputInstance () {
829 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
830 return $webOutputInstance;
834 * Setter for database instance
836 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
839 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
840 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
844 * Getter for database layer
846 * @return $databaseInstance The database layer instance
848 public final function getDatabaseInstance () {
850 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
853 return $databaseInstance;
857 * Setter for compressor channel
859 * @param $compressorInstance An instance of CompressorChannel
862 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
863 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
867 * Getter for compressor channel
869 * @return $compressorInstance The compressor channel
871 public final function getCompressorChannel () {
872 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
873 return $compressorInstance;
877 * Protected getter for a manageable application helper class
879 * @return $applicationInstance An instance of a manageable application helper class
881 protected final function getApplicationInstance () {
882 $applicationInstance = Registry::getRegistry()->getInstance('app');
883 return $applicationInstance;
887 * Setter for a manageable application helper class
889 * @param $applicationInstance An instance of a manageable application helper class
892 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
893 Registry::getRegistry()->addInstance('application', $applicationInstance);
897 * Private getter for language instance
899 * @return $langInstance An instance to the language sub-system
901 protected final function getLanguageInstance () {
902 $langInstance = Registry::getRegistry()->getInstance('language');
903 return $langInstance;
907 * Setter for language instance
909 * @param $langInstance An instance to the language sub-system
911 * @see LanguageSystem
913 public final function setLanguageInstance (ManageableLanguage $langInstance) {
914 Registry::getRegistry()->addInstance('language', $langInstance);
918 * Private getter for file IO instance
920 * @return $fileIoInstance An instance to the file I/O sub-system
922 protected final function getFileIoInstance () {
923 return $this->fileIoInstance;
927 * Setter for file I/O instance
929 * @param $fileIoInstance An instance to the file I/O sub-system
932 public final function setFileIoInstance (IoHandler $fileIoInstance) {
933 $this->fileIoInstance = $fileIoInstance;
937 * Protected setter for user instance
939 * @param $userInstance An instance of a user class
942 protected final function setUserInstance (ManageableAccount $userInstance) {
943 $this->userInstance = $userInstance;
947 * Getter for user instance
949 * @return $userInstance An instance of a user class
951 public final function getUserInstance () {
952 return $this->userInstance;
956 * Setter for controller instance (this surely breaks a bit the MVC patterm)
958 * @param $controllerInstance An instance of the controller
961 public final function setControllerInstance (Controller $controllerInstance) {
962 $this->controllerInstance = $controllerInstance;
966 * Getter for controller instance (this surely breaks a bit the MVC patterm)
968 * @return $controllerInstance An instance of the controller
970 public final function getControllerInstance () {
971 return $this->controllerInstance;
975 * Setter for RNG instance
977 * @param $rngInstance An instance of a random number generator (RNG)
980 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
981 $this->rngInstance = $rngInstance;
985 * Getter for RNG instance
987 * @return $rngInstance An instance of a random number generator (RNG)
989 public final function getRngInstance () {
990 return $this->rngInstance;
994 * Setter for Cryptable instance
996 * @param $cryptoInstance An instance of a Cryptable class
999 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1000 $this->cryptoInstance = $cryptoInstance;
1004 * Getter for Cryptable instance
1006 * @return $cryptoInstance An instance of a Cryptable class
1008 public final function getCryptoInstance () {
1009 return $this->cryptoInstance;
1013 * Setter for the list instance
1015 * @param $listInstance A list of Listable
1018 protected final function setListInstance (Listable $listInstance) {
1019 $this->listInstance = $listInstance;
1023 * Getter for the list instance
1025 * @return $listInstance A list of Listable
1027 protected final function getListInstance () {
1028 return $this->listInstance;
1032 * Setter for the menu instance
1034 * @param $menuInstance A RenderableMenu instance
1037 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1038 $this->menuInstance = $menuInstance;
1042 * Getter for the menu instance
1044 * @return $menuInstance A RenderableMenu instance
1046 protected final function getMenuInstance () {
1047 return $this->menuInstance;
1051 * Setter for image instance
1053 * @param $imageInstance An instance of an image
1056 public final function setImageInstance (BaseImage $imageInstance) {
1057 $this->imageInstance = $imageInstance;
1061 * Getter for image instance
1063 * @return $imageInstance An instance of an image
1065 public final function getImageInstance () {
1066 return $this->imageInstance;
1070 * Setter for stacker instance
1072 * @param $stackInstance An instance of an stacker
1075 public final function setStackInstance (Stackable $stackInstance) {
1076 $this->stackInstance = $stackInstance;
1080 * Getter for stacker instance
1082 * @return $stackInstance An instance of an stacker
1084 public final function getStackInstance () {
1085 return $this->stackInstance;
1089 * Setter for compressor instance
1091 * @param $compressorInstance An instance of an compressor
1094 public final function setCompressorInstance (Compressor $compressorInstance) {
1095 $this->compressorInstance = $compressorInstance;
1099 * Getter for compressor instance
1101 * @return $compressorInstance An instance of an compressor
1103 public final function getCompressorInstance () {
1104 return $this->compressorInstance;
1108 * Setter for Parseable instance
1110 * @param $parserInstance An instance of an Parseable
1113 public final function setParserInstance (Parseable $parserInstance) {
1114 $this->parserInstance = $parserInstance;
1118 * Getter for Parseable instance
1120 * @return $parserInstance An instance of an Parseable
1122 public final function getParserInstance () {
1123 return $this->parserInstance;
1127 * Setter for DatabaseWrapper instance
1129 * @param $wrapperInstance An instance of an DatabaseWrapper
1132 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1133 $this->wrapperInstance = $wrapperInstance;
1137 * Getter for DatabaseWrapper instance
1139 * @return $wrapperInstance An instance of an DatabaseWrapper
1141 public final function getWrapperInstance () {
1142 return $this->wrapperInstance;
1146 * Setter for socket resource
1148 * @param $socketResource A valid socket resource
1151 public final function setSocketResource ($socketResource) {
1152 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1153 $this->socketResource = $socketResource;
1157 * Getter for socket resource
1159 * @return $socketResource A valid socket resource
1161 public final function getSocketResource () {
1162 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1163 return $this->socketResource;
1167 * Setter for regular expression
1169 * @param $regularExpression A valid regular expression
1172 public final function setRegularExpression ($regularExpression) {
1173 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1174 $this->regularExpression = $regularExpression;
1178 * Getter for regular expression
1180 * @return $regularExpression A valid regular expression
1182 public final function getRegularExpression () {
1183 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1184 return $this->regularExpression;
1188 * Setter for helper instance
1190 * @param $helperInstance An instance of a helper class
1193 protected final function setHelperInstance (Helper $helperInstance) {
1194 $this->helperInstance = $helperInstance;
1198 * Getter for helper instance
1200 * @return $helperInstance An instance of a helper class
1202 public final function getHelperInstance () {
1203 return $this->helperInstance;
1207 * Setter for a Source instance
1209 * @param $sourceInstance An instance of a Source class
1212 protected final function setSourceInstance (Source $sourceInstance) {
1213 $this->sourceInstance = $sourceInstance;
1217 * Getter for a Source instance
1219 * @return $sourceInstance An instance of a Source class
1221 protected final function getSourceInstance () {
1222 return $this->sourceInstance;
1226 * Setter for a UrlSource instance
1228 * @param $sourceInstance An instance of a UrlSource class
1231 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1232 $this->urlSourceInstance = $urlSourceInstance;
1236 * Getter for a UrlSource instance
1238 * @return $urlSourceInstance An instance of a UrlSource class
1240 protected final function getUrlSourceInstance () {
1241 return $this->urlSourceInstance;
1245 * Getter for a InputStream instance
1247 * @param $inputStreamInstance The InputStream instance
1249 protected final function getInputStreamInstance () {
1250 return $this->inputStreamInstance;
1254 * Setter for a InputStream instance
1256 * @param $inputStreamInstance The InputStream instance
1259 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1260 $this->inputStreamInstance = $inputStreamInstance;
1264 * Getter for a OutputStream instance
1266 * @param $outputStreamInstance The OutputStream instance
1268 protected final function getOutputStreamInstance () {
1269 return $this->outputStreamInstance;
1273 * Setter for a OutputStream instance
1275 * @param $outputStreamInstance The OutputStream instance
1278 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1279 $this->outputStreamInstance = $outputStreamInstance;
1283 * Setter for handler instance
1285 * @param $handlerInstance An instance of a Handleable class
1288 protected final function setHandlerInstance (Handleable $handlerInstance) {
1289 $this->handlerInstance = $handlerInstance;
1293 * Getter for handler instance
1295 * @return $handlerInstance A Handleable instance
1297 protected final function getHandlerInstance () {
1298 return $this->handlerInstance;
1302 * Setter for visitor instance
1304 * @param $visitorInstance A Visitor instance
1307 protected final function setVisitorInstance (Visitor $visitorInstance) {
1308 $this->visitorInstance = $visitorInstance;
1312 * Getter for visitor instance
1314 * @return $visitorInstance A Visitor instance
1316 protected final function getVisitorInstance () {
1317 return $this->visitorInstance;
1321 * Setter for raw package Data
1323 * @param $packageData Raw package Data
1326 public final function setPackageData (array $packageData) {
1327 $this->packageData = $packageData;
1331 * Getter for raw package Data
1333 * @return $packageData Raw package Data
1335 public function getPackageData () {
1336 return $this->packageData;
1341 * Setter for Iterator instance
1343 * @param $iteratorInstance An instance of an Iterator
1346 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1347 $this->iteratorInstance = $iteratorInstance;
1351 * Getter for Iterator instance
1353 * @return $iteratorInstance An instance of an Iterator
1355 public final function getIteratorInstance () {
1356 return $this->iteratorInstance;
1360 * Setter for FilePointer instance
1362 * @param $pointerInstance An instance of an FilePointer class
1365 protected final function setPointerInstance (FilePointer $pointerInstance) {
1366 $this->pointerInstance = $pointerInstance;
1370 * Getter for FilePointer instance
1372 * @return $pointerInstance An instance of an FilePointer class
1374 public final function getPointerInstance () {
1375 return $this->pointerInstance;
1379 * Unsets pointer instance which triggers a call of __destruct() if the
1380 * instance is still there. This is surely not fatal on already "closed"
1381 * file pointer instances.
1383 * I don't want to mess around with above setter by giving it a default
1384 * value NULL as setter should always explicitly only set (existing) object
1385 * instances and NULL is NULL.
1389 protected final function unsetPointerInstance () {
1390 // Simply it to NULL
1391 $this->pointerInstance = NULL;
1395 * Setter for Indexable instance
1397 * @param $indexInstance An instance of an Indexable class
1400 protected final function setIndexInstance (Indexable $indexInstance) {
1401 $this->indexInstance = $indexInstance;
1405 * Getter for Indexable instance
1407 * @return $indexInstance An instance of an Indexable class
1409 public final function getIndexInstance () {
1410 return $this->indexInstance;
1414 * Setter for Block instance
1416 * @param $blockInstance An instance of an Block class
1419 protected final function setBlockInstance (Block $blockInstance) {
1420 $this->blockInstance = $blockInstance;
1424 * Getter for Block instance
1426 * @return $blockInstance An instance of an Block class
1428 public final function getBlockInstance () {
1429 return $this->blockInstance;
1433 * Setter for Minable instance
1435 * @param $minableInstance A Minable instance
1438 protected final function setMinableInstance (Minable $minableInstance) {
1439 $this->minableInstance = $minableInstance;
1443 * Getter for minable instance
1445 * @return $minableInstance A Minable instance
1447 protected final function getMinableInstance () {
1448 return $this->minableInstance;
1452 * Setter for FrameworkDirectory instance
1454 * @param $directoryInstance A FrameworkDirectory instance
1457 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1458 $this->directoryInstance = $directoryInstance;
1462 * Getter for FrameworkDirectory instance
1464 * @return $directoryInstance A FrameworkDirectory instance
1466 protected final function getDirectoryInstance () {
1467 return $this->directoryInstance;
1471 * Getter for communicator instance
1473 * @return $communicatorInstance An instance of a Communicator class
1475 public final function getCommunicatorInstance () {
1476 return $this->communicatorInstance;
1480 * Setter for communicator instance
1482 * @param $communicatorInstance An instance of a Communicator class
1485 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1486 $this->communicatorInstance = $communicatorInstance;
1490 * Setter for state instance
1492 * @param $stateInstance A Stateable instance
1495 public final function setStateInstance (Stateable $stateInstance) {
1496 $this->stateInstance = $stateInstance;
1500 * Getter for state instance
1502 * @return $stateInstance A Stateable instance
1504 public final function getStateInstance () {
1505 return $this->stateInstance;
1509 * Setter for output instance
1511 * @param $outputInstance The debug output instance
1514 public final function setOutputInstance (OutputStreamer $outputInstance) {
1515 $this->outputInstance = $outputInstance;
1519 * Getter for output instance
1521 * @return $outputInstance The debug output instance
1523 public final function getOutputInstance () {
1524 return $this->outputInstance;
1528 * Setter for command name
1530 * @param $commandName Last validated command name
1533 protected final function setCommandName ($commandName) {
1534 $this->commandName = $commandName;
1538 * Getter for command name
1540 * @return $commandName Last validated command name
1542 protected final function getCommandName () {
1543 return $this->commandName;
1547 * Setter for controller name
1549 * @param $controllerName Last validated controller name
1552 protected final function setControllerName ($controllerName) {
1553 $this->controllerName = $controllerName;
1557 * Getter for controller name
1559 * @return $controllerName Last validated controller name
1561 protected final function getControllerName () {
1562 return $this->controllerName;
1566 * Checks whether an object equals this object. You should overwrite this
1567 * method to implement own equality checks
1569 * @param $objectInstance An instance of a FrameworkInterface object
1570 * @return $equals Whether both objects equals
1572 public function equals (FrameworkInterface $objectInstance) {
1575 $this->__toString() == $objectInstance->__toString()
1577 $this->hashCode() == $objectInstance->hashCode()
1580 // Return the result
1585 * Generates a generic hash code of this class. You should really overwrite
1586 * this method with your own hash code generator code. But keep KISS in mind.
1588 * @return $hashCode A generic hash code respresenting this whole class
1590 public function hashCode () {
1592 return crc32($this->__toString());
1596 * Formats computer generated price values into human-understandable formats
1597 * with thousand and decimal separators.
1599 * @param $value The in computer format value for a price
1600 * @param $currency The currency symbol (use HTML-valid characters!)
1601 * @param $decNum Number of decimals after commata
1602 * @return $price The for the current language formated price string
1603 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1604 * thousands separator
1607 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1608 // Are all required attriutes set?
1609 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1610 // Throw an exception
1611 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1615 $value = (float) $value;
1617 // Reformat the US number
1618 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1620 // Return as string...
1625 * Appends a trailing slash to a string
1627 * @param $str A string (maybe) without trailing slash
1628 * @return $str A string with an auto-appended trailing slash
1630 public final function addMissingTrailingSlash ($str) {
1631 // Is there a trailing slash?
1632 if (substr($str, -1, 1) != '/') {
1636 // Return string with trailing slash
1641 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1642 * application helper instance (ApplicationHelper by default).
1644 * @param $applicationInstance An application helper instance or
1645 * null if we shall use the default
1646 * @return $templateInstance The template engine instance
1647 * @throws NullPointerException If the discovered application
1648 * instance is still null
1650 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1651 // Is the application instance set?
1652 if (is_null($applicationInstance)) {
1653 // Get the current instance
1654 $applicationInstance = Registry::getRegistry()->getInstance('app');
1657 if (is_null($applicationInstance)) {
1658 // Thrown an exception
1659 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1663 // Initialize the template engine
1664 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1666 // Return the prepared instance
1667 return $templateInstance;
1671 * Debugs this instance by putting out it's full content
1673 * @param $message Optional message to show in debug output
1676 public final function debugInstance ($message = '') {
1677 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1678 restore_error_handler();
1683 // Is a message set?
1684 if (!empty($message)) {
1685 // Construct message
1686 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1689 // Generate the output
1690 $content .= sprintf('<pre>%s</pre>',
1693 print_r($this, true)
1699 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>',
1700 $this->__toString(),
1702 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1707 * Replaces control characters with printable output
1709 * @param $str String with control characters
1710 * @return $str Replaced string
1712 protected function replaceControlCharacters ($str) {
1715 chr(13), '[r]', str_replace(
1716 chr(10), '[n]', str_replace(
1726 * Output a partial stub message for the caller method
1728 * @param $message An optional message to display
1731 protected function partialStub ($message = '') {
1732 // Get the backtrace
1733 $backtrace = debug_backtrace();
1735 // Generate the class::method string
1736 $methodName = 'UnknownClass->unknownMethod';
1737 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1738 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1741 // Construct the full message
1742 $stubMessage = sprintf('[%s]: Partial stub!',
1746 // Is the extra message given?
1747 if (!empty($message)) {
1748 // Then add it as well
1749 $stubMessage .= ' Message: ' . $message;
1752 // Debug instance is there?
1753 if (!is_null($this->getDebugInstance())) {
1754 // Output stub message
1755 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1758 trigger_error($stubMessage);
1764 * Outputs a debug backtrace and stops further script execution
1766 * @param $message An optional message to output
1767 * @param $doExit Whether exit the program (true is default)
1770 public function debugBackTrace ($message = '', $doExit = true) {
1771 // Sorry, there is no other way getting this nice backtrace
1772 if (!empty($message)) {
1774 printf('Message: %s<br />' . PHP_EOL, $message);
1778 debug_print_backtrace();
1782 if ($doExit === true) {
1788 * Creates an instance of a debugger instance
1790 * @param $className Name of the class (currently unsupported)
1791 * @param $lineNumber Line number where the call was made
1792 * @return $debugInstance An instance of a debugger class
1793 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1795 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1796 // Is the instance set?
1797 if (!Registry::getRegistry()->instanceExists('debug')) {
1798 // Init debug instance
1799 $debugInstance = NULL;
1803 // Get a debugger instance
1804 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1805 } catch (NullPointerException $e) {
1806 // Didn't work, no instance there
1807 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1810 // Empty string should be ignored and used for testing the middleware
1811 DebugMiddleware::getSelfInstance()->output('');
1813 // Set it in its own class. This will set it in the registry
1814 $debugInstance->setDebugInstance($debugInstance);
1816 // Get instance from registry
1817 $debugInstance = Registry::getRegistry()->getDebugInstance();
1821 return $debugInstance;
1825 * Simple output of a message with line-break
1827 * @param $message Message to output
1830 public function outputLine ($message) {
1832 print($message . PHP_EOL);
1836 * Outputs a debug message whether to debug instance (should be set!) or
1837 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1838 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1840 * @param $message Message we shall send out...
1841 * @param $doPrint Whether print or die here (default: print)
1842 * @paran $stripTags Whether to strip tags (default: false)
1845 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1846 // Set debug instance to NULL
1847 $debugInstance = NULL;
1851 // Get debug instance
1852 $debugInstance = $this->getDebugInstance();
1853 } catch (NullPointerException $e) {
1854 // The debug instance is not set (yet)
1857 // Is the debug instance there?
1858 if (is_object($debugInstance)) {
1859 // Use debug output handler
1860 $debugInstance->output($message, $stripTags);
1862 if ($doPrint === false) {
1863 // Die here if not printed
1867 // Are debug times enabled?
1868 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1870 $message = $this->getPrintableExecutionTime() . $message;
1874 if ($doPrint === true) {
1876 $this->outputLine($message);
1885 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1887 * @param $str The string, what ever it is needs to be converted
1888 * @return $className Generated class name
1890 public static final function convertToClassName ($str) {
1894 // Convert all dashes in underscores
1895 $str = self::convertDashesToUnderscores($str);
1897 // Now use that underscores to get classname parts for hungarian style
1898 foreach (explode('_', $str) as $strPart) {
1899 // Make the class name part lower case and first upper case
1900 $className .= ucfirst(strtolower($strPart));
1903 // Return class name
1908 * Converts dashes to underscores, e.g. useable for configuration entries
1910 * @param $str The string with maybe dashes inside
1911 * @return $str The converted string with no dashed, but underscores
1913 public static final function convertDashesToUnderscores ($str) {
1915 $str = str_replace('-', '_', $str);
1917 // Return converted string
1922 * Marks up the code by adding e.g. line numbers
1924 * @param $phpCode Unmarked PHP code
1925 * @return $markedCode Marked PHP code
1927 public function markupCode ($phpCode) {
1932 $errorArray = error_get_last();
1934 // Init the code with error message
1935 if (is_array($errorArray)) {
1937 $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>',
1938 basename($errorArray['file']),
1939 $errorArray['line'],
1940 $errorArray['message'],
1945 // Add line number to the code
1946 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1948 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1950 htmlentities($code, ENT_QUOTES)
1959 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1960 * beatiful for web-based front-ends. If null is given a message id
1961 * null_timestamp will be resolved and returned.
1963 * @param $timestamp Timestamp to prepare (filter) for display
1964 * @return $readable A readable timestamp
1966 public function doFilterFormatTimestamp ($timestamp) {
1967 // Default value to return
1970 // Is the timestamp null?
1971 if (is_null($timestamp)) {
1972 // Get a message string
1973 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1975 switch ($this->getLanguageInstance()->getLanguageCode()) {
1976 case 'de': // German format is a bit different to default
1977 // Split the GMT stamp up
1978 $dateTime = explode(' ', $timestamp );
1979 $dateArray = explode('-', $dateTime[0]);
1980 $timeArray = explode(':', $dateTime[1]);
1982 // Construct the timestamp
1983 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1993 default: // Default is pass-through
1994 $readable = $timestamp;
2004 * Filter a given number into a localized number
2006 * @param $value The raw value from e.g. database
2007 * @return $localized Localized value
2009 public function doFilterFormatNumber ($value) {
2010 // Generate it from config and localize dependencies
2011 switch ($this->getLanguageInstance()->getLanguageCode()) {
2012 case 'de': // German format is a bit different to default
2013 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2016 default: // US, etc.
2017 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2026 * "Getter" for databse entry
2028 * @return $entry An array with database entries
2029 * @throws NullPointerException If the database result is not found
2030 * @throws InvalidDatabaseResultException If the database result is invalid
2032 protected final function getDatabaseEntry () {
2033 // Is there an instance?
2034 if (!$this->getResultInstance() instanceof SearchableResult) {
2035 // Throw an exception here
2036 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2040 $this->getResultInstance()->rewind();
2042 // Do we have an entry?
2043 if ($this->getResultInstance()->valid() === false) {
2044 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2045 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2049 $this->getResultInstance()->next();
2052 $entry = $this->getResultInstance()->current();
2059 * Getter for field name
2061 * @param $fieldName Field name which we shall get
2062 * @return $fieldValue Field value from the user
2063 * @throws NullPointerException If the result instance is null
2065 public final function getField ($fieldName) {
2066 // Default field value
2069 // Get result instance
2070 $resultInstance = $this->getResultInstance();
2072 // Is this instance null?
2073 if (is_null($resultInstance)) {
2074 // Then the user instance is no longer valid (expired cookies?)
2075 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2078 // Get current array
2079 $fieldArray = $resultInstance->current();
2080 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2082 // Convert dashes to underscore
2083 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2085 // Does the field exist?
2086 if ($this->isFieldSet($fieldName)) {
2088 $fieldValue = $fieldArray[$fieldName2];
2089 } elseif (defined('DEVELOPER')) {
2090 // Missing field entry, may require debugging
2091 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2093 // Missing field entry, may require debugging
2094 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2102 * Checks if given field is set
2104 * @param $fieldName Field name to check
2105 * @return $isSet Whether the given field name is set
2106 * @throws NullPointerException If the result instance is null
2108 public function isFieldSet ($fieldName) {
2109 // Get result instance
2110 $resultInstance = $this->getResultInstance();
2112 // Is this instance null?
2113 if (is_null($resultInstance)) {
2114 // Then the user instance is no longer valid (expired cookies?)
2115 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2118 // Get current array
2119 $fieldArray = $resultInstance->current();
2120 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2122 // Convert dashes to underscore
2123 $fieldName = self::convertDashesToUnderscores($fieldName);
2126 $isSet = isset($fieldArray[$fieldName]);
2133 * Flushs all pending updates to the database layer
2137 public function flushPendingUpdates () {
2138 // Get result instance
2139 $resultInstance = $this->getResultInstance();
2141 // Do we have data to update?
2142 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2143 // Get wrapper class name config entry
2144 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2146 // Create object instance
2147 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2149 // Yes, then send the whole result to the database layer
2150 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2155 * Outputs a deprecation warning to the developer.
2157 * @param $message The message we shall output to the developer
2159 * @todo Write a logging mechanism for productive mode
2161 public function deprecationWarning ($message) {
2162 // Is developer mode active?
2163 if (defined('DEVELOPER')) {
2164 // Debug instance is there?
2165 if (!is_null($this->getDebugInstance())) {
2166 // Output stub message
2167 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2170 trigger_error($message . "<br />\n");
2174 // @TODO Finish this part!
2175 $this->partialStub('Developer mode inactive. Message:' . $message);
2180 * Checks whether the given PHP extension is loaded
2182 * @param $phpExtension The PHP extension we shall check
2183 * @return $isLoaded Whether the PHP extension is loaded
2185 public final function isPhpExtensionLoaded ($phpExtension) {
2187 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2194 * "Getter" as a time() replacement but with milliseconds. You should use this
2195 * method instead of the encapsulated getimeofday() function.
2197 * @return $milliTime Timestamp with milliseconds
2199 public function getMilliTime () {
2200 // Get the time of day as float
2201 $milliTime = gettimeofday(true);
2208 * Idles (sleeps) for given milliseconds
2210 * @return $hasSlept Whether it goes fine
2212 public function idle ($milliSeconds) {
2213 // Sleep is fine by default
2216 // Idle so long with found function
2217 if (function_exists('time_sleep_until')) {
2218 // Get current time and add idle time
2219 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2221 // New PHP 5.1.0 function found, ignore errors
2222 $hasSlept = @time_sleep_until($sleepUntil);
2225 * My Sun station doesn't have that function even with latest PHP
2228 usleep($milliSeconds * 1000);
2235 * Converts a hexadecimal string, even with negative sign as first string to
2236 * a decimal number using BC functions.
2238 * This work is based on comment #86673 on php.net documentation page at:
2239 * <http://de.php.net/manual/en/function.dechex.php#86673>
2241 * @param $hex Hexadecimal string
2242 * @return $dec Decimal number
2244 protected function hex2dec ($hex) {
2245 // Convert to all lower-case
2246 $hex = strtolower($hex);
2248 // Detect sign (negative/positive numbers)
2250 if (substr($hex, 0, 1) == '-') {
2252 $hex = substr($hex, 1);
2255 // Decode the hexadecimal string into a decimal number
2257 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2258 $factor = self::$hexdec[substr($hex, $i, 1)];
2259 $dec = bcadd($dec, bcmul($factor, $e));
2262 // Return the decimal number
2263 return $sign . $dec;
2267 * Converts even very large decimal numbers, also signed, to a hexadecimal
2270 * This work is based on comment #97756 on php.net documentation page at:
2271 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2273 * @param $dec Decimal number, even with negative sign
2274 * @param $maxLength Optional maximum length of the string
2275 * @return $hex Hexadecimal string
2277 protected function dec2hex ($dec, $maxLength = 0) {
2278 // maxLength can be zero or devideable by 2
2279 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2281 // Detect sign (negative/positive numbers)
2288 // Encode the decimal number into a hexadecimal string
2291 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2293 } while ($dec >= 1);
2296 * Leading zeros are required for hex-decimal "numbers". In some
2297 * situations more leading zeros are wanted, so check for both
2300 if ($maxLength > 0) {
2301 // Prepend more zeros
2302 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2303 } elseif ((strlen($hex) % 2) != 0) {
2304 // Only make string's length dividable by 2
2308 // Return the hexadecimal string
2309 return $sign . $hex;
2313 * Converts a ASCII string (0 to 255) into a decimal number.
2315 * @param $asc The ASCII string to be converted
2316 * @return $dec Decimal number
2318 protected function asc2dec ($asc) {
2319 // Convert it into a hexadecimal number
2320 $hex = bin2hex($asc);
2322 // And back into a decimal number
2323 $dec = $this->hex2dec($hex);
2330 * Converts a decimal number into an ASCII string.
2332 * @param $dec Decimal number
2333 * @return $asc An ASCII string
2335 protected function dec2asc ($dec) {
2336 // First convert the number into a hexadecimal string
2337 $hex = $this->dec2hex($dec);
2339 // Then convert it into the ASCII string
2340 $asc = $this->hex2asc($hex);
2347 * Converts a hexadecimal number into an ASCII string. Negative numbers
2350 * @param $hex Hexadecimal string
2351 * @return $asc An ASCII string
2353 protected function hex2asc ($hex) {
2354 // Check for length, it must be devideable by 2
2355 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2356 assert((strlen($hex) % 2) == 0);
2360 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2361 // Get the decimal number of the chunk
2362 $part = hexdec(substr($hex, $idx, 2));
2364 // Add it to the final string
2368 // Return the final string
2373 * Checks whether the given encoded data was encoded with Base64
2375 * @param $encodedData Encoded data we shall check
2376 * @return $isBase64 Whether the encoded data is Base64
2378 protected function isBase64Encoded ($encodedData) {
2380 $isBase64 = (@base64_decode($encodedData, true) !== false);
2387 * Gets a cache key from Criteria instance
2389 * @param $criteriaInstance An instance of a Criteria class
2390 * @param $onlyKeys Only use these keys for a cache key
2391 * @return $cacheKey A cache key suitable for lookup/storage purposes
2393 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2395 $cacheKey = sprintf('%s@%s',
2396 $this->__toString(),
2397 $criteriaInstance->getCacheKey($onlyKeys)
2401 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2406 * Getter for startup time in miliseconds
2408 * @return $startupTime Startup time in miliseconds
2410 protected function getStartupTime () {
2411 return self::$startupTime;
2415 * "Getter" for a printable currently execution time in nice braces
2417 * @return $executionTime Current execution time in nice braces
2419 protected function getPrintableExecutionTime () {
2420 // Caculate the execution time
2421 $executionTime = microtime(true) - $this->getStartupTime();
2423 // Pack it in nice braces
2424 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2427 return $executionTime;
2431 * Hashes a given string with a simple but stronger hash function (no salt)
2432 * and hex-encode it.
2434 * @param $str The string to be hashed
2435 * @return $hash The hash from string $str
2437 public static final function hash ($str) {
2438 // Hash given string with (better secure) hasher
2439 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2446 * "Getter" for length of hash() output. This will be "cached" to speed up
2449 * @return $length Length of hash() output
2451 public static final function getHashLength () {
2453 if (is_null(self::$hashLength)) {
2454 // No, then hash a string and save its length.
2455 self::$hashLength = strlen(self::hash('abc123'));
2459 return self::$hashLength;
2463 * Checks whether the given number is really a number (only chars 0-9).
2465 * @param $num A string consisting only chars between 0 and 9
2466 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2467 * @param $assertMismatch Whether to assert mismatches
2468 * @return $ret The (hopefully) secured numbered value
2470 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2471 // Filter all numbers out
2472 $ret = preg_replace('/[^0123456789]/', '', $num);
2475 if ($castValue === true) {
2476 // Cast to biggest numeric type
2477 $ret = (double) $ret;
2480 // Assert only if requested
2481 if ($assertMismatch === true) {
2482 // Has the whole value changed?
2483 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2491 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2493 * @param $num A string consisting only chars between 0 and 9
2494 * @param $assertMismatch Whether to assert mismatches
2495 * @return $ret The (hopefully) secured hext-numbered value
2497 public function hexval ($num, $assertMismatch = false) {
2498 // Filter all numbers out
2499 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2501 // Assert only if requested
2502 if ($assertMismatch === true) {
2503 // Has the whole value changed?
2504 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2512 * Determines if an element is set in the generic array
2514 * @param $keyGroup Main group for the key
2515 * @param $subGroup Sub group for the key
2516 * @param $key Key to check
2517 * @param $element Element to check
2518 * @return $isset Whether the given key is set
2520 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2522 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2525 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2531 * Determines if a key is set in the generic array
2533 * @param $keyGroup Main group for the key
2534 * @param $subGroup Sub group for the key
2535 * @param $key Key to check
2536 * @return $isset Whether the given key is set
2538 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2540 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2543 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2551 * Determines if a group is set in the generic array
2553 * @param $keyGroup Main group
2554 * @param $subGroup Sub group
2555 * @return $isset Whether the given group is set
2557 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2559 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2562 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2569 * Getter for sub key group
2571 * @param $keyGroup Main key group
2572 * @param $subGroup Sub key group
2573 * @return $array An array with all array elements
2575 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2577 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2578 // No, then abort here
2579 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2584 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2587 return $this->genericArray[$keyGroup][$subGroup];
2591 * Unsets a given key in generic array
2593 * @param $keyGroup Main group for the key
2594 * @param $subGroup Sub group for the key
2595 * @param $key Key to unset
2598 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2600 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2603 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2607 * Unsets a given element in generic array
2609 * @param $keyGroup Main group for the key
2610 * @param $subGroup Sub group for the key
2611 * @param $key Key to unset
2612 * @param $element Element to unset
2615 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2617 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2620 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2624 * Append a string to a given generic array key
2626 * @param $keyGroup Main group for the key
2627 * @param $subGroup Sub group for the key
2628 * @param $key Key to unset
2629 * @param $value Value to add/append
2632 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2634 //* 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);
2636 // Is it already there?
2637 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2639 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2642 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2647 * Append a string to a given generic array element
2649 * @param $keyGroup Main group for the key
2650 * @param $subGroup Sub group for the key
2651 * @param $key Key to unset
2652 * @param $element Element to check
2653 * @param $value Value to add/append
2656 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2658 //* 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);
2660 // Is it already there?
2661 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2663 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2666 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2671 * Sets a string in a given generic array element
2673 * @param $keyGroup Main group for the key
2674 * @param $subGroup Sub group for the key
2675 * @param $key Key to unset
2676 * @param $element Element to check
2677 * @param $value Value to add/append
2680 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2682 //* 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);
2685 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2689 * Initializes given generic array group
2691 * @param $keyGroup Main group for the key
2692 * @param $subGroup Sub group for the key
2693 * @param $key Key to use
2694 * @param $forceInit Optionally force initialization
2697 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2699 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2701 // Is it already set?
2702 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2703 // Already initialized
2704 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2709 $this->genericArray[$keyGroup][$subGroup] = array();
2713 * Initializes given generic array key
2715 * @param $keyGroup Main group for the key
2716 * @param $subGroup Sub group for the key
2717 * @param $key Key to use
2718 * @param $forceInit Optionally force initialization
2721 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2723 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2725 // Is it already set?
2726 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2727 // Already initialized
2728 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2733 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2737 * Initializes given generic array element
2739 * @param $keyGroup Main group for the key
2740 * @param $subGroup Sub group for the key
2741 * @param $key Key to use
2742 * @param $element Element to use
2743 * @param $forceInit Optionally force initialization
2746 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2748 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2750 // Is it already set?
2751 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2752 // Already initialized
2753 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2758 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2762 * Pushes an element to a generic key
2764 * @param $keyGroup Main group for the key
2765 * @param $subGroup Sub group for the key
2766 * @param $key Key to use
2767 * @param $value Value to add/append
2768 * @return $count Number of array elements
2770 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2772 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2775 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2777 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2781 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2784 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2785 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2790 * Pushes an element to a generic array element
2792 * @param $keyGroup Main group for the key
2793 * @param $subGroup Sub group for the key
2794 * @param $key Key to use
2795 * @param $element Element to check
2796 * @param $value Value to add/append
2797 * @return $count Number of array elements
2799 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2801 //* 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));
2804 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2806 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2810 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2813 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2814 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2819 * Pops an element from a generic group
2821 * @param $keyGroup Main group for the key
2822 * @param $subGroup Sub group for the key
2823 * @param $key Key to unset
2824 * @return $value Last "popped" value
2826 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2828 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2831 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2833 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2838 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2841 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2842 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2847 * Shifts an element from a generic group
2849 * @param $keyGroup Main group for the key
2850 * @param $subGroup Sub group for the key
2851 * @param $key Key to unset
2852 * @return $value Last "popped" value
2854 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2856 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2859 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2861 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2866 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2869 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2870 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2875 * Count generic array group
2877 * @param $keyGroup Main group for the key
2878 * @return $count Count of given group
2880 protected final function countGenericArray ($keyGroup) {
2882 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2885 if (!isset($this->genericArray[$keyGroup])) {
2887 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2892 $count = count($this->genericArray[$keyGroup]);
2895 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2902 * Count generic array sub group
2904 * @param $keyGroup Main group for the key
2905 * @param $subGroup Sub group for the key
2906 * @return $count Count of given group
2908 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2910 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2913 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2915 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2920 $count = count($this->genericArray[$keyGroup][$subGroup]);
2923 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2930 * Count generic array elements
2932 * @param $keyGroup Main group for the key
2933 * @param $subGroup Sub group for the key
2934 * @para $key Key to count
2935 * @return $count Count of given key
2937 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2939 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2942 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2944 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2946 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2948 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2953 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2956 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2963 * Getter for whole generic group array
2965 * @param $keyGroup Key group to get
2966 * @return $array Whole generic array group
2968 protected final function getGenericArray ($keyGroup) {
2970 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2973 if (!isset($this->genericArray[$keyGroup])) {
2975 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2980 return $this->genericArray[$keyGroup];
2984 * Setter for generic array key
2986 * @param $keyGroup Key group to get
2987 * @param $subGroup Sub group for the key
2988 * @param $key Key to unset
2989 * @param $value Mixed value from generic array element
2992 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2994 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2997 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3001 * Getter for generic array key
3003 * @param $keyGroup Key group to get
3004 * @param $subGroup Sub group for the key
3005 * @param $key Key to unset
3006 * @return $value Mixed value from generic array element
3008 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3010 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3013 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3015 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3020 return $this->genericArray[$keyGroup][$subGroup][$key];
3024 * Sets a value in given generic array key/element
3026 * @param $keyGroup Main group for the key
3027 * @param $subGroup Sub group for the key
3028 * @param $key Key to set
3029 * @param $element Element to set
3030 * @param $value Value to set
3033 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3035 //* 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));
3038 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3042 * Getter for generic array element
3044 * @param $keyGroup Key group to get
3045 * @param $subGroup Sub group for the key
3046 * @param $key Key to look for
3047 * @param $element Element to look for
3048 * @return $value Mixed value from generic array element
3050 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3052 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3055 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3057 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3062 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3066 * Checks if a given sub group is valid (array)
3068 * @param $keyGroup Key group to get
3069 * @param $subGroup Sub group for the key
3070 * @return $isValid Whether given sub group is valid
3072 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3074 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3077 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3084 * Checks if a given key is valid (array)
3086 * @param $keyGroup Key group to get
3087 * @param $subGroup Sub group for the key
3088 * @param $key Key to check
3089 * @return $isValid Whether given sub group is valid
3091 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3093 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3096 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3103 * Initializes the web output instance
3107 protected function initWebOutputInstance () {
3108 // Get application instance
3109 $applicationInstance = Registry::getRegistry()->getInstance('app');
3111 // Init web output instance
3112 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3115 $this->setWebOutputInstance($outputInstance);
3119 * Translates boolean true to 'Y' and false to 'N'
3121 * @param $boolean Boolean value
3122 * @return $translated Translated boolean value
3124 public static final function translateBooleanToYesNo ($boolean) {
3125 // Make sure it is really boolean
3126 assert(is_bool($boolean));
3129 $translated = ($boolean === true) ? 'Y' : 'N';
3131 // ... and return it
3136 * Encodes raw data (almost any type) by "serializing" it and then pack it
3137 * into a "binary format".
3139 * @param $rawData Raw data (almost any type)
3140 * @return $encoded Encoded data
3142 protected function encodeData ($rawData) {
3143 // Make sure no objects or resources pass through
3144 assert(!is_object($rawData));
3145 assert(!is_resource($rawData));
3147 // First "serialize" it (json_encode() is faster than serialize())
3148 $encoded = $this->packString(json_encode($rawData));
3155 * Pack a string into a "binary format". Please execuse me that this is
3156 * widely undocumented. :-(
3158 * @param $str Unpacked string
3159 * @return $packed Packed string
3160 * @todo Improve documentation
3162 protected function packString ($str) {
3164 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3166 // First compress the string (gzcompress is okay)
3167 $str = gzcompress($str);
3172 // And start the "encoding" loop
3173 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3175 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3176 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3178 if (($idx + $i) <= strlen($str)) {
3179 $ord = ord(substr($str, ($idx + $i), 1));
3181 $add = $ord * pow(256, $factor);
3185 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3189 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3190 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3192 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3193 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3199 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3204 * Creates a full-qualified file name (FQFN) for given file name by adding
3205 * a configured temporary file path to it.
3207 * @param $fileName Name for temporary file
3208 * @return $fqfn Full-qualified file name
3209 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3210 * @throws FileIoException If the file cannot be written
3212 protected static function createTempPathForFile ($fileName) {
3214 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3216 // Is the path writeable?
3217 if (!is_writable($basePath)) {
3218 // Path is write-protected
3219 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3223 $fqfn = $basePath . DIRECTORY_SEPARATOR . $fileName;
3226 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3228 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3236 * "Getter" for a printable state name
3238 * @return $stateName Name of the node's state in a printable format
3240 public final function getPrintableState () {
3241 // Default is 'null'
3242 $stateName = 'null';
3244 // Get the state instance
3245 $stateInstance = $this->getStateInstance();
3247 // Is it an instance of Stateable?
3248 if ($stateInstance instanceof Stateable) {
3249 // Then use that state name
3250 $stateName = $stateInstance->getStateName();