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\Output\OutputStreamer;
43 use CoreFramework\Template\CompileableTemplate;
44 use CoreFramework\User\ManageableAccount;
45 use CoreFramework\Visitor\Visitor;
53 * The simulator system class is the super class of all other classes. This
54 * class handles saving of games etc.
56 * @author Roland Haeder <webmaster@shipsimu.org>
58 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
59 * @license GNU GPL 3.0 or any newer version
60 * @link http://www.shipsimu.org
62 * This program is free software: you can redistribute it and/or modify
63 * it under the terms of the GNU General Public License as published by
64 * the Free Software Foundation, either version 3 of the License, or
65 * (at your option) any later version.
67 * This program is distributed in the hope that it will be useful,
68 * but WITHOUT ANY WARRANTY; without even the implied warranty of
69 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
70 * GNU General Public License for more details.
72 * You should have received a copy of the GNU General Public License
73 * along with this program. If not, see <http://www.gnu.org/licenses/>.
75 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
77 * Length of output from hash()
79 private static $hashLength = NULL;
84 private $realClass = 'BaseFrameworkSystem';
87 * Search criteria instance
89 private $searchInstance = NULL;
92 * Update criteria instance
94 private $updateInstance = NULL;
97 * The file I/O instance for the template loader
99 private $fileIoInstance = NULL;
104 private $resolverInstance = NULL;
107 * Template engine instance
109 private $templateInstance = NULL;
112 * Database result instance
114 private $resultInstance = NULL;
117 * Instance for user class
119 private $userInstance = NULL;
122 * A controller instance
124 private $controllerInstance = NULL;
129 private $rngInstance = NULL;
132 * Instance of a crypto helper
134 private $cryptoInstance = NULL;
137 * Instance of an Iterator class
139 private $iteratorInstance = NULL;
142 * Instance of the list
144 private $listInstance = NULL;
149 private $menuInstance = NULL;
152 * Instance of the image
154 private $imageInstance = NULL;
157 * Instance of the stacker
159 private $stackInstance = NULL;
162 * A Compressor instance
164 private $compressorInstance = NULL;
167 * A Parseable instance
169 private $parserInstance = NULL;
172 * A database wrapper instance
174 private $databaseInstance = NULL;
177 * A helper instance for the form
179 private $helperInstance = NULL;
182 * An instance of a Source class
184 private $sourceInstance = NULL;
187 * An instance of a UrlSource class
189 private $urlSourceInstance = NULL;
192 * An instance of a InputStream class
194 private $inputStreamInstance = NULL;
197 * An instance of a OutputStream class
199 private $outputStreamInstance = NULL;
204 private $handlerInstance = NULL;
207 * Visitor handler instance
209 private $visitorInstance = NULL;
212 * An instance of a database wrapper class
214 private $wrapperInstance = NULL;
217 * An instance of a file I/O pointer class (not handler)
219 private $pointerInstance = NULL;
222 * An instance of an Indexable class
224 private $indexInstance = NULL;
227 * An instance of a Block class
229 private $blockInstance = NULL;
234 private $minableInstance = NULL;
237 * A FrameworkDirectory instance
239 private $directoryInstance = NULL;
242 * An instance of a communicator
244 private $communicatorInstance = NULL;
247 * The concrete output instance
249 private $outputInstance = NULL;
254 private $stateInstance = NULL;
257 * Thousands separator
259 private $thousands = '.'; // German
264 private $decimals = ','; // German
269 private $socketResource = false;
272 * Regular expression to use for validation
274 private $regularExpression = '';
279 private $packageData = array();
284 private $genericArray = array();
289 private $commandName = '';
294 private $controllerName = '';
297 * Array with bitmasks and such for pack/unpack methods to support both
298 * 32-bit and 64-bit systems
300 private $packingData = array(
303 'left' => 0xffff0000,
304 'right' => 0x0000ffff,
310 'left' => 0xffffffff00000000,
311 'right' => 0x00000000ffffffff,
318 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
320 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
322 private $archArrayElement = false;
324 /***********************
325 * Exception codes.... *
326 ***********************/
328 // @todo Try to clean these constants up
329 const EXCEPTION_IS_NULL_POINTER = 0x001;
330 const EXCEPTION_IS_NO_OBJECT = 0x002;
331 const EXCEPTION_IS_NO_ARRAY = 0x003;
332 const EXCEPTION_MISSING_METHOD = 0x004;
333 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
334 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
335 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
336 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
337 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
338 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
339 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
340 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
341 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
342 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
343 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
344 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
345 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
346 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
347 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
348 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
349 const EXCEPTION_PATH_NOT_FOUND = 0x015;
350 const EXCEPTION_INVALID_PATH_NAME = 0x016;
351 const EXCEPTION_READ_PROTECED_PATH = 0x017;
352 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
353 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
354 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
355 const EXCEPTION_INVALID_RESOURCE = 0x01b;
356 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
357 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
358 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
359 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
360 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
361 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
362 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
363 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
364 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
365 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
366 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
367 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
368 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
369 const EXCEPTION_INVALID_STRING = 0x029;
370 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
371 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
372 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
373 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
374 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
375 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
376 const EXCEPTION_MISSING_ELEMENT = 0x030;
377 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
378 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
379 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
380 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
381 const EXCEPTION_FATAL_ERROR = 0x035;
382 const EXCEPTION_FILE_NOT_FOUND = 0x036;
383 const EXCEPTION_ASSERTION_FAILED = 0x037;
384 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
385 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
386 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
387 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
388 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
389 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
390 const EXCEPTION_INVALID_SOCKET = 0x03e;
393 * Hexadecimal->Decimal translation array
395 private static $hexdec = array(
415 * Decimal->hexadecimal translation array
417 private static $dechex = array(
437 * Startup time in miliseconds
439 private static $startupTime = 0;
442 * Protected super constructor
444 * @param $className Name of the class
447 protected function __construct ($className) {
449 $this->setRealClass($className);
451 // Set configuration instance if no registry ...
452 if (!$this instanceof Register) {
453 // ... because registries doesn't need to be configured
454 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
457 // Is the startup time set? (0 cannot be true anymore)
458 if (self::$startupTime == 0) {
460 self::$startupTime = microtime(true);
464 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
468 * Destructor for all classes. You should not call this method on your own.
472 public function __destruct () {
473 // Flush any updated entries to the database
474 $this->flushPendingUpdates();
476 // Is this object already destroyed?
477 if ($this->__toString() != 'DestructedObject') {
478 // Destroy all informations about this class but keep some text about it alive
479 $this->setRealClass('DestructedObject');
480 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
481 // Already destructed object
482 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
486 // Do not call this twice
487 trigger_error(__METHOD__ . ': Called twice.');
493 * The __call() method where all non-implemented methods end up
495 * @param $methodName Name of the missing method
496 * @args $args Arguments passed to the method
499 public final function __call ($methodName, $args) {
500 return self::__callStatic($methodName, $args);
504 * The __callStatic() method where all non-implemented static methods end up
506 * @param $methodName Name of the missing method
507 * @args $args Arguments passed to the method
510 public static final function __callStatic ($methodName, $args) {
512 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
514 // Init argument string
517 // Is it NULL, empty or an array?
518 if (is_null($args)) {
520 $argsString = 'NULL';
521 } elseif (is_array($args)) {
525 // Some arguments are there
526 foreach ($args as $arg) {
527 // Add data about the argument
528 $argsString .= gettype($arg) . ':';
531 // Found a NULL argument
532 $argsString .= 'NULL';
533 } elseif (is_string($arg)) {
534 // Add length for strings
535 $argsString .= strlen($arg);
536 } elseif ((is_int($arg)) || (is_float($arg))) {
539 } elseif (is_array($arg)) {
540 // .. or size if array
541 $argsString .= count($arg);
542 } elseif (is_object($arg)) {
544 $reflection = new ReflectionClass($arg);
546 // Is an other object, maybe no __toString() available
547 $argsString .= $reflection->getName();
548 } elseif ($arg === true) {
549 // ... is boolean 'true'
550 $argsString .= 'true';
551 } elseif ($arg === false) {
552 // ... is boolean 'false'
553 $argsString .= 'false';
556 // Comma for next one
561 if (substr($argsString, -2, 1) == ',') {
562 $argsString = substr($argsString, 0, -2);
568 // Invalid arguments!
569 $argsString = '!INVALID:' . gettype($args) . '!';
572 // Output stub message
573 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
574 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
584 * Getter for $realClass
586 * @return $realClass The name of the real class (not BaseFrameworkSystem)
588 public function __toString () {
589 return $this->realClass;
593 * Magic method to catch setting of missing but set class fields/attributes
595 * @param $name Name of the field/attribute
596 * @param $value Value to store
599 public final function __set ($name, $value) {
600 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
603 print_r($value, true)
608 * Magic method to catch getting of missing fields/attributes
610 * @param $name Name of the field/attribute
613 public final function __get ($name) {
614 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
620 * Magic method to catch unsetting of missing fields/attributes
622 * @param $name Name of the field/attribute
625 public final function __unset ($name) {
626 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
632 * Magic method to catch object serialization
634 * @return $unsupported Unsupported method
635 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
637 public final function __sleep () {
638 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
642 * Magic method to catch object deserialization
644 * @return $unsupported Unsupported method
645 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
647 public final function __wakeup () {
648 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
652 * Magic method to catch calls when an object instance is called
654 * @return $unsupported Unsupported method
655 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
657 public final function __invoke () {
658 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
662 * Setter for the real class name
664 * @param $realClass Class name (string)
667 public final function setRealClass ($realClass) {
669 $this->realClass = (string) $realClass;
673 * Setter for database result instance
675 * @param $resultInstance An instance of a database result class
677 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
679 protected final function setResultInstance (SearchableResult $resultInstance) {
680 $this->resultInstance = $resultInstance;
684 * Getter for database result instance
686 * @return $resultInstance An instance of a database result class
688 public final function getResultInstance () {
689 return $this->resultInstance;
693 * Setter for template engine instances
695 * @param $templateInstance An instance of a template engine class
698 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
699 $this->templateInstance = $templateInstance;
703 * Getter for template engine instances
705 * @return $templateInstance An instance of a template engine class
707 protected final function getTemplateInstance () {
708 return $this->templateInstance;
712 * Setter for search instance
714 * @param $searchInstance Searchable criteria instance
717 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
718 $this->searchInstance = $searchInstance;
722 * Getter for search instance
724 * @return $searchInstance Searchable criteria instance
726 public final function getSearchInstance () {
727 return $this->searchInstance;
731 * Setter for update instance
733 * @param $updateInstance An instance of a LocalUpdateCriteria clase
736 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
737 $this->updateInstance = $updateInstance;
741 * Getter for update instance
743 * @return $updateInstance Updateable criteria instance
745 public final function getUpdateInstance () {
746 return $this->updateInstance;
750 * Setter for resolver instance
752 * @param $resolverInstance Instance of a command resolver class
755 public final function setResolverInstance (Resolver $resolverInstance) {
756 $this->resolverInstance = $resolverInstance;
760 * Getter for resolver instance
762 * @return $resolverInstance Instance of a command resolver class
764 public final function getResolverInstance () {
765 return $this->resolverInstance;
769 * Setter for language instance
771 * @param $configInstance The configuration instance which shall
772 * be FrameworkConfiguration
775 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
776 Registry::getRegistry()->addInstance('config', $configInstance);
780 * Getter for configuration instance
782 * @return $configInstance Configuration instance
784 public final function getConfigInstance () {
785 $configInstance = Registry::getRegistry()->getInstance('config');
786 return $configInstance;
790 * Setter for debug instance
792 * @param $debugInstance The instance for debug output class
795 public final function setDebugInstance (DebugMiddleware $debugInstance) {
796 Registry::getRegistry()->addInstance('debug', $debugInstance);
800 * Getter for debug instance
802 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
804 public final function getDebugInstance () {
805 // Get debug instance
806 $debugInstance = Registry::getRegistry()->getInstance('debug');
809 return $debugInstance;
813 * Setter for web output instance
815 * @param $webInstance The instance for web output class
818 public final function setWebOutputInstance (OutputStreamer $webInstance) {
819 Registry::getRegistry()->addInstance('web_output', $webInstance);
823 * Getter for web output instance
825 * @return $webOutputInstance - Instance to class WebOutput
827 public final function getWebOutputInstance () {
828 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
829 return $webOutputInstance;
833 * Setter for database instance
835 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
838 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
839 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
843 * Getter for database layer
845 * @return $databaseInstance The database layer instance
847 public final function getDatabaseInstance () {
849 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
852 return $databaseInstance;
856 * Setter for compressor channel
858 * @param $compressorInstance An instance of CompressorChannel
861 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
862 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
866 * Getter for compressor channel
868 * @return $compressorInstance The compressor channel
870 public final function getCompressorChannel () {
871 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
872 return $compressorInstance;
876 * Protected getter for a manageable application helper class
878 * @return $applicationInstance An instance of a manageable application helper class
880 protected final function getApplicationInstance () {
881 $applicationInstance = Registry::getRegistry()->getInstance('app');
882 return $applicationInstance;
886 * Setter for a manageable application helper class
888 * @param $applicationInstance An instance of a manageable application helper class
891 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
892 Registry::getRegistry()->addInstance('application', $applicationInstance);
896 * Private getter for language instance
898 * @return $langInstance An instance to the language sub-system
900 protected final function getLanguageInstance () {
901 $langInstance = Registry::getRegistry()->getInstance('language');
902 return $langInstance;
906 * Setter for language instance
908 * @param $langInstance An instance to the language sub-system
910 * @see LanguageSystem
912 public final function setLanguageInstance (ManageableLanguage $langInstance) {
913 Registry::getRegistry()->addInstance('language', $langInstance);
917 * Private getter for file IO instance
919 * @return $fileIoInstance An instance to the file I/O sub-system
921 protected final function getFileIoInstance () {
922 return $this->fileIoInstance;
926 * Setter for file I/O instance
928 * @param $fileIoInstance An instance to the file I/O sub-system
931 public final function setFileIoInstance (IoHandler $fileIoInstance) {
932 $this->fileIoInstance = $fileIoInstance;
936 * Protected setter for user instance
938 * @param $userInstance An instance of a user class
941 protected final function setUserInstance (ManageableAccount $userInstance) {
942 $this->userInstance = $userInstance;
946 * Getter for user instance
948 * @return $userInstance An instance of a user class
950 public final function getUserInstance () {
951 return $this->userInstance;
955 * Setter for controller instance (this surely breaks a bit the MVC patterm)
957 * @param $controllerInstance An instance of the controller
960 public final function setControllerInstance (Controller $controllerInstance) {
961 $this->controllerInstance = $controllerInstance;
965 * Getter for controller instance (this surely breaks a bit the MVC patterm)
967 * @return $controllerInstance An instance of the controller
969 public final function getControllerInstance () {
970 return $this->controllerInstance;
974 * Setter for RNG instance
976 * @param $rngInstance An instance of a random number generator (RNG)
979 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
980 $this->rngInstance = $rngInstance;
984 * Getter for RNG instance
986 * @return $rngInstance An instance of a random number generator (RNG)
988 public final function getRngInstance () {
989 return $this->rngInstance;
993 * Setter for Cryptable instance
995 * @param $cryptoInstance An instance of a Cryptable class
998 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
999 $this->cryptoInstance = $cryptoInstance;
1003 * Getter for Cryptable instance
1005 * @return $cryptoInstance An instance of a Cryptable class
1007 public final function getCryptoInstance () {
1008 return $this->cryptoInstance;
1012 * Setter for the list instance
1014 * @param $listInstance A list of Listable
1017 protected final function setListInstance (Listable $listInstance) {
1018 $this->listInstance = $listInstance;
1022 * Getter for the list instance
1024 * @return $listInstance A list of Listable
1026 protected final function getListInstance () {
1027 return $this->listInstance;
1031 * Setter for the menu instance
1033 * @param $menuInstance A RenderableMenu instance
1036 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1037 $this->menuInstance = $menuInstance;
1041 * Getter for the menu instance
1043 * @return $menuInstance A RenderableMenu instance
1045 protected final function getMenuInstance () {
1046 return $this->menuInstance;
1050 * Setter for image instance
1052 * @param $imageInstance An instance of an image
1055 public final function setImageInstance (BaseImage $imageInstance) {
1056 $this->imageInstance = $imageInstance;
1060 * Getter for image instance
1062 * @return $imageInstance An instance of an image
1064 public final function getImageInstance () {
1065 return $this->imageInstance;
1069 * Setter for stacker instance
1071 * @param $stackInstance An instance of an stacker
1074 public final function setStackInstance (Stackable $stackInstance) {
1075 $this->stackInstance = $stackInstance;
1079 * Getter for stacker instance
1081 * @return $stackInstance An instance of an stacker
1083 public final function getStackInstance () {
1084 return $this->stackInstance;
1088 * Setter for compressor instance
1090 * @param $compressorInstance An instance of an compressor
1093 public final function setCompressorInstance (Compressor $compressorInstance) {
1094 $this->compressorInstance = $compressorInstance;
1098 * Getter for compressor instance
1100 * @return $compressorInstance An instance of an compressor
1102 public final function getCompressorInstance () {
1103 return $this->compressorInstance;
1107 * Setter for Parseable instance
1109 * @param $parserInstance An instance of an Parseable
1112 public final function setParserInstance (Parseable $parserInstance) {
1113 $this->parserInstance = $parserInstance;
1117 * Getter for Parseable instance
1119 * @return $parserInstance An instance of an Parseable
1121 public final function getParserInstance () {
1122 return $this->parserInstance;
1126 * Setter for DatabaseWrapper instance
1128 * @param $wrapperInstance An instance of an DatabaseWrapper
1131 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1132 $this->wrapperInstance = $wrapperInstance;
1136 * Getter for DatabaseWrapper instance
1138 * @return $wrapperInstance An instance of an DatabaseWrapper
1140 public final function getWrapperInstance () {
1141 return $this->wrapperInstance;
1145 * Setter for socket resource
1147 * @param $socketResource A valid socket resource
1150 public final function setSocketResource ($socketResource) {
1151 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1152 $this->socketResource = $socketResource;
1156 * Getter for socket resource
1158 * @return $socketResource A valid socket resource
1160 public final function getSocketResource () {
1161 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1162 return $this->socketResource;
1166 * Setter for regular expression
1168 * @param $regularExpression A valid regular expression
1171 public final function setRegularExpression ($regularExpression) {
1172 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1173 $this->regularExpression = $regularExpression;
1177 * Getter for regular expression
1179 * @return $regularExpression A valid regular expression
1181 public final function getRegularExpression () {
1182 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1183 return $this->regularExpression;
1187 * Setter for helper instance
1189 * @param $helperInstance An instance of a helper class
1192 protected final function setHelperInstance (Helper $helperInstance) {
1193 $this->helperInstance = $helperInstance;
1197 * Getter for helper instance
1199 * @return $helperInstance An instance of a helper class
1201 public final function getHelperInstance () {
1202 return $this->helperInstance;
1206 * Setter for a Source instance
1208 * @param $sourceInstance An instance of a Source class
1211 protected final function setSourceInstance (Source $sourceInstance) {
1212 $this->sourceInstance = $sourceInstance;
1216 * Getter for a Source instance
1218 * @return $sourceInstance An instance of a Source class
1220 protected final function getSourceInstance () {
1221 return $this->sourceInstance;
1225 * Setter for a UrlSource instance
1227 * @param $sourceInstance An instance of a UrlSource class
1230 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1231 $this->urlSourceInstance = $urlSourceInstance;
1235 * Getter for a UrlSource instance
1237 * @return $urlSourceInstance An instance of a UrlSource class
1239 protected final function getUrlSourceInstance () {
1240 return $this->urlSourceInstance;
1244 * Getter for a InputStream instance
1246 * @param $inputStreamInstance The InputStream instance
1248 protected final function getInputStreamInstance () {
1249 return $this->inputStreamInstance;
1253 * Setter for a InputStream instance
1255 * @param $inputStreamInstance The InputStream instance
1258 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1259 $this->inputStreamInstance = $inputStreamInstance;
1263 * Getter for a OutputStream instance
1265 * @param $outputStreamInstance The OutputStream instance
1267 protected final function getOutputStreamInstance () {
1268 return $this->outputStreamInstance;
1272 * Setter for a OutputStream instance
1274 * @param $outputStreamInstance The OutputStream instance
1277 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1278 $this->outputStreamInstance = $outputStreamInstance;
1282 * Setter for handler instance
1284 * @param $handlerInstance An instance of a Handleable class
1287 protected final function setHandlerInstance (Handleable $handlerInstance) {
1288 $this->handlerInstance = $handlerInstance;
1292 * Getter for handler instance
1294 * @return $handlerInstance A Handleable instance
1296 protected final function getHandlerInstance () {
1297 return $this->handlerInstance;
1301 * Setter for visitor instance
1303 * @param $visitorInstance A Visitor instance
1306 protected final function setVisitorInstance (Visitor $visitorInstance) {
1307 $this->visitorInstance = $visitorInstance;
1311 * Getter for visitor instance
1313 * @return $visitorInstance A Visitor instance
1315 protected final function getVisitorInstance () {
1316 return $this->visitorInstance;
1320 * Setter for raw package Data
1322 * @param $packageData Raw package Data
1325 public final function setPackageData (array $packageData) {
1326 $this->packageData = $packageData;
1330 * Getter for raw package Data
1332 * @return $packageData Raw package Data
1334 public function getPackageData () {
1335 return $this->packageData;
1340 * Setter for Iterator instance
1342 * @param $iteratorInstance An instance of an Iterator
1345 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1346 $this->iteratorInstance = $iteratorInstance;
1350 * Getter for Iterator instance
1352 * @return $iteratorInstance An instance of an Iterator
1354 public final function getIteratorInstance () {
1355 return $this->iteratorInstance;
1359 * Setter for FilePointer instance
1361 * @param $pointerInstance An instance of an FilePointer class
1364 protected final function setPointerInstance (FilePointer $pointerInstance) {
1365 $this->pointerInstance = $pointerInstance;
1369 * Getter for FilePointer instance
1371 * @return $pointerInstance An instance of an FilePointer class
1373 public final function getPointerInstance () {
1374 return $this->pointerInstance;
1378 * Unsets pointer instance which triggers a call of __destruct() if the
1379 * instance is still there. This is surely not fatal on already "closed"
1380 * file pointer instances.
1382 * I don't want to mess around with above setter by giving it a default
1383 * value NULL as setter should always explicitly only set (existing) object
1384 * instances and NULL is NULL.
1388 protected final function unsetPointerInstance () {
1389 // Simply it to NULL
1390 $this->pointerInstance = NULL;
1394 * Setter for Indexable instance
1396 * @param $indexInstance An instance of an Indexable class
1399 protected final function setIndexInstance (Indexable $indexInstance) {
1400 $this->indexInstance = $indexInstance;
1404 * Getter for Indexable instance
1406 * @return $indexInstance An instance of an Indexable class
1408 public final function getIndexInstance () {
1409 return $this->indexInstance;
1413 * Setter for Block instance
1415 * @param $blockInstance An instance of an Block class
1418 protected final function setBlockInstance (Block $blockInstance) {
1419 $this->blockInstance = $blockInstance;
1423 * Getter for Block instance
1425 * @return $blockInstance An instance of an Block class
1427 public final function getBlockInstance () {
1428 return $this->blockInstance;
1432 * Setter for Minable instance
1434 * @param $minableInstance A Minable instance
1437 protected final function setMinableInstance (Minable $minableInstance) {
1438 $this->minableInstance = $minableInstance;
1442 * Getter for minable instance
1444 * @return $minableInstance A Minable instance
1446 protected final function getMinableInstance () {
1447 return $this->minableInstance;
1451 * Setter for FrameworkDirectory instance
1453 * @param $directoryInstance A FrameworkDirectory instance
1456 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1457 $this->directoryInstance = $directoryInstance;
1461 * Getter for FrameworkDirectory instance
1463 * @return $directoryInstance A FrameworkDirectory instance
1465 protected final function getDirectoryInstance () {
1466 return $this->directoryInstance;
1470 * Getter for communicator instance
1472 * @return $communicatorInstance An instance of a Communicator class
1474 public final function getCommunicatorInstance () {
1475 return $this->communicatorInstance;
1479 * Setter for communicator instance
1481 * @param $communicatorInstance An instance of a Communicator class
1484 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1485 $this->communicatorInstance = $communicatorInstance;
1489 * Setter for state instance
1491 * @param $stateInstance A Stateable instance
1494 public final function setStateInstance (Stateable $stateInstance) {
1495 $this->stateInstance = $stateInstance;
1499 * Getter for state instance
1501 * @return $stateInstance A Stateable instance
1503 public final function getStateInstance () {
1504 return $this->stateInstance;
1508 * Setter for output instance
1510 * @param $outputInstance The debug output instance
1513 public final function setOutputInstance (OutputStreamer $outputInstance) {
1514 $this->outputInstance = $outputInstance;
1518 * Getter for output instance
1520 * @return $outputInstance The debug output instance
1522 public final function getOutputInstance () {
1523 return $this->outputInstance;
1527 * Setter for command name
1529 * @param $commandName Last validated command name
1532 protected final function setCommandName ($commandName) {
1533 $this->commandName = $commandName;
1537 * Getter for command name
1539 * @return $commandName Last validated command name
1541 protected final function getCommandName () {
1542 return $this->commandName;
1546 * Setter for controller name
1548 * @param $controllerName Last validated controller name
1551 protected final function setControllerName ($controllerName) {
1552 $this->controllerName = $controllerName;
1556 * Getter for controller name
1558 * @return $controllerName Last validated controller name
1560 protected final function getControllerName () {
1561 return $this->controllerName;
1565 * Checks whether an object equals this object. You should overwrite this
1566 * method to implement own equality checks
1568 * @param $objectInstance An instance of a FrameworkInterface object
1569 * @return $equals Whether both objects equals
1571 public function equals (FrameworkInterface $objectInstance) {
1574 $this->__toString() == $objectInstance->__toString()
1576 $this->hashCode() == $objectInstance->hashCode()
1579 // Return the result
1584 * Generates a generic hash code of this class. You should really overwrite
1585 * this method with your own hash code generator code. But keep KISS in mind.
1587 * @return $hashCode A generic hash code respresenting this whole class
1589 public function hashCode () {
1591 return crc32($this->__toString());
1595 * Formats computer generated price values into human-understandable formats
1596 * with thousand and decimal separators.
1598 * @param $value The in computer format value for a price
1599 * @param $currency The currency symbol (use HTML-valid characters!)
1600 * @param $decNum Number of decimals after commata
1601 * @return $price The for the current language formated price string
1602 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1603 * thousands separator
1606 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1607 // Are all required attriutes set?
1608 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1609 // Throw an exception
1610 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1614 $value = (float) $value;
1616 // Reformat the US number
1617 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1619 // Return as string...
1624 * Appends a trailing slash to a string
1626 * @param $str A string (maybe) without trailing slash
1627 * @return $str A string with an auto-appended trailing slash
1629 public final function addMissingTrailingSlash ($str) {
1630 // Is there a trailing slash?
1631 if (substr($str, -1, 1) != '/') {
1635 // Return string with trailing slash
1640 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1641 * application helper instance (ApplicationHelper by default).
1643 * @param $applicationInstance An application helper instance or
1644 * null if we shall use the default
1645 * @return $templateInstance The template engine instance
1646 * @throws NullPointerException If the discovered application
1647 * instance is still null
1649 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1650 // Is the application instance set?
1651 if (is_null($applicationInstance)) {
1652 // Get the current instance
1653 $applicationInstance = Registry::getRegistry()->getInstance('app');
1656 if (is_null($applicationInstance)) {
1657 // Thrown an exception
1658 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1662 // Initialize the template engine
1663 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1665 // Return the prepared instance
1666 return $templateInstance;
1670 * Debugs this instance by putting out it's full content
1672 * @param $message Optional message to show in debug output
1675 public final function debugInstance ($message = '') {
1676 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1677 restore_error_handler();
1682 // Is a message set?
1683 if (!empty($message)) {
1684 // Construct message
1685 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1688 // Generate the output
1689 $content .= sprintf('<pre>%s</pre>',
1692 print_r($this, true)
1698 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>',
1699 $this->__toString(),
1701 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1706 * Replaces control characters with printable output
1708 * @param $str String with control characters
1709 * @return $str Replaced string
1711 protected function replaceControlCharacters ($str) {
1714 chr(13), '[r]', str_replace(
1715 chr(10), '[n]', str_replace(
1725 * Output a partial stub message for the caller method
1727 * @param $message An optional message to display
1730 protected function partialStub ($message = '') {
1731 // Get the backtrace
1732 $backtrace = debug_backtrace();
1734 // Generate the class::method string
1735 $methodName = 'UnknownClass->unknownMethod';
1736 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1737 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1740 // Construct the full message
1741 $stubMessage = sprintf('[%s]: Partial stub!',
1745 // Is the extra message given?
1746 if (!empty($message)) {
1747 // Then add it as well
1748 $stubMessage .= ' Message: ' . $message;
1751 // Debug instance is there?
1752 if (!is_null($this->getDebugInstance())) {
1753 // Output stub message
1754 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1757 trigger_error($stubMessage);
1763 * Outputs a debug backtrace and stops further script execution
1765 * @param $message An optional message to output
1766 * @param $doExit Whether exit the program (true is default)
1769 public function debugBackTrace ($message = '', $doExit = true) {
1770 // Sorry, there is no other way getting this nice backtrace
1771 if (!empty($message)) {
1773 printf('Message: %s<br />' . PHP_EOL, $message);
1777 debug_print_backtrace();
1781 if ($doExit === true) {
1787 * Creates an instance of a debugger instance
1789 * @param $className Name of the class (currently unsupported)
1790 * @param $lineNumber Line number where the call was made
1791 * @return $debugInstance An instance of a debugger class
1792 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1794 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1795 // Is the instance set?
1796 if (!Registry::getRegistry()->instanceExists('debug')) {
1797 // Init debug instance
1798 $debugInstance = NULL;
1802 // Get a debugger instance
1803 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1804 } catch (NullPointerException $e) {
1805 // Didn't work, no instance there
1806 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1809 // Empty string should be ignored and used for testing the middleware
1810 DebugMiddleware::getSelfInstance()->output('');
1812 // Set it in its own class. This will set it in the registry
1813 $debugInstance->setDebugInstance($debugInstance);
1815 // Get instance from registry
1816 $debugInstance = Registry::getRegistry()->getDebugInstance();
1820 return $debugInstance;
1824 * Simple output of a message with line-break
1826 * @param $message Message to output
1829 public function outputLine ($message) {
1831 print($message . PHP_EOL);
1835 * Outputs a debug message whether to debug instance (should be set!) or
1836 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1837 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1839 * @param $message Message we shall send out...
1840 * @param $doPrint Whether print or die here (default: print)
1841 * @paran $stripTags Whether to strip tags (default: false)
1844 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1845 // Set debug instance to NULL
1846 $debugInstance = NULL;
1850 // Get debug instance
1851 $debugInstance = $this->getDebugInstance();
1852 } catch (NullPointerException $e) {
1853 // The debug instance is not set (yet)
1856 // Is the debug instance there?
1857 if (is_object($debugInstance)) {
1858 // Use debug output handler
1859 $debugInstance->output($message, $stripTags);
1861 if ($doPrint === false) {
1862 // Die here if not printed
1866 // Are debug times enabled?
1867 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1869 $message = $this->getPrintableExecutionTime() . $message;
1873 if ($doPrint === true) {
1875 $this->outputLine($message);
1884 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1886 * @param $str The string, what ever it is needs to be converted
1887 * @return $className Generated class name
1889 public static final function convertToClassName ($str) {
1893 // Convert all dashes in underscores
1894 $str = self::convertDashesToUnderscores($str);
1896 // Now use that underscores to get classname parts for hungarian style
1897 foreach (explode('_', $str) as $strPart) {
1898 // Make the class name part lower case and first upper case
1899 $className .= ucfirst(strtolower($strPart));
1902 // Return class name
1907 * Converts dashes to underscores, e.g. useable for configuration entries
1909 * @param $str The string with maybe dashes inside
1910 * @return $str The converted string with no dashed, but underscores
1912 public static final function convertDashesToUnderscores ($str) {
1914 $str = str_replace('-', '_', $str);
1916 // Return converted string
1921 * Marks up the code by adding e.g. line numbers
1923 * @param $phpCode Unmarked PHP code
1924 * @return $markedCode Marked PHP code
1926 public function markupCode ($phpCode) {
1931 $errorArray = error_get_last();
1933 // Init the code with error message
1934 if (is_array($errorArray)) {
1936 $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>',
1937 basename($errorArray['file']),
1938 $errorArray['line'],
1939 $errorArray['message'],
1944 // Add line number to the code
1945 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1947 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1949 htmlentities($code, ENT_QUOTES)
1958 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1959 * beatiful for web-based front-ends. If null is given a message id
1960 * null_timestamp will be resolved and returned.
1962 * @param $timestamp Timestamp to prepare (filter) for display
1963 * @return $readable A readable timestamp
1965 public function doFilterFormatTimestamp ($timestamp) {
1966 // Default value to return
1969 // Is the timestamp null?
1970 if (is_null($timestamp)) {
1971 // Get a message string
1972 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1974 switch ($this->getLanguageInstance()->getLanguageCode()) {
1975 case 'de': // German format is a bit different to default
1976 // Split the GMT stamp up
1977 $dateTime = explode(' ', $timestamp );
1978 $dateArray = explode('-', $dateTime[0]);
1979 $timeArray = explode(':', $dateTime[1]);
1981 // Construct the timestamp
1982 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1992 default: // Default is pass-through
1993 $readable = $timestamp;
2003 * Filter a given number into a localized number
2005 * @param $value The raw value from e.g. database
2006 * @return $localized Localized value
2008 public function doFilterFormatNumber ($value) {
2009 // Generate it from config and localize dependencies
2010 switch ($this->getLanguageInstance()->getLanguageCode()) {
2011 case 'de': // German format is a bit different to default
2012 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2015 default: // US, etc.
2016 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2025 * "Getter" for databse entry
2027 * @return $entry An array with database entries
2028 * @throws NullPointerException If the database result is not found
2029 * @throws InvalidDatabaseResultException If the database result is invalid
2031 protected final function getDatabaseEntry () {
2032 // Is there an instance?
2033 if (!$this->getResultInstance() instanceof SearchableResult) {
2034 // Throw an exception here
2035 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2039 $this->getResultInstance()->rewind();
2041 // Do we have an entry?
2042 if ($this->getResultInstance()->valid() === false) {
2043 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2044 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2048 $this->getResultInstance()->next();
2051 $entry = $this->getResultInstance()->current();
2058 * Getter for field name
2060 * @param $fieldName Field name which we shall get
2061 * @return $fieldValue Field value from the user
2062 * @throws NullPointerException If the result instance is null
2064 public final function getField ($fieldName) {
2065 // Default field value
2068 // Get result instance
2069 $resultInstance = $this->getResultInstance();
2071 // Is this instance null?
2072 if (is_null($resultInstance)) {
2073 // Then the user instance is no longer valid (expired cookies?)
2074 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2077 // Get current array
2078 $fieldArray = $resultInstance->current();
2079 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2081 // Convert dashes to underscore
2082 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2084 // Does the field exist?
2085 if ($this->isFieldSet($fieldName)) {
2087 $fieldValue = $fieldArray[$fieldName2];
2088 } elseif (defined('DEVELOPER')) {
2089 // Missing field entry, may require debugging
2090 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2092 // Missing field entry, may require debugging
2093 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2101 * Checks if given field is set
2103 * @param $fieldName Field name to check
2104 * @return $isSet Whether the given field name is set
2105 * @throws NullPointerException If the result instance is null
2107 public function isFieldSet ($fieldName) {
2108 // Get result instance
2109 $resultInstance = $this->getResultInstance();
2111 // Is this instance null?
2112 if (is_null($resultInstance)) {
2113 // Then the user instance is no longer valid (expired cookies?)
2114 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2117 // Get current array
2118 $fieldArray = $resultInstance->current();
2119 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2121 // Convert dashes to underscore
2122 $fieldName = self::convertDashesToUnderscores($fieldName);
2125 $isSet = isset($fieldArray[$fieldName]);
2132 * Flushs all pending updates to the database layer
2136 public function flushPendingUpdates () {
2137 // Get result instance
2138 $resultInstance = $this->getResultInstance();
2140 // Do we have data to update?
2141 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2142 // Get wrapper class name config entry
2143 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2145 // Create object instance
2146 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2148 // Yes, then send the whole result to the database layer
2149 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2154 * Outputs a deprecation warning to the developer.
2156 * @param $message The message we shall output to the developer
2158 * @todo Write a logging mechanism for productive mode
2160 public function deprecationWarning ($message) {
2161 // Is developer mode active?
2162 if (defined('DEVELOPER')) {
2163 // Debug instance is there?
2164 if (!is_null($this->getDebugInstance())) {
2165 // Output stub message
2166 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2169 trigger_error($message . "<br />\n");
2173 // @TODO Finish this part!
2174 $this->partialStub('Developer mode inactive. Message:' . $message);
2179 * Checks whether the given PHP extension is loaded
2181 * @param $phpExtension The PHP extension we shall check
2182 * @return $isLoaded Whether the PHP extension is loaded
2184 public final function isPhpExtensionLoaded ($phpExtension) {
2186 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2193 * "Getter" as a time() replacement but with milliseconds. You should use this
2194 * method instead of the encapsulated getimeofday() function.
2196 * @return $milliTime Timestamp with milliseconds
2198 public function getMilliTime () {
2199 // Get the time of day as float
2200 $milliTime = gettimeofday(true);
2207 * Idles (sleeps) for given milliseconds
2209 * @return $hasSlept Whether it goes fine
2211 public function idle ($milliSeconds) {
2212 // Sleep is fine by default
2215 // Idle so long with found function
2216 if (function_exists('time_sleep_until')) {
2217 // Get current time and add idle time
2218 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2220 // New PHP 5.1.0 function found, ignore errors
2221 $hasSlept = @time_sleep_until($sleepUntil);
2224 * My Sun station doesn't have that function even with latest PHP
2227 usleep($milliSeconds * 1000);
2234 * Converts a hexadecimal string, even with negative sign as first string to
2235 * a decimal number using BC functions.
2237 * This work is based on comment #86673 on php.net documentation page at:
2238 * <http://de.php.net/manual/en/function.dechex.php#86673>
2240 * @param $hex Hexadecimal string
2241 * @return $dec Decimal number
2243 protected function hex2dec ($hex) {
2244 // Convert to all lower-case
2245 $hex = strtolower($hex);
2247 // Detect sign (negative/positive numbers)
2249 if (substr($hex, 0, 1) == '-') {
2251 $hex = substr($hex, 1);
2254 // Decode the hexadecimal string into a decimal number
2256 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2257 $factor = self::$hexdec[substr($hex, $i, 1)];
2258 $dec = bcadd($dec, bcmul($factor, $e));
2261 // Return the decimal number
2262 return $sign . $dec;
2266 * Converts even very large decimal numbers, also signed, to a hexadecimal
2269 * This work is based on comment #97756 on php.net documentation page at:
2270 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2272 * @param $dec Decimal number, even with negative sign
2273 * @param $maxLength Optional maximum length of the string
2274 * @return $hex Hexadecimal string
2276 protected function dec2hex ($dec, $maxLength = 0) {
2277 // maxLength can be zero or devideable by 2
2278 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2280 // Detect sign (negative/positive numbers)
2287 // Encode the decimal number into a hexadecimal string
2290 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2292 } while ($dec >= 1);
2295 * Leading zeros are required for hex-decimal "numbers". In some
2296 * situations more leading zeros are wanted, so check for both
2299 if ($maxLength > 0) {
2300 // Prepend more zeros
2301 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2302 } elseif ((strlen($hex) % 2) != 0) {
2303 // Only make string's length dividable by 2
2307 // Return the hexadecimal string
2308 return $sign . $hex;
2312 * Converts a ASCII string (0 to 255) into a decimal number.
2314 * @param $asc The ASCII string to be converted
2315 * @return $dec Decimal number
2317 protected function asc2dec ($asc) {
2318 // Convert it into a hexadecimal number
2319 $hex = bin2hex($asc);
2321 // And back into a decimal number
2322 $dec = $this->hex2dec($hex);
2329 * Converts a decimal number into an ASCII string.
2331 * @param $dec Decimal number
2332 * @return $asc An ASCII string
2334 protected function dec2asc ($dec) {
2335 // First convert the number into a hexadecimal string
2336 $hex = $this->dec2hex($dec);
2338 // Then convert it into the ASCII string
2339 $asc = $this->hex2asc($hex);
2346 * Converts a hexadecimal number into an ASCII string. Negative numbers
2349 * @param $hex Hexadecimal string
2350 * @return $asc An ASCII string
2352 protected function hex2asc ($hex) {
2353 // Check for length, it must be devideable by 2
2354 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2355 assert((strlen($hex) % 2) == 0);
2359 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2360 // Get the decimal number of the chunk
2361 $part = hexdec(substr($hex, $idx, 2));
2363 // Add it to the final string
2367 // Return the final string
2372 * Checks whether the given encoded data was encoded with Base64
2374 * @param $encodedData Encoded data we shall check
2375 * @return $isBase64 Whether the encoded data is Base64
2377 protected function isBase64Encoded ($encodedData) {
2379 $isBase64 = (@base64_decode($encodedData, true) !== false);
2386 * Gets a cache key from Criteria instance
2388 * @param $criteriaInstance An instance of a Criteria class
2389 * @param $onlyKeys Only use these keys for a cache key
2390 * @return $cacheKey A cache key suitable for lookup/storage purposes
2392 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2394 $cacheKey = sprintf('%s@%s',
2395 $this->__toString(),
2396 $criteriaInstance->getCacheKey($onlyKeys)
2400 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2405 * Getter for startup time in miliseconds
2407 * @return $startupTime Startup time in miliseconds
2409 protected function getStartupTime () {
2410 return self::$startupTime;
2414 * "Getter" for a printable currently execution time in nice braces
2416 * @return $executionTime Current execution time in nice braces
2418 protected function getPrintableExecutionTime () {
2419 // Caculate the execution time
2420 $executionTime = microtime(true) - $this->getStartupTime();
2422 // Pack it in nice braces
2423 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2426 return $executionTime;
2430 * Hashes a given string with a simple but stronger hash function (no salt)
2431 * and hex-encode it.
2433 * @param $str The string to be hashed
2434 * @return $hash The hash from string $str
2436 public static final function hash ($str) {
2437 // Hash given string with (better secure) hasher
2438 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2445 * "Getter" for length of hash() output. This will be "cached" to speed up
2448 * @return $length Length of hash() output
2450 public static final function getHashLength () {
2452 if (is_null(self::$hashLength)) {
2453 // No, then hash a string and save its length.
2454 self::$hashLength = strlen(self::hash('abc123'));
2458 return self::$hashLength;
2462 * Checks whether the given number is really a number (only chars 0-9).
2464 * @param $num A string consisting only chars between 0 and 9
2465 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2466 * @param $assertMismatch Whether to assert mismatches
2467 * @return $ret The (hopefully) secured numbered value
2469 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2470 // Filter all numbers out
2471 $ret = preg_replace('/[^0123456789]/', '', $num);
2474 if ($castValue === true) {
2475 // Cast to biggest numeric type
2476 $ret = (double) $ret;
2479 // Assert only if requested
2480 if ($assertMismatch === true) {
2481 // Has the whole value changed?
2482 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2490 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2492 * @param $num A string consisting only chars between 0 and 9
2493 * @param $assertMismatch Whether to assert mismatches
2494 * @return $ret The (hopefully) secured hext-numbered value
2496 public function hexval ($num, $assertMismatch = false) {
2497 // Filter all numbers out
2498 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2500 // Assert only if requested
2501 if ($assertMismatch === true) {
2502 // Has the whole value changed?
2503 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2511 * Determines if an element is set in the generic array
2513 * @param $keyGroup Main group for the key
2514 * @param $subGroup Sub group for the key
2515 * @param $key Key to check
2516 * @param $element Element to check
2517 * @return $isset Whether the given key is set
2519 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2521 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2524 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2530 * Determines if a key is set in the generic array
2532 * @param $keyGroup Main group for the key
2533 * @param $subGroup Sub group for the key
2534 * @param $key Key to check
2535 * @return $isset Whether the given key is set
2537 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2539 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2542 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2550 * Determines if a group is set in the generic array
2552 * @param $keyGroup Main group
2553 * @param $subGroup Sub group
2554 * @return $isset Whether the given group is set
2556 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2558 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2561 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2568 * Getter for sub key group
2570 * @param $keyGroup Main key group
2571 * @param $subGroup Sub key group
2572 * @return $array An array with all array elements
2574 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2576 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2577 // No, then abort here
2578 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2583 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2586 return $this->genericArray[$keyGroup][$subGroup];
2590 * Unsets a given key in generic array
2592 * @param $keyGroup Main group for the key
2593 * @param $subGroup Sub group for the key
2594 * @param $key Key to unset
2597 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2599 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2602 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2606 * Unsets a given element in generic array
2608 * @param $keyGroup Main group for the key
2609 * @param $subGroup Sub group for the key
2610 * @param $key Key to unset
2611 * @param $element Element to unset
2614 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2616 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2619 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2623 * Append a string to a given generic array key
2625 * @param $keyGroup Main group for the key
2626 * @param $subGroup Sub group for the key
2627 * @param $key Key to unset
2628 * @param $value Value to add/append
2631 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2633 //* 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);
2635 // Is it already there?
2636 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2638 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2641 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2646 * Append a string to a given generic array element
2648 * @param $keyGroup Main group for the key
2649 * @param $subGroup Sub group for the key
2650 * @param $key Key to unset
2651 * @param $element Element to check
2652 * @param $value Value to add/append
2655 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2657 //* 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);
2659 // Is it already there?
2660 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2662 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2665 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2670 * Sets a string in a given generic array element
2672 * @param $keyGroup Main group for the key
2673 * @param $subGroup Sub group for the key
2674 * @param $key Key to unset
2675 * @param $element Element to check
2676 * @param $value Value to add/append
2679 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2681 //* 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);
2684 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2688 * Initializes given generic array group
2690 * @param $keyGroup Main group for the key
2691 * @param $subGroup Sub group for the key
2692 * @param $key Key to use
2693 * @param $forceInit Optionally force initialization
2696 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2698 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2700 // Is it already set?
2701 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2702 // Already initialized
2703 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2708 $this->genericArray[$keyGroup][$subGroup] = array();
2712 * Initializes given generic array key
2714 * @param $keyGroup Main group for the key
2715 * @param $subGroup Sub group for the key
2716 * @param $key Key to use
2717 * @param $forceInit Optionally force initialization
2720 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2722 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2724 // Is it already set?
2725 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2726 // Already initialized
2727 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2732 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2736 * Initializes given generic array element
2738 * @param $keyGroup Main group for the key
2739 * @param $subGroup Sub group for the key
2740 * @param $key Key to use
2741 * @param $element Element to use
2742 * @param $forceInit Optionally force initialization
2745 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2747 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2749 // Is it already set?
2750 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2751 // Already initialized
2752 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2757 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2761 * Pushes an element to a generic key
2763 * @param $keyGroup Main group for the key
2764 * @param $subGroup Sub group for the key
2765 * @param $key Key to use
2766 * @param $value Value to add/append
2767 * @return $count Number of array elements
2769 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2771 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2774 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2776 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2780 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2783 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2784 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2789 * Pushes an element to a generic array element
2791 * @param $keyGroup Main group for the key
2792 * @param $subGroup Sub group for the key
2793 * @param $key Key to use
2794 * @param $element Element to check
2795 * @param $value Value to add/append
2796 * @return $count Number of array elements
2798 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2800 //* 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));
2803 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2805 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2809 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2812 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2813 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2818 * Pops an element from a generic group
2820 * @param $keyGroup Main group for the key
2821 * @param $subGroup Sub group for the key
2822 * @param $key Key to unset
2823 * @return $value Last "popped" value
2825 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2827 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2830 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2832 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2837 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2840 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2841 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2846 * Shifts an element from a generic group
2848 * @param $keyGroup Main group for the key
2849 * @param $subGroup Sub group for the key
2850 * @param $key Key to unset
2851 * @return $value Last "popped" value
2853 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2855 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2858 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2860 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2865 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2868 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2869 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2874 * Count generic array group
2876 * @param $keyGroup Main group for the key
2877 * @return $count Count of given group
2879 protected final function countGenericArray ($keyGroup) {
2881 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2884 if (!isset($this->genericArray[$keyGroup])) {
2886 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2891 $count = count($this->genericArray[$keyGroup]);
2894 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2901 * Count generic array sub group
2903 * @param $keyGroup Main group for the key
2904 * @param $subGroup Sub group for the key
2905 * @return $count Count of given group
2907 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2909 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2912 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2914 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2919 $count = count($this->genericArray[$keyGroup][$subGroup]);
2922 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2929 * Count generic array elements
2931 * @param $keyGroup Main group for the key
2932 * @param $subGroup Sub group for the key
2933 * @para $key Key to count
2934 * @return $count Count of given key
2936 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2938 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2941 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2943 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2945 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2947 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2952 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2955 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2962 * Getter for whole generic group array
2964 * @param $keyGroup Key group to get
2965 * @return $array Whole generic array group
2967 protected final function getGenericArray ($keyGroup) {
2969 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2972 if (!isset($this->genericArray[$keyGroup])) {
2974 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2979 return $this->genericArray[$keyGroup];
2983 * Setter for generic array key
2985 * @param $keyGroup Key group to get
2986 * @param $subGroup Sub group for the key
2987 * @param $key Key to unset
2988 * @param $value Mixed value from generic array element
2991 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2993 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2996 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3000 * Getter for generic array key
3002 * @param $keyGroup Key group to get
3003 * @param $subGroup Sub group for the key
3004 * @param $key Key to unset
3005 * @return $value Mixed value from generic array element
3007 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3009 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3012 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3014 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3019 return $this->genericArray[$keyGroup][$subGroup][$key];
3023 * Sets a value in given generic array key/element
3025 * @param $keyGroup Main group for the key
3026 * @param $subGroup Sub group for the key
3027 * @param $key Key to set
3028 * @param $element Element to set
3029 * @param $value Value to set
3032 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3034 //* 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));
3037 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3041 * Getter for generic array element
3043 * @param $keyGroup Key group to get
3044 * @param $subGroup Sub group for the key
3045 * @param $key Key to look for
3046 * @param $element Element to look for
3047 * @return $value Mixed value from generic array element
3049 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3051 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3054 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3056 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3061 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3065 * Checks if a given sub group is valid (array)
3067 * @param $keyGroup Key group to get
3068 * @param $subGroup Sub group for the key
3069 * @return $isValid Whether given sub group is valid
3071 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3073 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3076 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3083 * Checks if a given key is valid (array)
3085 * @param $keyGroup Key group to get
3086 * @param $subGroup Sub group for the key
3087 * @param $key Key to check
3088 * @return $isValid Whether given sub group is valid
3090 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3092 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3095 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3102 * Initializes the web output instance
3106 protected function initWebOutputInstance () {
3107 // Get application instance
3108 $applicationInstance = Registry::getRegistry()->getInstance('app');
3110 // Init web output instance
3111 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3114 $this->setWebOutputInstance($outputInstance);
3118 * Translates boolean true to 'Y' and false to 'N'
3120 * @param $boolean Boolean value
3121 * @return $translated Translated boolean value
3123 public static final function translateBooleanToYesNo ($boolean) {
3124 // Make sure it is really boolean
3125 assert(is_bool($boolean));
3128 $translated = ($boolean === true) ? 'Y' : 'N';
3130 // ... and return it
3135 * Encodes raw data (almost any type) by "serializing" it and then pack it
3136 * into a "binary format".
3138 * @param $rawData Raw data (almost any type)
3139 * @return $encoded Encoded data
3141 protected function encodeData ($rawData) {
3142 // Make sure no objects or resources pass through
3143 assert(!is_object($rawData));
3144 assert(!is_resource($rawData));
3146 // First "serialize" it (json_encode() is faster than serialize())
3147 $encoded = $this->packString(json_encode($rawData));
3154 * Pack a string into a "binary format". Please execuse me that this is
3155 * widely undocumented. :-(
3157 * @param $str Unpacked string
3158 * @return $packed Packed string
3159 * @todo Improve documentation
3161 protected function packString ($str) {
3163 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3165 // First compress the string (gzcompress is okay)
3166 $str = gzcompress($str);
3171 // And start the "encoding" loop
3172 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3174 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3175 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3177 if (($idx + $i) <= strlen($str)) {
3178 $ord = ord(substr($str, ($idx + $i), 1));
3180 $add = $ord * pow(256, $factor);
3184 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3188 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3189 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3191 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3192 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3198 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3203 * Creates a full-qualified file name (FQFN) for given file name by adding
3204 * a configured temporary file path to it.
3206 * @param $fileName Name for temporary file
3207 * @return $fqfn Full-qualified file name
3208 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3209 * @throws FileIoException If the file cannot be written
3211 protected static function createTempPathForFile ($fileName) {
3213 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3215 // Is the path writeable?
3216 if (!is_writable($basePath)) {
3217 // Path is write-protected
3218 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3222 $fqfn = $basePath . '/' . $fileName;
3225 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3227 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3235 * "Getter" for a printable state name
3237 * @return $stateName Name of the node's state in a printable format
3239 public final function getPrintableState () {
3240 // Default is 'null'
3241 $stateName = 'null';
3243 // Get the state instance
3244 $stateInstance = $this->getStateInstance();
3246 // Is it an instance of Stateable?
3247 if ($stateInstance instanceof Stateable) {
3248 // Then use that state name
3249 $stateName = $stateInstance->getStateName();