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 <<<<<<< HEAD:framework/main/classes/class_BaseFrameworkSystem.php
65 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
67 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
68 >>>>>>> Some updates::inc/main/classes/class_BaseFrameworkSystem.php
69 * @license GNU GPL 3.0 or any newer version
70 * @link http://www.shipsimu.org
72 * This program is free software: you can redistribute it and/or modify
73 * it under the terms of the GNU General Public License as published by
74 * the Free Software Foundation, either version 3 of the License, or
75 * (at your option) any later version.
77 * This program is distributed in the hope that it will be useful,
78 * but WITHOUT ANY WARRANTY; without even the implied warranty of
79 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
80 * GNU General Public License for more details.
82 * You should have received a copy of the GNU General Public License
83 * along with this program. If not, see <http://www.gnu.org/licenses/>.
85 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
87 * Length of output from hash()
89 private static $hashLength = NULL;
94 private $realClass = 'BaseFrameworkSystem';
97 * Search criteria instance
99 private $searchInstance = NULL;
102 * Update criteria instance
104 private $updateInstance = NULL;
107 * The file I/O instance for the template loader
109 private $fileIoInstance = NULL;
114 private $resolverInstance = NULL;
117 * Template engine instance
119 private $templateInstance = NULL;
122 * Database result instance
124 private $resultInstance = NULL;
127 * Instance for user class
129 private $userInstance = NULL;
132 * A controller instance
134 private $controllerInstance = NULL;
139 private $rngInstance = NULL;
142 * Instance of a crypto helper
144 private $cryptoInstance = NULL;
147 * Instance of an Iterator class
149 private $iteratorInstance = NULL;
152 * Instance of the list
154 private $listInstance = NULL;
159 private $menuInstance = NULL;
162 * Instance of the image
164 private $imageInstance = NULL;
167 * Instance of the stacker
169 private $stackInstance = NULL;
172 * A Compressor instance
174 private $compressorInstance = NULL;
177 * A Parseable instance
179 private $parserInstance = NULL;
182 * A database wrapper instance
184 private $databaseInstance = NULL;
187 * A helper instance for the form
189 private $helperInstance = NULL;
192 * An instance of a InputStream class
194 private $inputStreamInstance = NULL;
197 * An instance of a OutputStream class
199 private $outputStreamInstance = NULL;
204 private $handlerInstance = NULL;
207 * Visitor handler instance
209 private $visitorInstance = NULL;
212 * An instance of a database wrapper class
214 private $wrapperInstance = NULL;
217 * An instance of a file I/O pointer class (not handler)
219 private $pointerInstance = NULL;
222 * An instance of an Indexable class
224 private $indexInstance = NULL;
227 * An instance of a Block class
229 private $blockInstance = NULL;
234 private $minableInstance = NULL;
237 * A FrameworkDirectory instance
239 private $directoryInstance = NULL;
242 * The concrete output instance
244 private $outputInstance = NULL;
249 private $stateInstance = NULL;
252 * Registry instance (implementing Register)
254 private $registryInstance = NULL;
259 private $callbackInstance = NULL;
262 * Thousands separator
264 private $thousands = '.'; // German
269 private $decimals = ','; // German
274 private $socketResource = false;
277 * Regular expression to use for validation
279 private $regularExpression = '';
284 private $packageData = array();
289 private $genericArray = array();
294 private $commandName = '';
299 private $controllerName = '';
302 * Array with bitmasks and such for pack/unpack methods to support both
303 * 32-bit and 64-bit systems
305 private $packingData = array(
308 'left' => 0xffff0000,
309 'right' => 0x0000ffff,
315 'left' => 0xffffffff00000000,
316 'right' => 0x00000000ffffffff,
323 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
325 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
327 private $archArrayElement = false;
329 /***********************
330 * Exception codes.... *
331 ***********************/
333 // @todo Try to clean these constants up
334 const EXCEPTION_IS_NULL_POINTER = 0x001;
335 const EXCEPTION_IS_NO_OBJECT = 0x002;
336 const EXCEPTION_IS_NO_ARRAY = 0x003;
337 const EXCEPTION_MISSING_METHOD = 0x004;
338 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
339 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
340 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
341 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
342 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
343 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
344 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
345 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
346 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
347 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
348 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
349 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
350 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
351 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
352 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
353 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
354 const EXCEPTION_PATH_NOT_FOUND = 0x015;
355 const EXCEPTION_INVALID_PATH_NAME = 0x016;
356 const EXCEPTION_READ_PROTECED_PATH = 0x017;
357 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
358 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
359 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
360 const EXCEPTION_INVALID_RESOURCE = 0x01b;
361 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
362 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
363 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
364 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
365 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
366 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
367 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
368 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
369 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
370 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
371 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
372 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
373 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
374 const EXCEPTION_INVALID_STRING = 0x029;
375 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
376 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
377 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
378 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
379 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
380 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
381 const EXCEPTION_MISSING_ELEMENT = 0x030;
382 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
383 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
384 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
385 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
386 const EXCEPTION_FATAL_ERROR = 0x035;
387 const EXCEPTION_FILE_NOT_FOUND = 0x036;
388 const EXCEPTION_ASSERTION_FAILED = 0x037;
389 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
390 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
391 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
392 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
393 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
394 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
395 const EXCEPTION_INVALID_SOCKET = 0x03e;
398 * Hexadecimal->Decimal translation array
400 private static $hexdec = array(
420 * Decimal->hexadecimal translation array
422 private static $dechex = array(
442 * Startup time in miliseconds
444 private static $startupTime = 0;
447 * Protected super constructor
449 * @param $className Name of the class
452 protected function __construct ($className) {
454 $this->setRealClass($className);
456 // Set configuration instance if no registry ...
457 if (!$this instanceof Register) {
458 // ... because registries doesn't need to be configured
459 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
462 // Is the startup time set? (0 cannot be true anymore)
463 if (self::$startupTime == 0) {
465 self::$startupTime = microtime(true);
469 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
473 * Destructor for all classes. You should not call this method on your own.
477 public function __destruct () {
478 // Flush any updated entries to the database
479 $this->flushPendingUpdates();
481 // Is this object already destroyed?
482 if ($this->__toString() != 'DestructedObject') {
483 // Destroy all informations about this class but keep some text about it alive
484 $this->setRealClass('DestructedObject');
485 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
486 // Already destructed object
487 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
491 // Do not call this twice
492 trigger_error(__METHOD__ . ': Called twice.');
498 * The __call() method where all non-implemented methods end up
500 * @param $methodName Name of the missing method
501 * @args $args Arguments passed to the method
504 public final function __call ($methodName, $args) {
505 return self::__callStatic($methodName, $args);
509 * The __callStatic() method where all non-implemented static methods end up
511 * @param $methodName Name of the missing method
512 * @args $args Arguments passed to the method
515 public static final function __callStatic ($methodName, $args) {
517 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
519 // Init argument string
522 // Is it NULL, empty or an array?
523 if (is_null($args)) {
525 $argsString = 'NULL';
526 } elseif (is_array($args)) {
530 // Some arguments are there
531 foreach ($args as $arg) {
532 // Add data about the argument
533 $argsString .= gettype($arg) . ':';
536 // Found a NULL argument
537 $argsString .= 'NULL';
538 } elseif (is_string($arg)) {
539 // Add length for strings
540 $argsString .= strlen($arg);
541 } elseif ((is_int($arg)) || (is_float($arg))) {
544 } elseif (is_array($arg)) {
545 // .. or size if array
546 $argsString .= count($arg);
547 } elseif (is_object($arg)) {
549 $reflection = new ReflectionClass($arg);
551 // Is an other object, maybe no __toString() available
552 $argsString .= $reflection->getName();
553 } elseif ($arg === true) {
554 // ... is boolean 'true'
555 $argsString .= 'true';
556 } elseif ($arg === false) {
557 // ... is boolean 'false'
558 $argsString .= 'false';
561 // Comma for next one
566 if (substr($argsString, -2, 1) == ',') {
567 $argsString = substr($argsString, 0, -2);
573 // Invalid arguments!
574 $argsString = '!INVALID:' . gettype($args) . '!';
577 // Output stub message
578 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
579 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
589 * Getter for $realClass
591 * @return $realClass The name of the real class (not BaseFrameworkSystem)
593 public function __toString () {
594 return $this->realClass;
598 * Magic method to catch setting of missing but set class fields/attributes
600 * @param $name Name of the field/attribute
601 * @param $value Value to store
604 public final function __set ($name, $value) {
605 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
608 print_r($value, true)
613 * Magic method to catch getting of missing fields/attributes
615 * @param $name Name of the field/attribute
618 public final function __get ($name) {
619 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
625 * Magic method to catch unsetting of missing fields/attributes
627 * @param $name Name of the field/attribute
630 public final function __unset ($name) {
631 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
637 * Magic method to catch object serialization
639 * @return $unsupported Unsupported method
640 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
642 public final function __sleep () {
643 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
647 * Magic method to catch object deserialization
649 * @return $unsupported Unsupported method
650 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
652 public final function __wakeup () {
653 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
657 * Magic method to catch calls when an object instance is called
659 * @return $unsupported Unsupported method
660 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
662 public final function __invoke () {
663 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
667 * Setter for the real class name
669 * @param $realClass Class name (string)
672 public final function setRealClass ($realClass) {
674 $this->realClass = (string) $realClass;
678 * Setter for database result instance
680 * @param $resultInstance An instance of a database result class
682 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
684 protected final function setResultInstance (SearchableResult $resultInstance) {
685 $this->resultInstance = $resultInstance;
689 * Getter for database result instance
691 * @return $resultInstance An instance of a database result class
693 public final function getResultInstance () {
694 return $this->resultInstance;
698 * Setter for template engine instances
700 * @param $templateInstance An instance of a template engine class
703 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
704 $this->templateInstance = $templateInstance;
708 * Getter for template engine instances
710 * @return $templateInstance An instance of a template engine class
712 protected final function getTemplateInstance () {
713 return $this->templateInstance;
717 * Setter for search instance
719 * @param $searchInstance Searchable criteria instance
722 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
723 $this->searchInstance = $searchInstance;
727 * Getter for search instance
729 * @return $searchInstance Searchable criteria instance
731 public final function getSearchInstance () {
732 return $this->searchInstance;
736 * Setter for update instance
738 * @param $updateInstance An instance of a LocalUpdateCriteria clase
741 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
742 $this->updateInstance = $updateInstance;
746 * Getter for update instance
748 * @return $updateInstance Updateable criteria instance
750 public final function getUpdateInstance () {
751 return $this->updateInstance;
755 * Setter for resolver instance
757 * @param $resolverInstance Instance of a command resolver class
760 public final function setResolverInstance (Resolver $resolverInstance) {
761 $this->resolverInstance = $resolverInstance;
765 * Getter for resolver instance
767 * @return $resolverInstance Instance of a command resolver class
769 public final function getResolverInstance () {
770 return $this->resolverInstance;
774 * Setter for language instance
776 * @param $configInstance The configuration instance which shall
777 * be FrameworkConfiguration
780 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
781 Registry::getRegistry()->addInstance('config', $configInstance);
785 * Getter for configuration instance
787 * @return $configInstance Configuration instance
789 public final function getConfigInstance () {
790 $configInstance = Registry::getRegistry()->getInstance('config');
791 return $configInstance;
795 * Setter for debug instance
797 * @param $debugInstance The instance for debug output class
800 public final function setDebugInstance (DebugMiddleware $debugInstance) {
801 Registry::getRegistry()->addInstance('debug', $debugInstance);
805 * Getter for debug instance
807 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
809 public final function getDebugInstance () {
810 // Get debug instance
811 $debugInstance = Registry::getRegistry()->getInstance('debug');
814 return $debugInstance;
818 * Setter for web output instance
820 * @param $webInstance The instance for web output class
823 public final function setWebOutputInstance (OutputStreamer $webInstance) {
824 Registry::getRegistry()->addInstance('web_output', $webInstance);
828 * Getter for web output instance
830 * @return $webOutputInstance - Instance to class WebOutput
832 public final function getWebOutputInstance () {
833 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
834 return $webOutputInstance;
838 * Setter for database instance
840 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
843 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
844 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
848 * Getter for database layer
850 * @return $databaseInstance The database layer instance
852 public final function getDatabaseInstance () {
854 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
857 return $databaseInstance;
861 * Setter for compressor channel
863 * @param $compressorInstance An instance of CompressorChannel
866 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
867 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
871 * Getter for compressor channel
873 * @return $compressorInstance The compressor channel
875 public final function getCompressorChannel () {
876 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
877 return $compressorInstance;
881 * Protected getter for a manageable application helper class
883 * @return $applicationInstance An instance of a manageable application helper class
885 protected final function getApplicationInstance () {
886 $applicationInstance = Registry::getRegistry()->getInstance('app');
887 return $applicationInstance;
891 * Setter for a manageable application helper class
893 * @param $applicationInstance An instance of a manageable application helper class
896 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
897 Registry::getRegistry()->addInstance('application', $applicationInstance);
901 * Private getter for language instance
903 * @return $langInstance An instance to the language sub-system
905 protected final function getLanguageInstance () {
906 $langInstance = Registry::getRegistry()->getInstance('language');
907 return $langInstance;
911 * Setter for language instance
913 * @param $langInstance An instance to the language sub-system
915 * @see LanguageSystem
917 public final function setLanguageInstance (ManageableLanguage $langInstance) {
918 Registry::getRegistry()->addInstance('language', $langInstance);
922 * Private getter for file IO instance
924 * @return $fileIoInstance An instance to the file I/O sub-system
926 protected final function getFileIoInstance () {
927 return $this->fileIoInstance;
931 * Setter for file I/O instance
933 * @param $fileIoInstance An instance to the file I/O sub-system
936 public final function setFileIoInstance (IoHandler $fileIoInstance) {
937 $this->fileIoInstance = $fileIoInstance;
941 * Protected setter for user instance
943 * @param $userInstance An instance of a user class
946 protected final function setUserInstance (ManageableAccount $userInstance) {
947 $this->userInstance = $userInstance;
951 * Getter for user instance
953 * @return $userInstance An instance of a user class
955 public final function getUserInstance () {
956 return $this->userInstance;
960 * Setter for controller instance (this surely breaks a bit the MVC patterm)
962 * @param $controllerInstance An instance of the controller
965 public final function setControllerInstance (Controller $controllerInstance) {
966 $this->controllerInstance = $controllerInstance;
970 * Getter for controller instance (this surely breaks a bit the MVC patterm)
972 * @return $controllerInstance An instance of the controller
974 public final function getControllerInstance () {
975 return $this->controllerInstance;
979 * Setter for RNG instance
981 * @param $rngInstance An instance of a random number generator (RNG)
984 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
985 $this->rngInstance = $rngInstance;
989 * Getter for RNG instance
991 * @return $rngInstance An instance of a random number generator (RNG)
993 public final function getRngInstance () {
994 return $this->rngInstance;
998 * Setter for Cryptable instance
1000 * @param $cryptoInstance An instance of a Cryptable class
1003 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1004 $this->cryptoInstance = $cryptoInstance;
1008 * Getter for Cryptable instance
1010 * @return $cryptoInstance An instance of a Cryptable class
1012 public final function getCryptoInstance () {
1013 return $this->cryptoInstance;
1017 * Setter for the list instance
1019 * @param $listInstance A list of Listable
1022 protected final function setListInstance (Listable $listInstance) {
1023 $this->listInstance = $listInstance;
1027 * Getter for the list instance
1029 * @return $listInstance A list of Listable
1031 protected final function getListInstance () {
1032 return $this->listInstance;
1036 * Setter for the menu instance
1038 * @param $menuInstance A RenderableMenu instance
1041 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1042 $this->menuInstance = $menuInstance;
1046 * Getter for the menu instance
1048 * @return $menuInstance A RenderableMenu instance
1050 protected final function getMenuInstance () {
1051 return $this->menuInstance;
1055 * Setter for image instance
1057 * @param $imageInstance An instance of an image
1060 public final function setImageInstance (BaseImage $imageInstance) {
1061 $this->imageInstance = $imageInstance;
1065 * Getter for image instance
1067 * @return $imageInstance An instance of an image
1069 public final function getImageInstance () {
1070 return $this->imageInstance;
1074 * Setter for stacker instance
1076 * @param $stackInstance An instance of an stacker
1079 public final function setStackInstance (Stackable $stackInstance) {
1080 $this->stackInstance = $stackInstance;
1084 * Getter for stacker instance
1086 * @return $stackInstance An instance of an stacker
1088 public final function getStackInstance () {
1089 return $this->stackInstance;
1093 * Setter for compressor instance
1095 * @param $compressorInstance An instance of an compressor
1098 public final function setCompressorInstance (Compressor $compressorInstance) {
1099 $this->compressorInstance = $compressorInstance;
1103 * Getter for compressor instance
1105 * @return $compressorInstance An instance of an compressor
1107 public final function getCompressorInstance () {
1108 return $this->compressorInstance;
1112 * Setter for Parseable instance
1114 * @param $parserInstance An instance of an Parseable
1117 public final function setParserInstance (Parseable $parserInstance) {
1118 $this->parserInstance = $parserInstance;
1122 * Getter for Parseable instance
1124 * @return $parserInstance An instance of an Parseable
1126 public final function getParserInstance () {
1127 return $this->parserInstance;
1131 * Setter for DatabaseWrapper instance
1133 * @param $wrapperInstance An instance of an DatabaseWrapper
1136 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1137 $this->wrapperInstance = $wrapperInstance;
1141 * Getter for DatabaseWrapper instance
1143 * @return $wrapperInstance An instance of an DatabaseWrapper
1145 public final function getWrapperInstance () {
1146 return $this->wrapperInstance;
1150 * Setter for socket resource
1152 * @param $socketResource A valid socket resource
1155 public final function setSocketResource ($socketResource) {
1156 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1157 $this->socketResource = $socketResource;
1161 * Getter for socket resource
1163 * @return $socketResource A valid socket resource
1165 public final function getSocketResource () {
1166 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1167 return $this->socketResource;
1171 * Setter for regular expression
1173 * @param $regularExpression A valid regular expression
1176 public final function setRegularExpression ($regularExpression) {
1177 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1178 $this->regularExpression = $regularExpression;
1182 * Getter for regular expression
1184 * @return $regularExpression A valid regular expression
1186 public final function getRegularExpression () {
1187 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1188 return $this->regularExpression;
1192 * Setter for helper instance
1194 * @param $helperInstance An instance of a helper class
1197 protected final function setHelperInstance (Helper $helperInstance) {
1198 $this->helperInstance = $helperInstance;
1202 * Getter for helper instance
1204 * @return $helperInstance An instance of a helper class
1206 public final function getHelperInstance () {
1207 return $this->helperInstance;
1211 * Getter for a InputStream instance
1213 * @param $inputStreamInstance The InputStream instance
1215 protected final function getInputStreamInstance () {
1216 return $this->inputStreamInstance;
1220 * Setter for a InputStream instance
1222 * @param $inputStreamInstance The InputStream instance
1225 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1226 $this->inputStreamInstance = $inputStreamInstance;
1230 * Getter for a OutputStream instance
1232 * @param $outputStreamInstance The OutputStream instance
1234 protected final function getOutputStreamInstance () {
1235 return $this->outputStreamInstance;
1239 * Setter for a OutputStream instance
1241 * @param $outputStreamInstance The OutputStream instance
1244 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1245 $this->outputStreamInstance = $outputStreamInstance;
1249 * Setter for handler instance
1251 * @param $handlerInstance An instance of a Handleable class
1254 protected final function setHandlerInstance (Handleable $handlerInstance) {
1255 $this->handlerInstance = $handlerInstance;
1259 * Getter for handler instance
1261 * @return $handlerInstance A Handleable instance
1263 protected final function getHandlerInstance () {
1264 return $this->handlerInstance;
1268 * Setter for visitor instance
1270 * @param $visitorInstance A Visitor instance
1273 protected final function setVisitorInstance (Visitor $visitorInstance) {
1274 $this->visitorInstance = $visitorInstance;
1278 * Getter for visitor instance
1280 * @return $visitorInstance A Visitor instance
1282 protected final function getVisitorInstance () {
1283 return $this->visitorInstance;
1287 * Setter for raw package Data
1289 * @param $packageData Raw package Data
1292 public final function setPackageData (array $packageData) {
1293 $this->packageData = $packageData;
1297 * Getter for raw package Data
1299 * @return $packageData Raw package Data
1301 public function getPackageData () {
1302 return $this->packageData;
1307 * Setter for Iterator instance
1309 * @param $iteratorInstance An instance of an Iterator
1312 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1313 $this->iteratorInstance = $iteratorInstance;
1317 * Getter for Iterator instance
1319 * @return $iteratorInstance An instance of an Iterator
1321 public final function getIteratorInstance () {
1322 return $this->iteratorInstance;
1326 * Setter for FilePointer instance
1328 * @param $pointerInstance An instance of an FilePointer class
1331 protected final function setPointerInstance (FilePointer $pointerInstance) {
1332 $this->pointerInstance = $pointerInstance;
1336 * Getter for FilePointer instance
1338 * @return $pointerInstance An instance of an FilePointer class
1340 public final function getPointerInstance () {
1341 return $this->pointerInstance;
1345 * Unsets pointer instance which triggers a call of __destruct() if the
1346 * instance is still there. This is surely not fatal on already "closed"
1347 * file pointer instances.
1349 * I don't want to mess around with above setter by giving it a default
1350 * value NULL as setter should always explicitly only set (existing) object
1351 * instances and NULL is NULL.
1355 protected final function unsetPointerInstance () {
1356 // Simply it to NULL
1357 $this->pointerInstance = NULL;
1361 * Setter for Indexable instance
1363 * @param $indexInstance An instance of an Indexable class
1366 protected final function setIndexInstance (Indexable $indexInstance) {
1367 $this->indexInstance = $indexInstance;
1371 * Getter for Indexable instance
1373 * @return $indexInstance An instance of an Indexable class
1375 public final function getIndexInstance () {
1376 return $this->indexInstance;
1380 * Setter for Block instance
1382 * @param $blockInstance An instance of an Block class
1385 protected final function setBlockInstance (Block $blockInstance) {
1386 $this->blockInstance = $blockInstance;
1390 * Getter for Block instance
1392 * @return $blockInstance An instance of an Block class
1394 public final function getBlockInstance () {
1395 return $this->blockInstance;
1399 * Setter for Minable instance
1401 * @param $minableInstance A Minable instance
1404 protected final function setMinableInstance (Minable $minableInstance) {
1405 $this->minableInstance = $minableInstance;
1409 * Getter for minable instance
1411 * @return $minableInstance A Minable instance
1413 protected final function getMinableInstance () {
1414 return $this->minableInstance;
1418 * Setter for FrameworkDirectory instance
1420 * @param $directoryInstance A FrameworkDirectory instance
1423 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1424 $this->directoryInstance = $directoryInstance;
1428 * Getter for FrameworkDirectory instance
1430 * @return $directoryInstance A FrameworkDirectory instance
1432 protected final function getDirectoryInstance () {
1433 return $this->directoryInstance;
1437 * Setter for state instance
1439 * @param $stateInstance A Stateable instance
1442 public final function setStateInstance (Stateable $stateInstance) {
1443 $this->stateInstance = $stateInstance;
1447 * Getter for state instance
1449 * @return $stateInstance A Stateable instance
1451 public final function getStateInstance () {
1452 return $this->stateInstance;
1456 * Setter for output instance
1458 * @param $outputInstance The debug output instance
1461 public final function setOutputInstance (OutputStreamer $outputInstance) {
1462 $this->outputInstance = $outputInstance;
1466 * Getter for output instance
1468 * @return $outputInstance The debug output instance
1470 public final function getOutputInstance () {
1471 return $this->outputInstance;
1475 * Setter for registry instance
1477 * @param $registryInstance An instance of a Register class
1480 protected final function setRegistryInstance (Register $registryInstance) {
1481 $this->registryInstance = $registryInstance;
1485 * Getter for registry instance
1487 * @return $registryInstance The debug registry instance
1489 public final function getRegistryInstance () {
1490 return $this->registryInstance;
1494 * Setter for call-back instance
1496 * @param $callbackInstance An instance of a FrameworkInterface class
1499 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1500 $this->callbackInstance = $callbackInstance;
1504 * Getter for call-back instance
1506 * @return $callbackInstance An instance of a FrameworkInterface class
1508 protected final function getCallbackInstance () {
1509 return $this->callbackInstance;
1513 * Setter for command name
1515 * @param $commandName Last validated command name
1518 protected final function setCommandName ($commandName) {
1519 $this->commandName = $commandName;
1523 * Getter for command name
1525 * @return $commandName Last validated command name
1527 protected final function getCommandName () {
1528 return $this->commandName;
1532 * Setter for controller name
1534 * @param $controllerName Last validated controller name
1537 protected final function setControllerName ($controllerName) {
1538 $this->controllerName = $controllerName;
1542 * Getter for controller name
1544 * @return $controllerName Last validated controller name
1546 protected final function getControllerName () {
1547 return $this->controllerName;
1551 * Checks whether an object equals this object. You should overwrite this
1552 * method to implement own equality checks
1554 * @param $objectInstance An instance of a FrameworkInterface object
1555 * @return $equals Whether both objects equals
1557 public function equals (FrameworkInterface $objectInstance) {
1560 $this->__toString() == $objectInstance->__toString()
1562 $this->hashCode() == $objectInstance->hashCode()
1565 // Return the result
1570 * Generates a generic hash code of this class. You should really overwrite
1571 * this method with your own hash code generator code. But keep KISS in mind.
1573 * @return $hashCode A generic hash code respresenting this whole class
1575 public function hashCode () {
1577 return crc32($this->__toString());
1581 * Formats computer generated price values into human-understandable formats
1582 * with thousand and decimal separators.
1584 * @param $value The in computer format value for a price
1585 * @param $currency The currency symbol (use HTML-valid characters!)
1586 * @param $decNum Number of decimals after commata
1587 * @return $price The for the current language formated price string
1588 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1589 * thousands separator
1592 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1593 // Are all required attriutes set?
1594 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1595 // Throw an exception
1596 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1600 $value = (float) $value;
1602 // Reformat the US number
1603 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1605 // Return as string...
1610 * Appends a trailing slash to a string
1612 * @param $str A string (maybe) without trailing slash
1613 * @return $str A string with an auto-appended trailing slash
1615 public final function addMissingTrailingSlash ($str) {
1616 // Is there a trailing slash?
1617 if (substr($str, -1, 1) != '/') {
1621 // Return string with trailing slash
1626 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1627 * application helper instance (ApplicationHelper by default).
1629 * @param $applicationInstance An application helper instance or
1630 * null if we shall use the default
1631 * @return $templateInstance The template engine instance
1632 * @throws NullPointerException If the discovered application
1633 * instance is still null
1635 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1636 // Is the application instance set?
1637 if (is_null($applicationInstance)) {
1638 // Get the current instance
1639 $applicationInstance = Registry::getRegistry()->getInstance('app');
1642 if (is_null($applicationInstance)) {
1643 // Thrown an exception
1644 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1648 // Initialize the template engine
1649 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1651 // Return the prepared instance
1652 return $templateInstance;
1656 * Debugs this instance by putting out it's full content
1658 * @param $message Optional message to show in debug output
1661 public final function debugInstance ($message = '') {
1662 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1663 restore_error_handler();
1668 // Is a message set?
1669 if (!empty($message)) {
1670 // Construct message
1671 $content = sprintf('<div class="debug_message">
1673 </div>' . PHP_EOL, $message);
1676 // Generate the output
1677 $content .= sprintf('<pre>%s</pre>',
1680 print_r($this, true)
1686 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1689 <div class="debug_content">
1693 <div class="debug_include_list">
1696 $this->__toString(),
1698 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1703 * Replaces control characters with printable output
1705 * @param $str String with control characters
1706 * @return $str Replaced string
1708 protected function replaceControlCharacters ($str) {
1711 chr(13), '[r]', str_replace(
1712 chr(10), '[n]', str_replace(
1722 * Output a partial stub message for the caller method
1724 * @param $message An optional message to display
1727 protected function partialStub ($message = '') {
1729 $stubMessage = 'Partial Stub!';
1731 // Is the extra message given?
1732 if (!empty($message)) {
1733 // Then add it as well
1734 $stubMessage .= ' Message: ' . $message;
1737 // Debug instance is there?
1738 if (!is_null($this->getDebugInstance())) {
1739 // Output stub message
1740 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1743 trigger_error($stubMessage);
1749 * Outputs a debug backtrace and stops further script execution
1751 * @param $message An optional message to output
1752 * @param $doExit Whether exit the program (true is default)
1755 public function debugBackTrace ($message = '', $doExit = true) {
1756 // Sorry, there is no other way getting this nice backtrace
1757 if (!empty($message)) {
1759 printf('Message: %s<br />' . PHP_EOL, $message);
1763 debug_print_backtrace();
1767 if ($doExit === true) {
1773 * Creates an instance of a debugger instance
1775 * @param $className Name of the class (currently unsupported)
1776 * @param $lineNumber Line number where the call was made
1777 * @return $debugInstance An instance of a debugger class
1778 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1780 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1781 // Is the instance set?
1782 if (!Registry::getRegistry()->instanceExists('debug')) {
1783 // Init debug instance
1784 $debugInstance = NULL;
1788 // Get a debugger instance
1789 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1790 } catch (NullPointerException $e) {
1791 // Didn't work, no instance there
1792 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1795 // Empty string should be ignored and used for testing the middleware
1796 DebugMiddleware::getSelfInstance()->output('');
1798 // Set it in registry
1799 Registry::getRegistry()->addInstance('debug', $debugInstance);
1801 // Get instance from registry
1802 $debugInstance = Registry::getRegistry()->getInstance('debug');
1806 return $debugInstance;
1810 * Simple output of a message with line-break
1812 * @param $message Message to output
1815 public function outputLine ($message) {
1817 print($message . PHP_EOL);
1821 * Outputs a debug message whether to debug instance (should be set!) or
1822 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1823 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1825 * @param $message Message we shall send out...
1826 * @param $doPrint Whether print or die here (default: print)
1827 * @paran $stripTags Whether to strip tags (default: false)
1830 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1831 // Set debug instance to NULL
1832 $debugInstance = NULL;
1835 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1837 // Is function partialStub/__callStatic ?
1838 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1839 // Prepend class::function:line from 3rd element
1840 $message = sprintf('[%s::%s:%d]: %s',
1841 $backtrace[2]['class'],
1842 $backtrace[2]['function'],
1843 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1847 // Prepend class::function:line from 2nd element
1848 $message = sprintf('[%s::%s:%d]: %s',
1849 $backtrace[1]['class'],
1850 $backtrace[1]['function'],
1851 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1858 // Get debug instance
1859 $debugInstance = $this->getDebugInstance();
1860 } catch (NullPointerException $e) {
1861 // The debug instance is not set (yet)
1864 // Is the debug instance there?
1865 if (is_object($debugInstance)) {
1866 // Use debug output handler
1867 $debugInstance->output($message, $stripTags);
1869 if ($doPrint === false) {
1870 // Die here if not printed
1874 // Are debug times enabled?
1875 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1877 $message = $this->getPrintableExecutionTime() . $message;
1881 if ($doPrint === true) {
1883 $this->outputLine($message);
1892 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1894 * @param $str The string, what ever it is needs to be converted
1895 * @return $className Generated class name
1897 public static final function convertToClassName ($str) {
1901 // Convert all dashes in underscores
1902 $str = self::convertDashesToUnderscores($str);
1904 // Now use that underscores to get classname parts for hungarian style
1905 foreach (explode('_', $str) as $strPart) {
1906 // Make the class name part lower case and first upper case
1907 $className .= ucfirst(strtolower($strPart));
1910 // Return class name
1915 * Converts dashes to underscores, e.g. useable for configuration entries
1917 * @param $str The string with maybe dashes inside
1918 * @return $str The converted string with no dashed, but underscores
1919 * @throws NullPointerException If $str is null
1920 * @throws InvalidArgumentException If $str is empty
1922 public static function convertDashesToUnderscores ($str) {
1924 if (is_null($str)) {
1926 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
1927 } elseif (!is_string($str)) {
1929 throw new InvalidArgumentException(sprintf('str[]=%s is not a string', gettype($str)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1930 } elseif ((is_string($str)) && (empty($str))) {
1932 throw new InvalidArgumentException('str is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1936 $str = str_replace('-', '_', $str);
1938 // Return converted string
1943 * Marks up the code by adding e.g. line numbers
1945 * @param $phpCode Unmarked PHP code
1946 * @return $markedCode Marked PHP code
1948 public function markupCode ($phpCode) {
1953 $errorArray = error_get_last();
1955 // Init the code with error message
1956 if (is_array($errorArray)) {
1958 $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>',
1959 basename($errorArray['file']),
1960 $errorArray['line'],
1961 $errorArray['message'],
1966 // Add line number to the code
1967 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1969 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1971 htmlentities($code, ENT_QUOTES)
1980 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1981 * beatiful for web-based front-ends. If null is given a message id
1982 * null_timestamp will be resolved and returned.
1984 * @param $timestamp Timestamp to prepare (filter) for display
1985 * @return $readable A readable timestamp
1987 public function doFilterFormatTimestamp ($timestamp) {
1988 // Default value to return
1991 // Is the timestamp null?
1992 if (is_null($timestamp)) {
1993 // Get a message string
1994 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1996 switch ($this->getLanguageInstance()->getLanguageCode()) {
1997 case 'de': // German format is a bit different to default
1998 // Split the GMT stamp up
1999 $dateTime = explode(' ', $timestamp );
2000 $dateArray = explode('-', $dateTime[0]);
2001 $timeArray = explode(':', $dateTime[1]);
2003 // Construct the timestamp
2004 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2014 default: // Default is pass-through
2015 $readable = $timestamp;
2025 * Filter a given number into a localized number
2027 * @param $value The raw value from e.g. database
2028 * @return $localized Localized value
2030 public function doFilterFormatNumber ($value) {
2031 // Generate it from config and localize dependencies
2032 switch ($this->getLanguageInstance()->getLanguageCode()) {
2033 case 'de': // German format is a bit different to default
2034 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2037 default: // US, etc.
2038 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2047 * "Getter" for databse entry
2049 * @return $entry An array with database entries
2050 * @throws NullPointerException If the database result is not found
2051 * @throws InvalidDatabaseResultException If the database result is invalid
2053 protected final function getDatabaseEntry () {
2054 // Is there an instance?
2055 if (!$this->getResultInstance() instanceof SearchableResult) {
2056 // Throw an exception here
2057 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2061 $this->getResultInstance()->rewind();
2063 // Do we have an entry?
2064 if ($this->getResultInstance()->valid() === false) {
2065 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2066 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2070 $this->getResultInstance()->next();
2073 $entry = $this->getResultInstance()->current();
2080 * Getter for field name
2082 * @param $fieldName Field name which we shall get
2083 * @return $fieldValue Field value from the user
2084 * @throws NullPointerException If the result instance is null
2086 public final function getField ($fieldName) {
2087 // Default field value
2090 // Get result instance
2091 $resultInstance = $this->getResultInstance();
2093 // Is this instance null?
2094 if (is_null($resultInstance)) {
2095 // Then the user instance is no longer valid (expired cookies?)
2096 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2099 // Get current array
2100 $fieldArray = $resultInstance->current();
2101 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2103 // Convert dashes to underscore
2104 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2106 // Does the field exist?
2107 if ($this->isFieldSet($fieldName)) {
2109 $fieldValue = $fieldArray[$fieldName2];
2110 } elseif (defined('DEVELOPER')) {
2111 // Missing field entry, may require debugging
2112 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2114 // Missing field entry, may require debugging
2115 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2123 * Checks if given field is set
2125 * @param $fieldName Field name to check
2126 * @return $isSet Whether the given field name is set
2127 * @throws NullPointerException If the result instance is null
2129 public function isFieldSet ($fieldName) {
2130 // Get result instance
2131 $resultInstance = $this->getResultInstance();
2133 // Is this instance null?
2134 if (is_null($resultInstance)) {
2135 // Then the user instance is no longer valid (expired cookies?)
2136 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2139 // Get current array
2140 $fieldArray = $resultInstance->current();
2141 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2143 // Convert dashes to underscore
2144 $fieldName = self::convertDashesToUnderscores($fieldName);
2147 $isSet = isset($fieldArray[$fieldName]);
2154 * Flushs all pending updates to the database layer
2158 public function flushPendingUpdates () {
2159 // Get result instance
2160 $resultInstance = $this->getResultInstance();
2162 // Do we have data to update?
2163 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2164 // Get wrapper class name config entry
2165 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2167 // Create object instance
2168 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2170 // Yes, then send the whole result to the database layer
2171 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2176 * Outputs a deprecation warning to the developer.
2178 * @param $message The message we shall output to the developer
2180 * @todo Write a logging mechanism for productive mode
2182 public function deprecationWarning ($message) {
2183 // Is developer mode active?
2184 if (defined('DEVELOPER')) {
2185 // Debug instance is there?
2186 if (!is_null($this->getDebugInstance())) {
2187 // Output stub message
2188 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2191 trigger_error($message . "<br />\n");
2195 // @TODO Finish this part!
2196 $this->partialStub('Developer mode inactive. Message:' . $message);
2201 * Checks whether the given PHP extension is loaded
2203 * @param $phpExtension The PHP extension we shall check
2204 * @return $isLoaded Whether the PHP extension is loaded
2206 public final function isPhpExtensionLoaded ($phpExtension) {
2208 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2215 * "Getter" as a time() replacement but with milliseconds. You should use this
2216 * method instead of the encapsulated getimeofday() function.
2218 * @return $milliTime Timestamp with milliseconds
2220 public function getMilliTime () {
2221 // Get the time of day as float
2222 $milliTime = gettimeofday(true);
2229 * Idles (sleeps) for given milliseconds
2231 * @return $hasSlept Whether it goes fine
2233 public function idle ($milliSeconds) {
2234 // Sleep is fine by default
2237 // Idle so long with found function
2238 if (function_exists('time_sleep_until')) {
2239 // Get current time and add idle time
2240 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2242 // New PHP 5.1.0 function found, ignore errors
2243 $hasSlept = @time_sleep_until($sleepUntil);
2246 * My Sun station doesn't have that function even with latest PHP
2249 usleep($milliSeconds * 1000);
2256 * Converts a hexadecimal string, even with negative sign as first string to
2257 * a decimal number using BC functions.
2259 * This work is based on comment #86673 on php.net documentation page at:
2260 * <http://de.php.net/manual/en/function.dechex.php#86673>
2262 * @param $hex Hexadecimal string
2263 * @return $dec Decimal number
2265 protected function hex2dec ($hex) {
2266 // Convert to all lower-case
2267 $hex = strtolower($hex);
2269 // Detect sign (negative/positive numbers)
2271 if (substr($hex, 0, 1) == '-') {
2273 $hex = substr($hex, 1);
2276 // Decode the hexadecimal string into a decimal number
2278 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2279 $factor = self::$hexdec[substr($hex, $i, 1)];
2280 $dec = bcadd($dec, bcmul($factor, $e));
2283 // Return the decimal number
2284 return $sign . $dec;
2288 * Converts even very large decimal numbers, also signed, to a hexadecimal
2291 * This work is based on comment #97756 on php.net documentation page at:
2292 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2294 * @param $dec Decimal number, even with negative sign
2295 * @param $maxLength Optional maximum length of the string
2296 * @return $hex Hexadecimal string
2298 protected function dec2hex ($dec, $maxLength = 0) {
2299 // maxLength can be zero or devideable by 2
2300 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2302 // Detect sign (negative/positive numbers)
2309 // Encode the decimal number into a hexadecimal string
2312 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2314 } while ($dec >= 1);
2317 * Leading zeros are required for hex-decimal "numbers". In some
2318 * situations more leading zeros are wanted, so check for both
2321 if ($maxLength > 0) {
2322 // Prepend more zeros
2323 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2324 } elseif ((strlen($hex) % 2) != 0) {
2325 // Only make string's length dividable by 2
2329 // Return the hexadecimal string
2330 return $sign . $hex;
2334 * Converts a ASCII string (0 to 255) into a decimal number.
2336 * @param $asc The ASCII string to be converted
2337 * @return $dec Decimal number
2339 protected function asc2dec ($asc) {
2340 // Convert it into a hexadecimal number
2341 $hex = bin2hex($asc);
2343 // And back into a decimal number
2344 $dec = $this->hex2dec($hex);
2351 * Converts a decimal number into an ASCII string.
2353 * @param $dec Decimal number
2354 * @return $asc An ASCII string
2356 protected function dec2asc ($dec) {
2357 // First convert the number into a hexadecimal string
2358 $hex = $this->dec2hex($dec);
2360 // Then convert it into the ASCII string
2361 $asc = $this->hex2asc($hex);
2368 * Converts a hexadecimal number into an ASCII string. Negative numbers
2371 * @param $hex Hexadecimal string
2372 * @return $asc An ASCII string
2374 protected function hex2asc ($hex) {
2375 // Check for length, it must be devideable by 2
2376 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2377 assert((strlen($hex) % 2) == 0);
2381 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2382 // Get the decimal number of the chunk
2383 $part = hexdec(substr($hex, $idx, 2));
2385 // Add it to the final string
2389 // Return the final string
2394 * Checks whether the given encoded data was encoded with Base64
2396 * @param $encodedData Encoded data we shall check
2397 * @return $isBase64 Whether the encoded data is Base64
2399 protected function isBase64Encoded ($encodedData) {
2401 $isBase64 = (@base64_decode($encodedData, true) !== false);
2408 * Gets a cache key from Criteria instance
2410 * @param $criteriaInstance An instance of a Criteria class
2411 * @param $onlyKeys Only use these keys for a cache key
2412 * @return $cacheKey A cache key suitable for lookup/storage purposes
2414 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2416 $cacheKey = sprintf('%s@%s',
2417 $this->__toString(),
2418 $criteriaInstance->getCacheKey($onlyKeys)
2422 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2427 * Getter for startup time in miliseconds
2429 * @return $startupTime Startup time in miliseconds
2431 protected function getStartupTime () {
2432 return self::$startupTime;
2436 * "Getter" for a printable currently execution time in nice braces
2438 * @return $executionTime Current execution time in nice braces
2440 protected function getPrintableExecutionTime () {
2441 // Caculate the execution time
2442 $executionTime = microtime(true) - $this->getStartupTime();
2444 // Pack it in nice braces
2445 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2448 return $executionTime;
2452 * Hashes a given string with a simple but stronger hash function (no salt)
2453 * and hex-encode it.
2455 * @param $str The string to be hashed
2456 * @return $hash The hash from string $str
2458 public static final function hash ($str) {
2459 // Hash given string with (better secure) hasher
2460 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2467 * "Getter" for length of hash() output. This will be "cached" to speed up
2470 * @return $length Length of hash() output
2472 public static final function getHashLength () {
2474 if (is_null(self::$hashLength)) {
2475 // No, then hash a string and save its length.
2476 self::$hashLength = strlen(self::hash('abc123'));
2480 return self::$hashLength;
2484 * Checks whether the given number is really a number (only chars 0-9).
2486 * @param $num A string consisting only chars between 0 and 9
2487 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2488 * @param $assertMismatch Whether to assert mismatches
2489 * @return $ret The (hopefully) secured numbered value
2491 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2492 // Filter all numbers out
2493 $ret = preg_replace('/[^0123456789]/', '', $num);
2496 if ($castValue === true) {
2497 // Cast to biggest numeric type
2498 $ret = (double) $ret;
2501 // Assert only if requested
2502 if ($assertMismatch === true) {
2503 // Has the whole value changed?
2504 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2512 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2514 * @param $num A string consisting only chars between 0 and 9
2515 * @param $assertMismatch Whether to assert mismatches
2516 * @return $ret The (hopefully) secured hext-numbered value
2518 public function hexval ($num, $assertMismatch = false) {
2519 // Filter all numbers out
2520 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2522 // Assert only if requested
2523 if ($assertMismatch === true) {
2524 // Has the whole value changed?
2525 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2533 * Determines if an element is set in the generic array
2535 * @param $keyGroup Main group for the key
2536 * @param $subGroup Sub group for the key
2537 * @param $key Key to check
2538 * @param $element Element to check
2539 * @return $isset Whether the given key is set
2541 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2543 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2546 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2552 * Determines if a key is set in the generic array
2554 * @param $keyGroup Main group for the key
2555 * @param $subGroup Sub group for the key
2556 * @param $key Key to check
2557 * @return $isset Whether the given key is set
2559 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2561 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2564 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2572 * Determines if a group is set in the generic array
2574 * @param $keyGroup Main group
2575 * @param $subGroup Sub group
2576 * @return $isset Whether the given group is set
2578 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2580 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2583 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2590 * Getter for sub key group
2592 * @param $keyGroup Main key group
2593 * @param $subGroup Sub key group
2594 * @return $array An array with all array elements
2596 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2598 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2599 // No, then abort here
2600 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2605 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2608 return $this->genericArray[$keyGroup][$subGroup];
2612 * Unsets a given key in generic array
2614 * @param $keyGroup Main group for the key
2615 * @param $subGroup Sub group for the key
2616 * @param $key Key to unset
2619 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2621 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2624 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2628 * Unsets a given element in generic array
2630 * @param $keyGroup Main group for the key
2631 * @param $subGroup Sub group for the key
2632 * @param $key Key to unset
2633 * @param $element Element to unset
2636 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2638 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2641 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2645 * Append a string to a given generic array key
2647 * @param $keyGroup Main group for the key
2648 * @param $subGroup Sub group for the key
2649 * @param $key Key to unset
2650 * @param $value Value to add/append
2653 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2655 //* 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);
2657 // Is it already there?
2658 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2660 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2663 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2668 * Append a string to a given generic array element
2670 * @param $keyGroup Main group for the key
2671 * @param $subGroup Sub group for the key
2672 * @param $key Key to unset
2673 * @param $element Element to check
2674 * @param $value Value to add/append
2677 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2679 //* 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);
2681 // Is it already there?
2682 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2684 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2687 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2692 * Sets a string in a given generic array element
2694 * @param $keyGroup Main group for the key
2695 * @param $subGroup Sub group for the key
2696 * @param $key Key to unset
2697 * @param $element Element to check
2698 * @param $value Value to add/append
2701 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2703 //* 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);
2706 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2710 * Initializes given generic array group
2712 * @param $keyGroup Main group for the key
2713 * @param $subGroup Sub group for the key
2714 * @param $key Key to use
2715 * @param $forceInit Optionally force initialization
2718 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2720 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2722 // Is it already set?
2723 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2724 // Already initialized
2725 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2730 $this->genericArray[$keyGroup][$subGroup] = array();
2734 * Initializes given generic array key
2736 * @param $keyGroup Main group for the key
2737 * @param $subGroup Sub group for the key
2738 * @param $key Key to use
2739 * @param $forceInit Optionally force initialization
2742 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2744 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2746 // Is it already set?
2747 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2748 // Already initialized
2749 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2754 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2758 * Initializes given generic array element
2760 * @param $keyGroup Main group for the key
2761 * @param $subGroup Sub group for the key
2762 * @param $key Key to use
2763 * @param $element Element to use
2764 * @param $forceInit Optionally force initialization
2767 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2769 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2771 // Is it already set?
2772 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2773 // Already initialized
2774 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2779 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2783 * Pushes an element to a generic key
2785 * @param $keyGroup Main group for the key
2786 * @param $subGroup Sub group for the key
2787 * @param $key Key to use
2788 * @param $value Value to add/append
2789 * @return $count Number of array elements
2791 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2793 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2796 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2798 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2802 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2805 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2806 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2811 * Pushes an element to a generic array element
2813 * @param $keyGroup Main group for the key
2814 * @param $subGroup Sub group for the key
2815 * @param $key Key to use
2816 * @param $element Element to check
2817 * @param $value Value to add/append
2818 * @return $count Number of array elements
2820 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2822 //* 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));
2825 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2827 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2831 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2834 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2835 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2840 * Pops an element from a generic group
2842 * @param $keyGroup Main group for the key
2843 * @param $subGroup Sub group for the key
2844 * @param $key Key to unset
2845 * @return $value Last "popped" value
2847 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2849 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2852 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2854 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2859 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2862 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2863 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2868 * Shifts an element from a generic group
2870 * @param $keyGroup Main group for the key
2871 * @param $subGroup Sub group for the key
2872 * @param $key Key to unset
2873 * @return $value Last "popped" value
2875 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2877 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2880 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2882 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2887 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2890 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2891 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2896 * Count generic array group
2898 * @param $keyGroup Main group for the key
2899 * @return $count Count of given group
2901 protected final function countGenericArray ($keyGroup) {
2903 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2906 if (!isset($this->genericArray[$keyGroup])) {
2908 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2913 $count = count($this->genericArray[$keyGroup]);
2916 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2923 * Count generic array sub group
2925 * @param $keyGroup Main group for the key
2926 * @param $subGroup Sub group for the key
2927 * @return $count Count of given group
2929 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2931 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2934 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2936 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2941 $count = count($this->genericArray[$keyGroup][$subGroup]);
2944 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2951 * Count generic array elements
2953 * @param $keyGroup Main group for the key
2954 * @param $subGroup Sub group for the key
2955 * @para $key Key to count
2956 * @return $count Count of given key
2958 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2960 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2963 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2965 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2967 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2969 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2974 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2977 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2984 * Getter for whole generic group array
2986 * @param $keyGroup Key group to get
2987 * @return $array Whole generic array group
2989 protected final function getGenericArray ($keyGroup) {
2991 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2994 if (!isset($this->genericArray[$keyGroup])) {
2996 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3001 return $this->genericArray[$keyGroup];
3005 * Setter for generic array key
3007 * @param $keyGroup Key group to get
3008 * @param $subGroup Sub group for the key
3009 * @param $key Key to unset
3010 * @param $value Mixed value from generic array element
3013 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3015 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3018 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3022 * Getter for generic array key
3024 * @param $keyGroup Key group to get
3025 * @param $subGroup Sub group for the key
3026 * @param $key Key to unset
3027 * @return $value Mixed value from generic array element
3029 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3031 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3034 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3036 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3041 return $this->genericArray[$keyGroup][$subGroup][$key];
3045 * Sets a value in given generic array key/element
3047 * @param $keyGroup Main group for the key
3048 * @param $subGroup Sub group for the key
3049 * @param $key Key to set
3050 * @param $element Element to set
3051 * @param $value Value to set
3054 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3056 //* 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));
3059 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3063 * Getter for generic array element
3065 * @param $keyGroup Key group to get
3066 * @param $subGroup Sub group for the key
3067 * @param $key Key to look for
3068 * @param $element Element to look for
3069 * @return $value Mixed value from generic array element
3071 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3073 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3076 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3078 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3083 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3087 * Checks if a given sub group is valid (array)
3089 * @param $keyGroup Key group to get
3090 * @param $subGroup Sub group for the key
3091 * @return $isValid Whether given sub group is valid
3093 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3095 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3098 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3105 * Checks if a given key is valid (array)
3107 * @param $keyGroup Key group to get
3108 * @param $subGroup Sub group for the key
3109 * @param $key Key to check
3110 * @return $isValid Whether given sub group is valid
3112 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3114 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3117 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3124 * Initializes the web output instance
3128 protected function initWebOutputInstance () {
3129 // Get application instance
3130 $applicationInstance = Registry::getRegistry()->getInstance('app');
3132 // Init web output instance
3133 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3136 $this->setWebOutputInstance($outputInstance);
3140 * Translates boolean true to 'Y' and false to 'N'
3142 * @param $boolean Boolean value
3143 * @return $translated Translated boolean value
3145 public static final function translateBooleanToYesNo ($boolean) {
3146 // Make sure it is really boolean
3147 assert(is_bool($boolean));
3150 $translated = ($boolean === true) ? 'Y' : 'N';
3152 // ... and return it
3157 * Encodes raw data (almost any type) by "serializing" it and then pack it
3158 * into a "binary format".
3160 * @param $rawData Raw data (almost any type)
3161 * @return $encoded Encoded data
3163 protected function encodeData ($rawData) {
3164 // Make sure no objects or resources pass through
3165 assert(!is_object($rawData));
3166 assert(!is_resource($rawData));
3168 // First "serialize" it (json_encode() is faster than serialize())
3169 $encoded = $this->packString(json_encode($rawData));
3176 * Pack a string into a "binary format". Please execuse me that this is
3177 * widely undocumented. :-(
3179 * @param $str Unpacked string
3180 * @return $packed Packed string
3181 * @todo Improve documentation
3183 protected function packString ($str) {
3185 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3187 // First compress the string (gzcompress is okay)
3188 $str = gzcompress($str);
3193 // And start the "encoding" loop
3194 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3196 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3197 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3199 if (($idx + $i) <= strlen($str)) {
3200 $ord = ord(substr($str, ($idx + $i), 1));
3202 $add = $ord * pow(256, $factor);
3206 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3210 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3211 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3213 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3214 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3220 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3225 * Creates a full-qualified file name (FQFN) for given file name by adding
3226 * a configured temporary file path to it.
3228 * @param $infoInstance An instance of a SplFileInfo class
3229 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3230 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3231 * @throws FileIoException If the file cannot be written
3233 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3235 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3237 // Is the path writeable?
3238 if (!is_writable($basePath)) {
3239 // Path is write-protected
3240 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3244 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3247 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3249 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3253 return $tempInstance;
3257 * "Getter" for a printable state name
3259 * @return $stateName Name of the node's state in a printable format
3261 public final function getPrintableState () {
3262 // Default is 'null'
3263 $stateName = 'null';
3265 // Get the state instance
3266 $stateInstance = $this->getStateInstance();
3268 // Is it an instance of Stateable?
3269 if ($stateInstance instanceof Stateable) {
3270 // Then use that state name
3271 $stateName = $stateInstance->getStateName();