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\Middleware\Compressor\CompressorChannel;
36 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
37 use Org\Mxchange\CoreFramework\Parser\Parseable;
38 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
39 use Org\Mxchange\CoreFramework\Registry\Register;
40 use Org\Mxchange\CoreFramework\Resolver\Resolver;
41 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
42 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
43 use Org\Mxchange\CoreFramework\Stacker\Stackable;
44 use Org\Mxchange\CoreFramework\State\Stateable;
45 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
46 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
47 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
48 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
49 use Org\Mxchange\CoreFramework\User\ManageableAccount;
50 use Org\Mxchange\CoreFramework\Visitor\Visitor;
54 use \InvalidArgumentException;
60 * The simulator system class is the super class of all other classes. This
61 * class handles saving of games etc.
63 * @author Roland Haeder <webmaster@shipsimu.org>
65 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
66 * @license GNU GPL 3.0 or any newer version
67 * @link http://www.shipsimu.org
69 * This program is free software: you can redistribute it and/or modify
70 * it under the terms of the GNU General Public License as published by
71 * the Free Software Foundation, either version 3 of the License, or
72 * (at your option) any later version.
74 * This program is distributed in the hope that it will be useful,
75 * but WITHOUT ANY WARRANTY; without even the implied warranty of
76 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
77 * GNU General Public License for more details.
79 * You should have received a copy of the GNU General Public License
80 * along with this program. If not, see <http://www.gnu.org/licenses/>.
82 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
84 * Length of output from hash()
86 private static $hashLength = NULL;
91 private $realClass = 'BaseFrameworkSystem';
94 * Search criteria instance
96 private $searchInstance = NULL;
99 * Update criteria instance
101 private $updateInstance = NULL;
104 * The file I/O instance for the template loader
106 private $fileIoInstance = NULL;
111 private $resolverInstance = NULL;
114 * Template engine instance
116 private $templateInstance = NULL;
119 * Database result instance
121 private $resultInstance = NULL;
124 * Instance for user class
126 private $userInstance = NULL;
129 * A controller instance
131 private $controllerInstance = NULL;
136 private $rngInstance = NULL;
139 * Instance of a crypto helper
141 private $cryptoInstance = NULL;
144 * Instance of an Iterator class
146 private $iteratorInstance = NULL;
149 * Instance of the list
151 private $listInstance = NULL;
156 private $menuInstance = NULL;
159 * Instance of the image
161 private $imageInstance = NULL;
164 * Instance of the stacker
166 private $stackInstance = NULL;
169 * A Compressor instance
171 private $compressorInstance = NULL;
174 * A Parseable instance
176 private $parserInstance = NULL;
179 * A database wrapper instance
181 private $databaseInstance = NULL;
184 * A helper instance for the form
186 private $helperInstance = NULL;
189 * An instance of a InputStream class
191 private $inputStreamInstance = NULL;
194 * An instance of a OutputStream class
196 private $outputStreamInstance = NULL;
201 private $handlerInstance = NULL;
204 * Visitor handler instance
206 private $visitorInstance = NULL;
209 * An instance of a database wrapper class
211 private $wrapperInstance = NULL;
214 * An instance of a file I/O pointer class (not handler)
216 private $pointerInstance = NULL;
219 * An instance of an Indexable class
221 private $indexInstance = NULL;
224 * An instance of a Block class
226 private $blockInstance = NULL;
231 private $minableInstance = NULL;
234 * A FrameworkDirectory instance
236 private $directoryInstance = NULL;
239 * The concrete output instance
241 private $outputInstance = NULL;
246 private $stateInstance = NULL;
249 * Registry instance (implementing Register)
251 private $registryInstance = NULL;
256 private $callbackInstance = NULL;
259 * Thousands separator
261 private $thousands = '.'; // German
266 private $decimals = ','; // German
271 private $socketResource = false;
274 * Regular expression to use for validation
276 private $regularExpression = '';
281 private $packageData = array();
286 private $genericArray = array();
291 private $commandName = '';
296 private $controllerName = '';
299 * Array with bitmasks and such for pack/unpack methods to support both
300 * 32-bit and 64-bit systems
302 private $packingData = array(
305 'left' => 0xffff0000,
306 'right' => 0x0000ffff,
312 'left' => 0xffffffff00000000,
313 'right' => 0x00000000ffffffff,
320 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
322 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
324 private $archArrayElement = false;
326 /***********************
327 * Exception codes.... *
328 ***********************/
330 // @todo Try to clean these constants up
331 const EXCEPTION_IS_NULL_POINTER = 0x001;
332 const EXCEPTION_IS_NO_OBJECT = 0x002;
333 const EXCEPTION_IS_NO_ARRAY = 0x003;
334 const EXCEPTION_MISSING_METHOD = 0x004;
335 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
336 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
337 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
338 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
339 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
340 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
341 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
342 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
343 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
344 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
345 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
346 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
347 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
348 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
349 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
350 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
351 const EXCEPTION_PATH_NOT_FOUND = 0x015;
352 const EXCEPTION_INVALID_PATH_NAME = 0x016;
353 const EXCEPTION_READ_PROTECED_PATH = 0x017;
354 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
355 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
356 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
357 const EXCEPTION_INVALID_RESOURCE = 0x01b;
358 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
359 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
360 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
361 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
362 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
363 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
364 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
365 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
366 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
367 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
368 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
369 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
370 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
371 const EXCEPTION_INVALID_STRING = 0x029;
372 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
373 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
374 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
375 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
376 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
377 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
378 const EXCEPTION_MISSING_ELEMENT = 0x030;
379 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
380 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
381 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
382 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
383 const EXCEPTION_FATAL_ERROR = 0x035;
384 const EXCEPTION_FILE_NOT_FOUND = 0x036;
385 const EXCEPTION_ASSERTION_FAILED = 0x037;
386 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
387 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
388 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
389 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
390 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
391 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
392 const EXCEPTION_INVALID_SOCKET = 0x03e;
395 * Hexadecimal->Decimal translation array
397 private static $hexdec = array(
417 * Decimal->hexadecimal translation array
419 private static $dechex = array(
439 * Startup time in miliseconds
441 private static $startupTime = 0;
444 * Protected super constructor
446 * @param $className Name of the class
449 protected function __construct ($className) {
451 $this->setRealClass($className);
453 // Set configuration instance if no registry ...
454 if (!$this instanceof Register) {
455 // ... because registries doesn't need to be configured
456 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
459 // Is the startup time set? (0 cannot be true anymore)
460 if (self::$startupTime == 0) {
462 self::$startupTime = microtime(true);
466 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
470 * Destructor for all classes. You should not call this method on your own.
474 public function __destruct () {
475 // Flush any updated entries to the database
476 $this->flushPendingUpdates();
478 // Is this object already destroyed?
479 if ($this->__toString() != 'DestructedObject') {
480 // Destroy all informations about this class but keep some text about it alive
481 $this->setRealClass('DestructedObject');
482 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
483 // Already destructed object
484 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
488 // Do not call this twice
489 trigger_error(__METHOD__ . ': Called twice.');
495 * The __call() method where all non-implemented methods end up
497 * @param $methodName Name of the missing method
498 * @args $args Arguments passed to the method
501 public final function __call ($methodName, $args) {
502 return self::__callStatic($methodName, $args);
506 * The __callStatic() method where all non-implemented static methods end up
508 * @param $methodName Name of the missing method
509 * @args $args Arguments passed to the method
512 public static final function __callStatic ($methodName, $args) {
514 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
516 // Init argument string
519 // Is it NULL, empty or an array?
520 if (is_null($args)) {
522 $argsString = 'NULL';
523 } elseif (is_array($args)) {
527 // Some arguments are there
528 foreach ($args as $arg) {
529 // Add data about the argument
530 $argsString .= gettype($arg) . ':';
533 // Found a NULL argument
534 $argsString .= 'NULL';
535 } elseif (is_string($arg)) {
536 // Add length for strings
537 $argsString .= strlen($arg);
538 } elseif ((is_int($arg)) || (is_float($arg))) {
541 } elseif (is_array($arg)) {
542 // .. or size if array
543 $argsString .= count($arg);
544 } elseif (is_object($arg)) {
546 $reflection = new ReflectionClass($arg);
548 // Is an other object, maybe no __toString() available
549 $argsString .= $reflection->getName();
550 } elseif ($arg === true) {
551 // ... is boolean 'true'
552 $argsString .= 'true';
553 } elseif ($arg === false) {
554 // ... is boolean 'false'
555 $argsString .= 'false';
558 // Comma for next one
563 if (substr($argsString, -2, 1) == ',') {
564 $argsString = substr($argsString, 0, -2);
570 // Invalid arguments!
571 $argsString = '!INVALID:' . gettype($args) . '!';
574 // Output stub message
575 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
576 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
586 * Getter for $realClass
588 * @return $realClass The name of the real class (not BaseFrameworkSystem)
590 public function __toString () {
591 return $this->realClass;
595 * Magic method to catch setting of missing but set class fields/attributes
597 * @param $name Name of the field/attribute
598 * @param $value Value to store
601 public final function __set ($name, $value) {
602 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
605 print_r($value, true)
610 * Magic method to catch getting of missing fields/attributes
612 * @param $name Name of the field/attribute
615 public final function __get ($name) {
616 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
622 * Magic method to catch unsetting of missing fields/attributes
624 * @param $name Name of the field/attribute
627 public final function __unset ($name) {
628 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
634 * Magic method to catch object serialization
636 * @return $unsupported Unsupported method
637 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
639 public final function __sleep () {
640 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
644 * Magic method to catch object deserialization
646 * @return $unsupported Unsupported method
647 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
649 public final function __wakeup () {
650 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
654 * Magic method to catch calls when an object instance is called
656 * @return $unsupported Unsupported method
657 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
659 public final function __invoke () {
660 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
664 * Setter for the real class name
666 * @param $realClass Class name (string)
669 public final function setRealClass ($realClass) {
671 $this->realClass = (string) $realClass;
675 * Setter for database result instance
677 * @param $resultInstance An instance of a database result class
679 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
681 protected final function setResultInstance (SearchableResult $resultInstance) {
682 $this->resultInstance = $resultInstance;
686 * Getter for database result instance
688 * @return $resultInstance An instance of a database result class
690 public final function getResultInstance () {
691 return $this->resultInstance;
695 * Setter for template engine instances
697 * @param $templateInstance An instance of a template engine class
700 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
701 $this->templateInstance = $templateInstance;
705 * Getter for template engine instances
707 * @return $templateInstance An instance of a template engine class
709 protected final function getTemplateInstance () {
710 return $this->templateInstance;
714 * Setter for search instance
716 * @param $searchInstance Searchable criteria instance
719 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
720 $this->searchInstance = $searchInstance;
724 * Getter for search instance
726 * @return $searchInstance Searchable criteria instance
728 public final function getSearchInstance () {
729 return $this->searchInstance;
733 * Setter for update instance
735 * @param $updateInstance An instance of a LocalUpdateCriteria clase
738 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
739 $this->updateInstance = $updateInstance;
743 * Getter for update instance
745 * @return $updateInstance Updateable criteria instance
747 public final function getUpdateInstance () {
748 return $this->updateInstance;
752 * Setter for resolver instance
754 * @param $resolverInstance Instance of a command resolver class
757 public final function setResolverInstance (Resolver $resolverInstance) {
758 $this->resolverInstance = $resolverInstance;
762 * Getter for resolver instance
764 * @return $resolverInstance Instance of a command resolver class
766 public final function getResolverInstance () {
767 return $this->resolverInstance;
771 * Setter for language instance
773 * @param $configInstance The configuration instance which shall
774 * be FrameworkConfiguration
777 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
778 GenericRegistry::getRegistry()->addInstance('config', $configInstance);
782 * Getter for configuration instance
784 * @return $configInstance Configuration instance
786 public final function getConfigInstance () {
787 $configInstance = GenericRegistry::getRegistry()->getInstance('config');
788 return $configInstance;
792 * Setter for debug instance
794 * @param $debugInstance The instance for debug output class
797 public final function setDebugInstance (DebugMiddleware $debugInstance) {
798 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
802 * Getter for debug instance
804 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
806 public final function getDebugInstance () {
807 // Get debug instance
808 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
811 return $debugInstance;
815 * Setter for web output instance
817 * @param $webInstance The instance for web output class
820 public final function setWebOutputInstance (OutputStreamer $webInstance) {
821 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
825 * Getter for web output instance
827 * @return $webOutputInstance - Instance to class WebOutput
829 public final function getWebOutputInstance () {
830 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
831 return $webOutputInstance;
835 * Setter for database instance
837 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
840 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
841 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
845 * Getter for database layer
847 * @return $databaseInstance The database layer instance
849 public final function getDatabaseInstance () {
851 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
854 return $databaseInstance;
858 * Setter for compressor channel
860 * @param $compressorInstance An instance of CompressorChannel
863 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
864 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
868 * Getter for compressor channel
870 * @return $compressorInstance The compressor channel
872 public final function getCompressorChannel () {
873 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
874 return $compressorInstance;
878 * Protected getter for a manageable application helper class
880 * @return $applicationInstance An instance of a manageable application helper class
882 protected final function getApplicationInstance () {
883 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
884 return $applicationInstance;
888 * Setter for a manageable application helper class
890 * @param $applicationInstance An instance of a manageable application helper class
893 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
894 GenericRegistry::getRegistry()->addInstance('application', $applicationInstance);
898 * Private getter for language instance
900 * @return $langInstance An instance to the language sub-system
902 protected final function getLanguageInstance () {
903 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
904 return $langInstance;
908 * Setter for language instance
910 * @param $langInstance An instance to the language sub-system
912 * @see LanguageSystem
914 public final function setLanguageInstance (ManageableLanguage $langInstance) {
915 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
919 * Private getter for file IO instance
921 * @return $fileIoInstance An instance to the file I/O sub-system
923 protected final function getFileIoInstance () {
924 return $this->fileIoInstance;
928 * Setter for file I/O instance
930 * @param $fileIoInstance An instance to the file I/O sub-system
933 public final function setFileIoInstance (IoHandler $fileIoInstance) {
934 $this->fileIoInstance = $fileIoInstance;
938 * Protected setter for user instance
940 * @param $userInstance An instance of a user class
943 protected final function setUserInstance (ManageableAccount $userInstance) {
944 $this->userInstance = $userInstance;
948 * Getter for user instance
950 * @return $userInstance An instance of a user class
952 public final function getUserInstance () {
953 return $this->userInstance;
957 * Setter for controller instance (this surely breaks a bit the MVC patterm)
959 * @param $controllerInstance An instance of the controller
962 public final function setControllerInstance (Controller $controllerInstance) {
963 $this->controllerInstance = $controllerInstance;
967 * Getter for controller instance (this surely breaks a bit the MVC patterm)
969 * @return $controllerInstance An instance of the controller
971 public final function getControllerInstance () {
972 return $this->controllerInstance;
976 * Setter for RNG instance
978 * @param $rngInstance An instance of a random number generator (RNG)
981 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
982 $this->rngInstance = $rngInstance;
986 * Getter for RNG instance
988 * @return $rngInstance An instance of a random number generator (RNG)
990 public final function getRngInstance () {
991 return $this->rngInstance;
995 * Setter for Cryptable instance
997 * @param $cryptoInstance An instance of a Cryptable class
1000 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1001 $this->cryptoInstance = $cryptoInstance;
1005 * Getter for Cryptable instance
1007 * @return $cryptoInstance An instance of a Cryptable class
1009 public final function getCryptoInstance () {
1010 return $this->cryptoInstance;
1014 * Setter for the list instance
1016 * @param $listInstance A list of Listable
1019 protected final function setListInstance (Listable $listInstance) {
1020 $this->listInstance = $listInstance;
1024 * Getter for the list instance
1026 * @return $listInstance A list of Listable
1028 protected final function getListInstance () {
1029 return $this->listInstance;
1033 * Setter for the menu instance
1035 * @param $menuInstance A RenderableMenu instance
1038 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1039 $this->menuInstance = $menuInstance;
1043 * Getter for the menu instance
1045 * @return $menuInstance A RenderableMenu instance
1047 protected final function getMenuInstance () {
1048 return $this->menuInstance;
1052 * Setter for image instance
1054 * @param $imageInstance An instance of an image
1057 public final function setImageInstance (BaseImage $imageInstance) {
1058 $this->imageInstance = $imageInstance;
1062 * Getter for image instance
1064 * @return $imageInstance An instance of an image
1066 public final function getImageInstance () {
1067 return $this->imageInstance;
1071 * Setter for stacker instance
1073 * @param $stackInstance An instance of an stacker
1076 public final function setStackInstance (Stackable $stackInstance) {
1077 $this->stackInstance = $stackInstance;
1081 * Getter for stacker instance
1083 * @return $stackInstance An instance of an stacker
1085 public final function getStackInstance () {
1086 return $this->stackInstance;
1090 * Setter for compressor instance
1092 * @param $compressorInstance An instance of an compressor
1095 public final function setCompressorInstance (Compressor $compressorInstance) {
1096 $this->compressorInstance = $compressorInstance;
1100 * Getter for compressor instance
1102 * @return $compressorInstance An instance of an compressor
1104 public final function getCompressorInstance () {
1105 return $this->compressorInstance;
1109 * Setter for Parseable instance
1111 * @param $parserInstance An instance of an Parseable
1114 public final function setParserInstance (Parseable $parserInstance) {
1115 $this->parserInstance = $parserInstance;
1119 * Getter for Parseable instance
1121 * @return $parserInstance An instance of an Parseable
1123 public final function getParserInstance () {
1124 return $this->parserInstance;
1128 * Setter for DatabaseWrapper instance
1130 * @param $wrapperInstance An instance of an DatabaseWrapper
1133 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1134 $this->wrapperInstance = $wrapperInstance;
1138 * Getter for DatabaseWrapper instance
1140 * @return $wrapperInstance An instance of an DatabaseWrapper
1142 public final function getWrapperInstance () {
1143 return $this->wrapperInstance;
1147 * Setter for socket resource
1149 * @param $socketResource A valid socket resource
1152 public final function setSocketResource ($socketResource) {
1153 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1154 $this->socketResource = $socketResource;
1158 * Getter for socket resource
1160 * @return $socketResource A valid socket resource
1162 public final function getSocketResource () {
1163 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1164 return $this->socketResource;
1168 * Setter for regular expression
1170 * @param $regularExpression A valid regular expression
1173 public final function setRegularExpression ($regularExpression) {
1174 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1175 $this->regularExpression = $regularExpression;
1179 * Getter for regular expression
1181 * @return $regularExpression A valid regular expression
1183 public final function getRegularExpression () {
1184 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1185 return $this->regularExpression;
1189 * Setter for helper instance
1191 * @param $helperInstance An instance of a helper class
1194 protected final function setHelperInstance (Helper $helperInstance) {
1195 $this->helperInstance = $helperInstance;
1199 * Getter for helper instance
1201 * @return $helperInstance An instance of a helper class
1203 public final function getHelperInstance () {
1204 return $this->helperInstance;
1208 * Getter for a InputStream instance
1210 * @param $inputStreamInstance The InputStream instance
1212 protected final function getInputStreamInstance () {
1213 return $this->inputStreamInstance;
1217 * Setter for a InputStream instance
1219 * @param $inputStreamInstance The InputStream instance
1222 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1223 $this->inputStreamInstance = $inputStreamInstance;
1227 * Getter for a OutputStream instance
1229 * @param $outputStreamInstance The OutputStream instance
1231 protected final function getOutputStreamInstance () {
1232 return $this->outputStreamInstance;
1236 * Setter for a OutputStream instance
1238 * @param $outputStreamInstance The OutputStream instance
1241 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1242 $this->outputStreamInstance = $outputStreamInstance;
1246 * Setter for handler instance
1248 * @param $handlerInstance An instance of a Handleable class
1251 protected final function setHandlerInstance (Handleable $handlerInstance) {
1252 $this->handlerInstance = $handlerInstance;
1256 * Getter for handler instance
1258 * @return $handlerInstance A Handleable instance
1260 protected final function getHandlerInstance () {
1261 return $this->handlerInstance;
1265 * Setter for visitor instance
1267 * @param $visitorInstance A Visitor instance
1270 protected final function setVisitorInstance (Visitor $visitorInstance) {
1271 $this->visitorInstance = $visitorInstance;
1275 * Getter for visitor instance
1277 * @return $visitorInstance A Visitor instance
1279 protected final function getVisitorInstance () {
1280 return $this->visitorInstance;
1284 * Setter for raw package Data
1286 * @param $packageData Raw package Data
1289 public final function setPackageData (array $packageData) {
1290 $this->packageData = $packageData;
1294 * Getter for raw package Data
1296 * @return $packageData Raw package Data
1298 public function getPackageData () {
1299 return $this->packageData;
1304 * Setter for Iterator instance
1306 * @param $iteratorInstance An instance of an Iterator
1309 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1310 $this->iteratorInstance = $iteratorInstance;
1314 * Getter for Iterator instance
1316 * @return $iteratorInstance An instance of an Iterator
1318 public final function getIteratorInstance () {
1319 return $this->iteratorInstance;
1323 * Setter for FilePointer instance
1325 * @param $pointerInstance An instance of an FilePointer class
1328 protected final function setPointerInstance (FilePointer $pointerInstance) {
1329 $this->pointerInstance = $pointerInstance;
1333 * Getter for FilePointer instance
1335 * @return $pointerInstance An instance of an FilePointer class
1337 public final function getPointerInstance () {
1338 return $this->pointerInstance;
1342 * Unsets pointer instance which triggers a call of __destruct() if the
1343 * instance is still there. This is surely not fatal on already "closed"
1344 * file pointer instances.
1346 * I don't want to mess around with above setter by giving it a default
1347 * value NULL as setter should always explicitly only set (existing) object
1348 * instances and NULL is NULL.
1352 protected final function unsetPointerInstance () {
1353 // Simply it to NULL
1354 $this->pointerInstance = NULL;
1358 * Setter for Indexable instance
1360 * @param $indexInstance An instance of an Indexable class
1363 protected final function setIndexInstance (Indexable $indexInstance) {
1364 $this->indexInstance = $indexInstance;
1368 * Getter for Indexable instance
1370 * @return $indexInstance An instance of an Indexable class
1372 public final function getIndexInstance () {
1373 return $this->indexInstance;
1377 * Setter for Block instance
1379 * @param $blockInstance An instance of an Block class
1382 protected final function setBlockInstance (Block $blockInstance) {
1383 $this->blockInstance = $blockInstance;
1387 * Getter for Block instance
1389 * @return $blockInstance An instance of an Block class
1391 public final function getBlockInstance () {
1392 return $this->blockInstance;
1396 * Setter for Minable instance
1398 * @param $minableInstance A Minable instance
1401 protected final function setMinableInstance (Minable $minableInstance) {
1402 $this->minableInstance = $minableInstance;
1406 * Getter for minable instance
1408 * @return $minableInstance A Minable instance
1410 protected final function getMinableInstance () {
1411 return $this->minableInstance;
1415 * Setter for FrameworkDirectory instance
1417 * @param $directoryInstance A FrameworkDirectory instance
1420 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1421 $this->directoryInstance = $directoryInstance;
1425 * Getter for FrameworkDirectory instance
1427 * @return $directoryInstance A FrameworkDirectory instance
1429 protected final function getDirectoryInstance () {
1430 return $this->directoryInstance;
1434 * Setter for state instance
1436 * @param $stateInstance A Stateable instance
1439 public final function setStateInstance (Stateable $stateInstance) {
1440 $this->stateInstance = $stateInstance;
1444 * Getter for state instance
1446 * @return $stateInstance A Stateable instance
1448 public final function getStateInstance () {
1449 return $this->stateInstance;
1453 * Setter for output instance
1455 * @param $outputInstance The debug output instance
1458 public final function setOutputInstance (OutputStreamer $outputInstance) {
1459 $this->outputInstance = $outputInstance;
1463 * Getter for output instance
1465 * @return $outputInstance The debug output instance
1467 public final function getOutputInstance () {
1468 return $this->outputInstance;
1472 * Setter for registry instance
1474 * @param $registryInstance An instance of a Register class
1477 protected final function setRegistryInstance (Register $registryInstance) {
1478 $this->registryInstance = $registryInstance;
1482 * Getter for registry instance
1484 * @return $registryInstance The debug registry instance
1486 public final function getRegistryInstance () {
1487 return $this->registryInstance;
1491 * Setter for call-back instance
1493 * @param $callbackInstance An instance of a FrameworkInterface class
1496 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1497 $this->callbackInstance = $callbackInstance;
1501 * Getter for call-back instance
1503 * @return $callbackInstance An instance of a FrameworkInterface class
1505 protected final function getCallbackInstance () {
1506 return $this->callbackInstance;
1510 * Setter for command name
1512 * @param $commandName Last validated command name
1515 protected final function setCommandName ($commandName) {
1516 $this->commandName = $commandName;
1520 * Getter for command name
1522 * @return $commandName Last validated command name
1524 protected final function getCommandName () {
1525 return $this->commandName;
1529 * Setter for controller name
1531 * @param $controllerName Last validated controller name
1534 protected final function setControllerName ($controllerName) {
1535 $this->controllerName = $controllerName;
1539 * Getter for controller name
1541 * @return $controllerName Last validated controller name
1543 protected final function getControllerName () {
1544 return $this->controllerName;
1548 * Checks whether an object equals this object. You should overwrite this
1549 * method to implement own equality checks
1551 * @param $objectInstance An instance of a FrameworkInterface object
1552 * @return $equals Whether both objects equals
1554 public function equals (FrameworkInterface $objectInstance) {
1557 $this->__toString() == $objectInstance->__toString()
1559 $this->hashCode() == $objectInstance->hashCode()
1562 // Return the result
1567 * Generates a generic hash code of this class. You should really overwrite
1568 * this method with your own hash code generator code. But keep KISS in mind.
1570 * @return $hashCode A generic hash code respresenting this whole class
1572 public function hashCode () {
1574 return crc32($this->__toString());
1578 * Formats computer generated price values into human-understandable formats
1579 * with thousand and decimal separators.
1581 * @param $value The in computer format value for a price
1582 * @param $currency The currency symbol (use HTML-valid characters!)
1583 * @param $decNum Number of decimals after commata
1584 * @return $price The for the current language formated price string
1585 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1586 * thousands separator
1589 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1590 // Are all required attriutes set?
1591 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1592 // Throw an exception
1593 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1597 $value = (float) $value;
1599 // Reformat the US number
1600 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1602 // Return as string...
1607 * Appends a trailing slash to a string
1609 * @param $str A string (maybe) without trailing slash
1610 * @return $str A string with an auto-appended trailing slash
1612 public final function addMissingTrailingSlash ($str) {
1613 // Is there a trailing slash?
1614 if (substr($str, -1, 1) != '/') {
1618 // Return string with trailing slash
1623 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1624 * application helper instance (ApplicationHelper by default).
1626 * @param $applicationInstance An application helper instance or
1627 * null if we shall use the default
1628 * @return $templateInstance The template engine instance
1629 * @throws NullPointerException If the discovered application
1630 * instance is still null
1632 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1633 // Is the application instance set?
1634 if (is_null($applicationInstance)) {
1635 // Get the current instance
1636 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1639 if (is_null($applicationInstance)) {
1640 // Thrown an exception
1641 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1645 // Initialize the template engine
1646 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1648 // Return the prepared instance
1649 return $templateInstance;
1653 * Debugs this instance by putting out it's full content
1655 * @param $message Optional message to show in debug output
1658 public final function debugInstance ($message = '') {
1659 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1660 restore_error_handler();
1665 // Is a message set?
1666 if (!empty($message)) {
1667 // Construct message
1668 $content = sprintf('<div class="debug_message">
1670 </div>' . PHP_EOL, $message);
1673 // Generate the output
1674 $content .= sprintf('<pre>%s</pre>',
1677 print_r($this, true)
1683 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1686 <div class="debug_content">
1690 <div class="debug_include_list">
1693 $this->__toString(),
1695 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1700 * Replaces control characters with printable output
1702 * @param $str String with control characters
1703 * @return $str Replaced string
1705 protected function replaceControlCharacters ($str) {
1708 chr(13), '[r]', str_replace(
1709 chr(10), '[n]', str_replace(
1719 * Output a partial stub message for the caller method
1721 * @param $message An optional message to display
1724 protected function partialStub ($message = '') {
1726 $stubMessage = 'Partial Stub!';
1728 // Is the extra message given?
1729 if (!empty($message)) {
1730 // Then add it as well
1731 $stubMessage .= ' Message: ' . $message;
1734 // Debug instance is there?
1735 if (!is_null($this->getDebugInstance())) {
1736 // Output stub message
1737 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1740 trigger_error($stubMessage);
1746 * Outputs a debug backtrace and stops further script execution
1748 * @param $message An optional message to output
1749 * @param $doExit Whether exit the program (true is default)
1752 public function debugBackTrace ($message = '', $doExit = true) {
1753 // Sorry, there is no other way getting this nice backtrace
1754 if (!empty($message)) {
1756 printf('Message: %s<br />' . PHP_EOL, $message);
1760 debug_print_backtrace();
1764 if ($doExit === true) {
1770 * Creates an instance of a debugger instance
1772 * @param $className Name of the class (currently unsupported)
1773 * @param $lineNumber Line number where the call was made
1774 * @return $debugInstance An instance of a debugger class
1775 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1777 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1778 // Is the instance set?
1779 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1780 // Init debug instance
1781 $debugInstance = NULL;
1785 // Get a debugger instance
1786 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1787 } catch (NullPointerException $e) {
1788 // Didn't work, no instance there
1789 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1792 // Empty string should be ignored and used for testing the middleware
1793 DebugMiddleware::getSelfInstance()->output('');
1795 // Set it in registry
1796 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1798 // Get instance from registry
1799 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1803 return $debugInstance;
1807 * Simple output of a message with line-break
1809 * @param $message Message to output
1812 public function outputLine ($message) {
1814 print($message . PHP_EOL);
1818 * Outputs a debug message whether to debug instance (should be set!) or
1819 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1820 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1822 * @param $message Message we shall send out...
1823 * @param $doPrint Whether print or die here (default: print)
1824 * @paran $stripTags Whether to strip tags (default: false)
1827 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1828 // Set debug instance to NULL
1829 $debugInstance = NULL;
1832 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1834 // Is function partialStub/__callStatic ?
1835 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1836 // Prepend class::function:line from 3rd element
1837 $message = sprintf('[%s::%s:%d]: %s',
1838 $backtrace[2]['class'],
1839 $backtrace[2]['function'],
1840 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1844 // Prepend class::function:line from 2nd element
1845 $message = sprintf('[%s::%s:%d]: %s',
1846 $backtrace[1]['class'],
1847 $backtrace[1]['function'],
1848 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1855 // Get debug instance
1856 $debugInstance = $this->getDebugInstance();
1857 } catch (NullPointerException $e) {
1858 // The debug instance is not set (yet)
1861 // Is the debug instance there?
1862 if (is_object($debugInstance)) {
1863 // Use debug output handler
1864 $debugInstance->output($message, $stripTags);
1866 if ($doPrint === false) {
1867 // Die here if not printed
1871 // Are debug times enabled?
1872 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1874 $message = $this->getPrintableExecutionTime() . $message;
1878 if ($doPrint === true) {
1880 $this->outputLine($message);
1889 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1891 * @param $str The string, what ever it is needs to be converted
1892 * @return $className Generated class name
1894 public static final function convertToClassName ($str) {
1898 // Convert all dashes in underscores
1899 $str = self::convertDashesToUnderscores($str);
1901 // Now use that underscores to get classname parts for hungarian style
1902 foreach (explode('_', $str) as $strPart) {
1903 // Make the class name part lower case and first upper case
1904 $className .= ucfirst(strtolower($strPart));
1907 // Return class name
1912 * Converts dashes to underscores, e.g. useable for configuration entries
1914 * @param $str The string with maybe dashes inside
1915 * @return $str The converted string with no dashed, but underscores
1916 * @throws NullPointerException If $str is null
1917 * @throws InvalidArgumentException If $str is empty
1919 public static function convertDashesToUnderscores ($str) {
1921 if (is_null($str)) {
1923 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
1924 } elseif (!is_string($str)) {
1926 throw new InvalidArgumentException(sprintf('str[]=%s is not a string', gettype($str)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1927 } elseif ((is_string($str)) && (empty($str))) {
1929 throw new InvalidArgumentException('str is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1933 $str = str_replace('-', '_', $str);
1935 // Return converted string
1940 * Marks up the code by adding e.g. line numbers
1942 * @param $phpCode Unmarked PHP code
1943 * @return $markedCode Marked PHP code
1945 public function markupCode ($phpCode) {
1950 $errorArray = error_get_last();
1952 // Init the code with error message
1953 if (is_array($errorArray)) {
1955 $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>',
1956 basename($errorArray['file']),
1957 $errorArray['line'],
1958 $errorArray['message'],
1963 // Add line number to the code
1964 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1966 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1968 htmlentities($code, ENT_QUOTES)
1977 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1978 * beatiful for web-based front-ends. If null is given a message id
1979 * null_timestamp will be resolved and returned.
1981 * @param $timestamp Timestamp to prepare (filter) for display
1982 * @return $readable A readable timestamp
1984 public function doFilterFormatTimestamp ($timestamp) {
1985 // Default value to return
1988 // Is the timestamp null?
1989 if (is_null($timestamp)) {
1990 // Get a message string
1991 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1993 switch ($this->getLanguageInstance()->getLanguageCode()) {
1994 case 'de': // German format is a bit different to default
1995 // Split the GMT stamp up
1996 $dateTime = explode(' ', $timestamp );
1997 $dateArray = explode('-', $dateTime[0]);
1998 $timeArray = explode(':', $dateTime[1]);
2000 // Construct the timestamp
2001 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2011 default: // Default is pass-through
2012 $readable = $timestamp;
2022 * Filter a given number into a localized number
2024 * @param $value The raw value from e.g. database
2025 * @return $localized Localized value
2027 public function doFilterFormatNumber ($value) {
2028 // Generate it from config and localize dependencies
2029 switch ($this->getLanguageInstance()->getLanguageCode()) {
2030 case 'de': // German format is a bit different to default
2031 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2034 default: // US, etc.
2035 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2044 * "Getter" for databse entry
2046 * @return $entry An array with database entries
2047 * @throws NullPointerException If the database result is not found
2048 * @throws InvalidDatabaseResultException If the database result is invalid
2050 protected final function getDatabaseEntry () {
2051 // Is there an instance?
2052 if (!$this->getResultInstance() instanceof SearchableResult) {
2053 // Throw an exception here
2054 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2058 $this->getResultInstance()->rewind();
2060 // Do we have an entry?
2061 if ($this->getResultInstance()->valid() === false) {
2062 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2063 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2067 $this->getResultInstance()->next();
2070 $entry = $this->getResultInstance()->current();
2077 * Getter for field name
2079 * @param $fieldName Field name which we shall get
2080 * @return $fieldValue Field value from the user
2081 * @throws NullPointerException If the result instance is null
2083 public final function getField ($fieldName) {
2084 // Default field value
2087 // Get result instance
2088 $resultInstance = $this->getResultInstance();
2090 // Is this instance null?
2091 if (is_null($resultInstance)) {
2092 // Then the user instance is no longer valid (expired cookies?)
2093 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2096 // Get current array
2097 $fieldArray = $resultInstance->current();
2098 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2100 // Convert dashes to underscore
2101 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2103 // Does the field exist?
2104 if ($this->isFieldSet($fieldName)) {
2106 $fieldValue = $fieldArray[$fieldName2];
2107 } elseif (defined('DEVELOPER')) {
2108 // Missing field entry, may require debugging
2109 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2111 // Missing field entry, may require debugging
2112 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2120 * Checks if given field is set
2122 * @param $fieldName Field name to check
2123 * @return $isSet Whether the given field name is set
2124 * @throws NullPointerException If the result instance is null
2126 public function isFieldSet ($fieldName) {
2127 // Get result instance
2128 $resultInstance = $this->getResultInstance();
2130 // Is this instance null?
2131 if (is_null($resultInstance)) {
2132 // Then the user instance is no longer valid (expired cookies?)
2133 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2136 // Get current array
2137 $fieldArray = $resultInstance->current();
2138 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2140 // Convert dashes to underscore
2141 $fieldName = self::convertDashesToUnderscores($fieldName);
2144 $isSet = isset($fieldArray[$fieldName]);
2151 * Flushs all pending updates to the database layer
2155 public function flushPendingUpdates () {
2156 // Get result instance
2157 $resultInstance = $this->getResultInstance();
2159 // Do we have data to update?
2160 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2161 // Get wrapper class name config entry
2162 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2164 // Create object instance
2165 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2167 // Yes, then send the whole result to the database layer
2168 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2173 * Outputs a deprecation warning to the developer.
2175 * @param $message The message we shall output to the developer
2177 * @todo Write a logging mechanism for productive mode
2179 public function deprecationWarning ($message) {
2180 // Is developer mode active?
2181 if (defined('DEVELOPER')) {
2182 // Debug instance is there?
2183 if (!is_null($this->getDebugInstance())) {
2184 // Output stub message
2185 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2188 trigger_error($message . "<br />\n");
2192 // @TODO Finish this part!
2193 $this->partialStub('Developer mode inactive. Message:' . $message);
2198 * Checks whether the given PHP extension is loaded
2200 * @param $phpExtension The PHP extension we shall check
2201 * @return $isLoaded Whether the PHP extension is loaded
2203 public final function isPhpExtensionLoaded ($phpExtension) {
2205 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2212 * "Getter" as a time() replacement but with milliseconds. You should use this
2213 * method instead of the encapsulated getimeofday() function.
2215 * @return $milliTime Timestamp with milliseconds
2217 public function getMilliTime () {
2218 // Get the time of day as float
2219 $milliTime = gettimeofday(true);
2226 * Idles (sleeps) for given milliseconds
2228 * @return $hasSlept Whether it goes fine
2230 public function idle ($milliSeconds) {
2231 // Sleep is fine by default
2234 // Idle so long with found function
2235 if (function_exists('time_sleep_until')) {
2236 // Get current time and add idle time
2237 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2239 // New PHP 5.1.0 function found, ignore errors
2240 $hasSlept = @time_sleep_until($sleepUntil);
2243 * My Sun station doesn't have that function even with latest PHP
2246 usleep($milliSeconds * 1000);
2253 * Converts a hexadecimal string, even with negative sign as first string to
2254 * a decimal number using BC functions.
2256 * This work is based on comment #86673 on php.net documentation page at:
2257 * <http://de.php.net/manual/en/function.dechex.php#86673>
2259 * @param $hex Hexadecimal string
2260 * @return $dec Decimal number
2262 protected function hex2dec ($hex) {
2263 // Convert to all lower-case
2264 $hex = strtolower($hex);
2266 // Detect sign (negative/positive numbers)
2268 if (substr($hex, 0, 1) == '-') {
2270 $hex = substr($hex, 1);
2273 // Decode the hexadecimal string into a decimal number
2275 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2276 $factor = self::$hexdec[substr($hex, $i, 1)];
2277 $dec = bcadd($dec, bcmul($factor, $e));
2280 // Return the decimal number
2281 return $sign . $dec;
2285 * Converts even very large decimal numbers, also signed, to a hexadecimal
2288 * This work is based on comment #97756 on php.net documentation page at:
2289 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2291 * @param $dec Decimal number, even with negative sign
2292 * @param $maxLength Optional maximum length of the string
2293 * @return $hex Hexadecimal string
2295 protected function dec2hex ($dec, $maxLength = 0) {
2296 // maxLength can be zero or devideable by 2
2297 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2299 // Detect sign (negative/positive numbers)
2306 // Encode the decimal number into a hexadecimal string
2309 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2311 } while ($dec >= 1);
2314 * Leading zeros are required for hex-decimal "numbers". In some
2315 * situations more leading zeros are wanted, so check for both
2318 if ($maxLength > 0) {
2319 // Prepend more zeros
2320 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2321 } elseif ((strlen($hex) % 2) != 0) {
2322 // Only make string's length dividable by 2
2326 // Return the hexadecimal string
2327 return $sign . $hex;
2331 * Converts a ASCII string (0 to 255) into a decimal number.
2333 * @param $asc The ASCII string to be converted
2334 * @return $dec Decimal number
2336 protected function asc2dec ($asc) {
2337 // Convert it into a hexadecimal number
2338 $hex = bin2hex($asc);
2340 // And back into a decimal number
2341 $dec = $this->hex2dec($hex);
2348 * Converts a decimal number into an ASCII string.
2350 * @param $dec Decimal number
2351 * @return $asc An ASCII string
2353 protected function dec2asc ($dec) {
2354 // First convert the number into a hexadecimal string
2355 $hex = $this->dec2hex($dec);
2357 // Then convert it into the ASCII string
2358 $asc = $this->hex2asc($hex);
2365 * Converts a hexadecimal number into an ASCII string. Negative numbers
2368 * @param $hex Hexadecimal string
2369 * @return $asc An ASCII string
2371 protected function hex2asc ($hex) {
2372 // Check for length, it must be devideable by 2
2373 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2374 assert((strlen($hex) % 2) == 0);
2378 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2379 // Get the decimal number of the chunk
2380 $part = hexdec(substr($hex, $idx, 2));
2382 // Add it to the final string
2386 // Return the final string
2391 * Checks whether the given encoded data was encoded with Base64
2393 * @param $encodedData Encoded data we shall check
2394 * @return $isBase64 Whether the encoded data is Base64
2396 protected function isBase64Encoded ($encodedData) {
2398 $isBase64 = (@base64_decode($encodedData, true) !== false);
2405 * Gets a cache key from Criteria instance
2407 * @param $criteriaInstance An instance of a Criteria class
2408 * @param $onlyKeys Only use these keys for a cache key
2409 * @return $cacheKey A cache key suitable for lookup/storage purposes
2411 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2413 $cacheKey = sprintf('%s@%s',
2414 $this->__toString(),
2415 $criteriaInstance->getCacheKey($onlyKeys)
2419 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2424 * Getter for startup time in miliseconds
2426 * @return $startupTime Startup time in miliseconds
2428 protected function getStartupTime () {
2429 return self::$startupTime;
2433 * "Getter" for a printable currently execution time in nice braces
2435 * @return $executionTime Current execution time in nice braces
2437 protected function getPrintableExecutionTime () {
2438 // Caculate the execution time
2439 $executionTime = microtime(true) - $this->getStartupTime();
2441 // Pack it in nice braces
2442 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2445 return $executionTime;
2449 * Hashes a given string with a simple but stronger hash function (no salt)
2450 * and hex-encode it.
2452 * @param $str The string to be hashed
2453 * @return $hash The hash from string $str
2455 public static final function hash ($str) {
2456 // Hash given string with (better secure) hasher
2457 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2464 * "Getter" for length of hash() output. This will be "cached" to speed up
2467 * @return $length Length of hash() output
2469 public static final function getHashLength () {
2471 if (is_null(self::$hashLength)) {
2472 // No, then hash a string and save its length.
2473 self::$hashLength = strlen(self::hash('abc123'));
2477 return self::$hashLength;
2481 * Checks whether the given number is really a number (only chars 0-9).
2483 * @param $num A string consisting only chars between 0 and 9
2484 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2485 * @param $assertMismatch Whether to assert mismatches
2486 * @return $ret The (hopefully) secured numbered value
2488 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2489 // Filter all numbers out
2490 $ret = preg_replace('/[^0123456789]/', '', $num);
2493 if ($castValue === true) {
2494 // Cast to biggest numeric type
2495 $ret = (double) $ret;
2498 // Assert only if requested
2499 if ($assertMismatch === true) {
2500 // Has the whole value changed?
2501 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2509 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2511 * @param $num A string consisting only chars between 0 and 9
2512 * @param $assertMismatch Whether to assert mismatches
2513 * @return $ret The (hopefully) secured hext-numbered value
2515 public function hexval ($num, $assertMismatch = false) {
2516 // Filter all numbers out
2517 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2519 // Assert only if requested
2520 if ($assertMismatch === true) {
2521 // Has the whole value changed?
2522 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2530 * Determines if an element is set in the generic array
2532 * @param $keyGroup Main group for the key
2533 * @param $subGroup Sub group for the key
2534 * @param $key Key to check
2535 * @param $element Element to check
2536 * @return $isset Whether the given key is set
2538 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2540 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2543 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2549 * Determines if a key is set in the generic array
2551 * @param $keyGroup Main group for the key
2552 * @param $subGroup Sub group for the key
2553 * @param $key Key to check
2554 * @return $isset Whether the given key is set
2556 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2558 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2561 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2569 * Determines if a group is set in the generic array
2571 * @param $keyGroup Main group
2572 * @param $subGroup Sub group
2573 * @return $isset Whether the given group is set
2575 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2577 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2580 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2587 * Getter for sub key group
2589 * @param $keyGroup Main key group
2590 * @param $subGroup Sub key group
2591 * @return $array An array with all array elements
2593 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2595 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2596 // No, then abort here
2597 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2602 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2605 return $this->genericArray[$keyGroup][$subGroup];
2609 * Unsets a given key in generic array
2611 * @param $keyGroup Main group for the key
2612 * @param $subGroup Sub group for the key
2613 * @param $key Key to unset
2616 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2618 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2621 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2625 * Unsets a given element in generic array
2627 * @param $keyGroup Main group for the key
2628 * @param $subGroup Sub group for the key
2629 * @param $key Key to unset
2630 * @param $element Element to unset
2633 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2635 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2638 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2642 * Append a string to a given generic array key
2644 * @param $keyGroup Main group for the key
2645 * @param $subGroup Sub group for the key
2646 * @param $key Key to unset
2647 * @param $value Value to add/append
2650 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2652 //* 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);
2654 // Is it already there?
2655 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2657 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2660 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2665 * Append a string to a given generic array element
2667 * @param $keyGroup Main group for the key
2668 * @param $subGroup Sub group for the key
2669 * @param $key Key to unset
2670 * @param $element Element to check
2671 * @param $value Value to add/append
2674 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2676 //* 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);
2678 // Is it already there?
2679 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2681 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2684 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2689 * Sets a string in a given generic array element
2691 * @param $keyGroup Main group for the key
2692 * @param $subGroup Sub group for the key
2693 * @param $key Key to unset
2694 * @param $element Element to check
2695 * @param $value Value to add/append
2698 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2700 //* 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);
2703 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2707 * Initializes given generic array group
2709 * @param $keyGroup Main group for the key
2710 * @param $subGroup Sub group for the key
2711 * @param $key Key to use
2712 * @param $forceInit Optionally force initialization
2715 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2717 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2719 // Is it already set?
2720 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2721 // Already initialized
2722 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2727 $this->genericArray[$keyGroup][$subGroup] = array();
2731 * Initializes given generic array key
2733 * @param $keyGroup Main group for the key
2734 * @param $subGroup Sub group for the key
2735 * @param $key Key to use
2736 * @param $forceInit Optionally force initialization
2739 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2741 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2743 // Is it already set?
2744 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2745 // Already initialized
2746 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2751 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2755 * Initializes given generic array element
2757 * @param $keyGroup Main group for the key
2758 * @param $subGroup Sub group for the key
2759 * @param $key Key to use
2760 * @param $element Element to use
2761 * @param $forceInit Optionally force initialization
2764 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2766 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2768 // Is it already set?
2769 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2770 // Already initialized
2771 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2776 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2780 * Pushes an element to a generic key
2782 * @param $keyGroup Main group for the key
2783 * @param $subGroup Sub group for the key
2784 * @param $key Key to use
2785 * @param $value Value to add/append
2786 * @return $count Number of array elements
2788 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2790 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2793 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2795 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2799 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2802 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2803 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2808 * Pushes an element to a generic array element
2810 * @param $keyGroup Main group for the key
2811 * @param $subGroup Sub group for the key
2812 * @param $key Key to use
2813 * @param $element Element to check
2814 * @param $value Value to add/append
2815 * @return $count Number of array elements
2817 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2819 //* 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));
2822 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2824 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2828 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2831 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2832 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2837 * Pops an element from a generic group
2839 * @param $keyGroup Main group for the key
2840 * @param $subGroup Sub group for the key
2841 * @param $key Key to unset
2842 * @return $value Last "popped" value
2844 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2846 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2849 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2851 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2856 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2859 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2860 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2865 * Shifts an element from a generic group
2867 * @param $keyGroup Main group for the key
2868 * @param $subGroup Sub group for the key
2869 * @param $key Key to unset
2870 * @return $value Last "popped" value
2872 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2874 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2877 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2879 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2884 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2887 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2888 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2893 * Count generic array group
2895 * @param $keyGroup Main group for the key
2896 * @return $count Count of given group
2898 protected final function countGenericArray ($keyGroup) {
2900 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2903 if (!isset($this->genericArray[$keyGroup])) {
2905 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2910 $count = count($this->genericArray[$keyGroup]);
2913 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2920 * Count generic array sub group
2922 * @param $keyGroup Main group for the key
2923 * @param $subGroup Sub group for the key
2924 * @return $count Count of given group
2926 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2928 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2931 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2933 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2938 $count = count($this->genericArray[$keyGroup][$subGroup]);
2941 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2948 * Count generic array elements
2950 * @param $keyGroup Main group for the key
2951 * @param $subGroup Sub group for the key
2952 * @para $key Key to count
2953 * @return $count Count of given key
2955 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2957 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2960 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2962 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2964 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2966 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2971 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2974 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2981 * Getter for whole generic group array
2983 * @param $keyGroup Key group to get
2984 * @return $array Whole generic array group
2986 protected final function getGenericArray ($keyGroup) {
2988 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2991 if (!isset($this->genericArray[$keyGroup])) {
2993 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2998 return $this->genericArray[$keyGroup];
3002 * Setter for generic array key
3004 * @param $keyGroup Key group to get
3005 * @param $subGroup Sub group for the key
3006 * @param $key Key to unset
3007 * @param $value Mixed value from generic array element
3010 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3012 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3015 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3019 * Getter for generic array key
3021 * @param $keyGroup Key group to get
3022 * @param $subGroup Sub group for the key
3023 * @param $key Key to unset
3024 * @return $value Mixed value from generic array element
3026 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3028 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3031 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3033 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3038 return $this->genericArray[$keyGroup][$subGroup][$key];
3042 * Sets a value in given generic array key/element
3044 * @param $keyGroup Main group for the key
3045 * @param $subGroup Sub group for the key
3046 * @param $key Key to set
3047 * @param $element Element to set
3048 * @param $value Value to set
3051 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3053 //* 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));
3056 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3060 * Getter for generic array element
3062 * @param $keyGroup Key group to get
3063 * @param $subGroup Sub group for the key
3064 * @param $key Key to look for
3065 * @param $element Element to look for
3066 * @return $value Mixed value from generic array element
3068 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3070 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3073 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3075 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3080 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3084 * Checks if a given sub group is valid (array)
3086 * @param $keyGroup Key group to get
3087 * @param $subGroup Sub group for the key
3088 * @return $isValid Whether given sub group is valid
3090 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3092 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3095 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3102 * Checks if a given key is valid (array)
3104 * @param $keyGroup Key group to get
3105 * @param $subGroup Sub group for the key
3106 * @param $key Key to check
3107 * @return $isValid Whether given sub group is valid
3109 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3111 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3114 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3121 * Initializes the web output instance
3125 protected function initWebOutputInstance () {
3126 // Get application instance
3127 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
3129 // Init web output instance
3130 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3133 $this->setWebOutputInstance($outputInstance);
3137 * Translates boolean true to 'Y' and false to 'N'
3139 * @param $boolean Boolean value
3140 * @return $translated Translated boolean value
3142 public static final function translateBooleanToYesNo ($boolean) {
3143 // Make sure it is really boolean
3144 assert(is_bool($boolean));
3147 $translated = ($boolean === true) ? 'Y' : 'N';
3149 // ... and return it
3154 * Encodes raw data (almost any type) by "serializing" it and then pack it
3155 * into a "binary format".
3157 * @param $rawData Raw data (almost any type)
3158 * @return $encoded Encoded data
3160 protected function encodeData ($rawData) {
3161 // Make sure no objects or resources pass through
3162 assert(!is_object($rawData));
3163 assert(!is_resource($rawData));
3165 // First "serialize" it (json_encode() is faster than serialize())
3166 $encoded = $this->packString(json_encode($rawData));
3173 * Pack a string into a "binary format". Please execuse me that this is
3174 * widely undocumented. :-(
3176 * @param $str Unpacked string
3177 * @return $packed Packed string
3178 * @todo Improve documentation
3180 protected function packString ($str) {
3182 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3184 // First compress the string (gzcompress is okay)
3185 $str = gzcompress($str);
3190 // And start the "encoding" loop
3191 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3193 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3194 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3196 if (($idx + $i) <= strlen($str)) {
3197 $ord = ord(substr($str, ($idx + $i), 1));
3199 $add = $ord * pow(256, $factor);
3203 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3207 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3208 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3210 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3211 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3217 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3222 * Creates a full-qualified file name (FQFN) for given file name by adding
3223 * a configured temporary file path to it.
3225 * @param $infoInstance An instance of a SplFileInfo class
3226 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3227 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3228 * @throws FileIoException If the file cannot be written
3230 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3232 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3234 // Is the path writeable?
3235 if (!is_writable($basePath)) {
3236 // Path is write-protected
3237 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3241 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3244 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3246 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3250 return $tempInstance;
3254 * "Getter" for a printable state name
3256 * @return $stateName Name of the node's state in a printable format
3258 public final function getPrintableState () {
3259 // Default is 'null'
3260 $stateName = 'null';
3262 // Get the state instance
3263 $stateInstance = $this->getStateInstance();
3265 // Is it an instance of Stateable?
3266 if ($stateInstance instanceof Stateable) {
3267 // Then use that state name
3268 $stateName = $stateInstance->getStateName();