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\Manager\ManageableApplication;
34 use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
35 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
36 use Org\Mxchange\CoreFramework\Parser\Parseable;
37 use Org\Mxchange\CoreFramework\Registry\Register;
38 use Org\Mxchange\CoreFramework\Registry\Registry;
39 use Org\Mxchange\CoreFramework\Resolver\Resolver;
40 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
41 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
42 use Org\Mxchange\CoreFramework\Stacker\Stackable;
43 use Org\Mxchange\CoreFramework\State\Stateable;
44 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
45 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
46 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
47 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
48 use Org\Mxchange\CoreFramework\User\ManageableAccount;
49 use Org\Mxchange\CoreFramework\Visitor\Visitor;
53 use \InvalidArgumentException;
59 * The simulator system class is the super class of all other classes. This
60 * class handles saving of games etc.
62 * @author Roland Haeder <webmaster@shipsimu.org>
64 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
65 * @license GNU GPL 3.0 or any newer version
66 * @link http://www.shipsimu.org
68 * This program is free software: you can redistribute it and/or modify
69 * it under the terms of the GNU General Public License as published by
70 * the Free Software Foundation, either version 3 of the License, or
71 * (at your option) any later version.
73 * This program is distributed in the hope that it will be useful,
74 * but WITHOUT ANY WARRANTY; without even the implied warranty of
75 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
76 * GNU General Public License for more details.
78 * You should have received a copy of the GNU General Public License
79 * along with this program. If not, see <http://www.gnu.org/licenses/>.
81 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
83 * Length of output from hash()
85 private static $hashLength = NULL;
90 private $realClass = 'BaseFrameworkSystem';
93 * Search criteria instance
95 private $searchInstance = NULL;
98 * Update criteria instance
100 private $updateInstance = NULL;
103 * The file I/O instance for the template loader
105 private $fileIoInstance = NULL;
110 private $resolverInstance = NULL;
113 * Template engine instance
115 private $templateInstance = NULL;
118 * Database result instance
120 private $resultInstance = NULL;
123 * Instance for user class
125 private $userInstance = NULL;
128 * A controller instance
130 private $controllerInstance = NULL;
135 private $rngInstance = NULL;
138 * Instance of a crypto helper
140 private $cryptoInstance = NULL;
143 * Instance of an Iterator class
145 private $iteratorInstance = NULL;
148 * Instance of the list
150 private $listInstance = NULL;
155 private $menuInstance = NULL;
158 * Instance of the image
160 private $imageInstance = NULL;
163 * Instance of the stacker
165 private $stackInstance = NULL;
168 * A Compressor instance
170 private $compressorInstance = NULL;
173 * A Parseable instance
175 private $parserInstance = NULL;
178 * A database wrapper instance
180 private $databaseInstance = NULL;
183 * A helper instance for the form
185 private $helperInstance = NULL;
188 * An instance of a Source class
190 private $sourceInstance = NULL;
193 * An instance of a UrlSource class
195 private $urlSourceInstance = NULL;
198 * An instance of a InputStream class
200 private $inputStreamInstance = NULL;
203 * An instance of a OutputStream class
205 private $outputStreamInstance = NULL;
210 private $handlerInstance = NULL;
213 * Visitor handler instance
215 private $visitorInstance = NULL;
218 * An instance of a database wrapper class
220 private $wrapperInstance = NULL;
223 * An instance of a file I/O pointer class (not handler)
225 private $pointerInstance = NULL;
228 * An instance of an Indexable class
230 private $indexInstance = NULL;
233 * An instance of a Block class
235 private $blockInstance = NULL;
240 private $minableInstance = NULL;
243 * A FrameworkDirectory instance
245 private $directoryInstance = NULL;
248 * The concrete output instance
250 private $outputInstance = NULL;
255 private $stateInstance = NULL;
258 * Registry instance (implementing Register)
260 private $registryInstance = NULL;
265 private $callbackInstance = NULL;
268 * Thousands separator
270 private $thousands = '.'; // German
275 private $decimals = ','; // German
280 private $socketResource = false;
283 * Regular expression to use for validation
285 private $regularExpression = '';
290 private $packageData = array();
295 private $genericArray = array();
300 private $commandName = '';
305 private $controllerName = '';
308 * Array with bitmasks and such for pack/unpack methods to support both
309 * 32-bit and 64-bit systems
311 private $packingData = array(
314 'left' => 0xffff0000,
315 'right' => 0x0000ffff,
321 'left' => 0xffffffff00000000,
322 'right' => 0x00000000ffffffff,
329 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
331 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
333 private $archArrayElement = false;
335 /***********************
336 * Exception codes.... *
337 ***********************/
339 // @todo Try to clean these constants up
340 const EXCEPTION_IS_NULL_POINTER = 0x001;
341 const EXCEPTION_IS_NO_OBJECT = 0x002;
342 const EXCEPTION_IS_NO_ARRAY = 0x003;
343 const EXCEPTION_MISSING_METHOD = 0x004;
344 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
345 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
346 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
347 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
348 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
349 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
350 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
351 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
352 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
353 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
354 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
355 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
356 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
357 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
358 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
359 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
360 const EXCEPTION_PATH_NOT_FOUND = 0x015;
361 const EXCEPTION_INVALID_PATH_NAME = 0x016;
362 const EXCEPTION_READ_PROTECED_PATH = 0x017;
363 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
364 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
365 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
366 const EXCEPTION_INVALID_RESOURCE = 0x01b;
367 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
368 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
369 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
370 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
371 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
372 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
373 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
374 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
375 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
376 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
377 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
378 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
379 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
380 const EXCEPTION_INVALID_STRING = 0x029;
381 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
382 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
383 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
384 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
385 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
386 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
387 const EXCEPTION_MISSING_ELEMENT = 0x030;
388 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
389 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
390 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
391 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
392 const EXCEPTION_FATAL_ERROR = 0x035;
393 const EXCEPTION_FILE_NOT_FOUND = 0x036;
394 const EXCEPTION_ASSERTION_FAILED = 0x037;
395 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
396 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
397 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
398 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
399 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
400 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
401 const EXCEPTION_INVALID_SOCKET = 0x03e;
404 * Hexadecimal->Decimal translation array
406 private static $hexdec = array(
426 * Decimal->hexadecimal translation array
428 private static $dechex = array(
448 * Startup time in miliseconds
450 private static $startupTime = 0;
453 * Protected super constructor
455 * @param $className Name of the class
458 protected function __construct ($className) {
460 $this->setRealClass($className);
462 // Set configuration instance if no registry ...
463 if (!$this instanceof Register) {
464 // ... because registries doesn't need to be configured
465 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
468 // Is the startup time set? (0 cannot be true anymore)
469 if (self::$startupTime == 0) {
471 self::$startupTime = microtime(true);
475 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
479 * Destructor for all classes. You should not call this method on your own.
483 public function __destruct () {
484 // Flush any updated entries to the database
485 $this->flushPendingUpdates();
487 // Is this object already destroyed?
488 if ($this->__toString() != 'DestructedObject') {
489 // Destroy all informations about this class but keep some text about it alive
490 $this->setRealClass('DestructedObject');
491 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
492 // Already destructed object
493 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
497 // Do not call this twice
498 trigger_error(__METHOD__ . ': Called twice.');
504 * The __call() method where all non-implemented methods end up
506 * @param $methodName Name of the missing method
507 * @args $args Arguments passed to the method
510 public final function __call ($methodName, $args) {
511 return self::__callStatic($methodName, $args);
515 * The __callStatic() method where all non-implemented static methods end up
517 * @param $methodName Name of the missing method
518 * @args $args Arguments passed to the method
521 public static final function __callStatic ($methodName, $args) {
523 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
525 // Init argument string
528 // Is it NULL, empty or an array?
529 if (is_null($args)) {
531 $argsString = 'NULL';
532 } elseif (is_array($args)) {
536 // Some arguments are there
537 foreach ($args as $arg) {
538 // Add data about the argument
539 $argsString .= gettype($arg) . ':';
542 // Found a NULL argument
543 $argsString .= 'NULL';
544 } elseif (is_string($arg)) {
545 // Add length for strings
546 $argsString .= strlen($arg);
547 } elseif ((is_int($arg)) || (is_float($arg))) {
550 } elseif (is_array($arg)) {
551 // .. or size if array
552 $argsString .= count($arg);
553 } elseif (is_object($arg)) {
555 $reflection = new ReflectionClass($arg);
557 // Is an other object, maybe no __toString() available
558 $argsString .= $reflection->getName();
559 } elseif ($arg === true) {
560 // ... is boolean 'true'
561 $argsString .= 'true';
562 } elseif ($arg === false) {
563 // ... is boolean 'false'
564 $argsString .= 'false';
567 // Comma for next one
572 if (substr($argsString, -2, 1) == ',') {
573 $argsString = substr($argsString, 0, -2);
579 // Invalid arguments!
580 $argsString = '!INVALID:' . gettype($args) . '!';
583 // Output stub message
584 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
585 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
595 * Getter for $realClass
597 * @return $realClass The name of the real class (not BaseFrameworkSystem)
599 public function __toString () {
600 return $this->realClass;
604 * Magic method to catch setting of missing but set class fields/attributes
606 * @param $name Name of the field/attribute
607 * @param $value Value to store
610 public final function __set ($name, $value) {
611 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
614 print_r($value, true)
619 * Magic method to catch getting of missing fields/attributes
621 * @param $name Name of the field/attribute
624 public final function __get ($name) {
625 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
631 * Magic method to catch unsetting of missing fields/attributes
633 * @param $name Name of the field/attribute
636 public final function __unset ($name) {
637 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
643 * Magic method to catch object serialization
645 * @return $unsupported Unsupported method
646 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
648 public final function __sleep () {
649 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
653 * Magic method to catch object deserialization
655 * @return $unsupported Unsupported method
656 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
658 public final function __wakeup () {
659 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
663 * Magic method to catch calls when an object instance is called
665 * @return $unsupported Unsupported method
666 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
668 public final function __invoke () {
669 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
673 * Setter for the real class name
675 * @param $realClass Class name (string)
678 public final function setRealClass ($realClass) {
680 $this->realClass = (string) $realClass;
684 * Setter for database result instance
686 * @param $resultInstance An instance of a database result class
688 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
690 protected final function setResultInstance (SearchableResult $resultInstance) {
691 $this->resultInstance = $resultInstance;
695 * Getter for database result instance
697 * @return $resultInstance An instance of a database result class
699 public final function getResultInstance () {
700 return $this->resultInstance;
704 * Setter for template engine instances
706 * @param $templateInstance An instance of a template engine class
709 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
710 $this->templateInstance = $templateInstance;
714 * Getter for template engine instances
716 * @return $templateInstance An instance of a template engine class
718 protected final function getTemplateInstance () {
719 return $this->templateInstance;
723 * Setter for search instance
725 * @param $searchInstance Searchable criteria instance
728 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
729 $this->searchInstance = $searchInstance;
733 * Getter for search instance
735 * @return $searchInstance Searchable criteria instance
737 public final function getSearchInstance () {
738 return $this->searchInstance;
742 * Setter for update instance
744 * @param $updateInstance An instance of a LocalUpdateCriteria clase
747 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
748 $this->updateInstance = $updateInstance;
752 * Getter for update instance
754 * @return $updateInstance Updateable criteria instance
756 public final function getUpdateInstance () {
757 return $this->updateInstance;
761 * Setter for resolver instance
763 * @param $resolverInstance Instance of a command resolver class
766 public final function setResolverInstance (Resolver $resolverInstance) {
767 $this->resolverInstance = $resolverInstance;
771 * Getter for resolver instance
773 * @return $resolverInstance Instance of a command resolver class
775 public final function getResolverInstance () {
776 return $this->resolverInstance;
780 * Setter for language instance
782 * @param $configInstance The configuration instance which shall
783 * be FrameworkConfiguration
786 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
787 Registry::getRegistry()->addInstance('config', $configInstance);
791 * Getter for configuration instance
793 * @return $configInstance Configuration instance
795 public final function getConfigInstance () {
796 $configInstance = Registry::getRegistry()->getInstance('config');
797 return $configInstance;
801 * Setter for debug instance
803 * @param $debugInstance The instance for debug output class
806 public final function setDebugInstance (DebugMiddleware $debugInstance) {
807 Registry::getRegistry()->addInstance('debug', $debugInstance);
811 * Getter for debug instance
813 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
815 public final function getDebugInstance () {
816 // Get debug instance
817 $debugInstance = Registry::getRegistry()->getInstance('debug');
820 return $debugInstance;
824 * Setter for web output instance
826 * @param $webInstance The instance for web output class
829 public final function setWebOutputInstance (OutputStreamer $webInstance) {
830 Registry::getRegistry()->addInstance('web_output', $webInstance);
834 * Getter for web output instance
836 * @return $webOutputInstance - Instance to class WebOutput
838 public final function getWebOutputInstance () {
839 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
840 return $webOutputInstance;
844 * Setter for database instance
846 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
849 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
850 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
854 * Getter for database layer
856 * @return $databaseInstance The database layer instance
858 public final function getDatabaseInstance () {
860 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
863 return $databaseInstance;
867 * Setter for compressor channel
869 * @param $compressorInstance An instance of CompressorChannel
872 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
873 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
877 * Getter for compressor channel
879 * @return $compressorInstance The compressor channel
881 public final function getCompressorChannel () {
882 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
883 return $compressorInstance;
887 * Protected getter for a manageable application helper class
889 * @return $applicationInstance An instance of a manageable application helper class
891 protected final function getApplicationInstance () {
892 $applicationInstance = Registry::getRegistry()->getInstance('app');
893 return $applicationInstance;
897 * Setter for a manageable application helper class
899 * @param $applicationInstance An instance of a manageable application helper class
902 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
903 Registry::getRegistry()->addInstance('application', $applicationInstance);
907 * Private getter for language instance
909 * @return $langInstance An instance to the language sub-system
911 protected final function getLanguageInstance () {
912 $langInstance = Registry::getRegistry()->getInstance('language');
913 return $langInstance;
917 * Setter for language instance
919 * @param $langInstance An instance to the language sub-system
921 * @see LanguageSystem
923 public final function setLanguageInstance (ManageableLanguage $langInstance) {
924 Registry::getRegistry()->addInstance('language', $langInstance);
928 * Private getter for file IO instance
930 * @return $fileIoInstance An instance to the file I/O sub-system
932 protected final function getFileIoInstance () {
933 return $this->fileIoInstance;
937 * Setter for file I/O instance
939 * @param $fileIoInstance An instance to the file I/O sub-system
942 public final function setFileIoInstance (IoHandler $fileIoInstance) {
943 $this->fileIoInstance = $fileIoInstance;
947 * Protected setter for user instance
949 * @param $userInstance An instance of a user class
952 protected final function setUserInstance (ManageableAccount $userInstance) {
953 $this->userInstance = $userInstance;
957 * Getter for user instance
959 * @return $userInstance An instance of a user class
961 public final function getUserInstance () {
962 return $this->userInstance;
966 * Setter for controller instance (this surely breaks a bit the MVC patterm)
968 * @param $controllerInstance An instance of the controller
971 public final function setControllerInstance (Controller $controllerInstance) {
972 $this->controllerInstance = $controllerInstance;
976 * Getter for controller instance (this surely breaks a bit the MVC patterm)
978 * @return $controllerInstance An instance of the controller
980 public final function getControllerInstance () {
981 return $this->controllerInstance;
985 * Setter for RNG instance
987 * @param $rngInstance An instance of a random number generator (RNG)
990 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
991 $this->rngInstance = $rngInstance;
995 * Getter for RNG instance
997 * @return $rngInstance An instance of a random number generator (RNG)
999 public final function getRngInstance () {
1000 return $this->rngInstance;
1004 * Setter for Cryptable instance
1006 * @param $cryptoInstance An instance of a Cryptable class
1009 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1010 $this->cryptoInstance = $cryptoInstance;
1014 * Getter for Cryptable instance
1016 * @return $cryptoInstance An instance of a Cryptable class
1018 public final function getCryptoInstance () {
1019 return $this->cryptoInstance;
1023 * Setter for the list instance
1025 * @param $listInstance A list of Listable
1028 protected final function setListInstance (Listable $listInstance) {
1029 $this->listInstance = $listInstance;
1033 * Getter for the list instance
1035 * @return $listInstance A list of Listable
1037 protected final function getListInstance () {
1038 return $this->listInstance;
1042 * Setter for the menu instance
1044 * @param $menuInstance A RenderableMenu instance
1047 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1048 $this->menuInstance = $menuInstance;
1052 * Getter for the menu instance
1054 * @return $menuInstance A RenderableMenu instance
1056 protected final function getMenuInstance () {
1057 return $this->menuInstance;
1061 * Setter for image instance
1063 * @param $imageInstance An instance of an image
1066 public final function setImageInstance (BaseImage $imageInstance) {
1067 $this->imageInstance = $imageInstance;
1071 * Getter for image instance
1073 * @return $imageInstance An instance of an image
1075 public final function getImageInstance () {
1076 return $this->imageInstance;
1080 * Setter for stacker instance
1082 * @param $stackInstance An instance of an stacker
1085 public final function setStackInstance (Stackable $stackInstance) {
1086 $this->stackInstance = $stackInstance;
1090 * Getter for stacker instance
1092 * @return $stackInstance An instance of an stacker
1094 public final function getStackInstance () {
1095 return $this->stackInstance;
1099 * Setter for compressor instance
1101 * @param $compressorInstance An instance of an compressor
1104 public final function setCompressorInstance (Compressor $compressorInstance) {
1105 $this->compressorInstance = $compressorInstance;
1109 * Getter for compressor instance
1111 * @return $compressorInstance An instance of an compressor
1113 public final function getCompressorInstance () {
1114 return $this->compressorInstance;
1118 * Setter for Parseable instance
1120 * @param $parserInstance An instance of an Parseable
1123 public final function setParserInstance (Parseable $parserInstance) {
1124 $this->parserInstance = $parserInstance;
1128 * Getter for Parseable instance
1130 * @return $parserInstance An instance of an Parseable
1132 public final function getParserInstance () {
1133 return $this->parserInstance;
1137 * Setter for DatabaseWrapper instance
1139 * @param $wrapperInstance An instance of an DatabaseWrapper
1142 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1143 $this->wrapperInstance = $wrapperInstance;
1147 * Getter for DatabaseWrapper instance
1149 * @return $wrapperInstance An instance of an DatabaseWrapper
1151 public final function getWrapperInstance () {
1152 return $this->wrapperInstance;
1156 * Setter for socket resource
1158 * @param $socketResource A valid socket resource
1161 public final function setSocketResource ($socketResource) {
1162 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1163 $this->socketResource = $socketResource;
1167 * Getter for socket resource
1169 * @return $socketResource A valid socket resource
1171 public final function getSocketResource () {
1172 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1173 return $this->socketResource;
1177 * Setter for regular expression
1179 * @param $regularExpression A valid regular expression
1182 public final function setRegularExpression ($regularExpression) {
1183 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1184 $this->regularExpression = $regularExpression;
1188 * Getter for regular expression
1190 * @return $regularExpression A valid regular expression
1192 public final function getRegularExpression () {
1193 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1194 return $this->regularExpression;
1198 * Setter for helper instance
1200 * @param $helperInstance An instance of a helper class
1203 protected final function setHelperInstance (Helper $helperInstance) {
1204 $this->helperInstance = $helperInstance;
1208 * Getter for helper instance
1210 * @return $helperInstance An instance of a helper class
1212 public final function getHelperInstance () {
1213 return $this->helperInstance;
1217 * Setter for a Source instance
1219 * @param $sourceInstance An instance of a Source class
1222 protected final function setSourceInstance (Source $sourceInstance) {
1223 $this->sourceInstance = $sourceInstance;
1227 * Getter for a Source instance
1229 * @return $sourceInstance An instance of a Source class
1231 protected final function getSourceInstance () {
1232 return $this->sourceInstance;
1236 * Setter for a UrlSource instance
1238 * @param $sourceInstance An instance of a UrlSource class
1241 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1242 $this->urlSourceInstance = $urlSourceInstance;
1246 * Getter for a UrlSource instance
1248 * @return $urlSourceInstance An instance of a UrlSource class
1250 protected final function getUrlSourceInstance () {
1251 return $this->urlSourceInstance;
1255 * Getter for a InputStream instance
1257 * @param $inputStreamInstance The InputStream instance
1259 protected final function getInputStreamInstance () {
1260 return $this->inputStreamInstance;
1264 * Setter for a InputStream instance
1266 * @param $inputStreamInstance The InputStream instance
1269 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1270 $this->inputStreamInstance = $inputStreamInstance;
1274 * Getter for a OutputStream instance
1276 * @param $outputStreamInstance The OutputStream instance
1278 protected final function getOutputStreamInstance () {
1279 return $this->outputStreamInstance;
1283 * Setter for a OutputStream instance
1285 * @param $outputStreamInstance The OutputStream instance
1288 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1289 $this->outputStreamInstance = $outputStreamInstance;
1293 * Setter for handler instance
1295 * @param $handlerInstance An instance of a Handleable class
1298 protected final function setHandlerInstance (Handleable $handlerInstance) {
1299 $this->handlerInstance = $handlerInstance;
1303 * Getter for handler instance
1305 * @return $handlerInstance A Handleable instance
1307 protected final function getHandlerInstance () {
1308 return $this->handlerInstance;
1312 * Setter for visitor instance
1314 * @param $visitorInstance A Visitor instance
1317 protected final function setVisitorInstance (Visitor $visitorInstance) {
1318 $this->visitorInstance = $visitorInstance;
1322 * Getter for visitor instance
1324 * @return $visitorInstance A Visitor instance
1326 protected final function getVisitorInstance () {
1327 return $this->visitorInstance;
1331 * Setter for raw package Data
1333 * @param $packageData Raw package Data
1336 public final function setPackageData (array $packageData) {
1337 $this->packageData = $packageData;
1341 * Getter for raw package Data
1343 * @return $packageData Raw package Data
1345 public function getPackageData () {
1346 return $this->packageData;
1351 * Setter for Iterator instance
1353 * @param $iteratorInstance An instance of an Iterator
1356 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1357 $this->iteratorInstance = $iteratorInstance;
1361 * Getter for Iterator instance
1363 * @return $iteratorInstance An instance of an Iterator
1365 public final function getIteratorInstance () {
1366 return $this->iteratorInstance;
1370 * Setter for FilePointer instance
1372 * @param $pointerInstance An instance of an FilePointer class
1375 protected final function setPointerInstance (FilePointer $pointerInstance) {
1376 $this->pointerInstance = $pointerInstance;
1380 * Getter for FilePointer instance
1382 * @return $pointerInstance An instance of an FilePointer class
1384 public final function getPointerInstance () {
1385 return $this->pointerInstance;
1389 * Unsets pointer instance which triggers a call of __destruct() if the
1390 * instance is still there. This is surely not fatal on already "closed"
1391 * file pointer instances.
1393 * I don't want to mess around with above setter by giving it a default
1394 * value NULL as setter should always explicitly only set (existing) object
1395 * instances and NULL is NULL.
1399 protected final function unsetPointerInstance () {
1400 // Simply it to NULL
1401 $this->pointerInstance = NULL;
1405 * Setter for Indexable instance
1407 * @param $indexInstance An instance of an Indexable class
1410 protected final function setIndexInstance (Indexable $indexInstance) {
1411 $this->indexInstance = $indexInstance;
1415 * Getter for Indexable instance
1417 * @return $indexInstance An instance of an Indexable class
1419 public final function getIndexInstance () {
1420 return $this->indexInstance;
1424 * Setter for Block instance
1426 * @param $blockInstance An instance of an Block class
1429 protected final function setBlockInstance (Block $blockInstance) {
1430 $this->blockInstance = $blockInstance;
1434 * Getter for Block instance
1436 * @return $blockInstance An instance of an Block class
1438 public final function getBlockInstance () {
1439 return $this->blockInstance;
1443 * Setter for Minable instance
1445 * @param $minableInstance A Minable instance
1448 protected final function setMinableInstance (Minable $minableInstance) {
1449 $this->minableInstance = $minableInstance;
1453 * Getter for minable instance
1455 * @return $minableInstance A Minable instance
1457 protected final function getMinableInstance () {
1458 return $this->minableInstance;
1462 * Setter for FrameworkDirectory instance
1464 * @param $directoryInstance A FrameworkDirectory instance
1467 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1468 $this->directoryInstance = $directoryInstance;
1472 * Getter for FrameworkDirectory instance
1474 * @return $directoryInstance A FrameworkDirectory instance
1476 protected final function getDirectoryInstance () {
1477 return $this->directoryInstance;
1481 * Setter for state instance
1483 * @param $stateInstance A Stateable instance
1486 public final function setStateInstance (Stateable $stateInstance) {
1487 $this->stateInstance = $stateInstance;
1491 * Getter for state instance
1493 * @return $stateInstance A Stateable instance
1495 public final function getStateInstance () {
1496 return $this->stateInstance;
1500 * Setter for output instance
1502 * @param $outputInstance The debug output instance
1505 public final function setOutputInstance (OutputStreamer $outputInstance) {
1506 $this->outputInstance = $outputInstance;
1510 * Getter for output instance
1512 * @return $outputInstance The debug output instance
1514 public final function getOutputInstance () {
1515 return $this->outputInstance;
1519 * Setter for registry instance
1521 * @param $registryInstance An instance of a Register class
1524 protected final function setRegistryInstance (Register $registryInstance) {
1525 $this->registryInstance = $registryInstance;
1529 * Getter for registry instance
1531 * @return $registryInstance The debug registry instance
1533 public final function getRegistryInstance () {
1534 return $this->registryInstance;
1538 * Setter for call-back instance
1540 * @param $callbackInstance An instance of a FrameworkInterface class
1543 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1544 $this->callbackInstance = $callbackInstance;
1548 * Getter for call-back instance
1550 * @return $callbackInstance An instance of a FrameworkInterface class
1552 protected final function getCallbackInstance () {
1553 return $this->callbackInstance;
1557 * Setter for command name
1559 * @param $commandName Last validated command name
1562 protected final function setCommandName ($commandName) {
1563 $this->commandName = $commandName;
1567 * Getter for command name
1569 * @return $commandName Last validated command name
1571 protected final function getCommandName () {
1572 return $this->commandName;
1576 * Setter for controller name
1578 * @param $controllerName Last validated controller name
1581 protected final function setControllerName ($controllerName) {
1582 $this->controllerName = $controllerName;
1586 * Getter for controller name
1588 * @return $controllerName Last validated controller name
1590 protected final function getControllerName () {
1591 return $this->controllerName;
1595 * Checks whether an object equals this object. You should overwrite this
1596 * method to implement own equality checks
1598 * @param $objectInstance An instance of a FrameworkInterface object
1599 * @return $equals Whether both objects equals
1601 public function equals (FrameworkInterface $objectInstance) {
1604 $this->__toString() == $objectInstance->__toString()
1606 $this->hashCode() == $objectInstance->hashCode()
1609 // Return the result
1614 * Generates a generic hash code of this class. You should really overwrite
1615 * this method with your own hash code generator code. But keep KISS in mind.
1617 * @return $hashCode A generic hash code respresenting this whole class
1619 public function hashCode () {
1621 return crc32($this->__toString());
1625 * Formats computer generated price values into human-understandable formats
1626 * with thousand and decimal separators.
1628 * @param $value The in computer format value for a price
1629 * @param $currency The currency symbol (use HTML-valid characters!)
1630 * @param $decNum Number of decimals after commata
1631 * @return $price The for the current language formated price string
1632 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1633 * thousands separator
1636 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1637 // Are all required attriutes set?
1638 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1639 // Throw an exception
1640 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1644 $value = (float) $value;
1646 // Reformat the US number
1647 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1649 // Return as string...
1654 * Appends a trailing slash to a string
1656 * @param $str A string (maybe) without trailing slash
1657 * @return $str A string with an auto-appended trailing slash
1659 public final function addMissingTrailingSlash ($str) {
1660 // Is there a trailing slash?
1661 if (substr($str, -1, 1) != '/') {
1665 // Return string with trailing slash
1670 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1671 * application helper instance (ApplicationHelper by default).
1673 * @param $applicationInstance An application helper instance or
1674 * null if we shall use the default
1675 * @return $templateInstance The template engine instance
1676 * @throws NullPointerException If the discovered application
1677 * instance is still null
1679 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1680 // Is the application instance set?
1681 if (is_null($applicationInstance)) {
1682 // Get the current instance
1683 $applicationInstance = Registry::getRegistry()->getInstance('app');
1686 if (is_null($applicationInstance)) {
1687 // Thrown an exception
1688 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1692 // Initialize the template engine
1693 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1695 // Return the prepared instance
1696 return $templateInstance;
1700 * Debugs this instance by putting out it's full content
1702 * @param $message Optional message to show in debug output
1705 public final function debugInstance ($message = '') {
1706 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1707 restore_error_handler();
1712 // Is a message set?
1713 if (!empty($message)) {
1714 // Construct message
1715 $content = sprintf('<div class="debug_message">
1717 </div>' . PHP_EOL, $message);
1720 // Generate the output
1721 $content .= sprintf('<pre>%s</pre>',
1724 print_r($this, true)
1730 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1733 <div class="debug_content">
1737 <div class="debug_include_list">
1740 $this->__toString(),
1742 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1747 * Replaces control characters with printable output
1749 * @param $str String with control characters
1750 * @return $str Replaced string
1752 protected function replaceControlCharacters ($str) {
1755 chr(13), '[r]', str_replace(
1756 chr(10), '[n]', str_replace(
1766 * Output a partial stub message for the caller method
1768 * @param $message An optional message to display
1771 protected function partialStub ($message = '') {
1773 $stubMessage = 'Partial Stub!';
1775 // Is the extra message given?
1776 if (!empty($message)) {
1777 // Then add it as well
1778 $stubMessage .= ' Message: ' . $message;
1781 // Debug instance is there?
1782 if (!is_null($this->getDebugInstance())) {
1783 // Output stub message
1784 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1787 trigger_error($stubMessage);
1793 * Outputs a debug backtrace and stops further script execution
1795 * @param $message An optional message to output
1796 * @param $doExit Whether exit the program (true is default)
1799 public function debugBackTrace ($message = '', $doExit = true) {
1800 // Sorry, there is no other way getting this nice backtrace
1801 if (!empty($message)) {
1803 printf('Message: %s<br />' . PHP_EOL, $message);
1807 debug_print_backtrace();
1811 if ($doExit === true) {
1817 * Creates an instance of a debugger instance
1819 * @param $className Name of the class (currently unsupported)
1820 * @param $lineNumber Line number where the call was made
1821 * @return $debugInstance An instance of a debugger class
1822 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1824 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1825 // Is the instance set?
1826 if (!Registry::getRegistry()->instanceExists('debug')) {
1827 // Init debug instance
1828 $debugInstance = NULL;
1832 // Get a debugger instance
1833 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1834 } catch (NullPointerException $e) {
1835 // Didn't work, no instance there
1836 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1839 // Empty string should be ignored and used for testing the middleware
1840 DebugMiddleware::getSelfInstance()->output('');
1842 // Set it in registry
1843 Registry::getRegistry()->addInstance('debug', $debugInstance);
1845 // Get instance from registry
1846 $debugInstance = Registry::getRegistry()->getInstance('debug');
1850 return $debugInstance;
1854 * Simple output of a message with line-break
1856 * @param $message Message to output
1859 public function outputLine ($message) {
1861 print($message . PHP_EOL);
1865 * Outputs a debug message whether to debug instance (should be set!) or
1866 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1867 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1869 * @param $message Message we shall send out...
1870 * @param $doPrint Whether print or die here (default: print)
1871 * @paran $stripTags Whether to strip tags (default: false)
1874 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1875 // Set debug instance to NULL
1876 $debugInstance = NULL;
1879 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1881 // Is function partialStub/__callStatic ?
1882 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1883 // Prepend class::function:line from 3rd element
1884 $message = sprintf('[%s::%s:%d]: %s',
1885 $backtrace[2]['class'],
1886 $backtrace[2]['function'],
1887 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1891 // Prepend class::function:line from 2nd element
1892 $message = sprintf('[%s::%s:%d]: %s',
1893 $backtrace[1]['class'],
1894 $backtrace[1]['function'],
1895 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1902 // Get debug instance
1903 $debugInstance = $this->getDebugInstance();
1904 } catch (NullPointerException $e) {
1905 // The debug instance is not set (yet)
1908 // Is the debug instance there?
1909 if (is_object($debugInstance)) {
1910 // Use debug output handler
1911 $debugInstance->output($message, $stripTags);
1913 if ($doPrint === false) {
1914 // Die here if not printed
1918 // Are debug times enabled?
1919 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1921 $message = $this->getPrintableExecutionTime() . $message;
1925 if ($doPrint === true) {
1927 $this->outputLine($message);
1936 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1938 * @param $str The string, what ever it is needs to be converted
1939 * @return $className Generated class name
1941 public static final function convertToClassName ($str) {
1945 // Convert all dashes in underscores
1946 $str = self::convertDashesToUnderscores($str);
1948 // Now use that underscores to get classname parts for hungarian style
1949 foreach (explode('_', $str) as $strPart) {
1950 // Make the class name part lower case and first upper case
1951 $className .= ucfirst(strtolower($strPart));
1954 // Return class name
1959 * Converts dashes to underscores, e.g. useable for configuration entries
1961 * @param $str The string with maybe dashes inside
1962 * @return $str The converted string with no dashed, but underscores
1963 * @throws NullPointerException If $str is null
1964 * @throws InvalidArgumentException If $str is empty
1966 public static function convertDashesToUnderscores ($str) {
1968 if (is_null($str)) {
1970 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
1971 } elseif (!is_string($str)) {
1973 throw new InvalidArgumentException(sprintf('str[]=%s is not a string', gettype($str)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1974 } elseif ((is_string($str)) && (empty($str))) {
1976 throw new InvalidArgumentException('str is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1980 $str = str_replace('-', '_', $str);
1982 // Return converted string
1987 * Marks up the code by adding e.g. line numbers
1989 * @param $phpCode Unmarked PHP code
1990 * @return $markedCode Marked PHP code
1992 public function markupCode ($phpCode) {
1997 $errorArray = error_get_last();
1999 // Init the code with error message
2000 if (is_array($errorArray)) {
2002 $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>',
2003 basename($errorArray['file']),
2004 $errorArray['line'],
2005 $errorArray['message'],
2010 // Add line number to the code
2011 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2013 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2015 htmlentities($code, ENT_QUOTES)
2024 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2025 * beatiful for web-based front-ends. If null is given a message id
2026 * null_timestamp will be resolved and returned.
2028 * @param $timestamp Timestamp to prepare (filter) for display
2029 * @return $readable A readable timestamp
2031 public function doFilterFormatTimestamp ($timestamp) {
2032 // Default value to return
2035 // Is the timestamp null?
2036 if (is_null($timestamp)) {
2037 // Get a message string
2038 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2040 switch ($this->getLanguageInstance()->getLanguageCode()) {
2041 case 'de': // German format is a bit different to default
2042 // Split the GMT stamp up
2043 $dateTime = explode(' ', $timestamp );
2044 $dateArray = explode('-', $dateTime[0]);
2045 $timeArray = explode(':', $dateTime[1]);
2047 // Construct the timestamp
2048 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2058 default: // Default is pass-through
2059 $readable = $timestamp;
2069 * Filter a given number into a localized number
2071 * @param $value The raw value from e.g. database
2072 * @return $localized Localized value
2074 public function doFilterFormatNumber ($value) {
2075 // Generate it from config and localize dependencies
2076 switch ($this->getLanguageInstance()->getLanguageCode()) {
2077 case 'de': // German format is a bit different to default
2078 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2081 default: // US, etc.
2082 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2091 * "Getter" for databse entry
2093 * @return $entry An array with database entries
2094 * @throws NullPointerException If the database result is not found
2095 * @throws InvalidDatabaseResultException If the database result is invalid
2097 protected final function getDatabaseEntry () {
2098 // Is there an instance?
2099 if (!$this->getResultInstance() instanceof SearchableResult) {
2100 // Throw an exception here
2101 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2105 $this->getResultInstance()->rewind();
2107 // Do we have an entry?
2108 if ($this->getResultInstance()->valid() === false) {
2109 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2110 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2114 $this->getResultInstance()->next();
2117 $entry = $this->getResultInstance()->current();
2124 * Getter for field name
2126 * @param $fieldName Field name which we shall get
2127 * @return $fieldValue Field value from the user
2128 * @throws NullPointerException If the result instance is null
2130 public final function getField ($fieldName) {
2131 // Default field value
2134 // Get result instance
2135 $resultInstance = $this->getResultInstance();
2137 // Is this instance null?
2138 if (is_null($resultInstance)) {
2139 // Then the user instance is no longer valid (expired cookies?)
2140 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2143 // Get current array
2144 $fieldArray = $resultInstance->current();
2145 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2147 // Convert dashes to underscore
2148 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2150 // Does the field exist?
2151 if ($this->isFieldSet($fieldName)) {
2153 $fieldValue = $fieldArray[$fieldName2];
2154 } elseif (defined('DEVELOPER')) {
2155 // Missing field entry, may require debugging
2156 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2158 // Missing field entry, may require debugging
2159 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2167 * Checks if given field is set
2169 * @param $fieldName Field name to check
2170 * @return $isSet Whether the given field name is set
2171 * @throws NullPointerException If the result instance is null
2173 public function isFieldSet ($fieldName) {
2174 // Get result instance
2175 $resultInstance = $this->getResultInstance();
2177 // Is this instance null?
2178 if (is_null($resultInstance)) {
2179 // Then the user instance is no longer valid (expired cookies?)
2180 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2183 // Get current array
2184 $fieldArray = $resultInstance->current();
2185 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2187 // Convert dashes to underscore
2188 $fieldName = self::convertDashesToUnderscores($fieldName);
2191 $isSet = isset($fieldArray[$fieldName]);
2198 * Flushs all pending updates to the database layer
2202 public function flushPendingUpdates () {
2203 // Get result instance
2204 $resultInstance = $this->getResultInstance();
2206 // Do we have data to update?
2207 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2208 // Get wrapper class name config entry
2209 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2211 // Create object instance
2212 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2214 // Yes, then send the whole result to the database layer
2215 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2220 * Outputs a deprecation warning to the developer.
2222 * @param $message The message we shall output to the developer
2224 * @todo Write a logging mechanism for productive mode
2226 public function deprecationWarning ($message) {
2227 // Is developer mode active?
2228 if (defined('DEVELOPER')) {
2229 // Debug instance is there?
2230 if (!is_null($this->getDebugInstance())) {
2231 // Output stub message
2232 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2235 trigger_error($message . "<br />\n");
2239 // @TODO Finish this part!
2240 $this->partialStub('Developer mode inactive. Message:' . $message);
2245 * Checks whether the given PHP extension is loaded
2247 * @param $phpExtension The PHP extension we shall check
2248 * @return $isLoaded Whether the PHP extension is loaded
2250 public final function isPhpExtensionLoaded ($phpExtension) {
2252 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2259 * "Getter" as a time() replacement but with milliseconds. You should use this
2260 * method instead of the encapsulated getimeofday() function.
2262 * @return $milliTime Timestamp with milliseconds
2264 public function getMilliTime () {
2265 // Get the time of day as float
2266 $milliTime = gettimeofday(true);
2273 * Idles (sleeps) for given milliseconds
2275 * @return $hasSlept Whether it goes fine
2277 public function idle ($milliSeconds) {
2278 // Sleep is fine by default
2281 // Idle so long with found function
2282 if (function_exists('time_sleep_until')) {
2283 // Get current time and add idle time
2284 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2286 // New PHP 5.1.0 function found, ignore errors
2287 $hasSlept = @time_sleep_until($sleepUntil);
2290 * My Sun station doesn't have that function even with latest PHP
2293 usleep($milliSeconds * 1000);
2300 * Converts a hexadecimal string, even with negative sign as first string to
2301 * a decimal number using BC functions.
2303 * This work is based on comment #86673 on php.net documentation page at:
2304 * <http://de.php.net/manual/en/function.dechex.php#86673>
2306 * @param $hex Hexadecimal string
2307 * @return $dec Decimal number
2309 protected function hex2dec ($hex) {
2310 // Convert to all lower-case
2311 $hex = strtolower($hex);
2313 // Detect sign (negative/positive numbers)
2315 if (substr($hex, 0, 1) == '-') {
2317 $hex = substr($hex, 1);
2320 // Decode the hexadecimal string into a decimal number
2322 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2323 $factor = self::$hexdec[substr($hex, $i, 1)];
2324 $dec = bcadd($dec, bcmul($factor, $e));
2327 // Return the decimal number
2328 return $sign . $dec;
2332 * Converts even very large decimal numbers, also signed, to a hexadecimal
2335 * This work is based on comment #97756 on php.net documentation page at:
2336 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2338 * @param $dec Decimal number, even with negative sign
2339 * @param $maxLength Optional maximum length of the string
2340 * @return $hex Hexadecimal string
2342 protected function dec2hex ($dec, $maxLength = 0) {
2343 // maxLength can be zero or devideable by 2
2344 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2346 // Detect sign (negative/positive numbers)
2353 // Encode the decimal number into a hexadecimal string
2356 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2358 } while ($dec >= 1);
2361 * Leading zeros are required for hex-decimal "numbers". In some
2362 * situations more leading zeros are wanted, so check for both
2365 if ($maxLength > 0) {
2366 // Prepend more zeros
2367 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2368 } elseif ((strlen($hex) % 2) != 0) {
2369 // Only make string's length dividable by 2
2373 // Return the hexadecimal string
2374 return $sign . $hex;
2378 * Converts a ASCII string (0 to 255) into a decimal number.
2380 * @param $asc The ASCII string to be converted
2381 * @return $dec Decimal number
2383 protected function asc2dec ($asc) {
2384 // Convert it into a hexadecimal number
2385 $hex = bin2hex($asc);
2387 // And back into a decimal number
2388 $dec = $this->hex2dec($hex);
2395 * Converts a decimal number into an ASCII string.
2397 * @param $dec Decimal number
2398 * @return $asc An ASCII string
2400 protected function dec2asc ($dec) {
2401 // First convert the number into a hexadecimal string
2402 $hex = $this->dec2hex($dec);
2404 // Then convert it into the ASCII string
2405 $asc = $this->hex2asc($hex);
2412 * Converts a hexadecimal number into an ASCII string. Negative numbers
2415 * @param $hex Hexadecimal string
2416 * @return $asc An ASCII string
2418 protected function hex2asc ($hex) {
2419 // Check for length, it must be devideable by 2
2420 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2421 assert((strlen($hex) % 2) == 0);
2425 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2426 // Get the decimal number of the chunk
2427 $part = hexdec(substr($hex, $idx, 2));
2429 // Add it to the final string
2433 // Return the final string
2438 * Checks whether the given encoded data was encoded with Base64
2440 * @param $encodedData Encoded data we shall check
2441 * @return $isBase64 Whether the encoded data is Base64
2443 protected function isBase64Encoded ($encodedData) {
2445 $isBase64 = (@base64_decode($encodedData, true) !== false);
2452 * Gets a cache key from Criteria instance
2454 * @param $criteriaInstance An instance of a Criteria class
2455 * @param $onlyKeys Only use these keys for a cache key
2456 * @return $cacheKey A cache key suitable for lookup/storage purposes
2458 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2460 $cacheKey = sprintf('%s@%s',
2461 $this->__toString(),
2462 $criteriaInstance->getCacheKey($onlyKeys)
2466 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2471 * Getter for startup time in miliseconds
2473 * @return $startupTime Startup time in miliseconds
2475 protected function getStartupTime () {
2476 return self::$startupTime;
2480 * "Getter" for a printable currently execution time in nice braces
2482 * @return $executionTime Current execution time in nice braces
2484 protected function getPrintableExecutionTime () {
2485 // Caculate the execution time
2486 $executionTime = microtime(true) - $this->getStartupTime();
2488 // Pack it in nice braces
2489 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2492 return $executionTime;
2496 * Hashes a given string with a simple but stronger hash function (no salt)
2497 * and hex-encode it.
2499 * @param $str The string to be hashed
2500 * @return $hash The hash from string $str
2502 public static final function hash ($str) {
2503 // Hash given string with (better secure) hasher
2504 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2511 * "Getter" for length of hash() output. This will be "cached" to speed up
2514 * @return $length Length of hash() output
2516 public static final function getHashLength () {
2518 if (is_null(self::$hashLength)) {
2519 // No, then hash a string and save its length.
2520 self::$hashLength = strlen(self::hash('abc123'));
2524 return self::$hashLength;
2528 * Checks whether the given number is really a number (only chars 0-9).
2530 * @param $num A string consisting only chars between 0 and 9
2531 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2532 * @param $assertMismatch Whether to assert mismatches
2533 * @return $ret The (hopefully) secured numbered value
2535 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2536 // Filter all numbers out
2537 $ret = preg_replace('/[^0123456789]/', '', $num);
2540 if ($castValue === true) {
2541 // Cast to biggest numeric type
2542 $ret = (double) $ret;
2545 // Assert only if requested
2546 if ($assertMismatch === true) {
2547 // Has the whole value changed?
2548 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2556 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2558 * @param $num A string consisting only chars between 0 and 9
2559 * @param $assertMismatch Whether to assert mismatches
2560 * @return $ret The (hopefully) secured hext-numbered value
2562 public function hexval ($num, $assertMismatch = false) {
2563 // Filter all numbers out
2564 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2566 // Assert only if requested
2567 if ($assertMismatch === true) {
2568 // Has the whole value changed?
2569 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2577 * Determines if an element is set in the generic array
2579 * @param $keyGroup Main group for the key
2580 * @param $subGroup Sub group for the key
2581 * @param $key Key to check
2582 * @param $element Element to check
2583 * @return $isset Whether the given key is set
2585 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2587 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2590 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2596 * Determines if a key is set in the generic array
2598 * @param $keyGroup Main group for the key
2599 * @param $subGroup Sub group for the key
2600 * @param $key Key to check
2601 * @return $isset Whether the given key is set
2603 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2605 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2608 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2616 * Determines if a group is set in the generic array
2618 * @param $keyGroup Main group
2619 * @param $subGroup Sub group
2620 * @return $isset Whether the given group is set
2622 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2624 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2627 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2634 * Getter for sub key group
2636 * @param $keyGroup Main key group
2637 * @param $subGroup Sub key group
2638 * @return $array An array with all array elements
2640 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2642 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2643 // No, then abort here
2644 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2649 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2652 return $this->genericArray[$keyGroup][$subGroup];
2656 * Unsets a given key in generic array
2658 * @param $keyGroup Main group for the key
2659 * @param $subGroup Sub group for the key
2660 * @param $key Key to unset
2663 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2665 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2668 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2672 * Unsets a given element in generic array
2674 * @param $keyGroup Main group for the key
2675 * @param $subGroup Sub group for the key
2676 * @param $key Key to unset
2677 * @param $element Element to unset
2680 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2682 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2685 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2689 * Append a string to a given generic array key
2691 * @param $keyGroup Main group for the key
2692 * @param $subGroup Sub group for the key
2693 * @param $key Key to unset
2694 * @param $value Value to add/append
2697 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2699 //* 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);
2701 // Is it already there?
2702 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2704 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2707 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2712 * Append a string to a given generic array element
2714 * @param $keyGroup Main group for the key
2715 * @param $subGroup Sub group for the key
2716 * @param $key Key to unset
2717 * @param $element Element to check
2718 * @param $value Value to add/append
2721 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
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) . ',appendGlue=' . $appendGlue);
2725 // Is it already there?
2726 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2728 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2731 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2736 * Sets a string in a given generic array element
2738 * @param $keyGroup Main group for the key
2739 * @param $subGroup Sub group for the key
2740 * @param $key Key to unset
2741 * @param $element Element to check
2742 * @param $value Value to add/append
2745 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2747 //* 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);
2750 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2754 * Initializes given generic array group
2756 * @param $keyGroup Main group for the key
2757 * @param $subGroup Sub group for the key
2758 * @param $key Key to use
2759 * @param $forceInit Optionally force initialization
2762 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2764 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2766 // Is it already set?
2767 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2768 // Already initialized
2769 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2774 $this->genericArray[$keyGroup][$subGroup] = array();
2778 * Initializes given generic array key
2780 * @param $keyGroup Main group for the key
2781 * @param $subGroup Sub group for the key
2782 * @param $key Key to use
2783 * @param $forceInit Optionally force initialization
2786 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2788 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2790 // Is it already set?
2791 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2792 // Already initialized
2793 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2798 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2802 * Initializes given generic array element
2804 * @param $keyGroup Main group for the key
2805 * @param $subGroup Sub group for the key
2806 * @param $key Key to use
2807 * @param $element Element to use
2808 * @param $forceInit Optionally force initialization
2811 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2813 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2815 // Is it already set?
2816 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2817 // Already initialized
2818 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2823 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2827 * Pushes an element to a generic key
2829 * @param $keyGroup Main group for the key
2830 * @param $subGroup Sub group for the key
2831 * @param $key Key to use
2832 * @param $value Value to add/append
2833 * @return $count Number of array elements
2835 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2837 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2840 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2842 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2846 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2849 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2850 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2855 * Pushes an element to a generic array element
2857 * @param $keyGroup Main group for the key
2858 * @param $subGroup Sub group for the key
2859 * @param $key Key to use
2860 * @param $element Element to check
2861 * @param $value Value to add/append
2862 * @return $count Number of array elements
2864 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2866 //* 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));
2869 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2871 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2875 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2878 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2879 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2884 * Pops an element from a generic group
2886 * @param $keyGroup Main group for the key
2887 * @param $subGroup Sub group for the key
2888 * @param $key Key to unset
2889 * @return $value Last "popped" value
2891 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2893 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2896 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2898 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2903 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2906 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2907 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2912 * Shifts an element from a generic group
2914 * @param $keyGroup Main group for the key
2915 * @param $subGroup Sub group for the key
2916 * @param $key Key to unset
2917 * @return $value Last "popped" value
2919 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2921 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2924 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2926 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2931 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2934 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2935 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2940 * Count generic array group
2942 * @param $keyGroup Main group for the key
2943 * @return $count Count of given group
2945 protected final function countGenericArray ($keyGroup) {
2947 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2950 if (!isset($this->genericArray[$keyGroup])) {
2952 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2957 $count = count($this->genericArray[$keyGroup]);
2960 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2967 * Count generic array sub group
2969 * @param $keyGroup Main group for the key
2970 * @param $subGroup Sub group for the key
2971 * @return $count Count of given group
2973 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2975 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2978 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2980 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2985 $count = count($this->genericArray[$keyGroup][$subGroup]);
2988 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2995 * Count generic array elements
2997 * @param $keyGroup Main group for the key
2998 * @param $subGroup Sub group for the key
2999 * @para $key Key to count
3000 * @return $count Count of given key
3002 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3004 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3007 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3009 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3011 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3013 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3018 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3021 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3028 * Getter for whole generic group array
3030 * @param $keyGroup Key group to get
3031 * @return $array Whole generic array group
3033 protected final function getGenericArray ($keyGroup) {
3035 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3038 if (!isset($this->genericArray[$keyGroup])) {
3040 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3045 return $this->genericArray[$keyGroup];
3049 * Setter for generic array key
3051 * @param $keyGroup Key group to get
3052 * @param $subGroup Sub group for the key
3053 * @param $key Key to unset
3054 * @param $value Mixed value from generic array element
3057 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3059 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3062 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3066 * Getter for generic array key
3068 * @param $keyGroup Key group to get
3069 * @param $subGroup Sub group for the key
3070 * @param $key Key to unset
3071 * @return $value Mixed value from generic array element
3073 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3075 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3078 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3080 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3085 return $this->genericArray[$keyGroup][$subGroup][$key];
3089 * Sets a value in given generic array key/element
3091 * @param $keyGroup Main group for the key
3092 * @param $subGroup Sub group for the key
3093 * @param $key Key to set
3094 * @param $element Element to set
3095 * @param $value Value to set
3098 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3100 //* 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));
3103 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3107 * Getter for generic array element
3109 * @param $keyGroup Key group to get
3110 * @param $subGroup Sub group for the key
3111 * @param $key Key to look for
3112 * @param $element Element to look for
3113 * @return $value Mixed value from generic array element
3115 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3117 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3120 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3122 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3127 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3131 * Checks if a given sub group is valid (array)
3133 * @param $keyGroup Key group to get
3134 * @param $subGroup Sub group for the key
3135 * @return $isValid Whether given sub group is valid
3137 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3139 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3142 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3149 * Checks if a given key is valid (array)
3151 * @param $keyGroup Key group to get
3152 * @param $subGroup Sub group for the key
3153 * @param $key Key to check
3154 * @return $isValid Whether given sub group is valid
3156 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3158 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3161 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3168 * Initializes the web output instance
3172 protected function initWebOutputInstance () {
3173 // Get application instance
3174 $applicationInstance = Registry::getRegistry()->getInstance('app');
3176 // Init web output instance
3177 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3180 $this->setWebOutputInstance($outputInstance);
3184 * Translates boolean true to 'Y' and false to 'N'
3186 * @param $boolean Boolean value
3187 * @return $translated Translated boolean value
3189 public static final function translateBooleanToYesNo ($boolean) {
3190 // Make sure it is really boolean
3191 assert(is_bool($boolean));
3194 $translated = ($boolean === true) ? 'Y' : 'N';
3196 // ... and return it
3201 * Encodes raw data (almost any type) by "serializing" it and then pack it
3202 * into a "binary format".
3204 * @param $rawData Raw data (almost any type)
3205 * @return $encoded Encoded data
3207 protected function encodeData ($rawData) {
3208 // Make sure no objects or resources pass through
3209 assert(!is_object($rawData));
3210 assert(!is_resource($rawData));
3212 // First "serialize" it (json_encode() is faster than serialize())
3213 $encoded = $this->packString(json_encode($rawData));
3220 * Pack a string into a "binary format". Please execuse me that this is
3221 * widely undocumented. :-(
3223 * @param $str Unpacked string
3224 * @return $packed Packed string
3225 * @todo Improve documentation
3227 protected function packString ($str) {
3229 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3231 // First compress the string (gzcompress is okay)
3232 $str = gzcompress($str);
3237 // And start the "encoding" loop
3238 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3240 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3241 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3243 if (($idx + $i) <= strlen($str)) {
3244 $ord = ord(substr($str, ($idx + $i), 1));
3246 $add = $ord * pow(256, $factor);
3250 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3254 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3255 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3257 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3258 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3264 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3269 * Creates a full-qualified file name (FQFN) for given file name by adding
3270 * a configured temporary file path to it.
3272 * @param $infoInstance An instance of a SplFileInfo class
3273 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3274 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3275 * @throws FileIoException If the file cannot be written
3277 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3279 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3281 // Is the path writeable?
3282 if (!is_writable($basePath)) {
3283 // Path is write-protected
3284 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3288 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3291 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3293 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3297 return $tempInstance;
3301 * "Getter" for a printable state name
3303 * @return $stateName Name of the node's state in a printable format
3305 public final function getPrintableState () {
3306 // Default is 'null'
3307 $stateName = 'null';
3309 // Get the state instance
3310 $stateInstance = $this->getStateInstance();
3312 // Is it an instance of Stateable?
3313 if ($stateInstance instanceof Stateable) {
3314 // Then use that state name
3315 $stateName = $stateInstance->getStateName();