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 - 2020 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 $genericArray = array();
283 private $commandName = '';
288 private $controllerName = '';
291 * Array with bitmasks and such for pack/unpack methods to support both
292 * 32-bit and 64-bit systems
294 private $packingData = array(
297 'left' => 0xffff0000,
298 'right' => 0x0000ffff,
304 'left' => 0xffffffff00000000,
305 'right' => 0x00000000ffffffff,
312 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
314 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
316 private $archArrayElement = false;
318 /***********************
319 * Exception codes.... *
320 ***********************/
322 // @todo Try to clean these constants up
323 const EXCEPTION_IS_NULL_POINTER = 0x001;
324 const EXCEPTION_IS_NO_OBJECT = 0x002;
325 const EXCEPTION_IS_NO_ARRAY = 0x003;
326 const EXCEPTION_MISSING_METHOD = 0x004;
327 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
328 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
329 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
330 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
331 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
332 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
333 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
334 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
335 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
336 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
337 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
338 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
339 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
340 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
341 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
342 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
343 const EXCEPTION_PATH_NOT_FOUND = 0x015;
344 const EXCEPTION_INVALID_PATH_NAME = 0x016;
345 const EXCEPTION_READ_PROTECED_PATH = 0x017;
346 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
347 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
348 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
349 const EXCEPTION_INVALID_RESOURCE = 0x01b;
350 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
351 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
352 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
353 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
354 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
355 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
356 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
357 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
358 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
359 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
360 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
361 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
362 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
363 const EXCEPTION_INVALID_STRING = 0x029;
364 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
365 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
366 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
367 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
368 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
369 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
370 const EXCEPTION_MISSING_ELEMENT = 0x030;
371 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
372 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
373 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
374 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
375 const EXCEPTION_FATAL_ERROR = 0x035;
376 const EXCEPTION_FILE_NOT_FOUND = 0x036;
377 const EXCEPTION_ASSERTION_FAILED = 0x037;
378 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
379 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
380 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
381 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
382 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
383 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
384 const EXCEPTION_INVALID_SOCKET = 0x03e;
385 const EXCEPTION_SELF_INSTANCE = 0x03f;
388 * Hexadecimal->Decimal translation array
390 private static $hexdec = array(
410 * Decimal->hexadecimal translation array
412 private static $dechex = array(
432 * Startup time in miliseconds
434 private static $startupTime = 0;
437 * Protected super constructor
439 * @param $className Name of the class
442 protected function __construct ($className) {
444 $this->setRealClass($className);
446 // Set configuration instance if no registry ...
447 if (!$this instanceof Register) {
448 // ... because registries doesn't need to be configured
449 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
452 // Is the startup time set? (0 cannot be true anymore)
453 if (self::$startupTime == 0) {
455 self::$startupTime = microtime(true);
459 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
463 * Destructor for all classes. You should not call this method on your own.
467 public function __destruct () {
468 // Flush any updated entries to the database
469 $this->flushPendingUpdates();
471 // Is this object already destroyed?
472 if ($this->__toString() != 'DestructedObject') {
473 // Destroy all informations about this class but keep some text about it alive
474 $this->setRealClass('DestructedObject');
475 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
476 // Already destructed object
477 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
481 // Do not call this twice
482 trigger_error(__METHOD__ . ': Called twice.');
488 * The __call() method where all non-implemented methods end up
490 * @param $methodName Name of the missing method
491 * @args $args Arguments passed to the method
494 public final function __call ($methodName, $args) {
496 self::$instance = $this;
498 // Call static method
499 self::__callStatic($methodName, $args);
501 // Clear self-instance
502 self::$instance = NULL;
506 * The __callStatic() method where all non-implemented static methods end up
508 * @param $methodName Name of the missing method
509 * @param $args Arguments passed to the method
511 * @throws InvalidArgumentException If self::$instance is not a framework's own object
513 public static final function __callStatic ($methodName, $args) {
515 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
517 // Init argument string and class name
519 $className = 'unknown';
521 // Is self-instance set?
522 if (self::$instance instanceof FrameworkInterface) {
523 // Framework's own instance
524 $className = self::$instance->__toString();
525 } elseif (!is_null(self::$instance)) {
527 throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$instance)), self::EXCEPTION_SELF_INSTANCE);
530 // Is it NULL, empty or an array?
531 if (is_null($args)) {
533 $argsString = 'NULL';
534 } elseif (is_array($args)) {
538 // Some arguments are there
539 foreach ($args as $arg) {
540 // Add data about the argument
541 $argsString .= gettype($arg) . ':';
544 // Found a NULL argument
545 $argsString .= 'NULL';
546 } elseif (is_string($arg)) {
547 // Add length for strings
548 $argsString .= strlen($arg);
549 } elseif ((is_int($arg)) || (is_float($arg))) {
552 } elseif (is_array($arg)) {
553 // .. or size if array
554 $argsString .= count($arg);
555 } elseif (is_object($arg)) {
557 $reflection = new ReflectionClass($arg);
559 // Is an other object, maybe no __toString() available
560 $argsString .= $reflection->getName();
561 } elseif ($arg === true) {
562 // ... is boolean 'true'
563 $argsString .= 'true';
564 } elseif ($arg === false) {
565 // ... is boolean 'false'
566 $argsString .= 'false';
569 // Comma for next one
574 if (substr($argsString, -2, 1) == ',') {
576 $argsString = substr($argsString, 0, -2);
582 // Invalid arguments!
583 $argsString = sprintf('!INVALID:%s!', gettype($args));
586 // Output stub message
587 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
588 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s::%s]: Stub! Args: %s',
599 * Getter for $realClass
601 * @return $realClass The name of the real class (not BaseFrameworkSystem)
603 public function __toString () {
604 return $this->realClass;
608 * Magic method to catch setting of missing but set class fields/attributes
610 * @param $name Name of the field/attribute
611 * @param $value Value to store
614 public final function __set ($name, $value) {
615 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
618 print_r($value, true)
623 * Magic method to catch getting of missing fields/attributes
625 * @param $name Name of the field/attribute
628 public final function __get ($name) {
629 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
635 * Magic method to catch unsetting of missing fields/attributes
637 * @param $name Name of the field/attribute
640 public final function __unset ($name) {
641 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
647 * Magic method to catch object serialization
649 * @return $unsupported Unsupported method
650 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
652 public final function __sleep () {
653 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
657 * Magic method to catch object deserialization
659 * @return $unsupported Unsupported method
660 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
662 public final function __wakeup () {
663 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
667 * Magic method to catch calls when an object instance is called
669 * @return $unsupported Unsupported method
670 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
672 public final function __invoke () {
673 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
677 * Setter for the real class name
679 * @param $realClass Class name (string)
682 public final function setRealClass ($realClass) {
684 $this->realClass = (string) $realClass;
688 * Setter for database result instance
690 * @param $resultInstance An instance of a database result class
692 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
694 protected final function setResultInstance (SearchableResult $resultInstance) {
695 $this->resultInstance = $resultInstance;
699 * Getter for database result instance
701 * @return $resultInstance An instance of a database result class
703 public final function getResultInstance () {
704 return $this->resultInstance;
708 * Setter for template engine instances
710 * @param $templateInstance An instance of a template engine class
713 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
714 $this->templateInstance = $templateInstance;
718 * Getter for template engine instances
720 * @return $templateInstance An instance of a template engine class
722 protected final function getTemplateInstance () {
723 return $this->templateInstance;
727 * Setter for search instance
729 * @param $searchInstance Searchable criteria instance
732 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
733 $this->searchInstance = $searchInstance;
737 * Getter for search instance
739 * @return $searchInstance Searchable criteria instance
741 public final function getSearchInstance () {
742 return $this->searchInstance;
746 * Setter for update instance
748 * @param $updateInstance An instance of a LocalUpdateCriteria clase
751 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
752 $this->updateInstance = $updateInstance;
756 * Getter for update instance
758 * @return $updateInstance Updateable criteria instance
760 public final function getUpdateInstance () {
761 return $this->updateInstance;
765 * Setter for resolver instance
767 * @param $resolverInstance Instance of a command resolver class
770 public final function setResolverInstance (Resolver $resolverInstance) {
771 $this->resolverInstance = $resolverInstance;
775 * Getter for resolver instance
777 * @return $resolverInstance Instance of a command resolver class
779 public final function getResolverInstance () {
780 return $this->resolverInstance;
784 * Setter for language instance
786 * @param $configInstance The configuration instance which shall
787 * be FrameworkConfiguration
790 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
791 GenericRegistry::getRegistry()->addInstance('config', $configInstance);
795 * Getter for configuration instance
797 * @return $configInstance Configuration instance
799 public final function getConfigInstance () {
800 $configInstance = GenericRegistry::getRegistry()->getInstance('config');
801 return $configInstance;
805 * Setter for debug instance
807 * @param $debugInstance The instance for debug output class
810 public final function setDebugInstance (DebugMiddleware $debugInstance) {
811 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
815 * Getter for debug instance
817 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
819 public final function getDebugInstance () {
820 // Get debug instance
821 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
824 return $debugInstance;
828 * Setter for web output instance
830 * @param $webInstance The instance for web output class
833 public final function setWebOutputInstance (OutputStreamer $webInstance) {
834 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
838 * Getter for web output instance
840 * @return $webOutputInstance - Instance to class WebOutput
842 public final function getWebOutputInstance () {
843 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
844 return $webOutputInstance;
848 * Setter for database instance
850 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
853 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
854 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
858 * Getter for database layer
860 * @return $databaseInstance The database layer instance
862 public final function getDatabaseInstance () {
864 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
867 return $databaseInstance;
871 * Setter for compressor channel
873 * @param $compressorInstance An instance of CompressorChannel
876 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
877 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
881 * Getter for compressor channel
883 * @return $compressorInstance The compressor channel
885 public final function getCompressorChannel () {
886 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
887 return $compressorInstance;
891 * Private getter for language instance
893 * @return $langInstance An instance to the language sub-system
895 protected final function getLanguageInstance () {
896 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
897 return $langInstance;
901 * Setter for language instance
903 * @param $langInstance An instance to the language sub-system
905 * @see LanguageSystem
907 public final function setLanguageInstance (ManageableLanguage $langInstance) {
908 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
912 * Private getter for file IO instance
914 * @return $fileIoInstance An instance to the file I/O sub-system
916 protected final function getFileIoInstance () {
917 return $this->fileIoInstance;
921 * Setter for file I/O instance
923 * @param $fileIoInstance An instance to the file I/O sub-system
926 public final function setFileIoInstance (IoHandler $fileIoInstance) {
927 $this->fileIoInstance = $fileIoInstance;
931 * Protected setter for user instance
933 * @param $userInstance An instance of a user class
936 protected final function setUserInstance (ManageableAccount $userInstance) {
937 $this->userInstance = $userInstance;
941 * Getter for user instance
943 * @return $userInstance An instance of a user class
945 public final function getUserInstance () {
946 return $this->userInstance;
950 * Setter for controller instance (this surely breaks a bit the MVC patterm)
952 * @param $controllerInstance An instance of the controller
955 public final function setControllerInstance (Controller $controllerInstance) {
956 $this->controllerInstance = $controllerInstance;
960 * Getter for controller instance (this surely breaks a bit the MVC patterm)
962 * @return $controllerInstance An instance of the controller
964 public final function getControllerInstance () {
965 return $this->controllerInstance;
969 * Setter for RNG instance
971 * @param $rngInstance An instance of a random number generator (RNG)
974 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
975 $this->rngInstance = $rngInstance;
979 * Getter for RNG instance
981 * @return $rngInstance An instance of a random number generator (RNG)
983 public final function getRngInstance () {
984 return $this->rngInstance;
988 * Setter for Cryptable instance
990 * @param $cryptoInstance An instance of a Cryptable class
993 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
994 $this->cryptoInstance = $cryptoInstance;
998 * Getter for Cryptable instance
1000 * @return $cryptoInstance An instance of a Cryptable class
1002 public final function getCryptoInstance () {
1003 return $this->cryptoInstance;
1007 * Setter for the list instance
1009 * @param $listInstance A list of Listable
1012 protected final function setListInstance (Listable $listInstance) {
1013 $this->listInstance = $listInstance;
1017 * Getter for the list instance
1019 * @return $listInstance A list of Listable
1021 protected final function getListInstance () {
1022 return $this->listInstance;
1026 * Setter for the menu instance
1028 * @param $menuInstance A RenderableMenu instance
1031 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1032 $this->menuInstance = $menuInstance;
1036 * Getter for the menu instance
1038 * @return $menuInstance A RenderableMenu instance
1040 protected final function getMenuInstance () {
1041 return $this->menuInstance;
1045 * Setter for image instance
1047 * @param $imageInstance An instance of an image
1050 public final function setImageInstance (BaseImage $imageInstance) {
1051 $this->imageInstance = $imageInstance;
1055 * Getter for image instance
1057 * @return $imageInstance An instance of an image
1059 public final function getImageInstance () {
1060 return $this->imageInstance;
1064 * Setter for stacker instance
1066 * @param $stackInstance An instance of an stacker
1069 public final function setStackInstance (Stackable $stackInstance) {
1070 $this->stackInstance = $stackInstance;
1074 * Getter for stacker instance
1076 * @return $stackInstance An instance of an stacker
1078 public final function getStackInstance () {
1079 return $this->stackInstance;
1083 * Setter for compressor instance
1085 * @param $compressorInstance An instance of an compressor
1088 public final function setCompressorInstance (Compressor $compressorInstance) {
1089 $this->compressorInstance = $compressorInstance;
1093 * Getter for compressor instance
1095 * @return $compressorInstance An instance of an compressor
1097 public final function getCompressorInstance () {
1098 return $this->compressorInstance;
1102 * Setter for Parseable instance
1104 * @param $parserInstance An instance of an Parseable
1107 public final function setParserInstance (Parseable $parserInstance) {
1108 $this->parserInstance = $parserInstance;
1112 * Getter for Parseable instance
1114 * @return $parserInstance An instance of an Parseable
1116 public final function getParserInstance () {
1117 return $this->parserInstance;
1121 * Setter for DatabaseWrapper instance
1123 * @param $wrapperInstance An instance of an DatabaseWrapper
1126 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1127 $this->wrapperInstance = $wrapperInstance;
1131 * Getter for DatabaseWrapper instance
1133 * @return $wrapperInstance An instance of an DatabaseWrapper
1135 public final function getWrapperInstance () {
1136 return $this->wrapperInstance;
1140 * Setter for helper instance
1142 * @param $helperInstance An instance of a helper class
1145 protected final function setHelperInstance (Helper $helperInstance) {
1146 $this->helperInstance = $helperInstance;
1150 * Getter for helper instance
1152 * @return $helperInstance An instance of a helper class
1154 public final function getHelperInstance () {
1155 return $this->helperInstance;
1159 * Getter for a InputStream instance
1161 * @param $inputStreamInstance The InputStream instance
1163 protected final function getInputStreamInstance () {
1164 return $this->inputStreamInstance;
1168 * Setter for a InputStream instance
1170 * @param $inputStreamInstance The InputStream instance
1173 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1174 $this->inputStreamInstance = $inputStreamInstance;
1178 * Getter for a OutputStream instance
1180 * @param $outputStreamInstance The OutputStream instance
1182 protected final function getOutputStreamInstance () {
1183 return $this->outputStreamInstance;
1187 * Setter for a OutputStream instance
1189 * @param $outputStreamInstance The OutputStream instance
1192 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1193 $this->outputStreamInstance = $outputStreamInstance;
1197 * Setter for handler instance
1199 * @param $handlerInstance An instance of a Handleable class
1202 protected final function setHandlerInstance (Handleable $handlerInstance) {
1203 $this->handlerInstance = $handlerInstance;
1207 * Getter for handler instance
1209 * @return $handlerInstance A Handleable instance
1211 protected final function getHandlerInstance () {
1212 return $this->handlerInstance;
1216 * Setter for visitor instance
1218 * @param $visitorInstance A Visitor instance
1221 protected final function setVisitorInstance (Visitor $visitorInstance) {
1222 $this->visitorInstance = $visitorInstance;
1226 * Getter for visitor instance
1228 * @return $visitorInstance A Visitor instance
1230 protected final function getVisitorInstance () {
1231 return $this->visitorInstance;
1235 * Setter for Iterator instance
1237 * @param $iteratorInstance An instance of an Iterator
1240 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1241 $this->iteratorInstance = $iteratorInstance;
1245 * Getter for Iterator instance
1247 * @return $iteratorInstance An instance of an Iterator
1249 public final function getIteratorInstance () {
1250 return $this->iteratorInstance;
1254 * Setter for FilePointer instance
1256 * @param $pointerInstance An instance of an FilePointer class
1259 protected final function setPointerInstance (FilePointer $pointerInstance) {
1260 $this->pointerInstance = $pointerInstance;
1264 * Getter for FilePointer instance
1266 * @return $pointerInstance An instance of an FilePointer class
1268 public final function getPointerInstance () {
1269 return $this->pointerInstance;
1273 * Unsets pointer instance which triggers a call of __destruct() if the
1274 * instance is still there. This is surely not fatal on already "closed"
1275 * file pointer instances.
1277 * I don't want to mess around with above setter by giving it a default
1278 * value NULL as setter should always explicitly only set (existing) object
1279 * instances and NULL is NULL.
1283 protected final function unsetPointerInstance () {
1284 // Simply it to NULL
1285 $this->pointerInstance = NULL;
1289 * Setter for Indexable instance
1291 * @param $indexInstance An instance of an Indexable class
1294 protected final function setIndexInstance (Indexable $indexInstance) {
1295 $this->indexInstance = $indexInstance;
1299 * Getter for Indexable instance
1301 * @return $indexInstance An instance of an Indexable class
1303 public final function getIndexInstance () {
1304 return $this->indexInstance;
1308 * Setter for Block instance
1310 * @param $blockInstance An instance of an Block class
1313 protected final function setBlockInstance (Block $blockInstance) {
1314 $this->blockInstance = $blockInstance;
1318 * Getter for Block instance
1320 * @return $blockInstance An instance of an Block class
1322 public final function getBlockInstance () {
1323 return $this->blockInstance;
1327 * Setter for Minable instance
1329 * @param $minableInstance A Minable instance
1332 protected final function setMinableInstance (Minable $minableInstance) {
1333 $this->minableInstance = $minableInstance;
1337 * Getter for minable instance
1339 * @return $minableInstance A Minable instance
1341 protected final function getMinableInstance () {
1342 return $this->minableInstance;
1346 * Setter for FrameworkDirectory instance
1348 * @param $directoryInstance A FrameworkDirectory instance
1351 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1352 $this->directoryInstance = $directoryInstance;
1356 * Getter for FrameworkDirectory instance
1358 * @return $directoryInstance A FrameworkDirectory instance
1360 protected final function getDirectoryInstance () {
1361 return $this->directoryInstance;
1365 * Setter for state instance
1367 * @param $stateInstance A Stateable instance
1370 public final function setStateInstance (Stateable $stateInstance) {
1371 $this->stateInstance = $stateInstance;
1375 * Getter for state instance
1377 * @return $stateInstance A Stateable instance
1379 public final function getStateInstance () {
1380 return $this->stateInstance;
1384 * Setter for output instance
1386 * @param $outputInstance The debug output instance
1389 public final function setOutputInstance (OutputStreamer $outputInstance) {
1390 $this->outputInstance = $outputInstance;
1394 * Getter for output instance
1396 * @return $outputInstance The debug output instance
1398 public final function getOutputInstance () {
1399 return $this->outputInstance;
1403 * Setter for registry instance
1405 * @param $registryInstance An instance of a Register class
1408 protected final function setRegistryInstance (Register $registryInstance) {
1409 $this->registryInstance = $registryInstance;
1413 * Getter for registry instance
1415 * @return $registryInstance The debug registry instance
1417 public final function getRegistryInstance () {
1418 return $this->registryInstance;
1422 * Setter for call-back instance
1424 * @param $callbackInstance An instance of a FrameworkInterface class
1427 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1428 $this->callbackInstance = $callbackInstance;
1432 * Getter for call-back instance
1434 * @return $callbackInstance An instance of a FrameworkInterface class
1436 protected final function getCallbackInstance () {
1437 return $this->callbackInstance;
1441 * Setter for command name
1443 * @param $commandName Last validated command name
1446 protected final function setCommandName ($commandName) {
1447 $this->commandName = $commandName;
1451 * Getter for command name
1453 * @return $commandName Last validated command name
1455 protected final function getCommandName () {
1456 return $this->commandName;
1460 * Setter for controller name
1462 * @param $controllerName Last validated controller name
1465 protected final function setControllerName ($controllerName) {
1466 $this->controllerName = $controllerName;
1470 * Getter for controller name
1472 * @return $controllerName Last validated controller name
1474 protected final function getControllerName () {
1475 return $this->controllerName;
1479 * Checks whether an object equals this object. You should overwrite this
1480 * method to implement own equality checks
1482 * @param $objectInstance An instance of a FrameworkInterface object
1483 * @return $equals Whether both objects equals
1485 public function equals (FrameworkInterface $objectInstance) {
1488 $this->__toString() == $objectInstance->__toString()
1490 $this->hashCode() == $objectInstance->hashCode()
1493 // Return the result
1498 * Generates a generic hash code of this class. You should really overwrite
1499 * this method with your own hash code generator code. But keep KISS in mind.
1501 * @return $hashCode A generic hash code respresenting this whole class
1503 public function hashCode () {
1505 return crc32($this->__toString());
1509 * Formats computer generated price values into human-understandable formats
1510 * with thousand and decimal separators.
1512 * @param $value The in computer format value for a price
1513 * @param $currency The currency symbol (use HTML-valid characters!)
1514 * @param $decNum Number of decimals after commata
1515 * @return $price The for the current language formated price string
1516 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1517 * thousands separator
1520 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1521 // Are all required attriutes set?
1522 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1523 // Throw an exception
1524 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1528 $value = (float) $value;
1530 // Reformat the US number
1531 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1533 // Return as string...
1538 * Appends a trailing slash to a string
1540 * @param $str A string (maybe) without trailing slash
1541 * @return $str A string with an auto-appended trailing slash
1543 public final function addMissingTrailingSlash ($str) {
1544 // Is there a trailing slash?
1545 if (substr($str, -1, 1) != '/') {
1549 // Return string with trailing slash
1554 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1555 * application helper instance (ApplicationHelper by default).
1557 * @param $applicationInstance An application helper instance or
1558 * null if we shall use the default
1559 * @return $templateInstance The template engine instance
1560 * @throws NullPointerException If the discovered application
1561 * instance is still null
1563 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1564 // Is the application instance set?
1565 if (is_null($applicationInstance)) {
1566 // Get the current instance
1567 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1570 if (is_null($applicationInstance)) {
1571 // Thrown an exception
1572 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1576 // Initialize the template engine
1577 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1579 // Return the prepared instance
1580 return $templateInstance;
1584 * Debugs this instance by putting out it's full content
1586 * @param $message Optional message to show in debug output
1589 public final function debugInstance ($message = '') {
1590 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1591 restore_error_handler();
1596 // Is a message set?
1597 if (!empty($message)) {
1598 // Construct message
1599 $content = sprintf('<div class="debug_message">
1601 </div>' . PHP_EOL, $message);
1604 // Generate the output
1605 $content .= sprintf('<pre>%s</pre>',
1608 print_r($this, true)
1614 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1617 <div class="debug_content">
1621 <div class="debug_include_list">
1624 $this->__toString(),
1626 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1631 * Replaces control characters with printable output
1633 * @param $str String with control characters
1634 * @return $str Replaced string
1636 protected function replaceControlCharacters ($str) {
1639 chr(13), '[r]', str_replace(
1640 chr(10), '[n]', str_replace(
1650 * Output a partial stub message for the caller method
1652 * @param $message An optional message to display
1655 protected function partialStub ($message = '') {
1657 $stubMessage = 'Partial stub!';
1659 // Is an extra message given?
1660 if (!empty($message)) {
1661 // Then add it as well
1662 $stubMessage .= ' Message: ' . $message;
1665 // Debug instance is there?
1666 if (!is_null($this->getDebugInstance())) {
1667 // Output stub message
1668 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1671 trigger_error($stubMessage);
1677 * Outputs a debug backtrace and stops further script execution
1679 * @param $message An optional message to output
1680 * @param $doExit Whether exit the program (true is default)
1683 public function debugBackTrace ($message = '', $doExit = true) {
1684 // Sorry, there is no other way getting this nice backtrace
1685 if (!empty($message)) {
1687 printf('Message: %s<br />' . PHP_EOL, $message);
1691 debug_print_backtrace();
1695 if ($doExit === true) {
1701 * Creates an instance of a debugger instance
1703 * @param $className Name of the class (currently unsupported)
1704 * @param $lineNumber Line number where the call was made
1705 * @return $debugInstance An instance of a debugger class
1706 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1708 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1709 // Is the instance set?
1710 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1711 // Init debug instance
1712 $debugInstance = NULL;
1716 // Get a debugger instance
1717 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1718 } catch (NullPointerException $e) {
1719 // Didn't work, no instance there
1720 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1723 // Empty string should be ignored and used for testing the middleware
1724 DebugMiddleware::getSelfInstance()->output('');
1726 // Set it in registry
1727 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1729 // Get instance from registry
1730 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1734 return $debugInstance;
1738 * Simple output of a message with line-break
1740 * @param $message Message to output
1743 public function outputLine ($message) {
1745 print($message . PHP_EOL);
1749 * Outputs a debug message whether to debug instance (should be set!) or
1750 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1751 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1753 * @param $message Message we shall send out...
1754 * @param $doPrint Whether print or die here (default: print)
1755 * @paran $stripTags Whether to strip tags (default: false)
1758 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1759 // Set debug instance to NULL
1760 $debugInstance = NULL;
1763 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1765 // Is function partialStub/__callStatic ?
1766 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1767 // Prepend class::function:line from 3rd element
1768 $message = sprintf('[%s::%s:%d]: %s',
1769 $backtrace[2]['class'],
1770 $backtrace[2]['function'],
1771 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1775 // Prepend class::function:line from 2nd element
1776 $message = sprintf('[%s::%s:%d]: %s',
1777 $backtrace[1]['class'],
1778 $backtrace[1]['function'],
1779 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1786 // Get debug instance
1787 $debugInstance = $this->getDebugInstance();
1788 } catch (NullPointerException $e) {
1789 // The debug instance is not set (yet)
1792 // Is the debug instance there?
1793 if (is_object($debugInstance)) {
1794 // Use debug output handler
1795 $debugInstance->output($message, $stripTags);
1797 if ($doPrint === false) {
1798 // Die here if not printed
1802 // Are debug times enabled?
1803 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1805 $message = $this->getPrintableExecutionTime() . $message;
1809 if ($doPrint === true) {
1811 $this->outputLine($message);
1820 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1822 * @param $str The string, what ever it is needs to be converted
1823 * @return $className Generated class name
1825 public static final function convertToClassName ($str) {
1829 // Convert all dashes in underscores
1830 $str = StringUtils::convertDashesToUnderscores($str);
1832 // Now use that underscores to get classname parts for hungarian style
1833 foreach (explode('_', $str) as $strPart) {
1834 // Make the class name part lower case and first upper case
1835 $className .= ucfirst(strtolower($strPart));
1838 // Return class name
1843 * Marks up the code by adding e.g. line numbers
1845 * @param $phpCode Unmarked PHP code
1846 * @return $markedCode Marked PHP code
1848 public function markupCode ($phpCode) {
1853 $errorArray = error_get_last();
1855 // Init the code with error message
1856 if (is_array($errorArray)) {
1858 $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>',
1859 basename($errorArray['file']),
1860 $errorArray['line'],
1861 $errorArray['message'],
1866 // Add line number to the code
1867 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1869 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1871 htmlentities($code, ENT_QUOTES)
1880 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1881 * beatiful for web-based front-ends. If null is given a message id
1882 * null_timestamp will be resolved and returned.
1884 * @param $timestamp Timestamp to prepare (filter) for display
1885 * @return $readable A readable timestamp
1887 public function doFilterFormatTimestamp ($timestamp) {
1888 // Default value to return
1891 // Is the timestamp null?
1892 if (is_null($timestamp)) {
1893 // Get a message string
1894 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1896 switch ($this->getLanguageInstance()->getLanguageCode()) {
1897 case 'de': // German format is a bit different to default
1898 // Split the GMT stamp up
1899 $dateTime = explode(' ', $timestamp );
1900 $dateArray = explode('-', $dateTime[0]);
1901 $timeArray = explode(':', $dateTime[1]);
1903 // Construct the timestamp
1904 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1914 default: // Default is pass-through
1915 $readable = $timestamp;
1925 * Filter a given number into a localized number
1927 * @param $value The raw value from e.g. database
1928 * @return $localized Localized value
1930 public function doFilterFormatNumber ($value) {
1931 // Generate it from config and localize dependencies
1932 switch ($this->getLanguageInstance()->getLanguageCode()) {
1933 case 'de': // German format is a bit different to default
1934 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1937 default: // US, etc.
1938 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1947 * "Getter" for databse entry
1949 * @return $entry An array with database entries
1950 * @throws NullPointerException If the database result is not found
1951 * @throws InvalidDatabaseResultException If the database result is invalid
1953 protected final function getDatabaseEntry () {
1954 // Is there an instance?
1955 if (!$this->getResultInstance() instanceof SearchableResult) {
1956 // Throw an exception here
1957 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1961 $this->getResultInstance()->rewind();
1963 // Do we have an entry?
1964 if ($this->getResultInstance()->valid() === false) {
1965 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
1966 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1970 $this->getResultInstance()->next();
1973 $entry = $this->getResultInstance()->current();
1980 * Getter for field name
1982 * @param $fieldName Field name which we shall get
1983 * @return $fieldValue Field value from the user
1984 * @throws NullPointerException If the result instance is null
1986 public final function getField ($fieldName) {
1987 // Default field value
1990 // Get result instance
1991 $resultInstance = $this->getResultInstance();
1993 // Is this instance null?
1994 if (is_null($resultInstance)) {
1995 // Then the user instance is no longer valid (expired cookies?)
1996 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1999 // Get current array
2000 $fieldArray = $resultInstance->current();
2001 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2003 // Convert dashes to underscore
2004 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
2006 // Does the field exist?
2007 if ($this->isFieldSet($fieldName)) {
2009 $fieldValue = $fieldArray[$fieldName2];
2010 } elseif (defined('DEVELOPER')) {
2011 // Missing field entry, may require debugging
2012 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2014 // Missing field entry, may require debugging
2015 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2023 * Checks if given field is set
2025 * @param $fieldName Field name to check
2026 * @return $isSet Whether the given field name is set
2027 * @throws NullPointerException If the result instance is null
2029 public function isFieldSet ($fieldName) {
2030 // Get result instance
2031 $resultInstance = $this->getResultInstance();
2033 // Is this instance null?
2034 if (is_null($resultInstance)) {
2035 // Then the user instance is no longer valid (expired cookies?)
2036 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2039 // Get current array
2040 $fieldArray = $resultInstance->current();
2041 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2043 // Convert dashes to underscore
2044 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
2047 $isSet = isset($fieldArray[$fieldName]);
2054 * Flushs all pending updates to the database layer
2058 public function flushPendingUpdates () {
2059 // Get result instance
2060 $resultInstance = $this->getResultInstance();
2062 // Do we have data to update?
2063 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2064 // Get wrapper class name config entry
2065 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2067 // Create object instance
2068 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2070 // Yes, then send the whole result to the database layer
2071 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2076 * Outputs a deprecation warning to the developer.
2078 * @param $message The message we shall output to the developer
2080 * @todo Write a logging mechanism for productive mode
2082 public function deprecationWarning ($message) {
2083 // Is developer mode active?
2084 if (defined('DEVELOPER')) {
2085 // Debug instance is there?
2086 if (!is_null($this->getDebugInstance())) {
2087 // Output stub message
2088 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2091 trigger_error($message . "<br />\n");
2095 // @TODO Finish this part!
2096 $this->partialStub('Developer mode inactive. Message:' . $message);
2101 * Checks whether the given PHP extension is loaded
2103 * @param $phpExtension The PHP extension we shall check
2104 * @return $isLoaded Whether the PHP extension is loaded
2106 public final function isPhpExtensionLoaded ($phpExtension) {
2108 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2115 * "Getter" as a time() replacement but with milliseconds. You should use this
2116 * method instead of the encapsulated getimeofday() function.
2118 * @return $milliTime Timestamp with milliseconds
2120 public function getMilliTime () {
2121 // Get the time of day as float
2122 $milliTime = gettimeofday(true);
2129 * Idles (sleeps) for given milliseconds
2131 * @return $hasSlept Whether it goes fine
2133 public function idle ($milliSeconds) {
2134 // Sleep is fine by default
2137 // Idle so long with found function
2138 if (function_exists('time_sleep_until')) {
2139 // Get current time and add idle time
2140 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2142 // New PHP 5.1.0 function found, ignore errors
2143 $hasSlept = @time_sleep_until($sleepUntil);
2146 * My Sun station doesn't have that function even with latest PHP
2149 usleep($milliSeconds * 1000);
2156 * Converts a hexadecimal string, even with negative sign as first string to
2157 * a decimal number using BC functions.
2159 * This work is based on comment #86673 on php.net documentation page at:
2160 * <http://de.php.net/manual/en/function.dechex.php#86673>
2162 * @param $hex Hexadecimal string
2163 * @return $dec Decimal number
2165 protected function hex2dec ($hex) {
2166 // Convert to all lower-case
2167 $hex = strtolower($hex);
2169 // Detect sign (negative/positive numbers)
2171 if (substr($hex, 0, 1) == '-') {
2173 $hex = substr($hex, 1);
2176 // Decode the hexadecimal string into a decimal number
2178 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2179 $factor = self::$hexdec[substr($hex, $i, 1)];
2180 $dec = bcadd($dec, bcmul($factor, $e));
2183 // Return the decimal number
2184 return $sign . $dec;
2188 * Converts even very large decimal numbers, also signed, to a hexadecimal
2191 * This work is based on comment #97756 on php.net documentation page at:
2192 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2194 * @param $dec Decimal number, even with negative sign
2195 * @param $maxLength Optional maximum length of the string
2196 * @return $hex Hexadecimal string
2198 protected function dec2hex ($dec, $maxLength = 0) {
2199 // maxLength can be zero or devideable by 2
2200 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2202 // Detect sign (negative/positive numbers)
2209 // Encode the decimal number into a hexadecimal string
2212 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2214 } while ($dec >= 1);
2217 * Leading zeros are required for hex-decimal "numbers". In some
2218 * situations more leading zeros are wanted, so check for both
2221 if ($maxLength > 0) {
2222 // Prepend more zeros
2223 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2224 } elseif ((strlen($hex) % 2) != 0) {
2225 // Only make string's length dividable by 2
2229 // Return the hexadecimal string
2230 return $sign . $hex;
2234 * Converts a ASCII string (0 to 255) into a decimal number.
2236 * @param $asc The ASCII string to be converted
2237 * @return $dec Decimal number
2239 protected function asc2dec ($asc) {
2240 // Convert it into a hexadecimal number
2241 $hex = bin2hex($asc);
2243 // And back into a decimal number
2244 $dec = $this->hex2dec($hex);
2251 * Converts a decimal number into an ASCII string.
2253 * @param $dec Decimal number
2254 * @return $asc An ASCII string
2256 protected function dec2asc ($dec) {
2257 // First convert the number into a hexadecimal string
2258 $hex = $this->dec2hex($dec);
2260 // Then convert it into the ASCII string
2261 $asc = $this->hex2asc($hex);
2268 * Converts a hexadecimal number into an ASCII string. Negative numbers
2271 * @param $hex Hexadecimal string
2272 * @return $asc An ASCII string
2274 protected function hex2asc ($hex) {
2275 // Check for length, it must be devideable by 2
2276 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2277 assert((strlen($hex) % 2) == 0);
2281 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2282 // Get the decimal number of the chunk
2283 $part = hexdec(substr($hex, $idx, 2));
2285 // Add it to the final string
2289 // Return the final string
2294 * Checks whether the given encoded data was encoded with Base64
2296 * @param $encodedData Encoded data we shall check
2297 * @return $isBase64 Whether the encoded data is Base64
2299 protected function isBase64Encoded ($encodedData) {
2301 $isBase64 = (@base64_decode($encodedData, true) !== false);
2308 * Gets a cache key from Criteria instance
2310 * @param $criteriaInstance An instance of a Criteria class
2311 * @param $onlyKeys Only use these keys for a cache key
2312 * @return $cacheKey A cache key suitable for lookup/storage purposes
2314 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2316 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: criteriaInstance=' . $criteriaInstance->__toString() . ',onlyKeys()=' . count($onlyKeys) . ' - CALLED!');
2317 $cacheKey = sprintf('%s@%s',
2318 $this->__toString(),
2319 $criteriaInstance->getCacheKey($onlyKeys)
2323 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
2328 * Getter for startup time in miliseconds
2330 * @return $startupTime Startup time in miliseconds
2332 protected function getStartupTime () {
2333 return self::$startupTime;
2337 * "Getter" for a printable currently execution time in nice braces
2339 * @return $executionTime Current execution time in nice braces
2341 protected function getPrintableExecutionTime () {
2342 // Caculate the execution time
2343 $executionTime = microtime(true) - $this->getStartupTime();
2345 // Pack it in nice braces
2346 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2349 return $executionTime;
2353 * Hashes a given string with a simple but stronger hash function (no salt)
2354 * and hex-encode it.
2356 * @param $str The string to be hashed
2357 * @return $hash The hash from string $str
2359 public static final function hash ($str) {
2360 // Hash given string with (better secure) hasher
2361 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2368 * "Getter" for length of hash() output. This will be "cached" to speed up
2371 * @return $length Length of hash() output
2373 public static final function getHashLength () {
2375 if (is_null(self::$hashLength)) {
2376 // No, then hash a string and save its length.
2377 self::$hashLength = strlen(self::hash('abc123'));
2381 return self::$hashLength;
2385 * Checks whether the given number is really a number (only chars 0-9).
2387 * @param $num A string consisting only chars between 0 and 9
2388 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2389 * @param $assertMismatch Whether to assert mismatches
2390 * @return $ret The (hopefully) secured numbered value
2392 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2393 // Filter all numbers out
2394 $ret = preg_replace('/[^0123456789]/', '', $num);
2397 if ($castValue === true) {
2398 // Cast to biggest numeric type
2399 $ret = (double) $ret;
2402 // Assert only if requested
2403 if ($assertMismatch === true) {
2404 // Has the whole value changed?
2405 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2413 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2415 * @param $num A string consisting only chars between 0 and 9
2416 * @param $assertMismatch Whether to assert mismatches
2417 * @return $ret The (hopefully) secured hext-numbered value
2419 public function hexval ($num, $assertMismatch = false) {
2420 // Filter all numbers out
2421 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2423 // Assert only if requested
2424 if ($assertMismatch === true) {
2425 // Has the whole value changed?
2426 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2434 * Determines if an element is set in the generic array
2436 * @param $keyGroup Main group for the key
2437 * @param $subGroup Sub group for the key
2438 * @param $key Key to check
2439 * @param $element Element to check
2440 * @return $isset Whether the given key is set
2442 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2444 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2447 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2453 * Determines if a key is set in the generic array
2455 * @param $keyGroup Main group for the key
2456 * @param $subGroup Sub group for the key
2457 * @param $key Key to check
2458 * @return $isset Whether the given key is set
2460 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2462 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2465 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2473 * Determines if a group is set in the generic array
2475 * @param $keyGroup Main group
2476 * @param $subGroup Sub group
2477 * @return $isset Whether the given group is set
2479 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2481 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2484 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2491 * Getter for sub key group
2493 * @param $keyGroup Main key group
2494 * @param $subGroup Sub key group
2495 * @return $array An array with all array elements
2497 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2499 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2500 // No, then abort here
2501 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2506 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2509 return $this->genericArray[$keyGroup][$subGroup];
2513 * Unsets a given key in generic array
2515 * @param $keyGroup Main group for the key
2516 * @param $subGroup Sub group for the key
2517 * @param $key Key to unset
2520 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2522 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2525 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2529 * Unsets a given element in generic array
2531 * @param $keyGroup Main group for the key
2532 * @param $subGroup Sub group for the key
2533 * @param $key Key to unset
2534 * @param $element Element to unset
2537 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2539 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2542 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2546 * Append a string to a given generic array key
2548 * @param $keyGroup Main group for the key
2549 * @param $subGroup Sub group for the key
2550 * @param $key Key to unset
2551 * @param $value Value to add/append
2554 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2556 //* 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);
2558 // Is it already there?
2559 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2561 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2564 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2569 * Append a string to a given generic array element
2571 * @param $keyGroup Main group for the key
2572 * @param $subGroup Sub group for the key
2573 * @param $key Key to unset
2574 * @param $element Element to check
2575 * @param $value Value to add/append
2578 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2580 //* 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);
2582 // Is it already there?
2583 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2585 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2588 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2593 * Sets a string in a given generic array element
2595 * @param $keyGroup Main group for the key
2596 * @param $subGroup Sub group for the key
2597 * @param $key Key to unset
2598 * @param $element Element to check
2599 * @param $value Value to add/append
2602 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2604 //* 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 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2611 * Initializes given generic array group
2613 * @param $keyGroup Main group for the key
2614 * @param $subGroup Sub group for the key
2615 * @param $key Key to use
2616 * @param $forceInit Optionally force initialization
2619 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2621 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2623 // Is it already set?
2624 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2625 // Already initialized
2626 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2631 $this->genericArray[$keyGroup][$subGroup] = array();
2635 * Initializes given generic array key
2637 * @param $keyGroup Main group for the key
2638 * @param $subGroup Sub group for the key
2639 * @param $key Key to use
2640 * @param $forceInit Optionally force initialization
2643 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2645 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2647 // Is it already set?
2648 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2649 // Already initialized
2650 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2655 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2659 * Initializes given generic array element
2661 * @param $keyGroup Main group for the key
2662 * @param $subGroup Sub group for the key
2663 * @param $key Key to use
2664 * @param $element Element to use
2665 * @param $forceInit Optionally force initialization
2668 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2670 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2672 // Is it already set?
2673 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2674 // Already initialized
2675 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2680 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2684 * Pushes an element to a generic key
2686 * @param $keyGroup Main group for the key
2687 * @param $subGroup Sub group for the key
2688 * @param $key Key to use
2689 * @param $value Value to add/append
2690 * @return $count Number of array elements
2692 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2694 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2697 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2699 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2703 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2706 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2707 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2712 * Pushes an element to a generic array element
2714 * @param $keyGroup Main group for the key
2715 * @param $subGroup Sub group for the key
2716 * @param $key Key to use
2717 * @param $element Element to check
2718 * @param $value Value to add/append
2719 * @return $count Number of array elements
2721 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2723 //* 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));
2726 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2728 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2732 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2735 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2736 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2741 * Pops an element from a generic group
2743 * @param $keyGroup Main group for the key
2744 * @param $subGroup Sub group for the key
2745 * @param $key Key to unset
2746 * @return $value Last "popped" value
2748 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2750 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2753 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2755 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2760 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2763 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2764 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2769 * Shifts an element from a generic group
2771 * @param $keyGroup Main group for the key
2772 * @param $subGroup Sub group for the key
2773 * @param $key Key to unset
2774 * @return $value Last "popped" value
2776 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2778 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2781 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2783 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2788 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2791 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2792 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2797 * Count generic array group
2799 * @param $keyGroup Main group for the key
2800 * @return $count Count of given group
2802 protected final function countGenericArray ($keyGroup) {
2804 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2807 if (!isset($this->genericArray[$keyGroup])) {
2809 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2814 $count = count($this->genericArray[$keyGroup]);
2817 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2824 * Count generic array sub group
2826 * @param $keyGroup Main group for the key
2827 * @param $subGroup Sub group for the key
2828 * @return $count Count of given group
2830 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2832 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2835 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2837 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2842 $count = count($this->genericArray[$keyGroup][$subGroup]);
2845 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2852 * Count generic array elements
2854 * @param $keyGroup Main group for the key
2855 * @param $subGroup Sub group for the key
2856 * @para $key Key to count
2857 * @return $count Count of given key
2859 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2861 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2864 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2866 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2868 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2870 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2875 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2878 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2885 * Getter for whole generic group array
2887 * @param $keyGroup Key group to get
2888 * @return $array Whole generic array group
2890 protected final function getGenericArray ($keyGroup) {
2892 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2895 if (!isset($this->genericArray[$keyGroup])) {
2897 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2902 return $this->genericArray[$keyGroup];
2906 * Setter for generic array key
2908 * @param $keyGroup Key group to get
2909 * @param $subGroup Sub group for the key
2910 * @param $key Key to unset
2911 * @param $value Mixed value from generic array element
2914 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2916 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2919 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2923 * Getter for generic array key
2925 * @param $keyGroup Key group to get
2926 * @param $subGroup Sub group for the key
2927 * @param $key Key to unset
2928 * @return $value Mixed value from generic array element
2930 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2932 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2935 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2937 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2942 return $this->genericArray[$keyGroup][$subGroup][$key];
2946 * Sets a value in given generic array key/element
2948 * @param $keyGroup Main group for the key
2949 * @param $subGroup Sub group for the key
2950 * @param $key Key to set
2951 * @param $element Element to set
2952 * @param $value Value to set
2955 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2957 //* 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));
2960 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2964 * Getter for generic array element
2966 * @param $keyGroup Key group to get
2967 * @param $subGroup Sub group for the key
2968 * @param $key Key to look for
2969 * @param $element Element to look for
2970 * @return $value Mixed value from generic array element
2972 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2974 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2977 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2979 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2984 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2988 * Checks if a given sub group is valid (array)
2990 * @param $keyGroup Key group to get
2991 * @param $subGroup Sub group for the key
2992 * @return $isValid Whether given sub group is valid
2994 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2996 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2999 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3006 * Checks if a given key is valid (array)
3008 * @param $keyGroup Key group to get
3009 * @param $subGroup Sub group for the key
3010 * @param $key Key to check
3011 * @return $isValid Whether given sub group is valid
3013 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3015 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3018 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3025 * Initializes the web output instance
3029 protected function initWebOutputInstance () {
3030 // Get application instance
3031 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
3033 // Init web output instance
3034 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3037 $this->setWebOutputInstance($outputInstance);
3041 * Translates boolean true to 'Y' and false to 'N'
3043 * @param $boolean Boolean value
3044 * @return $translated Translated boolean value
3046 public static final function translateBooleanToYesNo ($boolean) {
3047 // Make sure it is really boolean
3048 assert(is_bool($boolean));
3051 $translated = ($boolean === true) ? 'Y' : 'N';
3053 // ... and return it
3058 * Encodes raw data (almost any type) by "serializing" it and then pack it
3059 * into a "binary format".
3061 * @param $rawData Raw data (almost any type)
3062 * @return $encoded Encoded data
3064 protected function encodeData ($rawData) {
3065 // Make sure no objects or resources pass through
3066 assert(!is_object($rawData));
3067 assert(!is_resource($rawData));
3069 // First "serialize" it (json_encode() is faster than serialize())
3070 $encoded = $this->packString(json_encode($rawData));
3077 * Pack a string into a "binary format". Please execuse me that this is
3078 * widely undocumented. :-(
3080 * @param $str Unpacked string
3081 * @return $packed Packed string
3082 * @todo Improve documentation
3084 protected function packString ($str) {
3086 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3088 // First compress the string (gzcompress is okay)
3089 $str = gzcompress($str);
3094 // And start the "encoding" loop
3095 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3097 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3098 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3100 if (($idx + $i) <= strlen($str)) {
3101 $ord = ord(substr($str, ($idx + $i), 1));
3103 $add = $ord * pow(256, $factor);
3107 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3111 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3112 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3114 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3115 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3121 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3126 * Creates a full-qualified file name (FQFN) for given file name by adding
3127 * a configured temporary file path to it.
3129 * @param $infoInstance An instance of a SplFileInfo class
3130 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3131 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3132 * @throws FileIoException If the file cannot be written
3134 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3136 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3138 // Is the path writeable?
3139 if (!is_writable($basePath)) {
3140 // Path is write-protected
3141 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3145 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3148 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3150 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3154 return $tempInstance;
3158 * "Getter" for a printable state name
3160 * @return $stateName Name of the node's state in a printable format
3162 public final function getPrintableState () {
3163 // Default is 'null'
3164 $stateName = 'null';
3166 // Get the state instance
3167 $stateInstance = $this->getStateInstance();
3169 // Is it an instance of Stateable?
3170 if ($stateInstance instanceof Stateable) {
3171 // Then use that state name
3172 $stateName = $stateInstance->getStateName();