3 namespace Org\Mxchange\CoreFramework\Object;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Compressor\Compressor;
8 use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
9 use Org\Mxchange\CoreFramework\Connection\Database\DatabaseConnection;
10 use Org\Mxchange\CoreFramework\Controller\Controller;
11 use Org\Mxchange\CoreFramework\Criteria\Criteria;
12 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use Org\Mxchange\CoreFramework\Crypto\Cryptable;
15 use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
17 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
18 use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
19 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
20 use Org\Mxchange\CoreFramework\Filesystem\Block;
21 use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
22 use Org\Mxchange\CoreFramework\Filesystem\FrameworkDirectory;
23 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
24 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
25 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
26 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
27 use Org\Mxchange\CoreFramework\Handler\Handleable;
28 use Org\Mxchange\CoreFramework\Handler\Stream\IoHandler;
29 use Org\Mxchange\CoreFramework\Helper\Helper;
30 use Org\Mxchange\CoreFramework\Index\Indexable;
31 use Org\Mxchange\CoreFramework\Lists\Listable;
32 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
33 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
34 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
35 use Org\Mxchange\CoreFramework\Menu\RenderableMenu;
36 use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
37 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
38 use Org\Mxchange\CoreFramework\Parser\Parseable;
39 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
40 use Org\Mxchange\CoreFramework\Registry\Register;
41 use Org\Mxchange\CoreFramework\Resolver\Resolver;
42 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
43 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
44 use Org\Mxchange\CoreFramework\Stacker\Stackable;
45 use Org\Mxchange\CoreFramework\State\Stateable;
46 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
47 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
48 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
49 use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
50 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
51 use Org\Mxchange\CoreFramework\User\ManageableAccount;
52 use Org\Mxchange\CoreFramework\Visitor\Visitor;
56 use \InvalidArgumentException;
62 * The simulator system class is the super class of all other classes. This
63 * class handles saving of games etc.
65 * @author Roland Haeder <webmaster@shipsimu.org>
67 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
68 * @license GNU GPL 3.0 or any newer version
69 * @link http://www.shipsimu.org
71 * This program is free software: you can redistribute it and/or modify
72 * it under the terms of the GNU General Public License as published by
73 * the Free Software Foundation, either version 3 of the License, or
74 * (at your option) any later version.
76 * This program is distributed in the hope that it will be useful,
77 * but WITHOUT ANY WARRANTY; without even the implied warranty of
78 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
79 * GNU General Public License for more details.
81 * You should have received a copy of the GNU General Public License
82 * along with this program. If not, see <http://www.gnu.org/licenses/>.
84 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
86 * Length of output from hash()
88 private static $hashLength = NULL;
93 private $realClass = 'BaseFrameworkSystem';
96 * Search criteria instance
98 private $searchInstance = NULL;
101 * Update criteria instance
103 private $updateInstance = NULL;
106 * The file I/O instance for the template loader
108 private $fileIoInstance = NULL;
113 private $resolverInstance = NULL;
116 * Template engine instance
118 private $templateInstance = NULL;
121 * Database result instance
123 private $resultInstance = NULL;
126 * Instance for user class
128 private $userInstance = NULL;
131 * A controller instance
133 private $controllerInstance = NULL;
138 private $rngInstance = NULL;
141 * Instance of a crypto helper
143 private $cryptoInstance = NULL;
146 * Instance of an Iterator class
148 private $iteratorInstance = NULL;
151 * Instance of the list
153 private $listInstance = NULL;
158 private $menuInstance = NULL;
161 * Instance of the image
163 private $imageInstance = NULL;
166 * Instance of the stacker
168 private $stackInstance = NULL;
171 * A Compressor instance
173 private $compressorInstance = NULL;
176 * A Parseable instance
178 private $parserInstance = NULL;
181 * A database wrapper instance
183 private $databaseInstance = NULL;
186 * A helper instance for the form
188 private $helperInstance = NULL;
191 * An instance of a InputStream class
193 private $inputStreamInstance = NULL;
196 * An instance of a OutputStream class
198 private $outputStreamInstance = NULL;
203 private $handlerInstance = NULL;
206 * Visitor handler instance
208 private $visitorInstance = NULL;
211 * An instance of a database wrapper class
213 private $wrapperInstance = NULL;
216 * An instance of a file I/O pointer class (not handler)
218 private $pointerInstance = NULL;
221 * An instance of an Indexable class
223 private $indexInstance = NULL;
226 * An instance of a Block class
228 private $blockInstance = NULL;
233 private $minableInstance = NULL;
236 * A FrameworkDirectory instance
238 private $directoryInstance = NULL;
241 * The concrete output instance
243 private $outputInstance = NULL;
248 private $stateInstance = NULL;
251 * Registry instance (implementing Register)
253 private $registryInstance = NULL;
258 private $callbackInstance = NULL;
261 * Thousands separator
263 private $thousands = '.'; // German
268 private $decimals = ','; // German
273 private $socketResource = false;
276 * Regular expression to use for validation
278 private $regularExpression = '';
283 private $packageData = array();
288 private $genericArray = array();
293 private $commandName = '';
298 private $controllerName = '';
301 * Array with bitmasks and such for pack/unpack methods to support both
302 * 32-bit and 64-bit systems
304 private $packingData = array(
307 'left' => 0xffff0000,
308 'right' => 0x0000ffff,
314 'left' => 0xffffffff00000000,
315 'right' => 0x00000000ffffffff,
322 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
324 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
326 private $archArrayElement = false;
328 /***********************
329 * Exception codes.... *
330 ***********************/
332 // @todo Try to clean these constants up
333 const EXCEPTION_IS_NULL_POINTER = 0x001;
334 const EXCEPTION_IS_NO_OBJECT = 0x002;
335 const EXCEPTION_IS_NO_ARRAY = 0x003;
336 const EXCEPTION_MISSING_METHOD = 0x004;
337 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
338 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
339 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
340 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
341 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
342 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
343 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
344 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
345 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
346 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
347 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
348 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
349 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
350 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
351 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
352 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
353 const EXCEPTION_PATH_NOT_FOUND = 0x015;
354 const EXCEPTION_INVALID_PATH_NAME = 0x016;
355 const EXCEPTION_READ_PROTECED_PATH = 0x017;
356 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
357 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
358 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
359 const EXCEPTION_INVALID_RESOURCE = 0x01b;
360 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
361 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
362 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
363 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
364 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
365 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
366 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
367 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
368 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
369 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
370 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
371 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
372 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
373 const EXCEPTION_INVALID_STRING = 0x029;
374 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
375 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
376 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
377 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
378 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
379 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
380 const EXCEPTION_MISSING_ELEMENT = 0x030;
381 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
382 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
383 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
384 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
385 const EXCEPTION_FATAL_ERROR = 0x035;
386 const EXCEPTION_FILE_NOT_FOUND = 0x036;
387 const EXCEPTION_ASSERTION_FAILED = 0x037;
388 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
389 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
390 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
391 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
392 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
393 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
394 const EXCEPTION_INVALID_SOCKET = 0x03e;
397 * Hexadecimal->Decimal translation array
399 private static $hexdec = array(
419 * Decimal->hexadecimal translation array
421 private static $dechex = array(
441 * Startup time in miliseconds
443 private static $startupTime = 0;
446 * Protected super constructor
448 * @param $className Name of the class
451 protected function __construct ($className) {
453 $this->setRealClass($className);
455 // Set configuration instance if no registry ...
456 if (!$this instanceof Register) {
457 // ... because registries doesn't need to be configured
458 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
461 // Is the startup time set? (0 cannot be true anymore)
462 if (self::$startupTime == 0) {
464 self::$startupTime = microtime(true);
468 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
472 * Destructor for all classes. You should not call this method on your own.
476 public function __destruct () {
477 // Flush any updated entries to the database
478 $this->flushPendingUpdates();
480 // Is this object already destroyed?
481 if ($this->__toString() != 'DestructedObject') {
482 // Destroy all informations about this class but keep some text about it alive
483 $this->setRealClass('DestructedObject');
484 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
485 // Already destructed object
486 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
490 // Do not call this twice
491 trigger_error(__METHOD__ . ': Called twice.');
497 * The __call() method where all non-implemented methods end up
499 * @param $methodName Name of the missing method
500 * @args $args Arguments passed to the method
503 public final function __call ($methodName, $args) {
504 return self::__callStatic($methodName, $args);
508 * The __callStatic() method where all non-implemented static methods end up
510 * @param $methodName Name of the missing method
511 * @args $args Arguments passed to the method
514 public static final function __callStatic ($methodName, $args) {
516 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
518 // Init argument string
521 // Is it NULL, empty or an array?
522 if (is_null($args)) {
524 $argsString = 'NULL';
525 } elseif (is_array($args)) {
529 // Some arguments are there
530 foreach ($args as $arg) {
531 // Add data about the argument
532 $argsString .= gettype($arg) . ':';
535 // Found a NULL argument
536 $argsString .= 'NULL';
537 } elseif (is_string($arg)) {
538 // Add length for strings
539 $argsString .= strlen($arg);
540 } elseif ((is_int($arg)) || (is_float($arg))) {
543 } elseif (is_array($arg)) {
544 // .. or size if array
545 $argsString .= count($arg);
546 } elseif (is_object($arg)) {
548 $reflection = new ReflectionClass($arg);
550 // Is an other object, maybe no __toString() available
551 $argsString .= $reflection->getName();
552 } elseif ($arg === true) {
553 // ... is boolean 'true'
554 $argsString .= 'true';
555 } elseif ($arg === false) {
556 // ... is boolean 'false'
557 $argsString .= 'false';
560 // Comma for next one
565 if (substr($argsString, -2, 1) == ',') {
566 $argsString = substr($argsString, 0, -2);
572 // Invalid arguments!
573 $argsString = '!INVALID:' . gettype($args) . '!';
576 // Output stub message
577 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
578 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
588 * Getter for $realClass
590 * @return $realClass The name of the real class (not BaseFrameworkSystem)
592 public function __toString () {
593 return $this->realClass;
597 * Magic method to catch setting of missing but set class fields/attributes
599 * @param $name Name of the field/attribute
600 * @param $value Value to store
603 public final function __set ($name, $value) {
604 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
607 print_r($value, true)
612 * Magic method to catch getting of missing fields/attributes
614 * @param $name Name of the field/attribute
617 public final function __get ($name) {
618 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
624 * Magic method to catch unsetting of missing fields/attributes
626 * @param $name Name of the field/attribute
629 public final function __unset ($name) {
630 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
636 * Magic method to catch object serialization
638 * @return $unsupported Unsupported method
639 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
641 public final function __sleep () {
642 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
646 * Magic method to catch object deserialization
648 * @return $unsupported Unsupported method
649 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
651 public final function __wakeup () {
652 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
656 * Magic method to catch calls when an object instance is called
658 * @return $unsupported Unsupported method
659 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
661 public final function __invoke () {
662 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
666 * Setter for the real class name
668 * @param $realClass Class name (string)
671 public final function setRealClass ($realClass) {
673 $this->realClass = (string) $realClass;
677 * Setter for database result instance
679 * @param $resultInstance An instance of a database result class
681 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
683 protected final function setResultInstance (SearchableResult $resultInstance) {
684 $this->resultInstance = $resultInstance;
688 * Getter for database result instance
690 * @return $resultInstance An instance of a database result class
692 public final function getResultInstance () {
693 return $this->resultInstance;
697 * Setter for template engine instances
699 * @param $templateInstance An instance of a template engine class
702 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
703 $this->templateInstance = $templateInstance;
707 * Getter for template engine instances
709 * @return $templateInstance An instance of a template engine class
711 protected final function getTemplateInstance () {
712 return $this->templateInstance;
716 * Setter for search instance
718 * @param $searchInstance Searchable criteria instance
721 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
722 $this->searchInstance = $searchInstance;
726 * Getter for search instance
728 * @return $searchInstance Searchable criteria instance
730 public final function getSearchInstance () {
731 return $this->searchInstance;
735 * Setter for update instance
737 * @param $updateInstance An instance of a LocalUpdateCriteria clase
740 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
741 $this->updateInstance = $updateInstance;
745 * Getter for update instance
747 * @return $updateInstance Updateable criteria instance
749 public final function getUpdateInstance () {
750 return $this->updateInstance;
754 * Setter for resolver instance
756 * @param $resolverInstance Instance of a command resolver class
759 public final function setResolverInstance (Resolver $resolverInstance) {
760 $this->resolverInstance = $resolverInstance;
764 * Getter for resolver instance
766 * @return $resolverInstance Instance of a command resolver class
768 public final function getResolverInstance () {
769 return $this->resolverInstance;
773 * Setter for language instance
775 * @param $configInstance The configuration instance which shall
776 * be FrameworkConfiguration
779 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
780 GenericRegistry::getRegistry()->addInstance('config', $configInstance);
784 * Getter for configuration instance
786 * @return $configInstance Configuration instance
788 public final function getConfigInstance () {
789 $configInstance = GenericRegistry::getRegistry()->getInstance('config');
790 return $configInstance;
794 * Setter for debug instance
796 * @param $debugInstance The instance for debug output class
799 public final function setDebugInstance (DebugMiddleware $debugInstance) {
800 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
804 * Getter for debug instance
806 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
808 public final function getDebugInstance () {
809 // Get debug instance
810 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
813 return $debugInstance;
817 * Setter for web output instance
819 * @param $webInstance The instance for web output class
822 public final function setWebOutputInstance (OutputStreamer $webInstance) {
823 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
827 * Getter for web output instance
829 * @return $webOutputInstance - Instance to class WebOutput
831 public final function getWebOutputInstance () {
832 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
833 return $webOutputInstance;
837 * Setter for database instance
839 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
842 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
843 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
847 * Getter for database layer
849 * @return $databaseInstance The database layer instance
851 public final function getDatabaseInstance () {
853 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
856 return $databaseInstance;
860 * Setter for compressor channel
862 * @param $compressorInstance An instance of CompressorChannel
865 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
866 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
870 * Getter for compressor channel
872 * @return $compressorInstance The compressor channel
874 public final function getCompressorChannel () {
875 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
876 return $compressorInstance;
880 * Private getter for language instance
882 * @return $langInstance An instance to the language sub-system
884 protected final function getLanguageInstance () {
885 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
886 return $langInstance;
890 * Setter for language instance
892 * @param $langInstance An instance to the language sub-system
894 * @see LanguageSystem
896 public final function setLanguageInstance (ManageableLanguage $langInstance) {
897 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
901 * Private getter for file IO instance
903 * @return $fileIoInstance An instance to the file I/O sub-system
905 protected final function getFileIoInstance () {
906 return $this->fileIoInstance;
910 * Setter for file I/O instance
912 * @param $fileIoInstance An instance to the file I/O sub-system
915 public final function setFileIoInstance (IoHandler $fileIoInstance) {
916 $this->fileIoInstance = $fileIoInstance;
920 * Protected setter for user instance
922 * @param $userInstance An instance of a user class
925 protected final function setUserInstance (ManageableAccount $userInstance) {
926 $this->userInstance = $userInstance;
930 * Getter for user instance
932 * @return $userInstance An instance of a user class
934 public final function getUserInstance () {
935 return $this->userInstance;
939 * Setter for controller instance (this surely breaks a bit the MVC patterm)
941 * @param $controllerInstance An instance of the controller
944 public final function setControllerInstance (Controller $controllerInstance) {
945 $this->controllerInstance = $controllerInstance;
949 * Getter for controller instance (this surely breaks a bit the MVC patterm)
951 * @return $controllerInstance An instance of the controller
953 public final function getControllerInstance () {
954 return $this->controllerInstance;
958 * Setter for RNG instance
960 * @param $rngInstance An instance of a random number generator (RNG)
963 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
964 $this->rngInstance = $rngInstance;
968 * Getter for RNG instance
970 * @return $rngInstance An instance of a random number generator (RNG)
972 public final function getRngInstance () {
973 return $this->rngInstance;
977 * Setter for Cryptable instance
979 * @param $cryptoInstance An instance of a Cryptable class
982 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
983 $this->cryptoInstance = $cryptoInstance;
987 * Getter for Cryptable instance
989 * @return $cryptoInstance An instance of a Cryptable class
991 public final function getCryptoInstance () {
992 return $this->cryptoInstance;
996 * Setter for the list instance
998 * @param $listInstance A list of Listable
1001 protected final function setListInstance (Listable $listInstance) {
1002 $this->listInstance = $listInstance;
1006 * Getter for the list instance
1008 * @return $listInstance A list of Listable
1010 protected final function getListInstance () {
1011 return $this->listInstance;
1015 * Setter for the menu instance
1017 * @param $menuInstance A RenderableMenu instance
1020 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1021 $this->menuInstance = $menuInstance;
1025 * Getter for the menu instance
1027 * @return $menuInstance A RenderableMenu instance
1029 protected final function getMenuInstance () {
1030 return $this->menuInstance;
1034 * Setter for image instance
1036 * @param $imageInstance An instance of an image
1039 public final function setImageInstance (BaseImage $imageInstance) {
1040 $this->imageInstance = $imageInstance;
1044 * Getter for image instance
1046 * @return $imageInstance An instance of an image
1048 public final function getImageInstance () {
1049 return $this->imageInstance;
1053 * Setter for stacker instance
1055 * @param $stackInstance An instance of an stacker
1058 public final function setStackInstance (Stackable $stackInstance) {
1059 $this->stackInstance = $stackInstance;
1063 * Getter for stacker instance
1065 * @return $stackInstance An instance of an stacker
1067 public final function getStackInstance () {
1068 return $this->stackInstance;
1072 * Setter for compressor instance
1074 * @param $compressorInstance An instance of an compressor
1077 public final function setCompressorInstance (Compressor $compressorInstance) {
1078 $this->compressorInstance = $compressorInstance;
1082 * Getter for compressor instance
1084 * @return $compressorInstance An instance of an compressor
1086 public final function getCompressorInstance () {
1087 return $this->compressorInstance;
1091 * Setter for Parseable instance
1093 * @param $parserInstance An instance of an Parseable
1096 public final function setParserInstance (Parseable $parserInstance) {
1097 $this->parserInstance = $parserInstance;
1101 * Getter for Parseable instance
1103 * @return $parserInstance An instance of an Parseable
1105 public final function getParserInstance () {
1106 return $this->parserInstance;
1110 * Setter for DatabaseWrapper instance
1112 * @param $wrapperInstance An instance of an DatabaseWrapper
1115 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1116 $this->wrapperInstance = $wrapperInstance;
1120 * Getter for DatabaseWrapper instance
1122 * @return $wrapperInstance An instance of an DatabaseWrapper
1124 public final function getWrapperInstance () {
1125 return $this->wrapperInstance;
1129 * Setter for socket resource
1131 * @param $socketResource A valid socket resource
1134 public final function setSocketResource ($socketResource) {
1135 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1136 $this->socketResource = $socketResource;
1140 * Getter for socket resource
1142 * @return $socketResource A valid socket resource
1144 public final function getSocketResource () {
1145 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1146 return $this->socketResource;
1150 * Setter for regular expression
1152 * @param $regularExpression A valid regular expression
1155 public final function setRegularExpression ($regularExpression) {
1156 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1157 $this->regularExpression = $regularExpression;
1161 * Getter for regular expression
1163 * @return $regularExpression A valid regular expression
1165 public final function getRegularExpression () {
1166 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1167 return $this->regularExpression;
1171 * Setter for helper instance
1173 * @param $helperInstance An instance of a helper class
1176 protected final function setHelperInstance (Helper $helperInstance) {
1177 $this->helperInstance = $helperInstance;
1181 * Getter for helper instance
1183 * @return $helperInstance An instance of a helper class
1185 public final function getHelperInstance () {
1186 return $this->helperInstance;
1190 * Getter for a InputStream instance
1192 * @param $inputStreamInstance The InputStream instance
1194 protected final function getInputStreamInstance () {
1195 return $this->inputStreamInstance;
1199 * Setter for a InputStream instance
1201 * @param $inputStreamInstance The InputStream instance
1204 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1205 $this->inputStreamInstance = $inputStreamInstance;
1209 * Getter for a OutputStream instance
1211 * @param $outputStreamInstance The OutputStream instance
1213 protected final function getOutputStreamInstance () {
1214 return $this->outputStreamInstance;
1218 * Setter for a OutputStream instance
1220 * @param $outputStreamInstance The OutputStream instance
1223 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1224 $this->outputStreamInstance = $outputStreamInstance;
1228 * Setter for handler instance
1230 * @param $handlerInstance An instance of a Handleable class
1233 protected final function setHandlerInstance (Handleable $handlerInstance) {
1234 $this->handlerInstance = $handlerInstance;
1238 * Getter for handler instance
1240 * @return $handlerInstance A Handleable instance
1242 protected final function getHandlerInstance () {
1243 return $this->handlerInstance;
1247 * Setter for visitor instance
1249 * @param $visitorInstance A Visitor instance
1252 protected final function setVisitorInstance (Visitor $visitorInstance) {
1253 $this->visitorInstance = $visitorInstance;
1257 * Getter for visitor instance
1259 * @return $visitorInstance A Visitor instance
1261 protected final function getVisitorInstance () {
1262 return $this->visitorInstance;
1266 * Setter for raw package Data
1268 * @param $packageData Raw package Data
1271 public final function setPackageData (array $packageData) {
1272 $this->packageData = $packageData;
1276 * Getter for raw package Data
1278 * @return $packageData Raw package Data
1280 public function getPackageData () {
1281 return $this->packageData;
1286 * Setter for Iterator instance
1288 * @param $iteratorInstance An instance of an Iterator
1291 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1292 $this->iteratorInstance = $iteratorInstance;
1296 * Getter for Iterator instance
1298 * @return $iteratorInstance An instance of an Iterator
1300 public final function getIteratorInstance () {
1301 return $this->iteratorInstance;
1305 * Setter for FilePointer instance
1307 * @param $pointerInstance An instance of an FilePointer class
1310 protected final function setPointerInstance (FilePointer $pointerInstance) {
1311 $this->pointerInstance = $pointerInstance;
1315 * Getter for FilePointer instance
1317 * @return $pointerInstance An instance of an FilePointer class
1319 public final function getPointerInstance () {
1320 return $this->pointerInstance;
1324 * Unsets pointer instance which triggers a call of __destruct() if the
1325 * instance is still there. This is surely not fatal on already "closed"
1326 * file pointer instances.
1328 * I don't want to mess around with above setter by giving it a default
1329 * value NULL as setter should always explicitly only set (existing) object
1330 * instances and NULL is NULL.
1334 protected final function unsetPointerInstance () {
1335 // Simply it to NULL
1336 $this->pointerInstance = NULL;
1340 * Setter for Indexable instance
1342 * @param $indexInstance An instance of an Indexable class
1345 protected final function setIndexInstance (Indexable $indexInstance) {
1346 $this->indexInstance = $indexInstance;
1350 * Getter for Indexable instance
1352 * @return $indexInstance An instance of an Indexable class
1354 public final function getIndexInstance () {
1355 return $this->indexInstance;
1359 * Setter for Block instance
1361 * @param $blockInstance An instance of an Block class
1364 protected final function setBlockInstance (Block $blockInstance) {
1365 $this->blockInstance = $blockInstance;
1369 * Getter for Block instance
1371 * @return $blockInstance An instance of an Block class
1373 public final function getBlockInstance () {
1374 return $this->blockInstance;
1378 * Setter for Minable instance
1380 * @param $minableInstance A Minable instance
1383 protected final function setMinableInstance (Minable $minableInstance) {
1384 $this->minableInstance = $minableInstance;
1388 * Getter for minable instance
1390 * @return $minableInstance A Minable instance
1392 protected final function getMinableInstance () {
1393 return $this->minableInstance;
1397 * Setter for FrameworkDirectory instance
1399 * @param $directoryInstance A FrameworkDirectory instance
1402 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1403 $this->directoryInstance = $directoryInstance;
1407 * Getter for FrameworkDirectory instance
1409 * @return $directoryInstance A FrameworkDirectory instance
1411 protected final function getDirectoryInstance () {
1412 return $this->directoryInstance;
1416 * Setter for state instance
1418 * @param $stateInstance A Stateable instance
1421 public final function setStateInstance (Stateable $stateInstance) {
1422 $this->stateInstance = $stateInstance;
1426 * Getter for state instance
1428 * @return $stateInstance A Stateable instance
1430 public final function getStateInstance () {
1431 return $this->stateInstance;
1435 * Setter for output instance
1437 * @param $outputInstance The debug output instance
1440 public final function setOutputInstance (OutputStreamer $outputInstance) {
1441 $this->outputInstance = $outputInstance;
1445 * Getter for output instance
1447 * @return $outputInstance The debug output instance
1449 public final function getOutputInstance () {
1450 return $this->outputInstance;
1454 * Setter for registry instance
1456 * @param $registryInstance An instance of a Register class
1459 protected final function setRegistryInstance (Register $registryInstance) {
1460 $this->registryInstance = $registryInstance;
1464 * Getter for registry instance
1466 * @return $registryInstance The debug registry instance
1468 public final function getRegistryInstance () {
1469 return $this->registryInstance;
1473 * Setter for call-back instance
1475 * @param $callbackInstance An instance of a FrameworkInterface class
1478 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1479 $this->callbackInstance = $callbackInstance;
1483 * Getter for call-back instance
1485 * @return $callbackInstance An instance of a FrameworkInterface class
1487 protected final function getCallbackInstance () {
1488 return $this->callbackInstance;
1492 * Setter for command name
1494 * @param $commandName Last validated command name
1497 protected final function setCommandName ($commandName) {
1498 $this->commandName = $commandName;
1502 * Getter for command name
1504 * @return $commandName Last validated command name
1506 protected final function getCommandName () {
1507 return $this->commandName;
1511 * Setter for controller name
1513 * @param $controllerName Last validated controller name
1516 protected final function setControllerName ($controllerName) {
1517 $this->controllerName = $controllerName;
1521 * Getter for controller name
1523 * @return $controllerName Last validated controller name
1525 protected final function getControllerName () {
1526 return $this->controllerName;
1530 * Checks whether an object equals this object. You should overwrite this
1531 * method to implement own equality checks
1533 * @param $objectInstance An instance of a FrameworkInterface object
1534 * @return $equals Whether both objects equals
1536 public function equals (FrameworkInterface $objectInstance) {
1539 $this->__toString() == $objectInstance->__toString()
1541 $this->hashCode() == $objectInstance->hashCode()
1544 // Return the result
1549 * Generates a generic hash code of this class. You should really overwrite
1550 * this method with your own hash code generator code. But keep KISS in mind.
1552 * @return $hashCode A generic hash code respresenting this whole class
1554 public function hashCode () {
1556 return crc32($this->__toString());
1560 * Formats computer generated price values into human-understandable formats
1561 * with thousand and decimal separators.
1563 * @param $value The in computer format value for a price
1564 * @param $currency The currency symbol (use HTML-valid characters!)
1565 * @param $decNum Number of decimals after commata
1566 * @return $price The for the current language formated price string
1567 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1568 * thousands separator
1571 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1572 // Are all required attriutes set?
1573 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1574 // Throw an exception
1575 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1579 $value = (float) $value;
1581 // Reformat the US number
1582 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1584 // Return as string...
1589 * Appends a trailing slash to a string
1591 * @param $str A string (maybe) without trailing slash
1592 * @return $str A string with an auto-appended trailing slash
1594 public final function addMissingTrailingSlash ($str) {
1595 // Is there a trailing slash?
1596 if (substr($str, -1, 1) != '/') {
1600 // Return string with trailing slash
1605 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1606 * application helper instance (ApplicationHelper by default).
1608 * @param $applicationInstance An application helper instance or
1609 * null if we shall use the default
1610 * @return $templateInstance The template engine instance
1611 * @throws NullPointerException If the discovered application
1612 * instance is still null
1614 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1615 // Is the application instance set?
1616 if (is_null($applicationInstance)) {
1617 // Get the current instance
1618 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1621 if (is_null($applicationInstance)) {
1622 // Thrown an exception
1623 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1627 // Initialize the template engine
1628 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1630 // Return the prepared instance
1631 return $templateInstance;
1635 * Debugs this instance by putting out it's full content
1637 * @param $message Optional message to show in debug output
1640 public final function debugInstance ($message = '') {
1641 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1642 restore_error_handler();
1647 // Is a message set?
1648 if (!empty($message)) {
1649 // Construct message
1650 $content = sprintf('<div class="debug_message">
1652 </div>' . PHP_EOL, $message);
1655 // Generate the output
1656 $content .= sprintf('<pre>%s</pre>',
1659 print_r($this, true)
1665 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1668 <div class="debug_content">
1672 <div class="debug_include_list">
1675 $this->__toString(),
1677 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1682 * Replaces control characters with printable output
1684 * @param $str String with control characters
1685 * @return $str Replaced string
1687 protected function replaceControlCharacters ($str) {
1690 chr(13), '[r]', str_replace(
1691 chr(10), '[n]', str_replace(
1701 * Output a partial stub message for the caller method
1703 * @param $message An optional message to display
1706 protected function partialStub ($message = '') {
1708 $stubMessage = 'Partial Stub!';
1710 // Is the extra message given?
1711 if (!empty($message)) {
1712 // Then add it as well
1713 $stubMessage .= ' Message: ' . $message;
1716 // Debug instance is there?
1717 if (!is_null($this->getDebugInstance())) {
1718 // Output stub message
1719 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1722 trigger_error($stubMessage);
1728 * Outputs a debug backtrace and stops further script execution
1730 * @param $message An optional message to output
1731 * @param $doExit Whether exit the program (true is default)
1734 public function debugBackTrace ($message = '', $doExit = true) {
1735 // Sorry, there is no other way getting this nice backtrace
1736 if (!empty($message)) {
1738 printf('Message: %s<br />' . PHP_EOL, $message);
1742 debug_print_backtrace();
1746 if ($doExit === true) {
1752 * Creates an instance of a debugger instance
1754 * @param $className Name of the class (currently unsupported)
1755 * @param $lineNumber Line number where the call was made
1756 * @return $debugInstance An instance of a debugger class
1757 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1759 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1760 // Is the instance set?
1761 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1762 // Init debug instance
1763 $debugInstance = NULL;
1767 // Get a debugger instance
1768 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1769 } catch (NullPointerException $e) {
1770 // Didn't work, no instance there
1771 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1774 // Empty string should be ignored and used for testing the middleware
1775 DebugMiddleware::getSelfInstance()->output('');
1777 // Set it in registry
1778 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1780 // Get instance from registry
1781 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1785 return $debugInstance;
1789 * Simple output of a message with line-break
1791 * @param $message Message to output
1794 public function outputLine ($message) {
1796 print($message . PHP_EOL);
1800 * Outputs a debug message whether to debug instance (should be set!) or
1801 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1802 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1804 * @param $message Message we shall send out...
1805 * @param $doPrint Whether print or die here (default: print)
1806 * @paran $stripTags Whether to strip tags (default: false)
1809 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1810 // Set debug instance to NULL
1811 $debugInstance = NULL;
1814 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1816 // Is function partialStub/__callStatic ?
1817 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1818 // Prepend class::function:line from 3rd element
1819 $message = sprintf('[%s::%s:%d]: %s',
1820 $backtrace[2]['class'],
1821 $backtrace[2]['function'],
1822 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1826 // Prepend class::function:line from 2nd element
1827 $message = sprintf('[%s::%s:%d]: %s',
1828 $backtrace[1]['class'],
1829 $backtrace[1]['function'],
1830 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1837 // Get debug instance
1838 $debugInstance = $this->getDebugInstance();
1839 } catch (NullPointerException $e) {
1840 // The debug instance is not set (yet)
1843 // Is the debug instance there?
1844 if (is_object($debugInstance)) {
1845 // Use debug output handler
1846 $debugInstance->output($message, $stripTags);
1848 if ($doPrint === false) {
1849 // Die here if not printed
1853 // Are debug times enabled?
1854 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1856 $message = $this->getPrintableExecutionTime() . $message;
1860 if ($doPrint === true) {
1862 $this->outputLine($message);
1871 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1873 * @param $str The string, what ever it is needs to be converted
1874 * @return $className Generated class name
1876 public static final function convertToClassName ($str) {
1880 // Convert all dashes in underscores
1881 $str = StringUtils::convertDashesToUnderscores($str);
1883 // Now use that underscores to get classname parts for hungarian style
1884 foreach (explode('_', $str) as $strPart) {
1885 // Make the class name part lower case and first upper case
1886 $className .= ucfirst(strtolower($strPart));
1889 // Return class name
1894 * Marks up the code by adding e.g. line numbers
1896 * @param $phpCode Unmarked PHP code
1897 * @return $markedCode Marked PHP code
1899 public function markupCode ($phpCode) {
1904 $errorArray = error_get_last();
1906 // Init the code with error message
1907 if (is_array($errorArray)) {
1909 $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>',
1910 basename($errorArray['file']),
1911 $errorArray['line'],
1912 $errorArray['message'],
1917 // Add line number to the code
1918 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1920 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1922 htmlentities($code, ENT_QUOTES)
1931 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1932 * beatiful for web-based front-ends. If null is given a message id
1933 * null_timestamp will be resolved and returned.
1935 * @param $timestamp Timestamp to prepare (filter) for display
1936 * @return $readable A readable timestamp
1938 public function doFilterFormatTimestamp ($timestamp) {
1939 // Default value to return
1942 // Is the timestamp null?
1943 if (is_null($timestamp)) {
1944 // Get a message string
1945 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1947 switch ($this->getLanguageInstance()->getLanguageCode()) {
1948 case 'de': // German format is a bit different to default
1949 // Split the GMT stamp up
1950 $dateTime = explode(' ', $timestamp );
1951 $dateArray = explode('-', $dateTime[0]);
1952 $timeArray = explode(':', $dateTime[1]);
1954 // Construct the timestamp
1955 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1965 default: // Default is pass-through
1966 $readable = $timestamp;
1976 * Filter a given number into a localized number
1978 * @param $value The raw value from e.g. database
1979 * @return $localized Localized value
1981 public function doFilterFormatNumber ($value) {
1982 // Generate it from config and localize dependencies
1983 switch ($this->getLanguageInstance()->getLanguageCode()) {
1984 case 'de': // German format is a bit different to default
1985 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1988 default: // US, etc.
1989 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1998 * "Getter" for databse entry
2000 * @return $entry An array with database entries
2001 * @throws NullPointerException If the database result is not found
2002 * @throws InvalidDatabaseResultException If the database result is invalid
2004 protected final function getDatabaseEntry () {
2005 // Is there an instance?
2006 if (!$this->getResultInstance() instanceof SearchableResult) {
2007 // Throw an exception here
2008 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2012 $this->getResultInstance()->rewind();
2014 // Do we have an entry?
2015 if ($this->getResultInstance()->valid() === false) {
2016 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2017 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2021 $this->getResultInstance()->next();
2024 $entry = $this->getResultInstance()->current();
2031 * Getter for field name
2033 * @param $fieldName Field name which we shall get
2034 * @return $fieldValue Field value from the user
2035 * @throws NullPointerException If the result instance is null
2037 public final function getField ($fieldName) {
2038 // Default field value
2041 // Get result instance
2042 $resultInstance = $this->getResultInstance();
2044 // Is this instance null?
2045 if (is_null($resultInstance)) {
2046 // Then the user instance is no longer valid (expired cookies?)
2047 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2050 // Get current array
2051 $fieldArray = $resultInstance->current();
2052 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2054 // Convert dashes to underscore
2055 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
2057 // Does the field exist?
2058 if ($this->isFieldSet($fieldName)) {
2060 $fieldValue = $fieldArray[$fieldName2];
2061 } elseif (defined('DEVELOPER')) {
2062 // Missing field entry, may require debugging
2063 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2065 // Missing field entry, may require debugging
2066 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2074 * Checks if given field is set
2076 * @param $fieldName Field name to check
2077 * @return $isSet Whether the given field name is set
2078 * @throws NullPointerException If the result instance is null
2080 public function isFieldSet ($fieldName) {
2081 // Get result instance
2082 $resultInstance = $this->getResultInstance();
2084 // Is this instance null?
2085 if (is_null($resultInstance)) {
2086 // Then the user instance is no longer valid (expired cookies?)
2087 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2090 // Get current array
2091 $fieldArray = $resultInstance->current();
2092 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2094 // Convert dashes to underscore
2095 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
2098 $isSet = isset($fieldArray[$fieldName]);
2105 * Flushs all pending updates to the database layer
2109 public function flushPendingUpdates () {
2110 // Get result instance
2111 $resultInstance = $this->getResultInstance();
2113 // Do we have data to update?
2114 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2115 // Get wrapper class name config entry
2116 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2118 // Create object instance
2119 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2121 // Yes, then send the whole result to the database layer
2122 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2127 * Outputs a deprecation warning to the developer.
2129 * @param $message The message we shall output to the developer
2131 * @todo Write a logging mechanism for productive mode
2133 public function deprecationWarning ($message) {
2134 // Is developer mode active?
2135 if (defined('DEVELOPER')) {
2136 // Debug instance is there?
2137 if (!is_null($this->getDebugInstance())) {
2138 // Output stub message
2139 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2142 trigger_error($message . "<br />\n");
2146 // @TODO Finish this part!
2147 $this->partialStub('Developer mode inactive. Message:' . $message);
2152 * Checks whether the given PHP extension is loaded
2154 * @param $phpExtension The PHP extension we shall check
2155 * @return $isLoaded Whether the PHP extension is loaded
2157 public final function isPhpExtensionLoaded ($phpExtension) {
2159 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2166 * "Getter" as a time() replacement but with milliseconds. You should use this
2167 * method instead of the encapsulated getimeofday() function.
2169 * @return $milliTime Timestamp with milliseconds
2171 public function getMilliTime () {
2172 // Get the time of day as float
2173 $milliTime = gettimeofday(true);
2180 * Idles (sleeps) for given milliseconds
2182 * @return $hasSlept Whether it goes fine
2184 public function idle ($milliSeconds) {
2185 // Sleep is fine by default
2188 // Idle so long with found function
2189 if (function_exists('time_sleep_until')) {
2190 // Get current time and add idle time
2191 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2193 // New PHP 5.1.0 function found, ignore errors
2194 $hasSlept = @time_sleep_until($sleepUntil);
2197 * My Sun station doesn't have that function even with latest PHP
2200 usleep($milliSeconds * 1000);
2207 * Converts a hexadecimal string, even with negative sign as first string to
2208 * a decimal number using BC functions.
2210 * This work is based on comment #86673 on php.net documentation page at:
2211 * <http://de.php.net/manual/en/function.dechex.php#86673>
2213 * @param $hex Hexadecimal string
2214 * @return $dec Decimal number
2216 protected function hex2dec ($hex) {
2217 // Convert to all lower-case
2218 $hex = strtolower($hex);
2220 // Detect sign (negative/positive numbers)
2222 if (substr($hex, 0, 1) == '-') {
2224 $hex = substr($hex, 1);
2227 // Decode the hexadecimal string into a decimal number
2229 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2230 $factor = self::$hexdec[substr($hex, $i, 1)];
2231 $dec = bcadd($dec, bcmul($factor, $e));
2234 // Return the decimal number
2235 return $sign . $dec;
2239 * Converts even very large decimal numbers, also signed, to a hexadecimal
2242 * This work is based on comment #97756 on php.net documentation page at:
2243 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2245 * @param $dec Decimal number, even with negative sign
2246 * @param $maxLength Optional maximum length of the string
2247 * @return $hex Hexadecimal string
2249 protected function dec2hex ($dec, $maxLength = 0) {
2250 // maxLength can be zero or devideable by 2
2251 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2253 // Detect sign (negative/positive numbers)
2260 // Encode the decimal number into a hexadecimal string
2263 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2265 } while ($dec >= 1);
2268 * Leading zeros are required for hex-decimal "numbers". In some
2269 * situations more leading zeros are wanted, so check for both
2272 if ($maxLength > 0) {
2273 // Prepend more zeros
2274 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2275 } elseif ((strlen($hex) % 2) != 0) {
2276 // Only make string's length dividable by 2
2280 // Return the hexadecimal string
2281 return $sign . $hex;
2285 * Converts a ASCII string (0 to 255) into a decimal number.
2287 * @param $asc The ASCII string to be converted
2288 * @return $dec Decimal number
2290 protected function asc2dec ($asc) {
2291 // Convert it into a hexadecimal number
2292 $hex = bin2hex($asc);
2294 // And back into a decimal number
2295 $dec = $this->hex2dec($hex);
2302 * Converts a decimal number into an ASCII string.
2304 * @param $dec Decimal number
2305 * @return $asc An ASCII string
2307 protected function dec2asc ($dec) {
2308 // First convert the number into a hexadecimal string
2309 $hex = $this->dec2hex($dec);
2311 // Then convert it into the ASCII string
2312 $asc = $this->hex2asc($hex);
2319 * Converts a hexadecimal number into an ASCII string. Negative numbers
2322 * @param $hex Hexadecimal string
2323 * @return $asc An ASCII string
2325 protected function hex2asc ($hex) {
2326 // Check for length, it must be devideable by 2
2327 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2328 assert((strlen($hex) % 2) == 0);
2332 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2333 // Get the decimal number of the chunk
2334 $part = hexdec(substr($hex, $idx, 2));
2336 // Add it to the final string
2340 // Return the final string
2345 * Checks whether the given encoded data was encoded with Base64
2347 * @param $encodedData Encoded data we shall check
2348 * @return $isBase64 Whether the encoded data is Base64
2350 protected function isBase64Encoded ($encodedData) {
2352 $isBase64 = (@base64_decode($encodedData, true) !== false);
2359 * Gets a cache key from Criteria instance
2361 * @param $criteriaInstance An instance of a Criteria class
2362 * @param $onlyKeys Only use these keys for a cache key
2363 * @return $cacheKey A cache key suitable for lookup/storage purposes
2365 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2367 $cacheKey = sprintf('%s@%s',
2368 $this->__toString(),
2369 $criteriaInstance->getCacheKey($onlyKeys)
2373 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2378 * Getter for startup time in miliseconds
2380 * @return $startupTime Startup time in miliseconds
2382 protected function getStartupTime () {
2383 return self::$startupTime;
2387 * "Getter" for a printable currently execution time in nice braces
2389 * @return $executionTime Current execution time in nice braces
2391 protected function getPrintableExecutionTime () {
2392 // Caculate the execution time
2393 $executionTime = microtime(true) - $this->getStartupTime();
2395 // Pack it in nice braces
2396 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2399 return $executionTime;
2403 * Hashes a given string with a simple but stronger hash function (no salt)
2404 * and hex-encode it.
2406 * @param $str The string to be hashed
2407 * @return $hash The hash from string $str
2409 public static final function hash ($str) {
2410 // Hash given string with (better secure) hasher
2411 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2418 * "Getter" for length of hash() output. This will be "cached" to speed up
2421 * @return $length Length of hash() output
2423 public static final function getHashLength () {
2425 if (is_null(self::$hashLength)) {
2426 // No, then hash a string and save its length.
2427 self::$hashLength = strlen(self::hash('abc123'));
2431 return self::$hashLength;
2435 * Checks whether the given number is really a number (only chars 0-9).
2437 * @param $num A string consisting only chars between 0 and 9
2438 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2439 * @param $assertMismatch Whether to assert mismatches
2440 * @return $ret The (hopefully) secured numbered value
2442 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2443 // Filter all numbers out
2444 $ret = preg_replace('/[^0123456789]/', '', $num);
2447 if ($castValue === true) {
2448 // Cast to biggest numeric type
2449 $ret = (double) $ret;
2452 // Assert only if requested
2453 if ($assertMismatch === true) {
2454 // Has the whole value changed?
2455 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2463 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2465 * @param $num A string consisting only chars between 0 and 9
2466 * @param $assertMismatch Whether to assert mismatches
2467 * @return $ret The (hopefully) secured hext-numbered value
2469 public function hexval ($num, $assertMismatch = false) {
2470 // Filter all numbers out
2471 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2473 // Assert only if requested
2474 if ($assertMismatch === true) {
2475 // Has the whole value changed?
2476 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2484 * Determines if an element is set in the generic array
2486 * @param $keyGroup Main group for the key
2487 * @param $subGroup Sub group for the key
2488 * @param $key Key to check
2489 * @param $element Element to check
2490 * @return $isset Whether the given key is set
2492 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2494 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2497 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2503 * Determines if a key is set in the generic array
2505 * @param $keyGroup Main group for the key
2506 * @param $subGroup Sub group for the key
2507 * @param $key Key to check
2508 * @return $isset Whether the given key is set
2510 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2512 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2515 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2523 * Determines if a group is set in the generic array
2525 * @param $keyGroup Main group
2526 * @param $subGroup Sub group
2527 * @return $isset Whether the given group is set
2529 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2531 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2534 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2541 * Getter for sub key group
2543 * @param $keyGroup Main key group
2544 * @param $subGroup Sub key group
2545 * @return $array An array with all array elements
2547 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2549 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2550 // No, then abort here
2551 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2556 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2559 return $this->genericArray[$keyGroup][$subGroup];
2563 * Unsets a given key in generic array
2565 * @param $keyGroup Main group for the key
2566 * @param $subGroup Sub group for the key
2567 * @param $key Key to unset
2570 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2572 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2575 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2579 * Unsets a given element in generic array
2581 * @param $keyGroup Main group for the key
2582 * @param $subGroup Sub group for the key
2583 * @param $key Key to unset
2584 * @param $element Element to unset
2587 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2589 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2592 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2596 * Append a string to a given generic array key
2598 * @param $keyGroup Main group for the key
2599 * @param $subGroup Sub group for the key
2600 * @param $key Key to unset
2601 * @param $value Value to add/append
2604 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2606 //* 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);
2608 // Is it already there?
2609 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2611 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2614 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2619 * Append a string to a given generic array element
2621 * @param $keyGroup Main group for the key
2622 * @param $subGroup Sub group for the key
2623 * @param $key Key to unset
2624 * @param $element Element to check
2625 * @param $value Value to add/append
2628 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2630 //* 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);
2632 // Is it already there?
2633 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2635 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2638 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2643 * Sets a string in a given generic array element
2645 * @param $keyGroup Main group for the key
2646 * @param $subGroup Sub group for the key
2647 * @param $key Key to unset
2648 * @param $element Element to check
2649 * @param $value Value to add/append
2652 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2654 //* 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);
2657 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2661 * Initializes given generic array group
2663 * @param $keyGroup Main group for the key
2664 * @param $subGroup Sub group for the key
2665 * @param $key Key to use
2666 * @param $forceInit Optionally force initialization
2669 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2671 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2673 // Is it already set?
2674 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2675 // Already initialized
2676 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2681 $this->genericArray[$keyGroup][$subGroup] = array();
2685 * Initializes given generic array key
2687 * @param $keyGroup Main group for the key
2688 * @param $subGroup Sub group for the key
2689 * @param $key Key to use
2690 * @param $forceInit Optionally force initialization
2693 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2695 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2697 // Is it already set?
2698 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2699 // Already initialized
2700 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2705 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2709 * Initializes given generic array element
2711 * @param $keyGroup Main group for the key
2712 * @param $subGroup Sub group for the key
2713 * @param $key Key to use
2714 * @param $element Element to use
2715 * @param $forceInit Optionally force initialization
2718 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2720 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2722 // Is it already set?
2723 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2724 // Already initialized
2725 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2730 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2734 * Pushes an element to a generic key
2736 * @param $keyGroup Main group for the key
2737 * @param $subGroup Sub group for the key
2738 * @param $key Key to use
2739 * @param $value Value to add/append
2740 * @return $count Number of array elements
2742 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2744 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2747 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2749 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2753 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2756 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2757 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2762 * Pushes an element to a generic array element
2764 * @param $keyGroup Main group for the key
2765 * @param $subGroup Sub group for the key
2766 * @param $key Key to use
2767 * @param $element Element to check
2768 * @param $value Value to add/append
2769 * @return $count Number of array elements
2771 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2773 //* 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));
2776 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2778 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2782 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2785 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2786 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2791 * Pops an element from a generic group
2793 * @param $keyGroup Main group for the key
2794 * @param $subGroup Sub group for the key
2795 * @param $key Key to unset
2796 * @return $value Last "popped" value
2798 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2800 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2803 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2805 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2810 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2813 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2814 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2819 * Shifts an element from a generic group
2821 * @param $keyGroup Main group for the key
2822 * @param $subGroup Sub group for the key
2823 * @param $key Key to unset
2824 * @return $value Last "popped" value
2826 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2828 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2831 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2833 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2838 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2841 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2842 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2847 * Count generic array group
2849 * @param $keyGroup Main group for the key
2850 * @return $count Count of given group
2852 protected final function countGenericArray ($keyGroup) {
2854 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2857 if (!isset($this->genericArray[$keyGroup])) {
2859 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2864 $count = count($this->genericArray[$keyGroup]);
2867 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2874 * Count generic array sub group
2876 * @param $keyGroup Main group for the key
2877 * @param $subGroup Sub group for the key
2878 * @return $count Count of given group
2880 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2882 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2885 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2887 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2892 $count = count($this->genericArray[$keyGroup][$subGroup]);
2895 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2902 * Count generic array elements
2904 * @param $keyGroup Main group for the key
2905 * @param $subGroup Sub group for the key
2906 * @para $key Key to count
2907 * @return $count Count of given key
2909 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2911 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2914 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2916 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2918 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2920 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2925 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2928 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2935 * Getter for whole generic group array
2937 * @param $keyGroup Key group to get
2938 * @return $array Whole generic array group
2940 protected final function getGenericArray ($keyGroup) {
2942 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2945 if (!isset($this->genericArray[$keyGroup])) {
2947 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2952 return $this->genericArray[$keyGroup];
2956 * Setter for generic array key
2958 * @param $keyGroup Key group to get
2959 * @param $subGroup Sub group for the key
2960 * @param $key Key to unset
2961 * @param $value Mixed value from generic array element
2964 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2966 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2969 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2973 * Getter for generic array key
2975 * @param $keyGroup Key group to get
2976 * @param $subGroup Sub group for the key
2977 * @param $key Key to unset
2978 * @return $value Mixed value from generic array element
2980 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2982 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2985 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2987 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2992 return $this->genericArray[$keyGroup][$subGroup][$key];
2996 * Sets a value in given generic array key/element
2998 * @param $keyGroup Main group for the key
2999 * @param $subGroup Sub group for the key
3000 * @param $key Key to set
3001 * @param $element Element to set
3002 * @param $value Value to set
3005 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3007 //* 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));
3010 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3014 * Getter for generic array element
3016 * @param $keyGroup Key group to get
3017 * @param $subGroup Sub group for the key
3018 * @param $key Key to look for
3019 * @param $element Element to look for
3020 * @return $value Mixed value from generic array element
3022 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3024 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3027 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3029 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3034 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3038 * Checks if a given sub group is valid (array)
3040 * @param $keyGroup Key group to get
3041 * @param $subGroup Sub group for the key
3042 * @return $isValid Whether given sub group is valid
3044 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3046 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3049 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3056 * Checks if a given key is valid (array)
3058 * @param $keyGroup Key group to get
3059 * @param $subGroup Sub group for the key
3060 * @param $key Key to check
3061 * @return $isValid Whether given sub group is valid
3063 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3065 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3068 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3075 * Initializes the web output instance
3079 protected function initWebOutputInstance () {
3080 // Get application instance
3081 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
3083 // Init web output instance
3084 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3087 $this->setWebOutputInstance($outputInstance);
3091 * Translates boolean true to 'Y' and false to 'N'
3093 * @param $boolean Boolean value
3094 * @return $translated Translated boolean value
3096 public static final function translateBooleanToYesNo ($boolean) {
3097 // Make sure it is really boolean
3098 assert(is_bool($boolean));
3101 $translated = ($boolean === true) ? 'Y' : 'N';
3103 // ... and return it
3108 * Encodes raw data (almost any type) by "serializing" it and then pack it
3109 * into a "binary format".
3111 * @param $rawData Raw data (almost any type)
3112 * @return $encoded Encoded data
3114 protected function encodeData ($rawData) {
3115 // Make sure no objects or resources pass through
3116 assert(!is_object($rawData));
3117 assert(!is_resource($rawData));
3119 // First "serialize" it (json_encode() is faster than serialize())
3120 $encoded = $this->packString(json_encode($rawData));
3127 * Pack a string into a "binary format". Please execuse me that this is
3128 * widely undocumented. :-(
3130 * @param $str Unpacked string
3131 * @return $packed Packed string
3132 * @todo Improve documentation
3134 protected function packString ($str) {
3136 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3138 // First compress the string (gzcompress is okay)
3139 $str = gzcompress($str);
3144 // And start the "encoding" loop
3145 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3147 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3148 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3150 if (($idx + $i) <= strlen($str)) {
3151 $ord = ord(substr($str, ($idx + $i), 1));
3153 $add = $ord * pow(256, $factor);
3157 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3161 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3162 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3164 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3165 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3171 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3176 * Creates a full-qualified file name (FQFN) for given file name by adding
3177 * a configured temporary file path to it.
3179 * @param $infoInstance An instance of a SplFileInfo class
3180 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3181 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3182 * @throws FileIoException If the file cannot be written
3184 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3186 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3188 // Is the path writeable?
3189 if (!is_writable($basePath)) {
3190 // Path is write-protected
3191 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3195 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3198 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3200 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3204 return $tempInstance;
3208 * "Getter" for a printable state name
3210 * @return $stateName Name of the node's state in a printable format
3212 public final function getPrintableState () {
3213 // Default is 'null'
3214 $stateName = 'null';
3216 // Get the state instance
3217 $stateInstance = $this->getStateInstance();
3219 // Is it an instance of Stateable?
3220 if ($stateInstance instanceof Stateable) {
3221 // Then use that state name
3222 $stateName = $stateInstance->getStateName();