3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\Compressor\Compressor;
8 use CoreFramework\Configuration\FrameworkConfiguration;
9 use CoreFramework\Connection\Database\DatabaseConnection;
10 use CoreFramework\Controller\Controller;
11 use CoreFramework\Criteria\Criteria;
12 use CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use CoreFramework\Crypto\Cryptable;
15 use CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use CoreFramework\Database\Frontend\DatabaseWrapper;
17 use CoreFramework\EntryPoint\ApplicationEntryPoint;
18 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
19 use CoreFramework\Factory\ObjectFactory;
20 use CoreFramework\Filesystem\Block;
21 use CoreFramework\Filesystem\FilePointer;
22 use CoreFramework\Filesystem\FrameworkDirectory;
23 use CoreFramework\Filesystem\PathWriteProtectedException;
24 use CoreFramework\Generic\FrameworkInterface;
25 use CoreFramework\Generic\NullPointerException;
26 use CoreFramework\Generic\UnsupportedOperationException;
27 use CoreFramework\Handler\Handleable;
28 use CoreFramework\Handler\Stream\IoHandler;
29 use CoreFramework\Helper\Helper;
30 use CoreFramework\Index\Indexable;
31 use CoreFramework\Lists\Listable;
32 use CoreFramework\Loader\ClassLoader;
33 use CoreFramework\Manager\ManageableApplication;
34 use CoreFramework\Middleware\Compressor\CompressorChannel;
35 use CoreFramework\Middleware\Debug\DebugMiddleware;
36 use CoreFramework\Parser\Parseable;
37 use CoreFramework\Registry\Register;
38 use CoreFramework\Registry\Registry;
39 use CoreFramework\Resolver\Resolver;
40 use CoreFramework\Result\Database\CachedDatabaseResult;
41 use CoreFramework\Result\Search\SearchableResult;
42 use CoreFramework\Stacker\Stackable;
43 use CoreFramework\State\Stateable;
44 use CoreFramework\Stream\Input\InputStream;
45 use CoreFramework\Stream\Output\OutputStreamer;
46 use CoreFramework\Stream\Output\OutputStream;
47 use CoreFramework\Template\CompileableTemplate;
48 use CoreFramework\User\ManageableAccount;
49 use CoreFramework\Visitor\Visitor;
58 * The simulator system class is the super class of all other classes. This
59 * class handles saving of games etc.
61 * @author Roland Haeder <webmaster@shipsimu.org>
63 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
64 * @license GNU GPL 3.0 or any newer version
65 * @link http://www.shipsimu.org
67 * This program is free software: you can redistribute it and/or modify
68 * it under the terms of the GNU General Public License as published by
69 * the Free Software Foundation, either version 3 of the License, or
70 * (at your option) any later version.
72 * This program is distributed in the hope that it will be useful,
73 * but WITHOUT ANY WARRANTY; without even the implied warranty of
74 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
75 * GNU General Public License for more details.
77 * You should have received a copy of the GNU General Public License
78 * along with this program. If not, see <http://www.gnu.org/licenses/>.
80 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
82 * Length of output from hash()
84 private static $hashLength = NULL;
89 private $realClass = 'BaseFrameworkSystem';
92 * Search criteria instance
94 private $searchInstance = NULL;
97 * Update criteria instance
99 private $updateInstance = NULL;
102 * The file I/O instance for the template loader
104 private $fileIoInstance = NULL;
109 private $resolverInstance = NULL;
112 * Template engine instance
114 private $templateInstance = NULL;
117 * Database result instance
119 private $resultInstance = NULL;
122 * Instance for user class
124 private $userInstance = NULL;
127 * A controller instance
129 private $controllerInstance = NULL;
134 private $rngInstance = NULL;
137 * Instance of a crypto helper
139 private $cryptoInstance = NULL;
142 * Instance of an Iterator class
144 private $iteratorInstance = NULL;
147 * Instance of the list
149 private $listInstance = NULL;
154 private $menuInstance = NULL;
157 * Instance of the image
159 private $imageInstance = NULL;
162 * Instance of the stacker
164 private $stackInstance = NULL;
167 * A Compressor instance
169 private $compressorInstance = NULL;
172 * A Parseable instance
174 private $parserInstance = NULL;
177 * A database wrapper instance
179 private $databaseInstance = NULL;
182 * A helper instance for the form
184 private $helperInstance = NULL;
187 * An instance of a Source class
189 private $sourceInstance = NULL;
192 * An instance of a UrlSource class
194 private $urlSourceInstance = NULL;
197 * An instance of a InputStream class
199 private $inputStreamInstance = NULL;
202 * An instance of a OutputStream class
204 private $outputStreamInstance = NULL;
209 private $handlerInstance = NULL;
212 * Visitor handler instance
214 private $visitorInstance = NULL;
217 * An instance of a database wrapper class
219 private $wrapperInstance = NULL;
222 * An instance of a file I/O pointer class (not handler)
224 private $pointerInstance = NULL;
227 * An instance of an Indexable class
229 private $indexInstance = NULL;
232 * An instance of a Block class
234 private $blockInstance = NULL;
239 private $minableInstance = NULL;
242 * A FrameworkDirectory instance
244 private $directoryInstance = NULL;
247 * An instance of a communicator
249 private $communicatorInstance = NULL;
252 * The concrete output instance
254 private $outputInstance = NULL;
259 private $stateInstance = NULL;
262 * Registry instance (implementing Register)
264 private $registryInstance = NULL;
269 private $callbackInstance = NULL;
272 * Thousands separator
274 private $thousands = '.'; // German
279 private $decimals = ','; // German
284 private $socketResource = false;
287 * Regular expression to use for validation
289 private $regularExpression = '';
294 private $packageData = array();
299 private $genericArray = array();
304 private $commandName = '';
309 private $controllerName = '';
312 * Array with bitmasks and such for pack/unpack methods to support both
313 * 32-bit and 64-bit systems
315 private $packingData = array(
318 'left' => 0xffff0000,
319 'right' => 0x0000ffff,
325 'left' => 0xffffffff00000000,
326 'right' => 0x00000000ffffffff,
333 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
335 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
337 private $archArrayElement = false;
339 /***********************
340 * Exception codes.... *
341 ***********************/
343 // @todo Try to clean these constants up
344 const EXCEPTION_IS_NULL_POINTER = 0x001;
345 const EXCEPTION_IS_NO_OBJECT = 0x002;
346 const EXCEPTION_IS_NO_ARRAY = 0x003;
347 const EXCEPTION_MISSING_METHOD = 0x004;
348 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
349 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
350 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
351 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
352 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
353 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
354 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
355 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
356 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
357 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
358 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
359 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
360 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
361 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
362 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
363 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
364 const EXCEPTION_PATH_NOT_FOUND = 0x015;
365 const EXCEPTION_INVALID_PATH_NAME = 0x016;
366 const EXCEPTION_READ_PROTECED_PATH = 0x017;
367 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
368 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
369 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
370 const EXCEPTION_INVALID_RESOURCE = 0x01b;
371 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
372 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
373 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
374 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
375 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
376 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
377 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
378 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
379 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
380 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
381 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
382 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
383 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
384 const EXCEPTION_INVALID_STRING = 0x029;
385 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
386 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
387 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
388 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
389 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
390 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
391 const EXCEPTION_MISSING_ELEMENT = 0x030;
392 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
393 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
394 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
395 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
396 const EXCEPTION_FATAL_ERROR = 0x035;
397 const EXCEPTION_FILE_NOT_FOUND = 0x036;
398 const EXCEPTION_ASSERTION_FAILED = 0x037;
399 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
400 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
401 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
402 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
403 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
404 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
405 const EXCEPTION_INVALID_SOCKET = 0x03e;
408 * Hexadecimal->Decimal translation array
410 private static $hexdec = array(
430 * Decimal->hexadecimal translation array
432 private static $dechex = array(
452 * Startup time in miliseconds
454 private static $startupTime = 0;
457 * Protected super constructor
459 * @param $className Name of the class
462 protected function __construct ($className) {
464 $this->setRealClass($className);
466 // Set configuration instance if no registry ...
467 if (!$this instanceof Register) {
468 // ... because registries doesn't need to be configured
469 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
472 // Is the startup time set? (0 cannot be true anymore)
473 if (self::$startupTime == 0) {
475 self::$startupTime = microtime(true);
479 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
483 * Destructor for all classes. You should not call this method on your own.
487 public function __destruct () {
488 // Flush any updated entries to the database
489 $this->flushPendingUpdates();
491 // Is this object already destroyed?
492 if ($this->__toString() != 'DestructedObject') {
493 // Destroy all informations about this class but keep some text about it alive
494 $this->setRealClass('DestructedObject');
495 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
496 // Already destructed object
497 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
501 // Do not call this twice
502 trigger_error(__METHOD__ . ': Called twice.');
508 * The __call() method where all non-implemented methods end up
510 * @param $methodName Name of the missing method
511 * @args $args Arguments passed to the method
514 public final function __call ($methodName, $args) {
515 return self::__callStatic($methodName, $args);
519 * The __callStatic() method where all non-implemented static methods end up
521 * @param $methodName Name of the missing method
522 * @args $args Arguments passed to the method
525 public static final function __callStatic ($methodName, $args) {
527 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
529 // Init argument string
532 // Is it NULL, empty or an array?
533 if (is_null($args)) {
535 $argsString = 'NULL';
536 } elseif (is_array($args)) {
540 // Some arguments are there
541 foreach ($args as $arg) {
542 // Add data about the argument
543 $argsString .= gettype($arg) . ':';
546 // Found a NULL argument
547 $argsString .= 'NULL';
548 } elseif (is_string($arg)) {
549 // Add length for strings
550 $argsString .= strlen($arg);
551 } elseif ((is_int($arg)) || (is_float($arg))) {
554 } elseif (is_array($arg)) {
555 // .. or size if array
556 $argsString .= count($arg);
557 } elseif (is_object($arg)) {
559 $reflection = new ReflectionClass($arg);
561 // Is an other object, maybe no __toString() available
562 $argsString .= $reflection->getName();
563 } elseif ($arg === true) {
564 // ... is boolean 'true'
565 $argsString .= 'true';
566 } elseif ($arg === false) {
567 // ... is boolean 'false'
568 $argsString .= 'false';
571 // Comma for next one
576 if (substr($argsString, -2, 1) == ',') {
577 $argsString = substr($argsString, 0, -2);
583 // Invalid arguments!
584 $argsString = '!INVALID:' . gettype($args) . '!';
587 // Output stub message
588 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
589 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
599 * Getter for $realClass
601 * @return $realClass The name of the real class (not BaseFrameworkSystem)
603 public function __toString () {
604 return $this->realClass;
608 * Magic method to catch setting of missing but set class fields/attributes
610 * @param $name Name of the field/attribute
611 * @param $value Value to store
614 public final function __set ($name, $value) {
615 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
618 print_r($value, true)
623 * Magic method to catch getting of missing fields/attributes
625 * @param $name Name of the field/attribute
628 public final function __get ($name) {
629 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
635 * Magic method to catch unsetting of missing fields/attributes
637 * @param $name Name of the field/attribute
640 public final function __unset ($name) {
641 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
647 * Magic method to catch object serialization
649 * @return $unsupported Unsupported method
650 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
652 public final function __sleep () {
653 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
657 * Magic method to catch object deserialization
659 * @return $unsupported Unsupported method
660 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
662 public final function __wakeup () {
663 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
667 * Magic method to catch calls when an object instance is called
669 * @return $unsupported Unsupported method
670 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
672 public final function __invoke () {
673 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
677 * Setter for the real class name
679 * @param $realClass Class name (string)
682 public final function setRealClass ($realClass) {
684 $this->realClass = (string) $realClass;
688 * Setter for database result instance
690 * @param $resultInstance An instance of a database result class
692 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
694 protected final function setResultInstance (SearchableResult $resultInstance) {
695 $this->resultInstance = $resultInstance;
699 * Getter for database result instance
701 * @return $resultInstance An instance of a database result class
703 public final function getResultInstance () {
704 return $this->resultInstance;
708 * Setter for template engine instances
710 * @param $templateInstance An instance of a template engine class
713 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
714 $this->templateInstance = $templateInstance;
718 * Getter for template engine instances
720 * @return $templateInstance An instance of a template engine class
722 protected final function getTemplateInstance () {
723 return $this->templateInstance;
727 * Setter for search instance
729 * @param $searchInstance Searchable criteria instance
732 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
733 $this->searchInstance = $searchInstance;
737 * Getter for search instance
739 * @return $searchInstance Searchable criteria instance
741 public final function getSearchInstance () {
742 return $this->searchInstance;
746 * Setter for update instance
748 * @param $updateInstance An instance of a LocalUpdateCriteria clase
751 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
752 $this->updateInstance = $updateInstance;
756 * Getter for update instance
758 * @return $updateInstance Updateable criteria instance
760 public final function getUpdateInstance () {
761 return $this->updateInstance;
765 * Setter for resolver instance
767 * @param $resolverInstance Instance of a command resolver class
770 public final function setResolverInstance (Resolver $resolverInstance) {
771 $this->resolverInstance = $resolverInstance;
775 * Getter for resolver instance
777 * @return $resolverInstance Instance of a command resolver class
779 public final function getResolverInstance () {
780 return $this->resolverInstance;
784 * Setter for language instance
786 * @param $configInstance The configuration instance which shall
787 * be FrameworkConfiguration
790 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
791 Registry::getRegistry()->addInstance('config', $configInstance);
795 * Getter for configuration instance
797 * @return $configInstance Configuration instance
799 public final function getConfigInstance () {
800 $configInstance = Registry::getRegistry()->getInstance('config');
801 return $configInstance;
805 * Setter for debug instance
807 * @param $debugInstance The instance for debug output class
810 public final function setDebugInstance (DebugMiddleware $debugInstance) {
811 Registry::getRegistry()->addInstance('debug', $debugInstance);
815 * Getter for debug instance
817 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
819 public final function getDebugInstance () {
820 // Get debug instance
821 $debugInstance = Registry::getRegistry()->getInstance('debug');
824 return $debugInstance;
828 * Setter for web output instance
830 * @param $webInstance The instance for web output class
833 public final function setWebOutputInstance (OutputStreamer $webInstance) {
834 Registry::getRegistry()->addInstance('web_output', $webInstance);
838 * Getter for web output instance
840 * @return $webOutputInstance - Instance to class WebOutput
842 public final function getWebOutputInstance () {
843 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
844 return $webOutputInstance;
848 * Setter for database instance
850 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
853 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
854 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
858 * Getter for database layer
860 * @return $databaseInstance The database layer instance
862 public final function getDatabaseInstance () {
864 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
867 return $databaseInstance;
871 * Setter for compressor channel
873 * @param $compressorInstance An instance of CompressorChannel
876 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
877 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
881 * Getter for compressor channel
883 * @return $compressorInstance The compressor channel
885 public final function getCompressorChannel () {
886 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
887 return $compressorInstance;
891 * Protected getter for a manageable application helper class
893 * @return $applicationInstance An instance of a manageable application helper class
895 protected final function getApplicationInstance () {
896 $applicationInstance = Registry::getRegistry()->getInstance('app');
897 return $applicationInstance;
901 * Setter for a manageable application helper class
903 * @param $applicationInstance An instance of a manageable application helper class
906 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
907 Registry::getRegistry()->addInstance('application', $applicationInstance);
911 * Private getter for language instance
913 * @return $langInstance An instance to the language sub-system
915 protected final function getLanguageInstance () {
916 $langInstance = Registry::getRegistry()->getInstance('language');
917 return $langInstance;
921 * Setter for language instance
923 * @param $langInstance An instance to the language sub-system
925 * @see LanguageSystem
927 public final function setLanguageInstance (ManageableLanguage $langInstance) {
928 Registry::getRegistry()->addInstance('language', $langInstance);
932 * Private getter for file IO instance
934 * @return $fileIoInstance An instance to the file I/O sub-system
936 protected final function getFileIoInstance () {
937 return $this->fileIoInstance;
941 * Setter for file I/O instance
943 * @param $fileIoInstance An instance to the file I/O sub-system
946 public final function setFileIoInstance (IoHandler $fileIoInstance) {
947 $this->fileIoInstance = $fileIoInstance;
951 * Protected setter for user instance
953 * @param $userInstance An instance of a user class
956 protected final function setUserInstance (ManageableAccount $userInstance) {
957 $this->userInstance = $userInstance;
961 * Getter for user instance
963 * @return $userInstance An instance of a user class
965 public final function getUserInstance () {
966 return $this->userInstance;
970 * Setter for controller instance (this surely breaks a bit the MVC patterm)
972 * @param $controllerInstance An instance of the controller
975 public final function setControllerInstance (Controller $controllerInstance) {
976 $this->controllerInstance = $controllerInstance;
980 * Getter for controller instance (this surely breaks a bit the MVC patterm)
982 * @return $controllerInstance An instance of the controller
984 public final function getControllerInstance () {
985 return $this->controllerInstance;
989 * Setter for RNG instance
991 * @param $rngInstance An instance of a random number generator (RNG)
994 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
995 $this->rngInstance = $rngInstance;
999 * Getter for RNG instance
1001 * @return $rngInstance An instance of a random number generator (RNG)
1003 public final function getRngInstance () {
1004 return $this->rngInstance;
1008 * Setter for Cryptable instance
1010 * @param $cryptoInstance An instance of a Cryptable class
1013 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1014 $this->cryptoInstance = $cryptoInstance;
1018 * Getter for Cryptable instance
1020 * @return $cryptoInstance An instance of a Cryptable class
1022 public final function getCryptoInstance () {
1023 return $this->cryptoInstance;
1027 * Setter for the list instance
1029 * @param $listInstance A list of Listable
1032 protected final function setListInstance (Listable $listInstance) {
1033 $this->listInstance = $listInstance;
1037 * Getter for the list instance
1039 * @return $listInstance A list of Listable
1041 protected final function getListInstance () {
1042 return $this->listInstance;
1046 * Setter for the menu instance
1048 * @param $menuInstance A RenderableMenu instance
1051 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1052 $this->menuInstance = $menuInstance;
1056 * Getter for the menu instance
1058 * @return $menuInstance A RenderableMenu instance
1060 protected final function getMenuInstance () {
1061 return $this->menuInstance;
1065 * Setter for image instance
1067 * @param $imageInstance An instance of an image
1070 public final function setImageInstance (BaseImage $imageInstance) {
1071 $this->imageInstance = $imageInstance;
1075 * Getter for image instance
1077 * @return $imageInstance An instance of an image
1079 public final function getImageInstance () {
1080 return $this->imageInstance;
1084 * Setter for stacker instance
1086 * @param $stackInstance An instance of an stacker
1089 public final function setStackInstance (Stackable $stackInstance) {
1090 $this->stackInstance = $stackInstance;
1094 * Getter for stacker instance
1096 * @return $stackInstance An instance of an stacker
1098 public final function getStackInstance () {
1099 return $this->stackInstance;
1103 * Setter for compressor instance
1105 * @param $compressorInstance An instance of an compressor
1108 public final function setCompressorInstance (Compressor $compressorInstance) {
1109 $this->compressorInstance = $compressorInstance;
1113 * Getter for compressor instance
1115 * @return $compressorInstance An instance of an compressor
1117 public final function getCompressorInstance () {
1118 return $this->compressorInstance;
1122 * Setter for Parseable instance
1124 * @param $parserInstance An instance of an Parseable
1127 public final function setParserInstance (Parseable $parserInstance) {
1128 $this->parserInstance = $parserInstance;
1132 * Getter for Parseable instance
1134 * @return $parserInstance An instance of an Parseable
1136 public final function getParserInstance () {
1137 return $this->parserInstance;
1141 * Setter for DatabaseWrapper instance
1143 * @param $wrapperInstance An instance of an DatabaseWrapper
1146 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1147 $this->wrapperInstance = $wrapperInstance;
1151 * Getter for DatabaseWrapper instance
1153 * @return $wrapperInstance An instance of an DatabaseWrapper
1155 public final function getWrapperInstance () {
1156 return $this->wrapperInstance;
1160 * Setter for socket resource
1162 * @param $socketResource A valid socket resource
1165 public final function setSocketResource ($socketResource) {
1166 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1167 $this->socketResource = $socketResource;
1171 * Getter for socket resource
1173 * @return $socketResource A valid socket resource
1175 public final function getSocketResource () {
1176 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1177 return $this->socketResource;
1181 * Setter for regular expression
1183 * @param $regularExpression A valid regular expression
1186 public final function setRegularExpression ($regularExpression) {
1187 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1188 $this->regularExpression = $regularExpression;
1192 * Getter for regular expression
1194 * @return $regularExpression A valid regular expression
1196 public final function getRegularExpression () {
1197 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1198 return $this->regularExpression;
1202 * Setter for helper instance
1204 * @param $helperInstance An instance of a helper class
1207 protected final function setHelperInstance (Helper $helperInstance) {
1208 $this->helperInstance = $helperInstance;
1212 * Getter for helper instance
1214 * @return $helperInstance An instance of a helper class
1216 public final function getHelperInstance () {
1217 return $this->helperInstance;
1221 * Setter for a Source instance
1223 * @param $sourceInstance An instance of a Source class
1226 protected final function setSourceInstance (Source $sourceInstance) {
1227 $this->sourceInstance = $sourceInstance;
1231 * Getter for a Source instance
1233 * @return $sourceInstance An instance of a Source class
1235 protected final function getSourceInstance () {
1236 return $this->sourceInstance;
1240 * Setter for a UrlSource instance
1242 * @param $sourceInstance An instance of a UrlSource class
1245 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1246 $this->urlSourceInstance = $urlSourceInstance;
1250 * Getter for a UrlSource instance
1252 * @return $urlSourceInstance An instance of a UrlSource class
1254 protected final function getUrlSourceInstance () {
1255 return $this->urlSourceInstance;
1259 * Getter for a InputStream instance
1261 * @param $inputStreamInstance The InputStream instance
1263 protected final function getInputStreamInstance () {
1264 return $this->inputStreamInstance;
1268 * Setter for a InputStream instance
1270 * @param $inputStreamInstance The InputStream instance
1273 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1274 $this->inputStreamInstance = $inputStreamInstance;
1278 * Getter for a OutputStream instance
1280 * @param $outputStreamInstance The OutputStream instance
1282 protected final function getOutputStreamInstance () {
1283 return $this->outputStreamInstance;
1287 * Setter for a OutputStream instance
1289 * @param $outputStreamInstance The OutputStream instance
1292 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1293 $this->outputStreamInstance = $outputStreamInstance;
1297 * Setter for handler instance
1299 * @param $handlerInstance An instance of a Handleable class
1302 protected final function setHandlerInstance (Handleable $handlerInstance) {
1303 $this->handlerInstance = $handlerInstance;
1307 * Getter for handler instance
1309 * @return $handlerInstance A Handleable instance
1311 protected final function getHandlerInstance () {
1312 return $this->handlerInstance;
1316 * Setter for visitor instance
1318 * @param $visitorInstance A Visitor instance
1321 protected final function setVisitorInstance (Visitor $visitorInstance) {
1322 $this->visitorInstance = $visitorInstance;
1326 * Getter for visitor instance
1328 * @return $visitorInstance A Visitor instance
1330 protected final function getVisitorInstance () {
1331 return $this->visitorInstance;
1335 * Setter for raw package Data
1337 * @param $packageData Raw package Data
1340 public final function setPackageData (array $packageData) {
1341 $this->packageData = $packageData;
1345 * Getter for raw package Data
1347 * @return $packageData Raw package Data
1349 public function getPackageData () {
1350 return $this->packageData;
1355 * Setter for Iterator instance
1357 * @param $iteratorInstance An instance of an Iterator
1360 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1361 $this->iteratorInstance = $iteratorInstance;
1365 * Getter for Iterator instance
1367 * @return $iteratorInstance An instance of an Iterator
1369 public final function getIteratorInstance () {
1370 return $this->iteratorInstance;
1374 * Setter for FilePointer instance
1376 * @param $pointerInstance An instance of an FilePointer class
1379 protected final function setPointerInstance (FilePointer $pointerInstance) {
1380 $this->pointerInstance = $pointerInstance;
1384 * Getter for FilePointer instance
1386 * @return $pointerInstance An instance of an FilePointer class
1388 public final function getPointerInstance () {
1389 return $this->pointerInstance;
1393 * Unsets pointer instance which triggers a call of __destruct() if the
1394 * instance is still there. This is surely not fatal on already "closed"
1395 * file pointer instances.
1397 * I don't want to mess around with above setter by giving it a default
1398 * value NULL as setter should always explicitly only set (existing) object
1399 * instances and NULL is NULL.
1403 protected final function unsetPointerInstance () {
1404 // Simply it to NULL
1405 $this->pointerInstance = NULL;
1409 * Setter for Indexable instance
1411 * @param $indexInstance An instance of an Indexable class
1414 protected final function setIndexInstance (Indexable $indexInstance) {
1415 $this->indexInstance = $indexInstance;
1419 * Getter for Indexable instance
1421 * @return $indexInstance An instance of an Indexable class
1423 public final function getIndexInstance () {
1424 return $this->indexInstance;
1428 * Setter for Block instance
1430 * @param $blockInstance An instance of an Block class
1433 protected final function setBlockInstance (Block $blockInstance) {
1434 $this->blockInstance = $blockInstance;
1438 * Getter for Block instance
1440 * @return $blockInstance An instance of an Block class
1442 public final function getBlockInstance () {
1443 return $this->blockInstance;
1447 * Setter for Minable instance
1449 * @param $minableInstance A Minable instance
1452 protected final function setMinableInstance (Minable $minableInstance) {
1453 $this->minableInstance = $minableInstance;
1457 * Getter for minable instance
1459 * @return $minableInstance A Minable instance
1461 protected final function getMinableInstance () {
1462 return $this->minableInstance;
1466 * Setter for FrameworkDirectory instance
1468 * @param $directoryInstance A FrameworkDirectory instance
1471 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1472 $this->directoryInstance = $directoryInstance;
1476 * Getter for FrameworkDirectory instance
1478 * @return $directoryInstance A FrameworkDirectory instance
1480 protected final function getDirectoryInstance () {
1481 return $this->directoryInstance;
1485 * Getter for communicator instance
1487 * @return $communicatorInstance An instance of a Communicator class
1489 public final function getCommunicatorInstance () {
1490 return $this->communicatorInstance;
1494 * Setter for communicator instance
1496 * @param $communicatorInstance An instance of a Communicator class
1499 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1500 $this->communicatorInstance = $communicatorInstance;
1504 * Setter for state instance
1506 * @param $stateInstance A Stateable instance
1509 public final function setStateInstance (Stateable $stateInstance) {
1510 $this->stateInstance = $stateInstance;
1514 * Getter for state instance
1516 * @return $stateInstance A Stateable instance
1518 public final function getStateInstance () {
1519 return $this->stateInstance;
1523 * Setter for output instance
1525 * @param $outputInstance The debug output instance
1528 public final function setOutputInstance (OutputStreamer $outputInstance) {
1529 $this->outputInstance = $outputInstance;
1533 * Getter for output instance
1535 * @return $outputInstance The debug output instance
1537 public final function getOutputInstance () {
1538 return $this->outputInstance;
1542 * Setter for registry instance
1544 * @param $registryInstance An instance of a Register class
1547 protected final function setRegistryInstance (Register $registryInstance) {
1548 $this->registryInstance = $registryInstance;
1552 * Getter for registry instance
1554 * @return $registryInstance The debug registry instance
1556 public final function getRegistryInstance () {
1557 return $this->registryInstance;
1561 * Setter for call-back instance
1563 * @param $callbackInstance An instance of a FrameworkInterface class
1566 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1567 $this->callbackInstance = $callbackInstance;
1571 * Getter for call-back instance
1573 * @return $callbackInstance An instance of a FrameworkInterface class
1575 protected final function getCallbackInstance () {
1576 return $this->callbackInstance;
1580 * Setter for command name
1582 * @param $commandName Last validated command name
1585 protected final function setCommandName ($commandName) {
1586 $this->commandName = $commandName;
1590 * Getter for command name
1592 * @return $commandName Last validated command name
1594 protected final function getCommandName () {
1595 return $this->commandName;
1599 * Setter for controller name
1601 * @param $controllerName Last validated controller name
1604 protected final function setControllerName ($controllerName) {
1605 $this->controllerName = $controllerName;
1609 * Getter for controller name
1611 * @return $controllerName Last validated controller name
1613 protected final function getControllerName () {
1614 return $this->controllerName;
1618 * Checks whether an object equals this object. You should overwrite this
1619 * method to implement own equality checks
1621 * @param $objectInstance An instance of a FrameworkInterface object
1622 * @return $equals Whether both objects equals
1624 public function equals (FrameworkInterface $objectInstance) {
1627 $this->__toString() == $objectInstance->__toString()
1629 $this->hashCode() == $objectInstance->hashCode()
1632 // Return the result
1637 * Generates a generic hash code of this class. You should really overwrite
1638 * this method with your own hash code generator code. But keep KISS in mind.
1640 * @return $hashCode A generic hash code respresenting this whole class
1642 public function hashCode () {
1644 return crc32($this->__toString());
1648 * Formats computer generated price values into human-understandable formats
1649 * with thousand and decimal separators.
1651 * @param $value The in computer format value for a price
1652 * @param $currency The currency symbol (use HTML-valid characters!)
1653 * @param $decNum Number of decimals after commata
1654 * @return $price The for the current language formated price string
1655 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1656 * thousands separator
1659 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1660 // Are all required attriutes set?
1661 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1662 // Throw an exception
1663 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1667 $value = (float) $value;
1669 // Reformat the US number
1670 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1672 // Return as string...
1677 * Appends a trailing slash to a string
1679 * @param $str A string (maybe) without trailing slash
1680 * @return $str A string with an auto-appended trailing slash
1682 public final function addMissingTrailingSlash ($str) {
1683 // Is there a trailing slash?
1684 if (substr($str, -1, 1) != '/') {
1688 // Return string with trailing slash
1693 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1694 * application helper instance (ApplicationHelper by default).
1696 * @param $applicationInstance An application helper instance or
1697 * null if we shall use the default
1698 * @return $templateInstance The template engine instance
1699 * @throws NullPointerException If the discovered application
1700 * instance is still null
1702 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1703 // Is the application instance set?
1704 if (is_null($applicationInstance)) {
1705 // Get the current instance
1706 $applicationInstance = Registry::getRegistry()->getInstance('app');
1709 if (is_null($applicationInstance)) {
1710 // Thrown an exception
1711 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1715 // Initialize the template engine
1716 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1718 // Return the prepared instance
1719 return $templateInstance;
1723 * Debugs this instance by putting out it's full content
1725 * @param $message Optional message to show in debug output
1728 public final function debugInstance ($message = '') {
1729 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1730 restore_error_handler();
1735 // Is a message set?
1736 if (!empty($message)) {
1737 // Construct message
1738 $content = sprintf('<div class="debug_message">
1740 </div>' . PHP_EOL, $message);
1743 // Generate the output
1744 $content .= sprintf('<pre>%s</pre>',
1747 print_r($this, true)
1753 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1756 <div class="debug_content">
1760 <div class="debug_include_list">
1763 $this->__toString(),
1765 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1770 * Replaces control characters with printable output
1772 * @param $str String with control characters
1773 * @return $str Replaced string
1775 protected function replaceControlCharacters ($str) {
1778 chr(13), '[r]', str_replace(
1779 chr(10), '[n]', str_replace(
1789 * Output a partial stub message for the caller method
1791 * @param $message An optional message to display
1794 protected function partialStub ($message = '') {
1796 $stubMessage = 'Partial Stub!';
1798 // Is the extra message given?
1799 if (!empty($message)) {
1800 // Then add it as well
1801 $stubMessage .= ' Message: ' . $message;
1804 // Debug instance is there?
1805 if (!is_null($this->getDebugInstance())) {
1806 // Output stub message
1807 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1810 trigger_error($stubMessage);
1816 * Outputs a debug backtrace and stops further script execution
1818 * @param $message An optional message to output
1819 * @param $doExit Whether exit the program (true is default)
1822 public function debugBackTrace ($message = '', $doExit = true) {
1823 // Sorry, there is no other way getting this nice backtrace
1824 if (!empty($message)) {
1826 printf('Message: %s<br />' . PHP_EOL, $message);
1830 debug_print_backtrace();
1834 if ($doExit === true) {
1840 * Creates an instance of a debugger instance
1842 * @param $className Name of the class (currently unsupported)
1843 * @param $lineNumber Line number where the call was made
1844 * @return $debugInstance An instance of a debugger class
1845 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1847 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1848 // Is the instance set?
1849 if (!Registry::getRegistry()->instanceExists('debug')) {
1850 // Init debug instance
1851 $debugInstance = NULL;
1855 // Get a debugger instance
1856 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1857 } catch (NullPointerException $e) {
1858 // Didn't work, no instance there
1859 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1862 // Empty string should be ignored and used for testing the middleware
1863 DebugMiddleware::getSelfInstance()->output('');
1865 // Set it in registry
1866 Registry::getRegistry()->addInstance('debug', $debugInstance);
1868 // Get instance from registry
1869 $debugInstance = Registry::getRegistry()->getInstance('debug');
1873 return $debugInstance;
1877 * Simple output of a message with line-break
1879 * @param $message Message to output
1882 public function outputLine ($message) {
1884 print($message . PHP_EOL);
1888 * Outputs a debug message whether to debug instance (should be set!) or
1889 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1890 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1892 * @param $message Message we shall send out...
1893 * @param $doPrint Whether print or die here (default: print)
1894 * @paran $stripTags Whether to strip tags (default: false)
1897 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1898 // Set debug instance to NULL
1899 $debugInstance = NULL;
1902 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1904 // Is function partialStub/__callStatic ?
1905 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1906 // Prepend class::function:line from 3rd element
1907 $message = sprintf('[%s::%s:%d]: %s',
1908 $backtrace[2]['class'],
1909 $backtrace[2]['function'],
1910 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1914 // Prepend class::function:line from 2nd element
1915 $message = sprintf('[%s::%s:%d]: %s',
1916 $backtrace[1]['class'],
1917 $backtrace[1]['function'],
1918 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1925 // Get debug instance
1926 $debugInstance = $this->getDebugInstance();
1927 } catch (NullPointerException $e) {
1928 // The debug instance is not set (yet)
1931 // Is the debug instance there?
1932 if (is_object($debugInstance)) {
1933 // Use debug output handler
1934 $debugInstance->output($message, $stripTags);
1936 if ($doPrint === false) {
1937 // Die here if not printed
1941 // Are debug times enabled?
1942 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1944 $message = $this->getPrintableExecutionTime() . $message;
1948 if ($doPrint === true) {
1950 $this->outputLine($message);
1959 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1961 * @param $str The string, what ever it is needs to be converted
1962 * @return $className Generated class name
1964 public static final function convertToClassName ($str) {
1968 // Convert all dashes in underscores
1969 $str = self::convertDashesToUnderscores($str);
1971 // Now use that underscores to get classname parts for hungarian style
1972 foreach (explode('_', $str) as $strPart) {
1973 // Make the class name part lower case and first upper case
1974 $className .= ucfirst(strtolower($strPart));
1977 // Return class name
1982 * Converts dashes to underscores, e.g. useable for configuration entries
1984 * @param $str The string with maybe dashes inside
1985 * @return $str The converted string with no dashed, but underscores
1986 * @throws NullPointerException If $str is null
1987 * @throws InvalidArgumentException If $str is empty
1989 public static function convertDashesToUnderscores ($str) {
1991 if (is_null($str)) {
1993 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
1994 } elseif (!is_string($str)) {
1996 throw new InvalidArgumentException(sprintf('str[]=%s is not a string', gettype($str)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1997 } elseif ((is_string($str)) && (empty($str))) {
1999 throw new InvalidArgumentException('str is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
2003 $str = str_replace('-', '_', $str);
2005 // Return converted string
2010 * Marks up the code by adding e.g. line numbers
2012 * @param $phpCode Unmarked PHP code
2013 * @return $markedCode Marked PHP code
2015 public function markupCode ($phpCode) {
2020 $errorArray = error_get_last();
2022 // Init the code with error message
2023 if (is_array($errorArray)) {
2025 $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>',
2026 basename($errorArray['file']),
2027 $errorArray['line'],
2028 $errorArray['message'],
2033 // Add line number to the code
2034 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2036 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2038 htmlentities($code, ENT_QUOTES)
2047 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2048 * beatiful for web-based front-ends. If null is given a message id
2049 * null_timestamp will be resolved and returned.
2051 * @param $timestamp Timestamp to prepare (filter) for display
2052 * @return $readable A readable timestamp
2054 public function doFilterFormatTimestamp ($timestamp) {
2055 // Default value to return
2058 // Is the timestamp null?
2059 if (is_null($timestamp)) {
2060 // Get a message string
2061 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2063 switch ($this->getLanguageInstance()->getLanguageCode()) {
2064 case 'de': // German format is a bit different to default
2065 // Split the GMT stamp up
2066 $dateTime = explode(' ', $timestamp );
2067 $dateArray = explode('-', $dateTime[0]);
2068 $timeArray = explode(':', $dateTime[1]);
2070 // Construct the timestamp
2071 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2081 default: // Default is pass-through
2082 $readable = $timestamp;
2092 * Filter a given number into a localized number
2094 * @param $value The raw value from e.g. database
2095 * @return $localized Localized value
2097 public function doFilterFormatNumber ($value) {
2098 // Generate it from config and localize dependencies
2099 switch ($this->getLanguageInstance()->getLanguageCode()) {
2100 case 'de': // German format is a bit different to default
2101 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2104 default: // US, etc.
2105 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2114 * "Getter" for databse entry
2116 * @return $entry An array with database entries
2117 * @throws NullPointerException If the database result is not found
2118 * @throws InvalidDatabaseResultException If the database result is invalid
2120 protected final function getDatabaseEntry () {
2121 // Is there an instance?
2122 if (!$this->getResultInstance() instanceof SearchableResult) {
2123 // Throw an exception here
2124 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2128 $this->getResultInstance()->rewind();
2130 // Do we have an entry?
2131 if ($this->getResultInstance()->valid() === false) {
2132 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2133 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2137 $this->getResultInstance()->next();
2140 $entry = $this->getResultInstance()->current();
2147 * Getter for field name
2149 * @param $fieldName Field name which we shall get
2150 * @return $fieldValue Field value from the user
2151 * @throws NullPointerException If the result instance is null
2153 public final function getField ($fieldName) {
2154 // Default field value
2157 // Get result instance
2158 $resultInstance = $this->getResultInstance();
2160 // Is this instance null?
2161 if (is_null($resultInstance)) {
2162 // Then the user instance is no longer valid (expired cookies?)
2163 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2166 // Get current array
2167 $fieldArray = $resultInstance->current();
2168 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2170 // Convert dashes to underscore
2171 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2173 // Does the field exist?
2174 if ($this->isFieldSet($fieldName)) {
2176 $fieldValue = $fieldArray[$fieldName2];
2177 } elseif (defined('DEVELOPER')) {
2178 // Missing field entry, may require debugging
2179 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2181 // Missing field entry, may require debugging
2182 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2190 * Checks if given field is set
2192 * @param $fieldName Field name to check
2193 * @return $isSet Whether the given field name is set
2194 * @throws NullPointerException If the result instance is null
2196 public function isFieldSet ($fieldName) {
2197 // Get result instance
2198 $resultInstance = $this->getResultInstance();
2200 // Is this instance null?
2201 if (is_null($resultInstance)) {
2202 // Then the user instance is no longer valid (expired cookies?)
2203 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2206 // Get current array
2207 $fieldArray = $resultInstance->current();
2208 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2210 // Convert dashes to underscore
2211 $fieldName = self::convertDashesToUnderscores($fieldName);
2214 $isSet = isset($fieldArray[$fieldName]);
2221 * Flushs all pending updates to the database layer
2225 public function flushPendingUpdates () {
2226 // Get result instance
2227 $resultInstance = $this->getResultInstance();
2229 // Do we have data to update?
2230 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2231 // Get wrapper class name config entry
2232 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2234 // Create object instance
2235 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2237 // Yes, then send the whole result to the database layer
2238 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2243 * Outputs a deprecation warning to the developer.
2245 * @param $message The message we shall output to the developer
2247 * @todo Write a logging mechanism for productive mode
2249 public function deprecationWarning ($message) {
2250 // Is developer mode active?
2251 if (defined('DEVELOPER')) {
2252 // Debug instance is there?
2253 if (!is_null($this->getDebugInstance())) {
2254 // Output stub message
2255 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2258 trigger_error($message . "<br />\n");
2262 // @TODO Finish this part!
2263 $this->partialStub('Developer mode inactive. Message:' . $message);
2268 * Checks whether the given PHP extension is loaded
2270 * @param $phpExtension The PHP extension we shall check
2271 * @return $isLoaded Whether the PHP extension is loaded
2273 public final function isPhpExtensionLoaded ($phpExtension) {
2275 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2282 * "Getter" as a time() replacement but with milliseconds. You should use this
2283 * method instead of the encapsulated getimeofday() function.
2285 * @return $milliTime Timestamp with milliseconds
2287 public function getMilliTime () {
2288 // Get the time of day as float
2289 $milliTime = gettimeofday(true);
2296 * Idles (sleeps) for given milliseconds
2298 * @return $hasSlept Whether it goes fine
2300 public function idle ($milliSeconds) {
2301 // Sleep is fine by default
2304 // Idle so long with found function
2305 if (function_exists('time_sleep_until')) {
2306 // Get current time and add idle time
2307 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2309 // New PHP 5.1.0 function found, ignore errors
2310 $hasSlept = @time_sleep_until($sleepUntil);
2313 * My Sun station doesn't have that function even with latest PHP
2316 usleep($milliSeconds * 1000);
2323 * Converts a hexadecimal string, even with negative sign as first string to
2324 * a decimal number using BC functions.
2326 * This work is based on comment #86673 on php.net documentation page at:
2327 * <http://de.php.net/manual/en/function.dechex.php#86673>
2329 * @param $hex Hexadecimal string
2330 * @return $dec Decimal number
2332 protected function hex2dec ($hex) {
2333 // Convert to all lower-case
2334 $hex = strtolower($hex);
2336 // Detect sign (negative/positive numbers)
2338 if (substr($hex, 0, 1) == '-') {
2340 $hex = substr($hex, 1);
2343 // Decode the hexadecimal string into a decimal number
2345 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2346 $factor = self::$hexdec[substr($hex, $i, 1)];
2347 $dec = bcadd($dec, bcmul($factor, $e));
2350 // Return the decimal number
2351 return $sign . $dec;
2355 * Converts even very large decimal numbers, also signed, to a hexadecimal
2358 * This work is based on comment #97756 on php.net documentation page at:
2359 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2361 * @param $dec Decimal number, even with negative sign
2362 * @param $maxLength Optional maximum length of the string
2363 * @return $hex Hexadecimal string
2365 protected function dec2hex ($dec, $maxLength = 0) {
2366 // maxLength can be zero or devideable by 2
2367 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2369 // Detect sign (negative/positive numbers)
2376 // Encode the decimal number into a hexadecimal string
2379 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2381 } while ($dec >= 1);
2384 * Leading zeros are required for hex-decimal "numbers". In some
2385 * situations more leading zeros are wanted, so check for both
2388 if ($maxLength > 0) {
2389 // Prepend more zeros
2390 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2391 } elseif ((strlen($hex) % 2) != 0) {
2392 // Only make string's length dividable by 2
2396 // Return the hexadecimal string
2397 return $sign . $hex;
2401 * Converts a ASCII string (0 to 255) into a decimal number.
2403 * @param $asc The ASCII string to be converted
2404 * @return $dec Decimal number
2406 protected function asc2dec ($asc) {
2407 // Convert it into a hexadecimal number
2408 $hex = bin2hex($asc);
2410 // And back into a decimal number
2411 $dec = $this->hex2dec($hex);
2418 * Converts a decimal number into an ASCII string.
2420 * @param $dec Decimal number
2421 * @return $asc An ASCII string
2423 protected function dec2asc ($dec) {
2424 // First convert the number into a hexadecimal string
2425 $hex = $this->dec2hex($dec);
2427 // Then convert it into the ASCII string
2428 $asc = $this->hex2asc($hex);
2435 * Converts a hexadecimal number into an ASCII string. Negative numbers
2438 * @param $hex Hexadecimal string
2439 * @return $asc An ASCII string
2441 protected function hex2asc ($hex) {
2442 // Check for length, it must be devideable by 2
2443 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2444 assert((strlen($hex) % 2) == 0);
2448 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2449 // Get the decimal number of the chunk
2450 $part = hexdec(substr($hex, $idx, 2));
2452 // Add it to the final string
2456 // Return the final string
2461 * Checks whether the given encoded data was encoded with Base64
2463 * @param $encodedData Encoded data we shall check
2464 * @return $isBase64 Whether the encoded data is Base64
2466 protected function isBase64Encoded ($encodedData) {
2468 $isBase64 = (@base64_decode($encodedData, true) !== false);
2475 * Gets a cache key from Criteria instance
2477 * @param $criteriaInstance An instance of a Criteria class
2478 * @param $onlyKeys Only use these keys for a cache key
2479 * @return $cacheKey A cache key suitable for lookup/storage purposes
2481 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2483 $cacheKey = sprintf('%s@%s',
2484 $this->__toString(),
2485 $criteriaInstance->getCacheKey($onlyKeys)
2489 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2494 * Getter for startup time in miliseconds
2496 * @return $startupTime Startup time in miliseconds
2498 protected function getStartupTime () {
2499 return self::$startupTime;
2503 * "Getter" for a printable currently execution time in nice braces
2505 * @return $executionTime Current execution time in nice braces
2507 protected function getPrintableExecutionTime () {
2508 // Caculate the execution time
2509 $executionTime = microtime(true) - $this->getStartupTime();
2511 // Pack it in nice braces
2512 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2515 return $executionTime;
2519 * Hashes a given string with a simple but stronger hash function (no salt)
2520 * and hex-encode it.
2522 * @param $str The string to be hashed
2523 * @return $hash The hash from string $str
2525 public static final function hash ($str) {
2526 // Hash given string with (better secure) hasher
2527 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2534 * "Getter" for length of hash() output. This will be "cached" to speed up
2537 * @return $length Length of hash() output
2539 public static final function getHashLength () {
2541 if (is_null(self::$hashLength)) {
2542 // No, then hash a string and save its length.
2543 self::$hashLength = strlen(self::hash('abc123'));
2547 return self::$hashLength;
2551 * Checks whether the given number is really a number (only chars 0-9).
2553 * @param $num A string consisting only chars between 0 and 9
2554 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2555 * @param $assertMismatch Whether to assert mismatches
2556 * @return $ret The (hopefully) secured numbered value
2558 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2559 // Filter all numbers out
2560 $ret = preg_replace('/[^0123456789]/', '', $num);
2563 if ($castValue === true) {
2564 // Cast to biggest numeric type
2565 $ret = (double) $ret;
2568 // Assert only if requested
2569 if ($assertMismatch === true) {
2570 // Has the whole value changed?
2571 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2579 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2581 * @param $num A string consisting only chars between 0 and 9
2582 * @param $assertMismatch Whether to assert mismatches
2583 * @return $ret The (hopefully) secured hext-numbered value
2585 public function hexval ($num, $assertMismatch = false) {
2586 // Filter all numbers out
2587 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2589 // Assert only if requested
2590 if ($assertMismatch === true) {
2591 // Has the whole value changed?
2592 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2600 * Determines if an element is set in the generic array
2602 * @param $keyGroup Main group for the key
2603 * @param $subGroup Sub group for the key
2604 * @param $key Key to check
2605 * @param $element Element to check
2606 * @return $isset Whether the given key is set
2608 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2610 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2613 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2619 * Determines if a key is set in the generic array
2621 * @param $keyGroup Main group for the key
2622 * @param $subGroup Sub group for the key
2623 * @param $key Key to check
2624 * @return $isset Whether the given key is set
2626 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2628 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2631 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2639 * Determines if a group is set in the generic array
2641 * @param $keyGroup Main group
2642 * @param $subGroup Sub group
2643 * @return $isset Whether the given group is set
2645 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2647 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2650 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2657 * Getter for sub key group
2659 * @param $keyGroup Main key group
2660 * @param $subGroup Sub key group
2661 * @return $array An array with all array elements
2663 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2665 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2666 // No, then abort here
2667 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2672 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2675 return $this->genericArray[$keyGroup][$subGroup];
2679 * Unsets a given key in generic array
2681 * @param $keyGroup Main group for the key
2682 * @param $subGroup Sub group for the key
2683 * @param $key Key to unset
2686 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2688 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2691 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2695 * Unsets a given element in generic array
2697 * @param $keyGroup Main group for the key
2698 * @param $subGroup Sub group for the key
2699 * @param $key Key to unset
2700 * @param $element Element to unset
2703 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2705 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2708 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2712 * Append a string to a given generic array key
2714 * @param $keyGroup Main group for the key
2715 * @param $subGroup Sub group for the key
2716 * @param $key Key to unset
2717 * @param $value Value to add/append
2720 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2722 //* 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);
2724 // Is it already there?
2725 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2727 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2730 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2735 * Append a string to a given generic array element
2737 * @param $keyGroup Main group for the key
2738 * @param $subGroup Sub group for the key
2739 * @param $key Key to unset
2740 * @param $element Element to check
2741 * @param $value Value to add/append
2744 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2746 //* 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);
2748 // Is it already there?
2749 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2751 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2754 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2759 * Sets a string in a given generic array element
2761 * @param $keyGroup Main group for the key
2762 * @param $subGroup Sub group for the key
2763 * @param $key Key to unset
2764 * @param $element Element to check
2765 * @param $value Value to add/append
2768 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2770 //* 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);
2773 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2777 * Initializes given generic array group
2779 * @param $keyGroup Main group for the key
2780 * @param $subGroup Sub group for the key
2781 * @param $key Key to use
2782 * @param $forceInit Optionally force initialization
2785 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2787 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2789 // Is it already set?
2790 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2791 // Already initialized
2792 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2797 $this->genericArray[$keyGroup][$subGroup] = array();
2801 * Initializes given generic array key
2803 * @param $keyGroup Main group for the key
2804 * @param $subGroup Sub group for the key
2805 * @param $key Key to use
2806 * @param $forceInit Optionally force initialization
2809 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2811 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2813 // Is it already set?
2814 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2815 // Already initialized
2816 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2821 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2825 * Initializes given generic array element
2827 * @param $keyGroup Main group for the key
2828 * @param $subGroup Sub group for the key
2829 * @param $key Key to use
2830 * @param $element Element to use
2831 * @param $forceInit Optionally force initialization
2834 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2836 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2838 // Is it already set?
2839 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2840 // Already initialized
2841 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2846 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2850 * Pushes an element to a generic key
2852 * @param $keyGroup Main group for the key
2853 * @param $subGroup Sub group for the key
2854 * @param $key Key to use
2855 * @param $value Value to add/append
2856 * @return $count Number of array elements
2858 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2860 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2863 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2865 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2869 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2872 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2873 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2878 * Pushes an element to a generic array element
2880 * @param $keyGroup Main group for the key
2881 * @param $subGroup Sub group for the key
2882 * @param $key Key to use
2883 * @param $element Element to check
2884 * @param $value Value to add/append
2885 * @return $count Number of array elements
2887 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2889 //* 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));
2892 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2894 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2898 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2901 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2902 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2907 * Pops an element from a generic group
2909 * @param $keyGroup Main group for the key
2910 * @param $subGroup Sub group for the key
2911 * @param $key Key to unset
2912 * @return $value Last "popped" value
2914 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2916 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2919 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2921 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2926 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2929 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2930 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2935 * Shifts an element from a generic group
2937 * @param $keyGroup Main group for the key
2938 * @param $subGroup Sub group for the key
2939 * @param $key Key to unset
2940 * @return $value Last "popped" value
2942 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2944 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2947 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2949 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2954 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2957 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2958 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2963 * Count generic array group
2965 * @param $keyGroup Main group for the key
2966 * @return $count Count of given group
2968 protected final function countGenericArray ($keyGroup) {
2970 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2973 if (!isset($this->genericArray[$keyGroup])) {
2975 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2980 $count = count($this->genericArray[$keyGroup]);
2983 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2990 * Count generic array sub group
2992 * @param $keyGroup Main group for the key
2993 * @param $subGroup Sub group for the key
2994 * @return $count Count of given group
2996 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2998 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3001 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3003 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3008 $count = count($this->genericArray[$keyGroup][$subGroup]);
3011 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3018 * Count generic array elements
3020 * @param $keyGroup Main group for the key
3021 * @param $subGroup Sub group for the key
3022 * @para $key Key to count
3023 * @return $count Count of given key
3025 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3027 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3030 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3032 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3034 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3036 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3041 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3044 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3051 * Getter for whole generic group array
3053 * @param $keyGroup Key group to get
3054 * @return $array Whole generic array group
3056 protected final function getGenericArray ($keyGroup) {
3058 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3061 if (!isset($this->genericArray[$keyGroup])) {
3063 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3068 return $this->genericArray[$keyGroup];
3072 * Setter for generic array key
3074 * @param $keyGroup Key group to get
3075 * @param $subGroup Sub group for the key
3076 * @param $key Key to unset
3077 * @param $value Mixed value from generic array element
3080 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3082 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3085 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3089 * Getter for generic array key
3091 * @param $keyGroup Key group to get
3092 * @param $subGroup Sub group for the key
3093 * @param $key Key to unset
3094 * @return $value Mixed value from generic array element
3096 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3098 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3101 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3103 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3108 return $this->genericArray[$keyGroup][$subGroup][$key];
3112 * Sets a value in given generic array key/element
3114 * @param $keyGroup Main group for the key
3115 * @param $subGroup Sub group for the key
3116 * @param $key Key to set
3117 * @param $element Element to set
3118 * @param $value Value to set
3121 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3123 //* 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));
3126 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3130 * Getter for generic array element
3132 * @param $keyGroup Key group to get
3133 * @param $subGroup Sub group for the key
3134 * @param $key Key to look for
3135 * @param $element Element to look for
3136 * @return $value Mixed value from generic array element
3138 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3140 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3143 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3145 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3150 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3154 * Checks if a given sub group is valid (array)
3156 * @param $keyGroup Key group to get
3157 * @param $subGroup Sub group for the key
3158 * @return $isValid Whether given sub group is valid
3160 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3162 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3165 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3172 * Checks if a given key is valid (array)
3174 * @param $keyGroup Key group to get
3175 * @param $subGroup Sub group for the key
3176 * @param $key Key to check
3177 * @return $isValid Whether given sub group is valid
3179 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3181 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3184 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3191 * Initializes the web output instance
3195 protected function initWebOutputInstance () {
3196 // Get application instance
3197 $applicationInstance = Registry::getRegistry()->getInstance('app');
3199 // Init web output instance
3200 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3203 $this->setWebOutputInstance($outputInstance);
3207 * Translates boolean true to 'Y' and false to 'N'
3209 * @param $boolean Boolean value
3210 * @return $translated Translated boolean value
3212 public static final function translateBooleanToYesNo ($boolean) {
3213 // Make sure it is really boolean
3214 assert(is_bool($boolean));
3217 $translated = ($boolean === true) ? 'Y' : 'N';
3219 // ... and return it
3224 * Encodes raw data (almost any type) by "serializing" it and then pack it
3225 * into a "binary format".
3227 * @param $rawData Raw data (almost any type)
3228 * @return $encoded Encoded data
3230 protected function encodeData ($rawData) {
3231 // Make sure no objects or resources pass through
3232 assert(!is_object($rawData));
3233 assert(!is_resource($rawData));
3235 // First "serialize" it (json_encode() is faster than serialize())
3236 $encoded = $this->packString(json_encode($rawData));
3243 * Pack a string into a "binary format". Please execuse me that this is
3244 * widely undocumented. :-(
3246 * @param $str Unpacked string
3247 * @return $packed Packed string
3248 * @todo Improve documentation
3250 protected function packString ($str) {
3252 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3254 // First compress the string (gzcompress is okay)
3255 $str = gzcompress($str);
3260 // And start the "encoding" loop
3261 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3263 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3264 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3266 if (($idx + $i) <= strlen($str)) {
3267 $ord = ord(substr($str, ($idx + $i), 1));
3269 $add = $ord * pow(256, $factor);
3273 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3277 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3278 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3280 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3281 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3287 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3292 * Creates a full-qualified file name (FQFN) for given file name by adding
3293 * a configured temporary file path to it.
3295 * @param $infoInstance An instance of a SplFileInfo class
3296 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3297 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3298 * @throws FileIoException If the file cannot be written
3300 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3302 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3304 // Is the path writeable?
3305 if (!is_writable($basePath)) {
3306 // Path is write-protected
3307 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3311 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3314 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3316 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3320 return $tempInstance;
3324 * "Getter" for a printable state name
3326 * @return $stateName Name of the node's state in a printable format
3328 public final function getPrintableState () {
3329 // Default is 'null'
3330 $stateName = 'null';
3332 // Get the state instance
3333 $stateInstance = $this->getStateInstance();
3335 // Is it an instance of Stateable?
3336 if ($stateInstance instanceof Stateable) {
3337 // Then use that state name
3338 $stateName = $stateInstance->getStateName();