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 - 2019 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;
91 * Self-referencing instance
93 private static $instance = NULL;
98 private $realClass = 'BaseFrameworkSystem';
101 * Search criteria instance
103 private $searchInstance = NULL;
106 * Update criteria instance
108 private $updateInstance = NULL;
111 * The file I/O instance for the template loader
113 private $fileIoInstance = NULL;
118 private $resolverInstance = NULL;
121 * Template engine instance
123 private $templateInstance = NULL;
126 * Database result instance
128 private $resultInstance = NULL;
131 * Instance for user class
133 private $userInstance = NULL;
136 * A controller instance
138 private $controllerInstance = NULL;
143 private $rngInstance = NULL;
146 * Instance of a crypto helper
148 private $cryptoInstance = NULL;
151 * Instance of an Iterator class
153 private $iteratorInstance = NULL;
156 * Instance of the list
158 private $listInstance = NULL;
163 private $menuInstance = NULL;
166 * Instance of the image
168 private $imageInstance = NULL;
171 * Instance of the stacker
173 private $stackInstance = NULL;
176 * A Compressor instance
178 private $compressorInstance = NULL;
181 * A Parseable instance
183 private $parserInstance = NULL;
186 * A database wrapper instance
188 private $databaseInstance = NULL;
191 * A helper instance for the form
193 private $helperInstance = NULL;
196 * An instance of a InputStream class
198 private $inputStreamInstance = NULL;
201 * An instance of a OutputStream class
203 private $outputStreamInstance = NULL;
208 private $handlerInstance = NULL;
211 * Visitor handler instance
213 private $visitorInstance = NULL;
216 * An instance of a database wrapper class
218 private $wrapperInstance = NULL;
221 * An instance of a file I/O pointer class (not handler)
223 private $pointerInstance = NULL;
226 * An instance of an Indexable class
228 private $indexInstance = NULL;
231 * An instance of a Block class
233 private $blockInstance = NULL;
238 private $minableInstance = NULL;
241 * A FrameworkDirectory instance
243 private $directoryInstance = NULL;
246 * The concrete output instance
248 private $outputInstance = NULL;
253 private $stateInstance = NULL;
256 * Registry instance (implementing Register)
258 private $registryInstance = NULL;
263 private $callbackInstance = NULL;
266 * Thousands separator
268 private $thousands = '.'; // German
273 private $decimals = ','; // German
278 private $socketResource = false;
283 private $genericArray = array();
288 private $commandName = '';
293 private $controllerName = '';
296 * Array with bitmasks and such for pack/unpack methods to support both
297 * 32-bit and 64-bit systems
299 private $packingData = array(
302 'left' => 0xffff0000,
303 'right' => 0x0000ffff,
309 'left' => 0xffffffff00000000,
310 'right' => 0x00000000ffffffff,
317 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
319 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
321 private $archArrayElement = false;
323 /***********************
324 * Exception codes.... *
325 ***********************/
327 // @todo Try to clean these constants up
328 const EXCEPTION_IS_NULL_POINTER = 0x001;
329 const EXCEPTION_IS_NO_OBJECT = 0x002;
330 const EXCEPTION_IS_NO_ARRAY = 0x003;
331 const EXCEPTION_MISSING_METHOD = 0x004;
332 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
333 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
334 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
335 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
336 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
337 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
338 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
339 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
340 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
341 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
342 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
343 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
344 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
345 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
346 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
347 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
348 const EXCEPTION_PATH_NOT_FOUND = 0x015;
349 const EXCEPTION_INVALID_PATH_NAME = 0x016;
350 const EXCEPTION_READ_PROTECED_PATH = 0x017;
351 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
352 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
353 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
354 const EXCEPTION_INVALID_RESOURCE = 0x01b;
355 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
356 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
357 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
358 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
359 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
360 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
361 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
362 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
363 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
364 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
365 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
366 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
367 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
368 const EXCEPTION_INVALID_STRING = 0x029;
369 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
370 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
371 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
372 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
373 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
374 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
375 const EXCEPTION_MISSING_ELEMENT = 0x030;
376 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
377 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
378 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
379 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
380 const EXCEPTION_FATAL_ERROR = 0x035;
381 const EXCEPTION_FILE_NOT_FOUND = 0x036;
382 const EXCEPTION_ASSERTION_FAILED = 0x037;
383 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
384 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
385 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
386 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
387 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
388 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
389 const EXCEPTION_INVALID_SOCKET = 0x03e;
390 const EXCEPTION_SELF_INSTANCE = 0x03f;
393 * Hexadecimal->Decimal translation array
395 private static $hexdec = array(
415 * Decimal->hexadecimal translation array
417 private static $dechex = array(
437 * Startup time in miliseconds
439 private static $startupTime = 0;
442 * Protected super constructor
444 * @param $className Name of the class
447 protected function __construct ($className) {
449 $this->setRealClass($className);
451 // Set configuration instance if no registry ...
452 if (!$this instanceof Register) {
453 // ... because registries doesn't need to be configured
454 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
457 // Is the startup time set? (0 cannot be true anymore)
458 if (self::$startupTime == 0) {
460 self::$startupTime = microtime(true);
464 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
468 * Destructor for all classes. You should not call this method on your own.
472 public function __destruct () {
473 // Flush any updated entries to the database
474 $this->flushPendingUpdates();
476 // Is this object already destroyed?
477 if ($this->__toString() != 'DestructedObject') {
478 // Destroy all informations about this class but keep some text about it alive
479 $this->setRealClass('DestructedObject');
480 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
481 // Already destructed object
482 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
486 // Do not call this twice
487 trigger_error(__METHOD__ . ': Called twice.');
493 * The __call() method where all non-implemented methods end up
495 * @param $methodName Name of the missing method
496 * @args $args Arguments passed to the method
499 public final function __call ($methodName, $args) {
501 self::$instance = $this;
503 // Call static method
504 self::__callStatic($methodName, $args);
506 // Clear self-instance
507 self::$instance = NULL;
511 * The __callStatic() method where all non-implemented static methods end up
513 * @param $methodName Name of the missing method
514 * @param $args Arguments passed to the method
516 * @throws InvalidArgumentException If self::$instance is not a framework's own object
518 public static final function __callStatic ($methodName, $args) {
520 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
522 // Init argument string and class name
524 $className = 'unknown';
526 // Is self-instance set?
527 if (self::$instance instanceof FrameworkInterface) {
528 // Framework's own instance
529 $className = self::$instance->__toString();
530 } elseif (!is_null(self::$instance)) {
532 throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$instance)), self::EXCEPTION_SELF_INSTANCE);
535 // Is it NULL, empty or an array?
536 if (is_null($args)) {
538 $argsString = 'NULL';
539 } elseif (is_array($args)) {
543 // Some arguments are there
544 foreach ($args as $arg) {
545 // Add data about the argument
546 $argsString .= gettype($arg) . ':';
549 // Found a NULL argument
550 $argsString .= 'NULL';
551 } elseif (is_string($arg)) {
552 // Add length for strings
553 $argsString .= strlen($arg);
554 } elseif ((is_int($arg)) || (is_float($arg))) {
557 } elseif (is_array($arg)) {
558 // .. or size if array
559 $argsString .= count($arg);
560 } elseif (is_object($arg)) {
562 $reflection = new ReflectionClass($arg);
564 // Is an other object, maybe no __toString() available
565 $argsString .= $reflection->getName();
566 } elseif ($arg === true) {
567 // ... is boolean 'true'
568 $argsString .= 'true';
569 } elseif ($arg === false) {
570 // ... is boolean 'false'
571 $argsString .= 'false';
574 // Comma for next one
579 if (substr($argsString, -2, 1) == ',') {
581 $argsString = substr($argsString, 0, -2);
587 // Invalid arguments!
588 $argsString = sprintf('!INVALID:%s!', gettype($args));
591 // Output stub message
592 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
593 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s::%s]: Stub! Args: %s',
604 * Getter for $realClass
606 * @return $realClass The name of the real class (not BaseFrameworkSystem)
608 public function __toString () {
609 return $this->realClass;
613 * Magic method to catch setting of missing but set class fields/attributes
615 * @param $name Name of the field/attribute
616 * @param $value Value to store
619 public final function __set ($name, $value) {
620 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
623 print_r($value, true)
628 * Magic method to catch getting of missing fields/attributes
630 * @param $name Name of the field/attribute
633 public final function __get ($name) {
634 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
640 * Magic method to catch unsetting of missing fields/attributes
642 * @param $name Name of the field/attribute
645 public final function __unset ($name) {
646 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
652 * Magic method to catch object serialization
654 * @return $unsupported Unsupported method
655 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
657 public final function __sleep () {
658 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
662 * Magic method to catch object deserialization
664 * @return $unsupported Unsupported method
665 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
667 public final function __wakeup () {
668 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
672 * Magic method to catch calls when an object instance is called
674 * @return $unsupported Unsupported method
675 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
677 public final function __invoke () {
678 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
682 * Setter for the real class name
684 * @param $realClass Class name (string)
687 public final function setRealClass ($realClass) {
689 $this->realClass = (string) $realClass;
693 * Setter for database result instance
695 * @param $resultInstance An instance of a database result class
697 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
699 protected final function setResultInstance (SearchableResult $resultInstance) {
700 $this->resultInstance = $resultInstance;
704 * Getter for database result instance
706 * @return $resultInstance An instance of a database result class
708 public final function getResultInstance () {
709 return $this->resultInstance;
713 * Setter for template engine instances
715 * @param $templateInstance An instance of a template engine class
718 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
719 $this->templateInstance = $templateInstance;
723 * Getter for template engine instances
725 * @return $templateInstance An instance of a template engine class
727 protected final function getTemplateInstance () {
728 return $this->templateInstance;
732 * Setter for search instance
734 * @param $searchInstance Searchable criteria instance
737 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
738 $this->searchInstance = $searchInstance;
742 * Getter for search instance
744 * @return $searchInstance Searchable criteria instance
746 public final function getSearchInstance () {
747 return $this->searchInstance;
751 * Setter for update instance
753 * @param $updateInstance An instance of a LocalUpdateCriteria clase
756 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
757 $this->updateInstance = $updateInstance;
761 * Getter for update instance
763 * @return $updateInstance Updateable criteria instance
765 public final function getUpdateInstance () {
766 return $this->updateInstance;
770 * Setter for resolver instance
772 * @param $resolverInstance Instance of a command resolver class
775 public final function setResolverInstance (Resolver $resolverInstance) {
776 $this->resolverInstance = $resolverInstance;
780 * Getter for resolver instance
782 * @return $resolverInstance Instance of a command resolver class
784 public final function getResolverInstance () {
785 return $this->resolverInstance;
789 * Setter for language instance
791 * @param $configInstance The configuration instance which shall
792 * be FrameworkConfiguration
795 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
796 GenericRegistry::getRegistry()->addInstance('config', $configInstance);
800 * Getter for configuration instance
802 * @return $configInstance Configuration instance
804 public final function getConfigInstance () {
805 $configInstance = GenericRegistry::getRegistry()->getInstance('config');
806 return $configInstance;
810 * Setter for debug instance
812 * @param $debugInstance The instance for debug output class
815 public final function setDebugInstance (DebugMiddleware $debugInstance) {
816 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
820 * Getter for debug instance
822 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
824 public final function getDebugInstance () {
825 // Get debug instance
826 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
829 return $debugInstance;
833 * Setter for web output instance
835 * @param $webInstance The instance for web output class
838 public final function setWebOutputInstance (OutputStreamer $webInstance) {
839 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
843 * Getter for web output instance
845 * @return $webOutputInstance - Instance to class WebOutput
847 public final function getWebOutputInstance () {
848 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
849 return $webOutputInstance;
853 * Setter for database instance
855 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
858 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
859 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
863 * Getter for database layer
865 * @return $databaseInstance The database layer instance
867 public final function getDatabaseInstance () {
869 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
872 return $databaseInstance;
876 * Setter for compressor channel
878 * @param $compressorInstance An instance of CompressorChannel
881 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
882 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
886 * Getter for compressor channel
888 * @return $compressorInstance The compressor channel
890 public final function getCompressorChannel () {
891 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
892 return $compressorInstance;
896 * Private getter for language instance
898 * @return $langInstance An instance to the language sub-system
900 protected final function getLanguageInstance () {
901 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
902 return $langInstance;
906 * Setter for language instance
908 * @param $langInstance An instance to the language sub-system
910 * @see LanguageSystem
912 public final function setLanguageInstance (ManageableLanguage $langInstance) {
913 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
917 * Private getter for file IO instance
919 * @return $fileIoInstance An instance to the file I/O sub-system
921 protected final function getFileIoInstance () {
922 return $this->fileIoInstance;
926 * Setter for file I/O instance
928 * @param $fileIoInstance An instance to the file I/O sub-system
931 public final function setFileIoInstance (IoHandler $fileIoInstance) {
932 $this->fileIoInstance = $fileIoInstance;
936 * Protected setter for user instance
938 * @param $userInstance An instance of a user class
941 protected final function setUserInstance (ManageableAccount $userInstance) {
942 $this->userInstance = $userInstance;
946 * Getter for user instance
948 * @return $userInstance An instance of a user class
950 public final function getUserInstance () {
951 return $this->userInstance;
955 * Setter for controller instance (this surely breaks a bit the MVC patterm)
957 * @param $controllerInstance An instance of the controller
960 public final function setControllerInstance (Controller $controllerInstance) {
961 $this->controllerInstance = $controllerInstance;
965 * Getter for controller instance (this surely breaks a bit the MVC patterm)
967 * @return $controllerInstance An instance of the controller
969 public final function getControllerInstance () {
970 return $this->controllerInstance;
974 * Setter for RNG instance
976 * @param $rngInstance An instance of a random number generator (RNG)
979 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
980 $this->rngInstance = $rngInstance;
984 * Getter for RNG instance
986 * @return $rngInstance An instance of a random number generator (RNG)
988 public final function getRngInstance () {
989 return $this->rngInstance;
993 * Setter for Cryptable instance
995 * @param $cryptoInstance An instance of a Cryptable class
998 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
999 $this->cryptoInstance = $cryptoInstance;
1003 * Getter for Cryptable instance
1005 * @return $cryptoInstance An instance of a Cryptable class
1007 public final function getCryptoInstance () {
1008 return $this->cryptoInstance;
1012 * Setter for the list instance
1014 * @param $listInstance A list of Listable
1017 protected final function setListInstance (Listable $listInstance) {
1018 $this->listInstance = $listInstance;
1022 * Getter for the list instance
1024 * @return $listInstance A list of Listable
1026 protected final function getListInstance () {
1027 return $this->listInstance;
1031 * Setter for the menu instance
1033 * @param $menuInstance A RenderableMenu instance
1036 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1037 $this->menuInstance = $menuInstance;
1041 * Getter for the menu instance
1043 * @return $menuInstance A RenderableMenu instance
1045 protected final function getMenuInstance () {
1046 return $this->menuInstance;
1050 * Setter for image instance
1052 * @param $imageInstance An instance of an image
1055 public final function setImageInstance (BaseImage $imageInstance) {
1056 $this->imageInstance = $imageInstance;
1060 * Getter for image instance
1062 * @return $imageInstance An instance of an image
1064 public final function getImageInstance () {
1065 return $this->imageInstance;
1069 * Setter for stacker instance
1071 * @param $stackInstance An instance of an stacker
1074 public final function setStackInstance (Stackable $stackInstance) {
1075 $this->stackInstance = $stackInstance;
1079 * Getter for stacker instance
1081 * @return $stackInstance An instance of an stacker
1083 public final function getStackInstance () {
1084 return $this->stackInstance;
1088 * Setter for compressor instance
1090 * @param $compressorInstance An instance of an compressor
1093 public final function setCompressorInstance (Compressor $compressorInstance) {
1094 $this->compressorInstance = $compressorInstance;
1098 * Getter for compressor instance
1100 * @return $compressorInstance An instance of an compressor
1102 public final function getCompressorInstance () {
1103 return $this->compressorInstance;
1107 * Setter for Parseable instance
1109 * @param $parserInstance An instance of an Parseable
1112 public final function setParserInstance (Parseable $parserInstance) {
1113 $this->parserInstance = $parserInstance;
1117 * Getter for Parseable instance
1119 * @return $parserInstance An instance of an Parseable
1121 public final function getParserInstance () {
1122 return $this->parserInstance;
1126 * Setter for DatabaseWrapper instance
1128 * @param $wrapperInstance An instance of an DatabaseWrapper
1131 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1132 $this->wrapperInstance = $wrapperInstance;
1136 * Getter for DatabaseWrapper instance
1138 * @return $wrapperInstance An instance of an DatabaseWrapper
1140 public final function getWrapperInstance () {
1141 return $this->wrapperInstance;
1145 * Setter for socket resource
1147 * @param $socketResource A valid socket resource
1150 public final function setSocketResource ($socketResource) {
1151 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1152 $this->socketResource = $socketResource;
1156 * Getter for socket resource
1158 * @return $socketResource A valid socket resource
1160 public final function getSocketResource () {
1161 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1162 return $this->socketResource;
1166 * Setter for helper instance
1168 * @param $helperInstance An instance of a helper class
1171 protected final function setHelperInstance (Helper $helperInstance) {
1172 $this->helperInstance = $helperInstance;
1176 * Getter for helper instance
1178 * @return $helperInstance An instance of a helper class
1180 public final function getHelperInstance () {
1181 return $this->helperInstance;
1185 * Getter for a InputStream instance
1187 * @param $inputStreamInstance The InputStream instance
1189 protected final function getInputStreamInstance () {
1190 return $this->inputStreamInstance;
1194 * Setter for a InputStream instance
1196 * @param $inputStreamInstance The InputStream instance
1199 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1200 $this->inputStreamInstance = $inputStreamInstance;
1204 * Getter for a OutputStream instance
1206 * @param $outputStreamInstance The OutputStream instance
1208 protected final function getOutputStreamInstance () {
1209 return $this->outputStreamInstance;
1213 * Setter for a OutputStream instance
1215 * @param $outputStreamInstance The OutputStream instance
1218 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1219 $this->outputStreamInstance = $outputStreamInstance;
1223 * Setter for handler instance
1225 * @param $handlerInstance An instance of a Handleable class
1228 protected final function setHandlerInstance (Handleable $handlerInstance) {
1229 $this->handlerInstance = $handlerInstance;
1233 * Getter for handler instance
1235 * @return $handlerInstance A Handleable instance
1237 protected final function getHandlerInstance () {
1238 return $this->handlerInstance;
1242 * Setter for visitor instance
1244 * @param $visitorInstance A Visitor instance
1247 protected final function setVisitorInstance (Visitor $visitorInstance) {
1248 $this->visitorInstance = $visitorInstance;
1252 * Getter for visitor instance
1254 * @return $visitorInstance A Visitor instance
1256 protected final function getVisitorInstance () {
1257 return $this->visitorInstance;
1261 * Setter for Iterator instance
1263 * @param $iteratorInstance An instance of an Iterator
1266 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1267 $this->iteratorInstance = $iteratorInstance;
1271 * Getter for Iterator instance
1273 * @return $iteratorInstance An instance of an Iterator
1275 public final function getIteratorInstance () {
1276 return $this->iteratorInstance;
1280 * Setter for FilePointer instance
1282 * @param $pointerInstance An instance of an FilePointer class
1285 protected final function setPointerInstance (FilePointer $pointerInstance) {
1286 $this->pointerInstance = $pointerInstance;
1290 * Getter for FilePointer instance
1292 * @return $pointerInstance An instance of an FilePointer class
1294 public final function getPointerInstance () {
1295 return $this->pointerInstance;
1299 * Unsets pointer instance which triggers a call of __destruct() if the
1300 * instance is still there. This is surely not fatal on already "closed"
1301 * file pointer instances.
1303 * I don't want to mess around with above setter by giving it a default
1304 * value NULL as setter should always explicitly only set (existing) object
1305 * instances and NULL is NULL.
1309 protected final function unsetPointerInstance () {
1310 // Simply it to NULL
1311 $this->pointerInstance = NULL;
1315 * Setter for Indexable instance
1317 * @param $indexInstance An instance of an Indexable class
1320 protected final function setIndexInstance (Indexable $indexInstance) {
1321 $this->indexInstance = $indexInstance;
1325 * Getter for Indexable instance
1327 * @return $indexInstance An instance of an Indexable class
1329 public final function getIndexInstance () {
1330 return $this->indexInstance;
1334 * Setter for Block instance
1336 * @param $blockInstance An instance of an Block class
1339 protected final function setBlockInstance (Block $blockInstance) {
1340 $this->blockInstance = $blockInstance;
1344 * Getter for Block instance
1346 * @return $blockInstance An instance of an Block class
1348 public final function getBlockInstance () {
1349 return $this->blockInstance;
1353 * Setter for Minable instance
1355 * @param $minableInstance A Minable instance
1358 protected final function setMinableInstance (Minable $minableInstance) {
1359 $this->minableInstance = $minableInstance;
1363 * Getter for minable instance
1365 * @return $minableInstance A Minable instance
1367 protected final function getMinableInstance () {
1368 return $this->minableInstance;
1372 * Setter for FrameworkDirectory instance
1374 * @param $directoryInstance A FrameworkDirectory instance
1377 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1378 $this->directoryInstance = $directoryInstance;
1382 * Getter for FrameworkDirectory instance
1384 * @return $directoryInstance A FrameworkDirectory instance
1386 protected final function getDirectoryInstance () {
1387 return $this->directoryInstance;
1391 * Setter for state instance
1393 * @param $stateInstance A Stateable instance
1396 public final function setStateInstance (Stateable $stateInstance) {
1397 $this->stateInstance = $stateInstance;
1401 * Getter for state instance
1403 * @return $stateInstance A Stateable instance
1405 public final function getStateInstance () {
1406 return $this->stateInstance;
1410 * Setter for output instance
1412 * @param $outputInstance The debug output instance
1415 public final function setOutputInstance (OutputStreamer $outputInstance) {
1416 $this->outputInstance = $outputInstance;
1420 * Getter for output instance
1422 * @return $outputInstance The debug output instance
1424 public final function getOutputInstance () {
1425 return $this->outputInstance;
1429 * Setter for registry instance
1431 * @param $registryInstance An instance of a Register class
1434 protected final function setRegistryInstance (Register $registryInstance) {
1435 $this->registryInstance = $registryInstance;
1439 * Getter for registry instance
1441 * @return $registryInstance The debug registry instance
1443 public final function getRegistryInstance () {
1444 return $this->registryInstance;
1448 * Setter for call-back instance
1450 * @param $callbackInstance An instance of a FrameworkInterface class
1453 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1454 $this->callbackInstance = $callbackInstance;
1458 * Getter for call-back instance
1460 * @return $callbackInstance An instance of a FrameworkInterface class
1462 protected final function getCallbackInstance () {
1463 return $this->callbackInstance;
1467 * Setter for command name
1469 * @param $commandName Last validated command name
1472 protected final function setCommandName ($commandName) {
1473 $this->commandName = $commandName;
1477 * Getter for command name
1479 * @return $commandName Last validated command name
1481 protected final function getCommandName () {
1482 return $this->commandName;
1486 * Setter for controller name
1488 * @param $controllerName Last validated controller name
1491 protected final function setControllerName ($controllerName) {
1492 $this->controllerName = $controllerName;
1496 * Getter for controller name
1498 * @return $controllerName Last validated controller name
1500 protected final function getControllerName () {
1501 return $this->controllerName;
1505 * Checks whether an object equals this object. You should overwrite this
1506 * method to implement own equality checks
1508 * @param $objectInstance An instance of a FrameworkInterface object
1509 * @return $equals Whether both objects equals
1511 public function equals (FrameworkInterface $objectInstance) {
1514 $this->__toString() == $objectInstance->__toString()
1516 $this->hashCode() == $objectInstance->hashCode()
1519 // Return the result
1524 * Generates a generic hash code of this class. You should really overwrite
1525 * this method with your own hash code generator code. But keep KISS in mind.
1527 * @return $hashCode A generic hash code respresenting this whole class
1529 public function hashCode () {
1531 return crc32($this->__toString());
1535 * Formats computer generated price values into human-understandable formats
1536 * with thousand and decimal separators.
1538 * @param $value The in computer format value for a price
1539 * @param $currency The currency symbol (use HTML-valid characters!)
1540 * @param $decNum Number of decimals after commata
1541 * @return $price The for the current language formated price string
1542 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1543 * thousands separator
1546 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1547 // Are all required attriutes set?
1548 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1549 // Throw an exception
1550 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1554 $value = (float) $value;
1556 // Reformat the US number
1557 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1559 // Return as string...
1564 * Appends a trailing slash to a string
1566 * @param $str A string (maybe) without trailing slash
1567 * @return $str A string with an auto-appended trailing slash
1569 public final function addMissingTrailingSlash ($str) {
1570 // Is there a trailing slash?
1571 if (substr($str, -1, 1) != '/') {
1575 // Return string with trailing slash
1580 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1581 * application helper instance (ApplicationHelper by default).
1583 * @param $applicationInstance An application helper instance or
1584 * null if we shall use the default
1585 * @return $templateInstance The template engine instance
1586 * @throws NullPointerException If the discovered application
1587 * instance is still null
1589 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1590 // Is the application instance set?
1591 if (is_null($applicationInstance)) {
1592 // Get the current instance
1593 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1596 if (is_null($applicationInstance)) {
1597 // Thrown an exception
1598 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1602 // Initialize the template engine
1603 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1605 // Return the prepared instance
1606 return $templateInstance;
1610 * Debugs this instance by putting out it's full content
1612 * @param $message Optional message to show in debug output
1615 public final function debugInstance ($message = '') {
1616 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1617 restore_error_handler();
1622 // Is a message set?
1623 if (!empty($message)) {
1624 // Construct message
1625 $content = sprintf('<div class="debug_message">
1627 </div>' . PHP_EOL, $message);
1630 // Generate the output
1631 $content .= sprintf('<pre>%s</pre>',
1634 print_r($this, true)
1640 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1643 <div class="debug_content">
1647 <div class="debug_include_list">
1650 $this->__toString(),
1652 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1657 * Replaces control characters with printable output
1659 * @param $str String with control characters
1660 * @return $str Replaced string
1662 protected function replaceControlCharacters ($str) {
1665 chr(13), '[r]', str_replace(
1666 chr(10), '[n]', str_replace(
1676 * Output a partial stub message for the caller method
1678 * @param $message An optional message to display
1681 protected function partialStub ($message = '') {
1683 $stubMessage = 'Partial stub!';
1685 // Is an extra message given?
1686 if (!empty($message)) {
1687 // Then add it as well
1688 $stubMessage .= ' Message: ' . $message;
1691 // Debug instance is there?
1692 if (!is_null($this->getDebugInstance())) {
1693 // Output stub message
1694 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1697 trigger_error($stubMessage);
1703 * Outputs a debug backtrace and stops further script execution
1705 * @param $message An optional message to output
1706 * @param $doExit Whether exit the program (true is default)
1709 public function debugBackTrace ($message = '', $doExit = true) {
1710 // Sorry, there is no other way getting this nice backtrace
1711 if (!empty($message)) {
1713 printf('Message: %s<br />' . PHP_EOL, $message);
1717 debug_print_backtrace();
1721 if ($doExit === true) {
1727 * Creates an instance of a debugger instance
1729 * @param $className Name of the class (currently unsupported)
1730 * @param $lineNumber Line number where the call was made
1731 * @return $debugInstance An instance of a debugger class
1732 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1734 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1735 // Is the instance set?
1736 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1737 // Init debug instance
1738 $debugInstance = NULL;
1742 // Get a debugger instance
1743 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1744 } catch (NullPointerException $e) {
1745 // Didn't work, no instance there
1746 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1749 // Empty string should be ignored and used for testing the middleware
1750 DebugMiddleware::getSelfInstance()->output('');
1752 // Set it in registry
1753 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1755 // Get instance from registry
1756 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1760 return $debugInstance;
1764 * Simple output of a message with line-break
1766 * @param $message Message to output
1769 public function outputLine ($message) {
1771 print($message . PHP_EOL);
1775 * Outputs a debug message whether to debug instance (should be set!) or
1776 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1777 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1779 * @param $message Message we shall send out...
1780 * @param $doPrint Whether print or die here (default: print)
1781 * @paran $stripTags Whether to strip tags (default: false)
1784 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1785 // Set debug instance to NULL
1786 $debugInstance = NULL;
1789 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1791 // Is function partialStub/__callStatic ?
1792 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1793 // Prepend class::function:line from 3rd element
1794 $message = sprintf('[%s::%s:%d]: %s',
1795 $backtrace[2]['class'],
1796 $backtrace[2]['function'],
1797 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1801 // Prepend class::function:line from 2nd element
1802 $message = sprintf('[%s::%s:%d]: %s',
1803 $backtrace[1]['class'],
1804 $backtrace[1]['function'],
1805 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1812 // Get debug instance
1813 $debugInstance = $this->getDebugInstance();
1814 } catch (NullPointerException $e) {
1815 // The debug instance is not set (yet)
1818 // Is the debug instance there?
1819 if (is_object($debugInstance)) {
1820 // Use debug output handler
1821 $debugInstance->output($message, $stripTags);
1823 if ($doPrint === false) {
1824 // Die here if not printed
1828 // Are debug times enabled?
1829 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1831 $message = $this->getPrintableExecutionTime() . $message;
1835 if ($doPrint === true) {
1837 $this->outputLine($message);
1846 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1848 * @param $str The string, what ever it is needs to be converted
1849 * @return $className Generated class name
1851 public static final function convertToClassName ($str) {
1855 // Convert all dashes in underscores
1856 $str = StringUtils::convertDashesToUnderscores($str);
1858 // Now use that underscores to get classname parts for hungarian style
1859 foreach (explode('_', $str) as $strPart) {
1860 // Make the class name part lower case and first upper case
1861 $className .= ucfirst(strtolower($strPart));
1864 // Return class name
1869 * Marks up the code by adding e.g. line numbers
1871 * @param $phpCode Unmarked PHP code
1872 * @return $markedCode Marked PHP code
1874 public function markupCode ($phpCode) {
1879 $errorArray = error_get_last();
1881 // Init the code with error message
1882 if (is_array($errorArray)) {
1884 $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>',
1885 basename($errorArray['file']),
1886 $errorArray['line'],
1887 $errorArray['message'],
1892 // Add line number to the code
1893 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1895 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1897 htmlentities($code, ENT_QUOTES)
1906 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1907 * beatiful for web-based front-ends. If null is given a message id
1908 * null_timestamp will be resolved and returned.
1910 * @param $timestamp Timestamp to prepare (filter) for display
1911 * @return $readable A readable timestamp
1913 public function doFilterFormatTimestamp ($timestamp) {
1914 // Default value to return
1917 // Is the timestamp null?
1918 if (is_null($timestamp)) {
1919 // Get a message string
1920 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1922 switch ($this->getLanguageInstance()->getLanguageCode()) {
1923 case 'de': // German format is a bit different to default
1924 // Split the GMT stamp up
1925 $dateTime = explode(' ', $timestamp );
1926 $dateArray = explode('-', $dateTime[0]);
1927 $timeArray = explode(':', $dateTime[1]);
1929 // Construct the timestamp
1930 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1940 default: // Default is pass-through
1941 $readable = $timestamp;
1951 * Filter a given number into a localized number
1953 * @param $value The raw value from e.g. database
1954 * @return $localized Localized value
1956 public function doFilterFormatNumber ($value) {
1957 // Generate it from config and localize dependencies
1958 switch ($this->getLanguageInstance()->getLanguageCode()) {
1959 case 'de': // German format is a bit different to default
1960 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1963 default: // US, etc.
1964 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1973 * "Getter" for databse entry
1975 * @return $entry An array with database entries
1976 * @throws NullPointerException If the database result is not found
1977 * @throws InvalidDatabaseResultException If the database result is invalid
1979 protected final function getDatabaseEntry () {
1980 // Is there an instance?
1981 if (!$this->getResultInstance() instanceof SearchableResult) {
1982 // Throw an exception here
1983 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1987 $this->getResultInstance()->rewind();
1989 // Do we have an entry?
1990 if ($this->getResultInstance()->valid() === false) {
1991 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
1992 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1996 $this->getResultInstance()->next();
1999 $entry = $this->getResultInstance()->current();
2006 * Getter for field name
2008 * @param $fieldName Field name which we shall get
2009 * @return $fieldValue Field value from the user
2010 * @throws NullPointerException If the result instance is null
2012 public final function getField ($fieldName) {
2013 // Default field value
2016 // Get result instance
2017 $resultInstance = $this->getResultInstance();
2019 // Is this instance null?
2020 if (is_null($resultInstance)) {
2021 // Then the user instance is no longer valid (expired cookies?)
2022 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2025 // Get current array
2026 $fieldArray = $resultInstance->current();
2027 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2029 // Convert dashes to underscore
2030 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
2032 // Does the field exist?
2033 if ($this->isFieldSet($fieldName)) {
2035 $fieldValue = $fieldArray[$fieldName2];
2036 } elseif (defined('DEVELOPER')) {
2037 // Missing field entry, may require debugging
2038 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2040 // Missing field entry, may require debugging
2041 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2049 * Checks if given field is set
2051 * @param $fieldName Field name to check
2052 * @return $isSet Whether the given field name is set
2053 * @throws NullPointerException If the result instance is null
2055 public function isFieldSet ($fieldName) {
2056 // Get result instance
2057 $resultInstance = $this->getResultInstance();
2059 // Is this instance null?
2060 if (is_null($resultInstance)) {
2061 // Then the user instance is no longer valid (expired cookies?)
2062 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2065 // Get current array
2066 $fieldArray = $resultInstance->current();
2067 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2069 // Convert dashes to underscore
2070 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
2073 $isSet = isset($fieldArray[$fieldName]);
2080 * Flushs all pending updates to the database layer
2084 public function flushPendingUpdates () {
2085 // Get result instance
2086 $resultInstance = $this->getResultInstance();
2088 // Do we have data to update?
2089 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2090 // Get wrapper class name config entry
2091 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2093 // Create object instance
2094 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2096 // Yes, then send the whole result to the database layer
2097 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2102 * Outputs a deprecation warning to the developer.
2104 * @param $message The message we shall output to the developer
2106 * @todo Write a logging mechanism for productive mode
2108 public function deprecationWarning ($message) {
2109 // Is developer mode active?
2110 if (defined('DEVELOPER')) {
2111 // Debug instance is there?
2112 if (!is_null($this->getDebugInstance())) {
2113 // Output stub message
2114 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2117 trigger_error($message . "<br />\n");
2121 // @TODO Finish this part!
2122 $this->partialStub('Developer mode inactive. Message:' . $message);
2127 * Checks whether the given PHP extension is loaded
2129 * @param $phpExtension The PHP extension we shall check
2130 * @return $isLoaded Whether the PHP extension is loaded
2132 public final function isPhpExtensionLoaded ($phpExtension) {
2134 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2141 * "Getter" as a time() replacement but with milliseconds. You should use this
2142 * method instead of the encapsulated getimeofday() function.
2144 * @return $milliTime Timestamp with milliseconds
2146 public function getMilliTime () {
2147 // Get the time of day as float
2148 $milliTime = gettimeofday(true);
2155 * Idles (sleeps) for given milliseconds
2157 * @return $hasSlept Whether it goes fine
2159 public function idle ($milliSeconds) {
2160 // Sleep is fine by default
2163 // Idle so long with found function
2164 if (function_exists('time_sleep_until')) {
2165 // Get current time and add idle time
2166 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2168 // New PHP 5.1.0 function found, ignore errors
2169 $hasSlept = @time_sleep_until($sleepUntil);
2172 * My Sun station doesn't have that function even with latest PHP
2175 usleep($milliSeconds * 1000);
2182 * Converts a hexadecimal string, even with negative sign as first string to
2183 * a decimal number using BC functions.
2185 * This work is based on comment #86673 on php.net documentation page at:
2186 * <http://de.php.net/manual/en/function.dechex.php#86673>
2188 * @param $hex Hexadecimal string
2189 * @return $dec Decimal number
2191 protected function hex2dec ($hex) {
2192 // Convert to all lower-case
2193 $hex = strtolower($hex);
2195 // Detect sign (negative/positive numbers)
2197 if (substr($hex, 0, 1) == '-') {
2199 $hex = substr($hex, 1);
2202 // Decode the hexadecimal string into a decimal number
2204 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2205 $factor = self::$hexdec[substr($hex, $i, 1)];
2206 $dec = bcadd($dec, bcmul($factor, $e));
2209 // Return the decimal number
2210 return $sign . $dec;
2214 * Converts even very large decimal numbers, also signed, to a hexadecimal
2217 * This work is based on comment #97756 on php.net documentation page at:
2218 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2220 * @param $dec Decimal number, even with negative sign
2221 * @param $maxLength Optional maximum length of the string
2222 * @return $hex Hexadecimal string
2224 protected function dec2hex ($dec, $maxLength = 0) {
2225 // maxLength can be zero or devideable by 2
2226 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2228 // Detect sign (negative/positive numbers)
2235 // Encode the decimal number into a hexadecimal string
2238 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2240 } while ($dec >= 1);
2243 * Leading zeros are required for hex-decimal "numbers". In some
2244 * situations more leading zeros are wanted, so check for both
2247 if ($maxLength > 0) {
2248 // Prepend more zeros
2249 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2250 } elseif ((strlen($hex) % 2) != 0) {
2251 // Only make string's length dividable by 2
2255 // Return the hexadecimal string
2256 return $sign . $hex;
2260 * Converts a ASCII string (0 to 255) into a decimal number.
2262 * @param $asc The ASCII string to be converted
2263 * @return $dec Decimal number
2265 protected function asc2dec ($asc) {
2266 // Convert it into a hexadecimal number
2267 $hex = bin2hex($asc);
2269 // And back into a decimal number
2270 $dec = $this->hex2dec($hex);
2277 * Converts a decimal number into an ASCII string.
2279 * @param $dec Decimal number
2280 * @return $asc An ASCII string
2282 protected function dec2asc ($dec) {
2283 // First convert the number into a hexadecimal string
2284 $hex = $this->dec2hex($dec);
2286 // Then convert it into the ASCII string
2287 $asc = $this->hex2asc($hex);
2294 * Converts a hexadecimal number into an ASCII string. Negative numbers
2297 * @param $hex Hexadecimal string
2298 * @return $asc An ASCII string
2300 protected function hex2asc ($hex) {
2301 // Check for length, it must be devideable by 2
2302 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2303 assert((strlen($hex) % 2) == 0);
2307 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2308 // Get the decimal number of the chunk
2309 $part = hexdec(substr($hex, $idx, 2));
2311 // Add it to the final string
2315 // Return the final string
2320 * Checks whether the given encoded data was encoded with Base64
2322 * @param $encodedData Encoded data we shall check
2323 * @return $isBase64 Whether the encoded data is Base64
2325 protected function isBase64Encoded ($encodedData) {
2327 $isBase64 = (@base64_decode($encodedData, true) !== false);
2334 * Gets a cache key from Criteria instance
2336 * @param $criteriaInstance An instance of a Criteria class
2337 * @param $onlyKeys Only use these keys for a cache key
2338 * @return $cacheKey A cache key suitable for lookup/storage purposes
2340 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2342 $cacheKey = sprintf('%s@%s',
2343 $this->__toString(),
2344 $criteriaInstance->getCacheKey($onlyKeys)
2348 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2353 * Getter for startup time in miliseconds
2355 * @return $startupTime Startup time in miliseconds
2357 protected function getStartupTime () {
2358 return self::$startupTime;
2362 * "Getter" for a printable currently execution time in nice braces
2364 * @return $executionTime Current execution time in nice braces
2366 protected function getPrintableExecutionTime () {
2367 // Caculate the execution time
2368 $executionTime = microtime(true) - $this->getStartupTime();
2370 // Pack it in nice braces
2371 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2374 return $executionTime;
2378 * Hashes a given string with a simple but stronger hash function (no salt)
2379 * and hex-encode it.
2381 * @param $str The string to be hashed
2382 * @return $hash The hash from string $str
2384 public static final function hash ($str) {
2385 // Hash given string with (better secure) hasher
2386 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2393 * "Getter" for length of hash() output. This will be "cached" to speed up
2396 * @return $length Length of hash() output
2398 public static final function getHashLength () {
2400 if (is_null(self::$hashLength)) {
2401 // No, then hash a string and save its length.
2402 self::$hashLength = strlen(self::hash('abc123'));
2406 return self::$hashLength;
2410 * Checks whether the given number is really a number (only chars 0-9).
2412 * @param $num A string consisting only chars between 0 and 9
2413 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2414 * @param $assertMismatch Whether to assert mismatches
2415 * @return $ret The (hopefully) secured numbered value
2417 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2418 // Filter all numbers out
2419 $ret = preg_replace('/[^0123456789]/', '', $num);
2422 if ($castValue === true) {
2423 // Cast to biggest numeric type
2424 $ret = (double) $ret;
2427 // Assert only if requested
2428 if ($assertMismatch === true) {
2429 // Has the whole value changed?
2430 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2438 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2440 * @param $num A string consisting only chars between 0 and 9
2441 * @param $assertMismatch Whether to assert mismatches
2442 * @return $ret The (hopefully) secured hext-numbered value
2444 public function hexval ($num, $assertMismatch = false) {
2445 // Filter all numbers out
2446 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2448 // Assert only if requested
2449 if ($assertMismatch === true) {
2450 // Has the whole value changed?
2451 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2459 * Determines if an element is set in the generic array
2461 * @param $keyGroup Main group for the key
2462 * @param $subGroup Sub group for the key
2463 * @param $key Key to check
2464 * @param $element Element to check
2465 * @return $isset Whether the given key is set
2467 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2469 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2472 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2478 * Determines if a key is set in the generic array
2480 * @param $keyGroup Main group for the key
2481 * @param $subGroup Sub group for the key
2482 * @param $key Key to check
2483 * @return $isset Whether the given key is set
2485 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2487 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2490 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2498 * Determines if a group is set in the generic array
2500 * @param $keyGroup Main group
2501 * @param $subGroup Sub group
2502 * @return $isset Whether the given group is set
2504 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2506 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2509 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2516 * Getter for sub key group
2518 * @param $keyGroup Main key group
2519 * @param $subGroup Sub key group
2520 * @return $array An array with all array elements
2522 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2524 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2525 // No, then abort here
2526 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2531 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2534 return $this->genericArray[$keyGroup][$subGroup];
2538 * Unsets a given key in generic array
2540 * @param $keyGroup Main group for the key
2541 * @param $subGroup Sub group for the key
2542 * @param $key Key to unset
2545 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2547 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2550 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2554 * Unsets a given element in generic array
2556 * @param $keyGroup Main group for the key
2557 * @param $subGroup Sub group for the key
2558 * @param $key Key to unset
2559 * @param $element Element to unset
2562 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2564 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2567 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2571 * Append a string to a given generic array key
2573 * @param $keyGroup Main group for the key
2574 * @param $subGroup Sub group for the key
2575 * @param $key Key to unset
2576 * @param $value Value to add/append
2579 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2581 //* 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);
2583 // Is it already there?
2584 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2586 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2589 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2594 * Append a string to a given generic array element
2596 * @param $keyGroup Main group for the key
2597 * @param $subGroup Sub group for the key
2598 * @param $key Key to unset
2599 * @param $element Element to check
2600 * @param $value Value to add/append
2603 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2605 //* 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);
2607 // Is it already there?
2608 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2610 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2613 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2618 * Sets a string in a given generic array element
2620 * @param $keyGroup Main group for the key
2621 * @param $subGroup Sub group for the key
2622 * @param $key Key to unset
2623 * @param $element Element to check
2624 * @param $value Value to add/append
2627 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2629 //* 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 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2636 * Initializes given generic array group
2638 * @param $keyGroup Main group for the key
2639 * @param $subGroup Sub group for the key
2640 * @param $key Key to use
2641 * @param $forceInit Optionally force initialization
2644 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2646 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2648 // Is it already set?
2649 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2650 // Already initialized
2651 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2656 $this->genericArray[$keyGroup][$subGroup] = array();
2660 * Initializes given generic array key
2662 * @param $keyGroup Main group for the key
2663 * @param $subGroup Sub group for the key
2664 * @param $key Key to use
2665 * @param $forceInit Optionally force initialization
2668 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2670 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2672 // Is it already set?
2673 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2674 // Already initialized
2675 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2680 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2684 * Initializes 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 use
2689 * @param $element Element to use
2690 * @param $forceInit Optionally force initialization
2693 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2695 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2697 // Is it already set?
2698 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2699 // Already initialized
2700 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2705 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2709 * Pushes an element to a generic key
2711 * @param $keyGroup Main group for the key
2712 * @param $subGroup Sub group for the key
2713 * @param $key Key to use
2714 * @param $value Value to add/append
2715 * @return $count Number of array elements
2717 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2719 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2722 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2724 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2728 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2731 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2732 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2737 * Pushes an element to a generic array element
2739 * @param $keyGroup Main group for the key
2740 * @param $subGroup Sub group for the key
2741 * @param $key Key to use
2742 * @param $element Element to check
2743 * @param $value Value to add/append
2744 * @return $count Number of array elements
2746 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2748 //* 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));
2751 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2753 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2757 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2760 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2761 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2766 * Pops an element from a generic group
2768 * @param $keyGroup Main group for the key
2769 * @param $subGroup Sub group for the key
2770 * @param $key Key to unset
2771 * @return $value Last "popped" value
2773 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2775 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2778 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2780 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2785 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2788 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2789 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2794 * Shifts an element from a generic group
2796 * @param $keyGroup Main group for the key
2797 * @param $subGroup Sub group for the key
2798 * @param $key Key to unset
2799 * @return $value Last "popped" value
2801 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2803 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2806 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2808 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2813 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2816 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2817 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2822 * Count generic array group
2824 * @param $keyGroup Main group for the key
2825 * @return $count Count of given group
2827 protected final function countGenericArray ($keyGroup) {
2829 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2832 if (!isset($this->genericArray[$keyGroup])) {
2834 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2839 $count = count($this->genericArray[$keyGroup]);
2842 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2849 * Count generic array sub group
2851 * @param $keyGroup Main group for the key
2852 * @param $subGroup Sub group for the key
2853 * @return $count Count of given group
2855 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2857 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2860 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2862 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2867 $count = count($this->genericArray[$keyGroup][$subGroup]);
2870 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2877 * Count generic array elements
2879 * @param $keyGroup Main group for the key
2880 * @param $subGroup Sub group for the key
2881 * @para $key Key to count
2882 * @return $count Count of given key
2884 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2886 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2889 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2891 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2893 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2895 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2900 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2903 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2910 * Getter for whole generic group array
2912 * @param $keyGroup Key group to get
2913 * @return $array Whole generic array group
2915 protected final function getGenericArray ($keyGroup) {
2917 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2920 if (!isset($this->genericArray[$keyGroup])) {
2922 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2927 return $this->genericArray[$keyGroup];
2931 * Setter for generic array key
2933 * @param $keyGroup Key group to get
2934 * @param $subGroup Sub group for the key
2935 * @param $key Key to unset
2936 * @param $value Mixed value from generic array element
2939 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2941 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2944 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2948 * Getter for generic array key
2950 * @param $keyGroup Key group to get
2951 * @param $subGroup Sub group for the key
2952 * @param $key Key to unset
2953 * @return $value Mixed value from generic array element
2955 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2957 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2960 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2962 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2967 return $this->genericArray[$keyGroup][$subGroup][$key];
2971 * Sets a value in given generic array key/element
2973 * @param $keyGroup Main group for the key
2974 * @param $subGroup Sub group for the key
2975 * @param $key Key to set
2976 * @param $element Element to set
2977 * @param $value Value to set
2980 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2982 //* 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));
2985 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2989 * Getter for generic array element
2991 * @param $keyGroup Key group to get
2992 * @param $subGroup Sub group for the key
2993 * @param $key Key to look for
2994 * @param $element Element to look for
2995 * @return $value Mixed value from generic array element
2997 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2999 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3002 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3004 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3009 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3013 * Checks if a given sub group is valid (array)
3015 * @param $keyGroup Key group to get
3016 * @param $subGroup Sub group for the key
3017 * @return $isValid Whether given sub group is valid
3019 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3021 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3024 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3031 * Checks if a given key is valid (array)
3033 * @param $keyGroup Key group to get
3034 * @param $subGroup Sub group for the key
3035 * @param $key Key to check
3036 * @return $isValid Whether given sub group is valid
3038 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3040 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3043 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3050 * Initializes the web output instance
3054 protected function initWebOutputInstance () {
3055 // Get application instance
3056 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
3058 // Init web output instance
3059 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3062 $this->setWebOutputInstance($outputInstance);
3066 * Translates boolean true to 'Y' and false to 'N'
3068 * @param $boolean Boolean value
3069 * @return $translated Translated boolean value
3071 public static final function translateBooleanToYesNo ($boolean) {
3072 // Make sure it is really boolean
3073 assert(is_bool($boolean));
3076 $translated = ($boolean === true) ? 'Y' : 'N';
3078 // ... and return it
3083 * Encodes raw data (almost any type) by "serializing" it and then pack it
3084 * into a "binary format".
3086 * @param $rawData Raw data (almost any type)
3087 * @return $encoded Encoded data
3089 protected function encodeData ($rawData) {
3090 // Make sure no objects or resources pass through
3091 assert(!is_object($rawData));
3092 assert(!is_resource($rawData));
3094 // First "serialize" it (json_encode() is faster than serialize())
3095 $encoded = $this->packString(json_encode($rawData));
3102 * Pack a string into a "binary format". Please execuse me that this is
3103 * widely undocumented. :-(
3105 * @param $str Unpacked string
3106 * @return $packed Packed string
3107 * @todo Improve documentation
3109 protected function packString ($str) {
3111 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3113 // First compress the string (gzcompress is okay)
3114 $str = gzcompress($str);
3119 // And start the "encoding" loop
3120 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3122 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3123 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3125 if (($idx + $i) <= strlen($str)) {
3126 $ord = ord(substr($str, ($idx + $i), 1));
3128 $add = $ord * pow(256, $factor);
3132 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3136 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3137 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3139 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3140 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3146 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3151 * Creates a full-qualified file name (FQFN) for given file name by adding
3152 * a configured temporary file path to it.
3154 * @param $infoInstance An instance of a SplFileInfo class
3155 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3156 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3157 * @throws FileIoException If the file cannot be written
3159 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3161 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3163 // Is the path writeable?
3164 if (!is_writable($basePath)) {
3165 // Path is write-protected
3166 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3170 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3173 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3175 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3179 return $tempInstance;
3183 * "Getter" for a printable state name
3185 * @return $stateName Name of the node's state in a printable format
3187 public final function getPrintableState () {
3188 // Default is 'null'
3189 $stateName = 'null';
3191 // Get the state instance
3192 $stateInstance = $this->getStateInstance();
3194 // Is it an instance of Stateable?
3195 if ($stateInstance instanceof Stateable) {
3196 // Then use that state name
3197 $stateName = $stateInstance->getStateName();