3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\Compressor\Compressor;
8 use CoreFramework\Configuration\FrameworkConfiguration;
9 use CoreFramework\Connection\Database\DatabaseConnection;
10 use CoreFramework\Controller\Controller;
11 use CoreFramework\Criteria\Criteria;
12 use CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use CoreFramework\Crypto\Cryptable;
15 use CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use CoreFramework\Database\Frontend\DatabaseWrapper;
17 use CoreFramework\EntryPoint\ApplicationEntryPoint;
18 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
19 use CoreFramework\Factory\ObjectFactory;
20 use CoreFramework\Filesystem\Block;
21 use CoreFramework\Filesystem\FilePointer;
22 use CoreFramework\Filesystem\FrameworkDirectory;
23 use CoreFramework\Filesystem\PathWriteProtectedException;
24 use CoreFramework\Generic\FrameworkInterface;
25 use CoreFramework\Generic\NullPointerException;
26 use CoreFramework\Generic\UnsupportedOperationException;
27 use CoreFramework\Handler\Handleable;
28 use CoreFramework\Handler\Stream\IoHandler;
29 use CoreFramework\Index\Indexable;
30 use CoreFramework\Lists\Listable;
31 use CoreFramework\Loader\ClassLoader;
32 use CoreFramework\Manager\ManageableApplication;
33 use CoreFramework\Middleware\Compressor\CompressorChannel;
34 use CoreFramework\Middleware\Debug\DebugMiddleware;
35 use CoreFramework\Parser\Parseable;
36 use CoreFramework\Registry\Register;
37 use CoreFramework\Registry\Registry;
38 use CoreFramework\Resolver\Resolver;
39 use CoreFramework\Result\Database\CachedDatabaseResult;
40 use CoreFramework\Result\Search\SearchableResult;
41 use CoreFramework\Stacker\Stackable;
42 use CoreFramework\State\Stateable;
43 use CoreFramework\Stream\Input\InputStream;
44 use CoreFramework\Stream\Output\OutputStreamer;
45 use CoreFramework\Stream\Output\OutputStream;
46 use CoreFramework\Template\CompileableTemplate;
47 use CoreFramework\User\ManageableAccount;
48 use CoreFramework\Visitor\Visitor;
56 * The simulator system class is the super class of all other classes. This
57 * class handles saving of games etc.
59 * @author Roland Haeder <webmaster@shipsimu.org>
61 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
62 * @license GNU GPL 3.0 or any newer version
63 * @link http://www.shipsimu.org
65 * This program is free software: you can redistribute it and/or modify
66 * it under the terms of the GNU General Public License as published by
67 * the Free Software Foundation, either version 3 of the License, or
68 * (at your option) any later version.
70 * This program is distributed in the hope that it will be useful,
71 * but WITHOUT ANY WARRANTY; without even the implied warranty of
72 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
73 * GNU General Public License for more details.
75 * You should have received a copy of the GNU General Public License
76 * along with this program. If not, see <http://www.gnu.org/licenses/>.
78 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
80 * Length of output from hash()
82 private static $hashLength = NULL;
87 private $realClass = 'BaseFrameworkSystem';
90 * Search criteria instance
92 private $searchInstance = NULL;
95 * Update criteria instance
97 private $updateInstance = NULL;
100 * The file I/O instance for the template loader
102 private $fileIoInstance = NULL;
107 private $resolverInstance = NULL;
110 * Template engine instance
112 private $templateInstance = NULL;
115 * Database result instance
117 private $resultInstance = NULL;
120 * Instance for user class
122 private $userInstance = NULL;
125 * A controller instance
127 private $controllerInstance = NULL;
132 private $rngInstance = NULL;
135 * Instance of a crypto helper
137 private $cryptoInstance = NULL;
140 * Instance of an Iterator class
142 private $iteratorInstance = NULL;
145 * Instance of the list
147 private $listInstance = NULL;
152 private $menuInstance = NULL;
155 * Instance of the image
157 private $imageInstance = NULL;
160 * Instance of the stacker
162 private $stackInstance = NULL;
165 * A Compressor instance
167 private $compressorInstance = NULL;
170 * A Parseable instance
172 private $parserInstance = NULL;
175 * A database wrapper instance
177 private $databaseInstance = NULL;
180 * A helper instance for the form
182 private $helperInstance = NULL;
185 * An instance of a Source class
187 private $sourceInstance = NULL;
190 * An instance of a UrlSource class
192 private $urlSourceInstance = NULL;
195 * An instance of a InputStream class
197 private $inputStreamInstance = NULL;
200 * An instance of a OutputStream class
202 private $outputStreamInstance = NULL;
207 private $handlerInstance = NULL;
210 * Visitor handler instance
212 private $visitorInstance = NULL;
215 * An instance of a database wrapper class
217 private $wrapperInstance = NULL;
220 * An instance of a file I/O pointer class (not handler)
222 private $pointerInstance = NULL;
225 * An instance of an Indexable class
227 private $indexInstance = NULL;
230 * An instance of a Block class
232 private $blockInstance = NULL;
237 private $minableInstance = NULL;
240 * A FrameworkDirectory instance
242 private $directoryInstance = NULL;
245 * An instance of a communicator
247 private $communicatorInstance = NULL;
250 * The concrete output instance
252 private $outputInstance = NULL;
257 private $stateInstance = NULL;
260 * Thousands separator
262 private $thousands = '.'; // German
267 private $decimals = ','; // German
272 private $socketResource = false;
275 * Regular expression to use for validation
277 private $regularExpression = '';
282 private $packageData = array();
287 private $genericArray = array();
292 private $commandName = '';
297 private $controllerName = '';
300 * Array with bitmasks and such for pack/unpack methods to support both
301 * 32-bit and 64-bit systems
303 private $packingData = array(
306 'left' => 0xffff0000,
307 'right' => 0x0000ffff,
313 'left' => 0xffffffff00000000,
314 'right' => 0x00000000ffffffff,
321 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
323 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
325 private $archArrayElement = false;
327 /***********************
328 * Exception codes.... *
329 ***********************/
331 // @todo Try to clean these constants up
332 const EXCEPTION_IS_NULL_POINTER = 0x001;
333 const EXCEPTION_IS_NO_OBJECT = 0x002;
334 const EXCEPTION_IS_NO_ARRAY = 0x003;
335 const EXCEPTION_MISSING_METHOD = 0x004;
336 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
337 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
338 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
339 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
340 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
341 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
342 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
343 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
344 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
345 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
346 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
347 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
348 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
349 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
350 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
351 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
352 const EXCEPTION_PATH_NOT_FOUND = 0x015;
353 const EXCEPTION_INVALID_PATH_NAME = 0x016;
354 const EXCEPTION_READ_PROTECED_PATH = 0x017;
355 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
356 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
357 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
358 const EXCEPTION_INVALID_RESOURCE = 0x01b;
359 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
360 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
361 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
362 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
363 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
364 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
365 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
366 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
367 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
368 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
369 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
370 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
371 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
372 const EXCEPTION_INVALID_STRING = 0x029;
373 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
374 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
375 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
376 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
377 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
378 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
379 const EXCEPTION_MISSING_ELEMENT = 0x030;
380 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
381 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
382 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
383 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
384 const EXCEPTION_FATAL_ERROR = 0x035;
385 const EXCEPTION_FILE_NOT_FOUND = 0x036;
386 const EXCEPTION_ASSERTION_FAILED = 0x037;
387 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
388 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
389 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
390 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
391 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
392 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
393 const EXCEPTION_INVALID_SOCKET = 0x03e;
396 * Hexadecimal->Decimal translation array
398 private static $hexdec = array(
418 * Decimal->hexadecimal translation array
420 private static $dechex = array(
440 * Startup time in miliseconds
442 private static $startupTime = 0;
445 * Protected super constructor
447 * @param $className Name of the class
450 protected function __construct ($className) {
452 $this->setRealClass($className);
454 // Set configuration instance if no registry ...
455 if (!$this instanceof Register) {
456 // ... because registries doesn't need to be configured
457 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
460 // Is the startup time set? (0 cannot be true anymore)
461 if (self::$startupTime == 0) {
463 self::$startupTime = microtime(true);
467 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
471 * Destructor for all classes. You should not call this method on your own.
475 public function __destruct () {
476 // Flush any updated entries to the database
477 $this->flushPendingUpdates();
479 // Is this object already destroyed?
480 if ($this->__toString() != 'DestructedObject') {
481 // Destroy all informations about this class but keep some text about it alive
482 $this->setRealClass('DestructedObject');
483 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
484 // Already destructed object
485 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
489 // Do not call this twice
490 trigger_error(__METHOD__ . ': Called twice.');
496 * The __call() method where all non-implemented methods end up
498 * @param $methodName Name of the missing method
499 * @args $args Arguments passed to the method
502 public final function __call ($methodName, $args) {
503 return self::__callStatic($methodName, $args);
507 * The __callStatic() method where all non-implemented static methods end up
509 * @param $methodName Name of the missing method
510 * @args $args Arguments passed to the method
513 public static final function __callStatic ($methodName, $args) {
515 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
517 // Init argument string
520 // Is it NULL, empty or an array?
521 if (is_null($args)) {
523 $argsString = 'NULL';
524 } elseif (is_array($args)) {
528 // Some arguments are there
529 foreach ($args as $arg) {
530 // Add data about the argument
531 $argsString .= gettype($arg) . ':';
534 // Found a NULL argument
535 $argsString .= 'NULL';
536 } elseif (is_string($arg)) {
537 // Add length for strings
538 $argsString .= strlen($arg);
539 } elseif ((is_int($arg)) || (is_float($arg))) {
542 } elseif (is_array($arg)) {
543 // .. or size if array
544 $argsString .= count($arg);
545 } elseif (is_object($arg)) {
547 $reflection = new ReflectionClass($arg);
549 // Is an other object, maybe no __toString() available
550 $argsString .= $reflection->getName();
551 } elseif ($arg === true) {
552 // ... is boolean 'true'
553 $argsString .= 'true';
554 } elseif ($arg === false) {
555 // ... is boolean 'false'
556 $argsString .= 'false';
559 // Comma for next one
564 if (substr($argsString, -2, 1) == ',') {
565 $argsString = substr($argsString, 0, -2);
571 // Invalid arguments!
572 $argsString = '!INVALID:' . gettype($args) . '!';
575 // Output stub message
576 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
577 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
587 * Getter for $realClass
589 * @return $realClass The name of the real class (not BaseFrameworkSystem)
591 public function __toString () {
592 return $this->realClass;
596 * Magic method to catch setting of missing but set class fields/attributes
598 * @param $name Name of the field/attribute
599 * @param $value Value to store
602 public final function __set ($name, $value) {
603 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
606 print_r($value, true)
611 * Magic method to catch getting of missing fields/attributes
613 * @param $name Name of the field/attribute
616 public final function __get ($name) {
617 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
623 * Magic method to catch unsetting of missing fields/attributes
625 * @param $name Name of the field/attribute
628 public final function __unset ($name) {
629 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
635 * Magic method to catch object serialization
637 * @return $unsupported Unsupported method
638 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
640 public final function __sleep () {
641 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
645 * Magic method to catch object deserialization
647 * @return $unsupported Unsupported method
648 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
650 public final function __wakeup () {
651 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
655 * Magic method to catch calls when an object instance is called
657 * @return $unsupported Unsupported method
658 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
660 public final function __invoke () {
661 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
665 * Setter for the real class name
667 * @param $realClass Class name (string)
670 public final function setRealClass ($realClass) {
672 $this->realClass = (string) $realClass;
676 * Setter for database result instance
678 * @param $resultInstance An instance of a database result class
680 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
682 protected final function setResultInstance (SearchableResult $resultInstance) {
683 $this->resultInstance = $resultInstance;
687 * Getter for database result instance
689 * @return $resultInstance An instance of a database result class
691 public final function getResultInstance () {
692 return $this->resultInstance;
696 * Setter for template engine instances
698 * @param $templateInstance An instance of a template engine class
701 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
702 $this->templateInstance = $templateInstance;
706 * Getter for template engine instances
708 * @return $templateInstance An instance of a template engine class
710 protected final function getTemplateInstance () {
711 return $this->templateInstance;
715 * Setter for search instance
717 * @param $searchInstance Searchable criteria instance
720 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
721 $this->searchInstance = $searchInstance;
725 * Getter for search instance
727 * @return $searchInstance Searchable criteria instance
729 public final function getSearchInstance () {
730 return $this->searchInstance;
734 * Setter for update instance
736 * @param $updateInstance An instance of a LocalUpdateCriteria clase
739 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
740 $this->updateInstance = $updateInstance;
744 * Getter for update instance
746 * @return $updateInstance Updateable criteria instance
748 public final function getUpdateInstance () {
749 return $this->updateInstance;
753 * Setter for resolver instance
755 * @param $resolverInstance Instance of a command resolver class
758 public final function setResolverInstance (Resolver $resolverInstance) {
759 $this->resolverInstance = $resolverInstance;
763 * Getter for resolver instance
765 * @return $resolverInstance Instance of a command resolver class
767 public final function getResolverInstance () {
768 return $this->resolverInstance;
772 * Setter for language instance
774 * @param $configInstance The configuration instance which shall
775 * be FrameworkConfiguration
778 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
779 Registry::getRegistry()->addInstance('config', $configInstance);
783 * Getter for configuration instance
785 * @return $configInstance Configuration instance
787 public final function getConfigInstance () {
788 $configInstance = Registry::getRegistry()->getInstance('config');
789 return $configInstance;
793 * Setter for debug instance
795 * @param $debugInstance The instance for debug output class
798 public final function setDebugInstance (DebugMiddleware $debugInstance) {
799 Registry::getRegistry()->addInstance('debug', $debugInstance);
803 * Getter for debug instance
805 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
807 public final function getDebugInstance () {
808 // Get debug instance
809 $debugInstance = Registry::getRegistry()->getInstance('debug');
812 return $debugInstance;
816 * Setter for web output instance
818 * @param $webInstance The instance for web output class
821 public final function setWebOutputInstance (OutputStreamer $webInstance) {
822 Registry::getRegistry()->addInstance('web_output', $webInstance);
826 * Getter for web output instance
828 * @return $webOutputInstance - Instance to class WebOutput
830 public final function getWebOutputInstance () {
831 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
832 return $webOutputInstance;
836 * Setter for database instance
838 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
841 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
842 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
846 * Getter for database layer
848 * @return $databaseInstance The database layer instance
850 public final function getDatabaseInstance () {
852 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
855 return $databaseInstance;
859 * Setter for compressor channel
861 * @param $compressorInstance An instance of CompressorChannel
864 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
865 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
869 * Getter for compressor channel
871 * @return $compressorInstance The compressor channel
873 public final function getCompressorChannel () {
874 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
875 return $compressorInstance;
879 * Protected getter for a manageable application helper class
881 * @return $applicationInstance An instance of a manageable application helper class
883 protected final function getApplicationInstance () {
884 $applicationInstance = Registry::getRegistry()->getInstance('app');
885 return $applicationInstance;
889 * Setter for a manageable application helper class
891 * @param $applicationInstance An instance of a manageable application helper class
894 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
895 Registry::getRegistry()->addInstance('application', $applicationInstance);
899 * Private getter for language instance
901 * @return $langInstance An instance to the language sub-system
903 protected final function getLanguageInstance () {
904 $langInstance = Registry::getRegistry()->getInstance('language');
905 return $langInstance;
909 * Setter for language instance
911 * @param $langInstance An instance to the language sub-system
913 * @see LanguageSystem
915 public final function setLanguageInstance (ManageableLanguage $langInstance) {
916 Registry::getRegistry()->addInstance('language', $langInstance);
920 * Private getter for file IO instance
922 * @return $fileIoInstance An instance to the file I/O sub-system
924 protected final function getFileIoInstance () {
925 return $this->fileIoInstance;
929 * Setter for file I/O instance
931 * @param $fileIoInstance An instance to the file I/O sub-system
934 public final function setFileIoInstance (IoHandler $fileIoInstance) {
935 $this->fileIoInstance = $fileIoInstance;
939 * Protected setter for user instance
941 * @param $userInstance An instance of a user class
944 protected final function setUserInstance (ManageableAccount $userInstance) {
945 $this->userInstance = $userInstance;
949 * Getter for user instance
951 * @return $userInstance An instance of a user class
953 public final function getUserInstance () {
954 return $this->userInstance;
958 * Setter for controller instance (this surely breaks a bit the MVC patterm)
960 * @param $controllerInstance An instance of the controller
963 public final function setControllerInstance (Controller $controllerInstance) {
964 $this->controllerInstance = $controllerInstance;
968 * Getter for controller instance (this surely breaks a bit the MVC patterm)
970 * @return $controllerInstance An instance of the controller
972 public final function getControllerInstance () {
973 return $this->controllerInstance;
977 * Setter for RNG instance
979 * @param $rngInstance An instance of a random number generator (RNG)
982 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
983 $this->rngInstance = $rngInstance;
987 * Getter for RNG instance
989 * @return $rngInstance An instance of a random number generator (RNG)
991 public final function getRngInstance () {
992 return $this->rngInstance;
996 * Setter for Cryptable instance
998 * @param $cryptoInstance An instance of a Cryptable class
1001 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1002 $this->cryptoInstance = $cryptoInstance;
1006 * Getter for Cryptable instance
1008 * @return $cryptoInstance An instance of a Cryptable class
1010 public final function getCryptoInstance () {
1011 return $this->cryptoInstance;
1015 * Setter for the list instance
1017 * @param $listInstance A list of Listable
1020 protected final function setListInstance (Listable $listInstance) {
1021 $this->listInstance = $listInstance;
1025 * Getter for the list instance
1027 * @return $listInstance A list of Listable
1029 protected final function getListInstance () {
1030 return $this->listInstance;
1034 * Setter for the menu instance
1036 * @param $menuInstance A RenderableMenu instance
1039 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1040 $this->menuInstance = $menuInstance;
1044 * Getter for the menu instance
1046 * @return $menuInstance A RenderableMenu instance
1048 protected final function getMenuInstance () {
1049 return $this->menuInstance;
1053 * Setter for image instance
1055 * @param $imageInstance An instance of an image
1058 public final function setImageInstance (BaseImage $imageInstance) {
1059 $this->imageInstance = $imageInstance;
1063 * Getter for image instance
1065 * @return $imageInstance An instance of an image
1067 public final function getImageInstance () {
1068 return $this->imageInstance;
1072 * Setter for stacker instance
1074 * @param $stackInstance An instance of an stacker
1077 public final function setStackInstance (Stackable $stackInstance) {
1078 $this->stackInstance = $stackInstance;
1082 * Getter for stacker instance
1084 * @return $stackInstance An instance of an stacker
1086 public final function getStackInstance () {
1087 return $this->stackInstance;
1091 * Setter for compressor instance
1093 * @param $compressorInstance An instance of an compressor
1096 public final function setCompressorInstance (Compressor $compressorInstance) {
1097 $this->compressorInstance = $compressorInstance;
1101 * Getter for compressor instance
1103 * @return $compressorInstance An instance of an compressor
1105 public final function getCompressorInstance () {
1106 return $this->compressorInstance;
1110 * Setter for Parseable instance
1112 * @param $parserInstance An instance of an Parseable
1115 public final function setParserInstance (Parseable $parserInstance) {
1116 $this->parserInstance = $parserInstance;
1120 * Getter for Parseable instance
1122 * @return $parserInstance An instance of an Parseable
1124 public final function getParserInstance () {
1125 return $this->parserInstance;
1129 * Setter for DatabaseWrapper instance
1131 * @param $wrapperInstance An instance of an DatabaseWrapper
1134 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1135 $this->wrapperInstance = $wrapperInstance;
1139 * Getter for DatabaseWrapper instance
1141 * @return $wrapperInstance An instance of an DatabaseWrapper
1143 public final function getWrapperInstance () {
1144 return $this->wrapperInstance;
1148 * Setter for socket resource
1150 * @param $socketResource A valid socket resource
1153 public final function setSocketResource ($socketResource) {
1154 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1155 $this->socketResource = $socketResource;
1159 * Getter for socket resource
1161 * @return $socketResource A valid socket resource
1163 public final function getSocketResource () {
1164 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1165 return $this->socketResource;
1169 * Setter for regular expression
1171 * @param $regularExpression A valid regular expression
1174 public final function setRegularExpression ($regularExpression) {
1175 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1176 $this->regularExpression = $regularExpression;
1180 * Getter for regular expression
1182 * @return $regularExpression A valid regular expression
1184 public final function getRegularExpression () {
1185 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1186 return $this->regularExpression;
1190 * Setter for helper instance
1192 * @param $helperInstance An instance of a helper class
1195 protected final function setHelperInstance (Helper $helperInstance) {
1196 $this->helperInstance = $helperInstance;
1200 * Getter for helper instance
1202 * @return $helperInstance An instance of a helper class
1204 public final function getHelperInstance () {
1205 return $this->helperInstance;
1209 * Setter for a Source instance
1211 * @param $sourceInstance An instance of a Source class
1214 protected final function setSourceInstance (Source $sourceInstance) {
1215 $this->sourceInstance = $sourceInstance;
1219 * Getter for a Source instance
1221 * @return $sourceInstance An instance of a Source class
1223 protected final function getSourceInstance () {
1224 return $this->sourceInstance;
1228 * Setter for a UrlSource instance
1230 * @param $sourceInstance An instance of a UrlSource class
1233 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1234 $this->urlSourceInstance = $urlSourceInstance;
1238 * Getter for a UrlSource instance
1240 * @return $urlSourceInstance An instance of a UrlSource class
1242 protected final function getUrlSourceInstance () {
1243 return $this->urlSourceInstance;
1247 * Getter for a InputStream instance
1249 * @param $inputStreamInstance The InputStream instance
1251 protected final function getInputStreamInstance () {
1252 return $this->inputStreamInstance;
1256 * Setter for a InputStream instance
1258 * @param $inputStreamInstance The InputStream instance
1261 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1262 $this->inputStreamInstance = $inputStreamInstance;
1266 * Getter for a OutputStream instance
1268 * @param $outputStreamInstance The OutputStream instance
1270 protected final function getOutputStreamInstance () {
1271 return $this->outputStreamInstance;
1275 * Setter for a OutputStream instance
1277 * @param $outputStreamInstance The OutputStream instance
1280 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1281 $this->outputStreamInstance = $outputStreamInstance;
1285 * Setter for handler instance
1287 * @param $handlerInstance An instance of a Handleable class
1290 protected final function setHandlerInstance (Handleable $handlerInstance) {
1291 $this->handlerInstance = $handlerInstance;
1295 * Getter for handler instance
1297 * @return $handlerInstance A Handleable instance
1299 protected final function getHandlerInstance () {
1300 return $this->handlerInstance;
1304 * Setter for visitor instance
1306 * @param $visitorInstance A Visitor instance
1309 protected final function setVisitorInstance (Visitor $visitorInstance) {
1310 $this->visitorInstance = $visitorInstance;
1314 * Getter for visitor instance
1316 * @return $visitorInstance A Visitor instance
1318 protected final function getVisitorInstance () {
1319 return $this->visitorInstance;
1323 * Setter for raw package Data
1325 * @param $packageData Raw package Data
1328 public final function setPackageData (array $packageData) {
1329 $this->packageData = $packageData;
1333 * Getter for raw package Data
1335 * @return $packageData Raw package Data
1337 public function getPackageData () {
1338 return $this->packageData;
1343 * Setter for Iterator instance
1345 * @param $iteratorInstance An instance of an Iterator
1348 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1349 $this->iteratorInstance = $iteratorInstance;
1353 * Getter for Iterator instance
1355 * @return $iteratorInstance An instance of an Iterator
1357 public final function getIteratorInstance () {
1358 return $this->iteratorInstance;
1362 * Setter for FilePointer instance
1364 * @param $pointerInstance An instance of an FilePointer class
1367 protected final function setPointerInstance (FilePointer $pointerInstance) {
1368 $this->pointerInstance = $pointerInstance;
1372 * Getter for FilePointer instance
1374 * @return $pointerInstance An instance of an FilePointer class
1376 public final function getPointerInstance () {
1377 return $this->pointerInstance;
1381 * Unsets pointer instance which triggers a call of __destruct() if the
1382 * instance is still there. This is surely not fatal on already "closed"
1383 * file pointer instances.
1385 * I don't want to mess around with above setter by giving it a default
1386 * value NULL as setter should always explicitly only set (existing) object
1387 * instances and NULL is NULL.
1391 protected final function unsetPointerInstance () {
1392 // Simply it to NULL
1393 $this->pointerInstance = NULL;
1397 * Setter for Indexable instance
1399 * @param $indexInstance An instance of an Indexable class
1402 protected final function setIndexInstance (Indexable $indexInstance) {
1403 $this->indexInstance = $indexInstance;
1407 * Getter for Indexable instance
1409 * @return $indexInstance An instance of an Indexable class
1411 public final function getIndexInstance () {
1412 return $this->indexInstance;
1416 * Setter for Block instance
1418 * @param $blockInstance An instance of an Block class
1421 protected final function setBlockInstance (Block $blockInstance) {
1422 $this->blockInstance = $blockInstance;
1426 * Getter for Block instance
1428 * @return $blockInstance An instance of an Block class
1430 public final function getBlockInstance () {
1431 return $this->blockInstance;
1435 * Setter for Minable instance
1437 * @param $minableInstance A Minable instance
1440 protected final function setMinableInstance (Minable $minableInstance) {
1441 $this->minableInstance = $minableInstance;
1445 * Getter for minable instance
1447 * @return $minableInstance A Minable instance
1449 protected final function getMinableInstance () {
1450 return $this->minableInstance;
1454 * Setter for FrameworkDirectory instance
1456 * @param $directoryInstance A FrameworkDirectory instance
1459 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1460 $this->directoryInstance = $directoryInstance;
1464 * Getter for FrameworkDirectory instance
1466 * @return $directoryInstance A FrameworkDirectory instance
1468 protected final function getDirectoryInstance () {
1469 return $this->directoryInstance;
1473 * Getter for communicator instance
1475 * @return $communicatorInstance An instance of a Communicator class
1477 public final function getCommunicatorInstance () {
1478 return $this->communicatorInstance;
1482 * Setter for communicator instance
1484 * @param $communicatorInstance An instance of a Communicator class
1487 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1488 $this->communicatorInstance = $communicatorInstance;
1492 * Setter for state instance
1494 * @param $stateInstance A Stateable instance
1497 public final function setStateInstance (Stateable $stateInstance) {
1498 $this->stateInstance = $stateInstance;
1502 * Getter for state instance
1504 * @return $stateInstance A Stateable instance
1506 public final function getStateInstance () {
1507 return $this->stateInstance;
1511 * Setter for output instance
1513 * @param $outputInstance The debug output instance
1516 public final function setOutputInstance (OutputStreamer $outputInstance) {
1517 $this->outputInstance = $outputInstance;
1521 * Getter for output instance
1523 * @return $outputInstance The debug output instance
1525 public final function getOutputInstance () {
1526 return $this->outputInstance;
1530 * Setter for command name
1532 * @param $commandName Last validated command name
1535 protected final function setCommandName ($commandName) {
1536 $this->commandName = $commandName;
1540 * Getter for command name
1542 * @return $commandName Last validated command name
1544 protected final function getCommandName () {
1545 return $this->commandName;
1549 * Setter for controller name
1551 * @param $controllerName Last validated controller name
1554 protected final function setControllerName ($controllerName) {
1555 $this->controllerName = $controllerName;
1559 * Getter for controller name
1561 * @return $controllerName Last validated controller name
1563 protected final function getControllerName () {
1564 return $this->controllerName;
1568 * Checks whether an object equals this object. You should overwrite this
1569 * method to implement own equality checks
1571 * @param $objectInstance An instance of a FrameworkInterface object
1572 * @return $equals Whether both objects equals
1574 public function equals (FrameworkInterface $objectInstance) {
1577 $this->__toString() == $objectInstance->__toString()
1579 $this->hashCode() == $objectInstance->hashCode()
1582 // Return the result
1587 * Generates a generic hash code of this class. You should really overwrite
1588 * this method with your own hash code generator code. But keep KISS in mind.
1590 * @return $hashCode A generic hash code respresenting this whole class
1592 public function hashCode () {
1594 return crc32($this->__toString());
1598 * Formats computer generated price values into human-understandable formats
1599 * with thousand and decimal separators.
1601 * @param $value The in computer format value for a price
1602 * @param $currency The currency symbol (use HTML-valid characters!)
1603 * @param $decNum Number of decimals after commata
1604 * @return $price The for the current language formated price string
1605 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1606 * thousands separator
1609 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1610 // Are all required attriutes set?
1611 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1612 // Throw an exception
1613 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1617 $value = (float) $value;
1619 // Reformat the US number
1620 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1622 // Return as string...
1627 * Appends a trailing slash to a string
1629 * @param $str A string (maybe) without trailing slash
1630 * @return $str A string with an auto-appended trailing slash
1632 public final function addMissingTrailingSlash ($str) {
1633 // Is there a trailing slash?
1634 if (substr($str, -1, 1) != '/') {
1638 // Return string with trailing slash
1643 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1644 * application helper instance (ApplicationHelper by default).
1646 * @param $applicationInstance An application helper instance or
1647 * null if we shall use the default
1648 * @return $templateInstance The template engine instance
1649 * @throws NullPointerException If the discovered application
1650 * instance is still null
1652 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1653 // Is the application instance set?
1654 if (is_null($applicationInstance)) {
1655 // Get the current instance
1656 $applicationInstance = Registry::getRegistry()->getInstance('app');
1659 if (is_null($applicationInstance)) {
1660 // Thrown an exception
1661 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1665 // Initialize the template engine
1666 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1668 // Return the prepared instance
1669 return $templateInstance;
1673 * Debugs this instance by putting out it's full content
1675 * @param $message Optional message to show in debug output
1678 public final function debugInstance ($message = '') {
1679 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1680 restore_error_handler();
1685 // Is a message set?
1686 if (!empty($message)) {
1687 // Construct message
1688 $content = sprintf('<div class="debug_message">
1690 </div>' . PHP_EOL, $message);
1693 // Generate the output
1694 $content .= sprintf('<pre>%s</pre>',
1697 print_r($this, true)
1703 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">
1706 <div class="debug_content">
1710 <div class="debug_include_list">
1713 $this->__toString(),
1715 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1720 * Replaces control characters with printable output
1722 * @param $str String with control characters
1723 * @return $str Replaced string
1725 protected function replaceControlCharacters ($str) {
1728 chr(13), '[r]', str_replace(
1729 chr(10), '[n]', str_replace(
1739 * Output a partial stub message for the caller method
1741 * @param $message An optional message to display
1744 protected function partialStub ($message = '') {
1745 // Get the backtrace
1746 $backtrace = debug_backtrace();
1748 // Generate the class::method string
1749 $methodName = 'UnknownClass->unknownMethod';
1750 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1751 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1754 // Construct the full message
1755 $stubMessage = sprintf('[%s]: Partial stub!',
1759 // Is the extra message given?
1760 if (!empty($message)) {
1761 // Then add it as well
1762 $stubMessage .= ' Message: ' . $message;
1765 // Debug instance is there?
1766 if (!is_null($this->getDebugInstance())) {
1767 // Output stub message
1768 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1771 trigger_error($stubMessage);
1777 * Outputs a debug backtrace and stops further script execution
1779 * @param $message An optional message to output
1780 * @param $doExit Whether exit the program (true is default)
1783 public function debugBackTrace ($message = '', $doExit = true) {
1784 // Sorry, there is no other way getting this nice backtrace
1785 if (!empty($message)) {
1787 printf('Message: %s<br />' . PHP_EOL, $message);
1791 debug_print_backtrace();
1795 if ($doExit === true) {
1801 * Creates an instance of a debugger instance
1803 * @param $className Name of the class (currently unsupported)
1804 * @param $lineNumber Line number where the call was made
1805 * @return $debugInstance An instance of a debugger class
1806 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1808 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1809 // Is the instance set?
1810 if (!Registry::getRegistry()->instanceExists('debug')) {
1811 // Init debug instance
1812 $debugInstance = NULL;
1816 // Get a debugger instance
1817 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1818 } catch (NullPointerException $e) {
1819 // Didn't work, no instance there
1820 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1823 // Empty string should be ignored and used for testing the middleware
1824 DebugMiddleware::getSelfInstance()->output('');
1826 // Set it in its own class. This will set it in the registry
1827 $debugInstance->setDebugInstance($debugInstance);
1829 // Get instance from registry
1830 $debugInstance = Registry::getRegistry()->getDebugInstance();
1834 return $debugInstance;
1838 * Simple output of a message with line-break
1840 * @param $message Message to output
1843 public function outputLine ($message) {
1845 print($message . PHP_EOL);
1849 * Outputs a debug message whether to debug instance (should be set!) or
1850 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1851 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1853 * @param $message Message we shall send out...
1854 * @param $doPrint Whether print or die here (default: print)
1855 * @paran $stripTags Whether to strip tags (default: false)
1858 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1859 // Set debug instance to NULL
1860 $debugInstance = NULL;
1864 // Get debug instance
1865 $debugInstance = $this->getDebugInstance();
1866 } catch (NullPointerException $e) {
1867 // The debug instance is not set (yet)
1870 // Is the debug instance there?
1871 if (is_object($debugInstance)) {
1872 // Use debug output handler
1873 $debugInstance->output($message, $stripTags);
1875 if ($doPrint === false) {
1876 // Die here if not printed
1880 // Are debug times enabled?
1881 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1883 $message = $this->getPrintableExecutionTime() . $message;
1887 if ($doPrint === true) {
1889 $this->outputLine($message);
1898 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1900 * @param $str The string, what ever it is needs to be converted
1901 * @return $className Generated class name
1903 public static final function convertToClassName ($str) {
1907 // Convert all dashes in underscores
1908 $str = self::convertDashesToUnderscores($str);
1910 // Now use that underscores to get classname parts for hungarian style
1911 foreach (explode('_', $str) as $strPart) {
1912 // Make the class name part lower case and first upper case
1913 $className .= ucfirst(strtolower($strPart));
1916 // Return class name
1921 * Converts dashes to underscores, e.g. useable for configuration entries
1923 * @param $str The string with maybe dashes inside
1924 * @return $str The converted string with no dashed, but underscores
1926 public static final function convertDashesToUnderscores ($str) {
1928 $str = str_replace('-', '_', $str);
1930 // Return converted string
1935 * Marks up the code by adding e.g. line numbers
1937 * @param $phpCode Unmarked PHP code
1938 * @return $markedCode Marked PHP code
1940 public function markupCode ($phpCode) {
1945 $errorArray = error_get_last();
1947 // Init the code with error message
1948 if (is_array($errorArray)) {
1950 $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>',
1951 basename($errorArray['file']),
1952 $errorArray['line'],
1953 $errorArray['message'],
1958 // Add line number to the code
1959 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1961 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1963 htmlentities($code, ENT_QUOTES)
1972 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1973 * beatiful for web-based front-ends. If null is given a message id
1974 * null_timestamp will be resolved and returned.
1976 * @param $timestamp Timestamp to prepare (filter) for display
1977 * @return $readable A readable timestamp
1979 public function doFilterFormatTimestamp ($timestamp) {
1980 // Default value to return
1983 // Is the timestamp null?
1984 if (is_null($timestamp)) {
1985 // Get a message string
1986 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1988 switch ($this->getLanguageInstance()->getLanguageCode()) {
1989 case 'de': // German format is a bit different to default
1990 // Split the GMT stamp up
1991 $dateTime = explode(' ', $timestamp );
1992 $dateArray = explode('-', $dateTime[0]);
1993 $timeArray = explode(':', $dateTime[1]);
1995 // Construct the timestamp
1996 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2006 default: // Default is pass-through
2007 $readable = $timestamp;
2017 * Filter a given number into a localized number
2019 * @param $value The raw value from e.g. database
2020 * @return $localized Localized value
2022 public function doFilterFormatNumber ($value) {
2023 // Generate it from config and localize dependencies
2024 switch ($this->getLanguageInstance()->getLanguageCode()) {
2025 case 'de': // German format is a bit different to default
2026 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2029 default: // US, etc.
2030 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2039 * "Getter" for databse entry
2041 * @return $entry An array with database entries
2042 * @throws NullPointerException If the database result is not found
2043 * @throws InvalidDatabaseResultException If the database result is invalid
2045 protected final function getDatabaseEntry () {
2046 // Is there an instance?
2047 if (!$this->getResultInstance() instanceof SearchableResult) {
2048 // Throw an exception here
2049 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2053 $this->getResultInstance()->rewind();
2055 // Do we have an entry?
2056 if ($this->getResultInstance()->valid() === false) {
2057 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2058 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2062 $this->getResultInstance()->next();
2065 $entry = $this->getResultInstance()->current();
2072 * Getter for field name
2074 * @param $fieldName Field name which we shall get
2075 * @return $fieldValue Field value from the user
2076 * @throws NullPointerException If the result instance is null
2078 public final function getField ($fieldName) {
2079 // Default field value
2082 // Get result instance
2083 $resultInstance = $this->getResultInstance();
2085 // Is this instance null?
2086 if (is_null($resultInstance)) {
2087 // Then the user instance is no longer valid (expired cookies?)
2088 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2091 // Get current array
2092 $fieldArray = $resultInstance->current();
2093 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2095 // Convert dashes to underscore
2096 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2098 // Does the field exist?
2099 if ($this->isFieldSet($fieldName)) {
2101 $fieldValue = $fieldArray[$fieldName2];
2102 } elseif (defined('DEVELOPER')) {
2103 // Missing field entry, may require debugging
2104 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2106 // Missing field entry, may require debugging
2107 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2115 * Checks if given field is set
2117 * @param $fieldName Field name to check
2118 * @return $isSet Whether the given field name is set
2119 * @throws NullPointerException If the result instance is null
2121 public function isFieldSet ($fieldName) {
2122 // Get result instance
2123 $resultInstance = $this->getResultInstance();
2125 // Is this instance null?
2126 if (is_null($resultInstance)) {
2127 // Then the user instance is no longer valid (expired cookies?)
2128 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2131 // Get current array
2132 $fieldArray = $resultInstance->current();
2133 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2135 // Convert dashes to underscore
2136 $fieldName = self::convertDashesToUnderscores($fieldName);
2139 $isSet = isset($fieldArray[$fieldName]);
2146 * Flushs all pending updates to the database layer
2150 public function flushPendingUpdates () {
2151 // Get result instance
2152 $resultInstance = $this->getResultInstance();
2154 // Do we have data to update?
2155 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2156 // Get wrapper class name config entry
2157 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2159 // Create object instance
2160 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2162 // Yes, then send the whole result to the database layer
2163 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2168 * Outputs a deprecation warning to the developer.
2170 * @param $message The message we shall output to the developer
2172 * @todo Write a logging mechanism for productive mode
2174 public function deprecationWarning ($message) {
2175 // Is developer mode active?
2176 if (defined('DEVELOPER')) {
2177 // Debug instance is there?
2178 if (!is_null($this->getDebugInstance())) {
2179 // Output stub message
2180 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2183 trigger_error($message . "<br />\n");
2187 // @TODO Finish this part!
2188 $this->partialStub('Developer mode inactive. Message:' . $message);
2193 * Checks whether the given PHP extension is loaded
2195 * @param $phpExtension The PHP extension we shall check
2196 * @return $isLoaded Whether the PHP extension is loaded
2198 public final function isPhpExtensionLoaded ($phpExtension) {
2200 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2207 * "Getter" as a time() replacement but with milliseconds. You should use this
2208 * method instead of the encapsulated getimeofday() function.
2210 * @return $milliTime Timestamp with milliseconds
2212 public function getMilliTime () {
2213 // Get the time of day as float
2214 $milliTime = gettimeofday(true);
2221 * Idles (sleeps) for given milliseconds
2223 * @return $hasSlept Whether it goes fine
2225 public function idle ($milliSeconds) {
2226 // Sleep is fine by default
2229 // Idle so long with found function
2230 if (function_exists('time_sleep_until')) {
2231 // Get current time and add idle time
2232 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2234 // New PHP 5.1.0 function found, ignore errors
2235 $hasSlept = @time_sleep_until($sleepUntil);
2238 * My Sun station doesn't have that function even with latest PHP
2241 usleep($milliSeconds * 1000);
2248 * Converts a hexadecimal string, even with negative sign as first string to
2249 * a decimal number using BC functions.
2251 * This work is based on comment #86673 on php.net documentation page at:
2252 * <http://de.php.net/manual/en/function.dechex.php#86673>
2254 * @param $hex Hexadecimal string
2255 * @return $dec Decimal number
2257 protected function hex2dec ($hex) {
2258 // Convert to all lower-case
2259 $hex = strtolower($hex);
2261 // Detect sign (negative/positive numbers)
2263 if (substr($hex, 0, 1) == '-') {
2265 $hex = substr($hex, 1);
2268 // Decode the hexadecimal string into a decimal number
2270 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2271 $factor = self::$hexdec[substr($hex, $i, 1)];
2272 $dec = bcadd($dec, bcmul($factor, $e));
2275 // Return the decimal number
2276 return $sign . $dec;
2280 * Converts even very large decimal numbers, also signed, to a hexadecimal
2283 * This work is based on comment #97756 on php.net documentation page at:
2284 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2286 * @param $dec Decimal number, even with negative sign
2287 * @param $maxLength Optional maximum length of the string
2288 * @return $hex Hexadecimal string
2290 protected function dec2hex ($dec, $maxLength = 0) {
2291 // maxLength can be zero or devideable by 2
2292 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2294 // Detect sign (negative/positive numbers)
2301 // Encode the decimal number into a hexadecimal string
2304 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2306 } while ($dec >= 1);
2309 * Leading zeros are required for hex-decimal "numbers". In some
2310 * situations more leading zeros are wanted, so check for both
2313 if ($maxLength > 0) {
2314 // Prepend more zeros
2315 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2316 } elseif ((strlen($hex) % 2) != 0) {
2317 // Only make string's length dividable by 2
2321 // Return the hexadecimal string
2322 return $sign . $hex;
2326 * Converts a ASCII string (0 to 255) into a decimal number.
2328 * @param $asc The ASCII string to be converted
2329 * @return $dec Decimal number
2331 protected function asc2dec ($asc) {
2332 // Convert it into a hexadecimal number
2333 $hex = bin2hex($asc);
2335 // And back into a decimal number
2336 $dec = $this->hex2dec($hex);
2343 * Converts a decimal number into an ASCII string.
2345 * @param $dec Decimal number
2346 * @return $asc An ASCII string
2348 protected function dec2asc ($dec) {
2349 // First convert the number into a hexadecimal string
2350 $hex = $this->dec2hex($dec);
2352 // Then convert it into the ASCII string
2353 $asc = $this->hex2asc($hex);
2360 * Converts a hexadecimal number into an ASCII string. Negative numbers
2363 * @param $hex Hexadecimal string
2364 * @return $asc An ASCII string
2366 protected function hex2asc ($hex) {
2367 // Check for length, it must be devideable by 2
2368 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2369 assert((strlen($hex) % 2) == 0);
2373 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2374 // Get the decimal number of the chunk
2375 $part = hexdec(substr($hex, $idx, 2));
2377 // Add it to the final string
2381 // Return the final string
2386 * Checks whether the given encoded data was encoded with Base64
2388 * @param $encodedData Encoded data we shall check
2389 * @return $isBase64 Whether the encoded data is Base64
2391 protected function isBase64Encoded ($encodedData) {
2393 $isBase64 = (@base64_decode($encodedData, true) !== false);
2400 * Gets a cache key from Criteria instance
2402 * @param $criteriaInstance An instance of a Criteria class
2403 * @param $onlyKeys Only use these keys for a cache key
2404 * @return $cacheKey A cache key suitable for lookup/storage purposes
2406 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2408 $cacheKey = sprintf('%s@%s',
2409 $this->__toString(),
2410 $criteriaInstance->getCacheKey($onlyKeys)
2414 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2419 * Getter for startup time in miliseconds
2421 * @return $startupTime Startup time in miliseconds
2423 protected function getStartupTime () {
2424 return self::$startupTime;
2428 * "Getter" for a printable currently execution time in nice braces
2430 * @return $executionTime Current execution time in nice braces
2432 protected function getPrintableExecutionTime () {
2433 // Caculate the execution time
2434 $executionTime = microtime(true) - $this->getStartupTime();
2436 // Pack it in nice braces
2437 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2440 return $executionTime;
2444 * Hashes a given string with a simple but stronger hash function (no salt)
2445 * and hex-encode it.
2447 * @param $str The string to be hashed
2448 * @return $hash The hash from string $str
2450 public static final function hash ($str) {
2451 // Hash given string with (better secure) hasher
2452 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2459 * "Getter" for length of hash() output. This will be "cached" to speed up
2462 * @return $length Length of hash() output
2464 public static final function getHashLength () {
2466 if (is_null(self::$hashLength)) {
2467 // No, then hash a string and save its length.
2468 self::$hashLength = strlen(self::hash('abc123'));
2472 return self::$hashLength;
2476 * Checks whether the given number is really a number (only chars 0-9).
2478 * @param $num A string consisting only chars between 0 and 9
2479 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2480 * @param $assertMismatch Whether to assert mismatches
2481 * @return $ret The (hopefully) secured numbered value
2483 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2484 // Filter all numbers out
2485 $ret = preg_replace('/[^0123456789]/', '', $num);
2488 if ($castValue === true) {
2489 // Cast to biggest numeric type
2490 $ret = (double) $ret;
2493 // Assert only if requested
2494 if ($assertMismatch === true) {
2495 // Has the whole value changed?
2496 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2504 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2506 * @param $num A string consisting only chars between 0 and 9
2507 * @param $assertMismatch Whether to assert mismatches
2508 * @return $ret The (hopefully) secured hext-numbered value
2510 public function hexval ($num, $assertMismatch = false) {
2511 // Filter all numbers out
2512 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2514 // Assert only if requested
2515 if ($assertMismatch === true) {
2516 // Has the whole value changed?
2517 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2525 * Determines if an element is set in the generic array
2527 * @param $keyGroup Main group for the key
2528 * @param $subGroup Sub group for the key
2529 * @param $key Key to check
2530 * @param $element Element to check
2531 * @return $isset Whether the given key is set
2533 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2535 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2538 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2544 * Determines if a key is set in the generic array
2546 * @param $keyGroup Main group for the key
2547 * @param $subGroup Sub group for the key
2548 * @param $key Key to check
2549 * @return $isset Whether the given key is set
2551 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2553 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2556 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2564 * Determines if a group is set in the generic array
2566 * @param $keyGroup Main group
2567 * @param $subGroup Sub group
2568 * @return $isset Whether the given group is set
2570 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2572 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2575 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2582 * Getter for sub key group
2584 * @param $keyGroup Main key group
2585 * @param $subGroup Sub key group
2586 * @return $array An array with all array elements
2588 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2590 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2591 // No, then abort here
2592 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2597 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2600 return $this->genericArray[$keyGroup][$subGroup];
2604 * Unsets a given key in generic array
2606 * @param $keyGroup Main group for the key
2607 * @param $subGroup Sub group for the key
2608 * @param $key Key to unset
2611 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2613 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2616 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2620 * Unsets a given element in generic array
2622 * @param $keyGroup Main group for the key
2623 * @param $subGroup Sub group for the key
2624 * @param $key Key to unset
2625 * @param $element Element to unset
2628 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2630 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2633 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2637 * Append a string to a given generic array key
2639 * @param $keyGroup Main group for the key
2640 * @param $subGroup Sub group for the key
2641 * @param $key Key to unset
2642 * @param $value Value to add/append
2645 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2647 //* 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);
2649 // Is it already there?
2650 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2652 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2655 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2660 * Append a string to a given generic array element
2662 * @param $keyGroup Main group for the key
2663 * @param $subGroup Sub group for the key
2664 * @param $key Key to unset
2665 * @param $element Element to check
2666 * @param $value Value to add/append
2669 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2671 //* 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);
2673 // Is it already there?
2674 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2676 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2679 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2684 * Sets a string in a given generic array element
2686 * @param $keyGroup Main group for the key
2687 * @param $subGroup Sub group for the key
2688 * @param $key Key to unset
2689 * @param $element Element to check
2690 * @param $value Value to add/append
2693 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2695 //* 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);
2698 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2702 * Initializes given generic array group
2704 * @param $keyGroup Main group for the key
2705 * @param $subGroup Sub group for the key
2706 * @param $key Key to use
2707 * @param $forceInit Optionally force initialization
2710 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2712 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2714 // Is it already set?
2715 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2716 // Already initialized
2717 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2722 $this->genericArray[$keyGroup][$subGroup] = array();
2726 * Initializes given generic array key
2728 * @param $keyGroup Main group for the key
2729 * @param $subGroup Sub group for the key
2730 * @param $key Key to use
2731 * @param $forceInit Optionally force initialization
2734 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2736 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2738 // Is it already set?
2739 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2740 // Already initialized
2741 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2746 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2750 * Initializes given generic array element
2752 * @param $keyGroup Main group for the key
2753 * @param $subGroup Sub group for the key
2754 * @param $key Key to use
2755 * @param $element Element to use
2756 * @param $forceInit Optionally force initialization
2759 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2761 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2763 // Is it already set?
2764 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2765 // Already initialized
2766 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2771 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2775 * Pushes an element to a generic key
2777 * @param $keyGroup Main group for the key
2778 * @param $subGroup Sub group for the key
2779 * @param $key Key to use
2780 * @param $value Value to add/append
2781 * @return $count Number of array elements
2783 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2785 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2788 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2790 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2794 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2797 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2798 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2803 * Pushes an element to a generic array element
2805 * @param $keyGroup Main group for the key
2806 * @param $subGroup Sub group for the key
2807 * @param $key Key to use
2808 * @param $element Element to check
2809 * @param $value Value to add/append
2810 * @return $count Number of array elements
2812 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2814 //* 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));
2817 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2819 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2823 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2826 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2827 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2832 * Pops an element from a generic group
2834 * @param $keyGroup Main group for the key
2835 * @param $subGroup Sub group for the key
2836 * @param $key Key to unset
2837 * @return $value Last "popped" value
2839 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2841 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2844 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2846 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2851 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2854 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2855 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2860 * Shifts an element from a generic group
2862 * @param $keyGroup Main group for the key
2863 * @param $subGroup Sub group for the key
2864 * @param $key Key to unset
2865 * @return $value Last "popped" value
2867 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2869 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2872 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2874 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2879 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2882 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2883 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2888 * Count generic array group
2890 * @param $keyGroup Main group for the key
2891 * @return $count Count of given group
2893 protected final function countGenericArray ($keyGroup) {
2895 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2898 if (!isset($this->genericArray[$keyGroup])) {
2900 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2905 $count = count($this->genericArray[$keyGroup]);
2908 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2915 * Count generic array sub group
2917 * @param $keyGroup Main group for the key
2918 * @param $subGroup Sub group for the key
2919 * @return $count Count of given group
2921 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2923 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2926 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2928 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2933 $count = count($this->genericArray[$keyGroup][$subGroup]);
2936 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2943 * Count generic array elements
2945 * @param $keyGroup Main group for the key
2946 * @param $subGroup Sub group for the key
2947 * @para $key Key to count
2948 * @return $count Count of given key
2950 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2952 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2955 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2957 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2959 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2961 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2966 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2969 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2976 * Getter for whole generic group array
2978 * @param $keyGroup Key group to get
2979 * @return $array Whole generic array group
2981 protected final function getGenericArray ($keyGroup) {
2983 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2986 if (!isset($this->genericArray[$keyGroup])) {
2988 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2993 return $this->genericArray[$keyGroup];
2997 * Setter for generic array key
2999 * @param $keyGroup Key group to get
3000 * @param $subGroup Sub group for the key
3001 * @param $key Key to unset
3002 * @param $value Mixed value from generic array element
3005 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3007 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3010 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3014 * Getter for generic array key
3016 * @param $keyGroup Key group to get
3017 * @param $subGroup Sub group for the key
3018 * @param $key Key to unset
3019 * @return $value Mixed value from generic array element
3021 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3023 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3026 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3028 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3033 return $this->genericArray[$keyGroup][$subGroup][$key];
3037 * Sets a value in given generic array key/element
3039 * @param $keyGroup Main group for the key
3040 * @param $subGroup Sub group for the key
3041 * @param $key Key to set
3042 * @param $element Element to set
3043 * @param $value Value to set
3046 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3048 //* 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));
3051 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3055 * Getter for generic array element
3057 * @param $keyGroup Key group to get
3058 * @param $subGroup Sub group for the key
3059 * @param $key Key to look for
3060 * @param $element Element to look for
3061 * @return $value Mixed value from generic array element
3063 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3065 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3068 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3070 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3075 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3079 * Checks if a given sub group is valid (array)
3081 * @param $keyGroup Key group to get
3082 * @param $subGroup Sub group for the key
3083 * @return $isValid Whether given sub group is valid
3085 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3087 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3090 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3097 * Checks if a given key is valid (array)
3099 * @param $keyGroup Key group to get
3100 * @param $subGroup Sub group for the key
3101 * @param $key Key to check
3102 * @return $isValid Whether given sub group is valid
3104 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3106 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3109 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3116 * Initializes the web output instance
3120 protected function initWebOutputInstance () {
3121 // Get application instance
3122 $applicationInstance = Registry::getRegistry()->getInstance('app');
3124 // Init web output instance
3125 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3128 $this->setWebOutputInstance($outputInstance);
3132 * Translates boolean true to 'Y' and false to 'N'
3134 * @param $boolean Boolean value
3135 * @return $translated Translated boolean value
3137 public static final function translateBooleanToYesNo ($boolean) {
3138 // Make sure it is really boolean
3139 assert(is_bool($boolean));
3142 $translated = ($boolean === true) ? 'Y' : 'N';
3144 // ... and return it
3149 * Encodes raw data (almost any type) by "serializing" it and then pack it
3150 * into a "binary format".
3152 * @param $rawData Raw data (almost any type)
3153 * @return $encoded Encoded data
3155 protected function encodeData ($rawData) {
3156 // Make sure no objects or resources pass through
3157 assert(!is_object($rawData));
3158 assert(!is_resource($rawData));
3160 // First "serialize" it (json_encode() is faster than serialize())
3161 $encoded = $this->packString(json_encode($rawData));
3168 * Pack a string into a "binary format". Please execuse me that this is
3169 * widely undocumented. :-(
3171 * @param $str Unpacked string
3172 * @return $packed Packed string
3173 * @todo Improve documentation
3175 protected function packString ($str) {
3177 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3179 // First compress the string (gzcompress is okay)
3180 $str = gzcompress($str);
3185 // And start the "encoding" loop
3186 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3188 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3189 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3191 if (($idx + $i) <= strlen($str)) {
3192 $ord = ord(substr($str, ($idx + $i), 1));
3194 $add = $ord * pow(256, $factor);
3198 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3202 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3203 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3205 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3206 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3212 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3217 * Creates a full-qualified file name (FQFN) for given file name by adding
3218 * a configured temporary file path to it.
3220 * @param $fileName Name for temporary file
3221 * @return $fqfn Full-qualified file name
3222 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3223 * @throws FileIoException If the file cannot be written
3225 protected static function createTempPathForFile ($fileName) {
3227 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3229 // Is the path writeable?
3230 if (!is_writable($basePath)) {
3231 // Path is write-protected
3232 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3236 $fqfn = $basePath . DIRECTORY_SEPARATOR . $fileName;
3239 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3241 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3249 * "Getter" for a printable state name
3251 * @return $stateName Name of the node's state in a printable format
3253 public final function getPrintableState () {
3254 // Default is 'null'
3255 $stateName = 'null';
3257 // Get the state instance
3258 $stateInstance = $this->getStateInstance();
3260 // Is it an instance of Stateable?
3261 if ($stateInstance instanceof Stateable) {
3262 // Then use that state name
3263 $stateName = $stateInstance->getStateName();