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\Connection\Database\DatabaseConnection;
9 use Org\Mxchange\CoreFramework\Criteria\Criteria;
10 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
11 use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
12 use Org\Mxchange\CoreFramework\Crypto\Cryptable;
13 use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
14 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
15 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
16 use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
17 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
18 use Org\Mxchange\CoreFramework\Filesystem\Block;
19 use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
20 use Org\Mxchange\CoreFramework\Filesystem\FrameworkDirectory;
21 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
22 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
23 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
24 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
25 use Org\Mxchange\CoreFramework\Handler\Handleable;
26 use Org\Mxchange\CoreFramework\Helper\Helper;
27 use Org\Mxchange\CoreFramework\Index\Indexable;
28 use Org\Mxchange\CoreFramework\Lists\Listable;
29 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
30 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
31 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
32 use Org\Mxchange\CoreFramework\Menu\RenderableMenu;
33 use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
34 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
35 use Org\Mxchange\CoreFramework\Parser\Parseable;
36 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
37 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
38 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
39 use Org\Mxchange\CoreFramework\Stacker\Stackable;
40 use Org\Mxchange\CoreFramework\State\Stateable;
41 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
42 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
43 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
44 use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
45 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
46 use Org\Mxchange\CoreFramework\User\ManageableAccount;
47 use Org\Mxchange\CoreFramework\Visitor\Visitor;
51 use \InvalidArgumentException;
57 * The simulator system class is the super class of all other classes. This
58 * class handles saving of games etc.
60 * @author Roland Haeder <webmaster@shipsimu.org>
62 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
63 * @license GNU GPL 3.0 or any newer version
64 * @link http://www.shipsimu.org
66 * This program is free software: you can redistribute it and/or modify
67 * it under the terms of the GNU General Public License as published by
68 * the Free Software Foundation, either version 3 of the License, or
69 * (at your option) any later version.
71 * This program is distributed in the hope that it will be useful,
72 * but WITHOUT ANY WARRANTY; without even the implied warranty of
73 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
74 * GNU General Public License for more details.
76 * You should have received a copy of the GNU General Public License
77 * along with this program. If not, see <http://www.gnu.org/licenses/>.
79 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
81 * Length of output from hash()
83 private static $hashLength = NULL;
86 * Self-referencing instance
88 private static $instance = NULL;
93 private $realClass = __CLASS__;
96 * Search criteria instance
98 private $searchInstance = NULL;
101 * Update criteria instance
103 private $updateInstance = NULL;
106 * Template engine instance
108 private $templateInstance = NULL;
111 * Database result instance
113 private $resultInstance = NULL;
116 * Instance for user class
118 private $userInstance = NULL;
123 private $rngInstance = NULL;
126 * Instance of a crypto helper
128 private $cryptoInstance = NULL;
131 * Instance of an Iterator class
133 private $iteratorInstance = NULL;
136 * Instance of the list
138 private $listInstance = NULL;
143 private $menuInstance = NULL;
146 * Instance of the image
148 private $imageInstance = NULL;
151 * Instance of the stacker
153 private $stackInstance = NULL;
156 * A Compressor instance
158 private $compressorInstance = NULL;
161 * A Parseable instance
163 private $parserInstance = NULL;
166 * A database wrapper instance
168 private $databaseInstance = NULL;
171 * A helper instance for the form
173 private $helperInstance = NULL;
176 * An instance of a InputStream class
178 private $inputStreamInstance = NULL;
181 * An instance of a OutputStream class
183 private $outputStreamInstance = NULL;
188 private $handlerInstance = NULL;
191 * Visitor handler instance
193 private $visitorInstance = NULL;
196 * An instance of a database wrapper class
198 private $wrapperInstance = NULL;
201 * An instance of a file I/O pointer class (not handler)
203 private $pointerInstance = NULL;
206 * An instance of an Indexable class
208 private $indexInstance = NULL;
211 * An instance of a Block class
213 private $blockInstance = NULL;
216 * A FrameworkDirectory instance
218 private $directoryInstance = NULL;
221 * The concrete output instance
223 private $outputInstance = NULL;
228 private $stateInstance = NULL;
233 private $callbackInstance = NULL;
236 * Thousands separator
238 private $thousands = '.'; // German
243 private $decimals = ','; // German
248 private $genericArray = array();
251 * Array with bitmasks and such for pack/unpack methods to support both
252 * 32-bit and 64-bit systems
254 private $packingData = array(
257 'left' => 0xffff0000,
258 'right' => 0x0000ffff,
264 'left' => 0xffffffff00000000,
265 'right' => 0x00000000ffffffff,
272 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
274 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
276 private $archArrayElement = false;
278 /***********************
279 * Exception codes.... *
280 ***********************/
282 // @todo Try to clean these constants up
283 const EXCEPTION_IS_NULL_POINTER = 0x001;
284 const EXCEPTION_IS_NO_OBJECT = 0x002;
285 const EXCEPTION_IS_NO_ARRAY = 0x003;
286 const EXCEPTION_MISSING_METHOD = 0x004;
287 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
288 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
289 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
290 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
291 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
292 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
293 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
294 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
295 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
296 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
297 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
298 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
299 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
300 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
301 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
302 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
303 const EXCEPTION_PATH_NOT_FOUND = 0x015;
304 const EXCEPTION_INVALID_PATH_NAME = 0x016;
305 const EXCEPTION_READ_PROTECED_PATH = 0x017;
306 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
307 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
308 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
309 const EXCEPTION_INVALID_RESOURCE = 0x01b;
310 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
311 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
312 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
313 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
314 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
315 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
316 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
317 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
318 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
319 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
320 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
321 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
322 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
323 const EXCEPTION_INVALID_STRING = 0x029;
324 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
325 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
326 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
327 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
328 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
329 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
330 const EXCEPTION_MISSING_ELEMENT = 0x030;
331 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
332 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
333 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
334 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
335 const EXCEPTION_FATAL_ERROR = 0x035;
336 const EXCEPTION_FILE_NOT_FOUND = 0x036;
337 const EXCEPTION_ASSERTION_FAILED = 0x037;
338 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
339 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
340 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
341 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
342 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
343 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
344 const EXCEPTION_INVALID_SOCKET = 0x03e;
345 const EXCEPTION_SELF_INSTANCE = 0x03f;
348 * Hexadecimal->Decimal translation array
350 private static $hexdec = array(
370 * Decimal->hexadecimal translation array
372 private static $dechex = array(
392 * Startup time in miliseconds
394 private static $startupTime = 0;
397 * Protected super constructor
399 * @param $className Name of the class
402 protected function __construct ($className) {
404 $this->setRealClass($className);
406 // Is the startup time set? (0 cannot be true anymore)
407 if (self::$startupTime == 0) {
409 self::$startupTime = microtime(true);
413 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
417 * Destructor for all classes. You should not call this method on your own.
421 public function __destruct () {
422 // Flush any updated entries to the database
423 $this->flushPendingUpdates();
425 // Is this object already destroyed?
426 if ($this->__toString() != 'DestructedObject') {
427 // Destroy all informations about this class but keep some text about it alive
428 $this->setRealClass('DestructedObject');
429 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
430 // Already destructed object
431 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
435 // Do not call this twice
436 trigger_error(__METHOD__ . ': Called twice.');
442 * The __call() method where all non-implemented methods end up
444 * @param $methodName Name of the missing method
445 * @args $args Arguments passed to the method
448 public final function __call ($methodName, $args) {
450 self::$instance = $this;
452 // Call static method
453 self::__callStatic($methodName, $args);
455 // Clear self-instance
456 self::$instance = NULL;
460 * The __callStatic() method where all non-implemented static methods end up
462 * @param $methodName Name of the missing method
463 * @param $args Arguments passed to the method
465 * @throws InvalidArgumentException If self::$instance is not a framework's own object
467 public static final function __callStatic ($methodName, $args) {
469 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
471 // Init argument string and class name
473 $className = 'unknown';
475 // Is self-instance set?
476 if (self::$instance instanceof FrameworkInterface) {
477 // Framework's own instance
478 $className = self::$instance->__toString();
479 } elseif (!is_null(self::$instance)) {
481 throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$instance)), self::EXCEPTION_SELF_INSTANCE);
484 // Is it NULL, empty or an array?
485 if (is_null($args)) {
487 $argsString = 'NULL';
488 } elseif (is_array($args)) {
492 // Some arguments are there
493 foreach ($args as $arg) {
494 // Add data about the argument
495 $argsString .= gettype($arg) . ':';
498 // Found a NULL argument
499 $argsString .= 'NULL';
500 } elseif (is_string($arg)) {
501 // Add length for strings
502 $argsString .= strlen($arg);
503 } elseif ((is_int($arg)) || (is_float($arg))) {
506 } elseif (is_array($arg)) {
507 // .. or size if array
508 $argsString .= count($arg);
509 } elseif (is_object($arg)) {
511 $reflection = new ReflectionClass($arg);
513 // Is an other object, maybe no __toString() available
514 $argsString .= $reflection->getName();
515 } elseif ($arg === true) {
516 // ... is boolean 'true'
517 $argsString .= 'true';
518 } elseif ($arg === false) {
519 // ... is boolean 'false'
520 $argsString .= 'false';
523 // Comma for next one
528 if (substr($argsString, -2, 1) == ',') {
530 $argsString = substr($argsString, 0, -2);
536 // Invalid arguments!
537 $argsString = sprintf('!INVALID:%s!', gettype($args));
540 // Output stub message
541 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
542 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s::%s]: Stub! Args: %s',
553 * Getter for $realClass
555 * @return $realClass The name of the real class (not BaseFrameworkSystem)
557 public function __toString () {
558 return $this->realClass;
562 * Magic method to catch setting of missing but set class fields/attributes
564 * @param $name Name of the field/attribute
565 * @param $value Value to store
568 public final function __set ($name, $value) {
569 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
572 print_r($value, true)
577 * Magic method to catch getting of missing fields/attributes
579 * @param $name Name of the field/attribute
582 public final function __get ($name) {
583 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
589 * Magic method to catch unsetting of missing fields/attributes
591 * @param $name Name of the field/attribute
594 public final function __unset ($name) {
595 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
601 * Magic method to catch object serialization
603 * @return $unsupported Unsupported method
604 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
606 public final function __sleep () {
607 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
611 * Magic method to catch object deserialization
613 * @return $unsupported Unsupported method
614 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
616 public final function __wakeup () {
617 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
621 * Magic method to catch calls when an object instance is called
623 * @return $unsupported Unsupported method
624 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
626 public final function __invoke () {
627 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
631 * Setter for the real class name
633 * @param $realClass Class name (string)
636 public final function setRealClass ($realClass) {
638 $this->realClass = (string) $realClass;
642 * Setter for database result instance
644 * @param $resultInstance An instance of a database result class
646 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
648 protected final function setResultInstance (SearchableResult $resultInstance) {
649 $this->resultInstance = $resultInstance;
653 * Getter for database result instance
655 * @return $resultInstance An instance of a database result class
657 public final function getResultInstance () {
658 return $this->resultInstance;
662 * Setter for template engine instances
664 * @param $templateInstance An instance of a template engine class
667 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
668 $this->templateInstance = $templateInstance;
672 * Getter for template engine instances
674 * @return $templateInstance An instance of a template engine class
676 protected final function getTemplateInstance () {
677 return $this->templateInstance;
681 * Setter for search instance
683 * @param $searchInstance Searchable criteria instance
686 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
687 $this->searchInstance = $searchInstance;
691 * Getter for search instance
693 * @return $searchInstance Searchable criteria instance
695 public final function getSearchInstance () {
696 return $this->searchInstance;
700 * Setter for update instance
702 * @param $updateInstance An instance of a LocalUpdateCriteria clase
705 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
706 $this->updateInstance = $updateInstance;
710 * Getter for update instance
712 * @return $updateInstance Updateable criteria instance
714 public final function getUpdateInstance () {
715 return $this->updateInstance;
719 * Setter for debug instance
721 * @param $debugInstance The instance for debug output class
724 public final function setDebugInstance (DebugMiddleware $debugInstance) {
725 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
729 * Getter for debug instance
731 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
733 public final function getDebugInstance () {
734 // Get debug instance
735 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
738 return $debugInstance;
742 * Setter for web output instance
744 * @param $webInstance The instance for web output class
747 public final function setWebOutputInstance (OutputStreamer $webInstance) {
748 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
752 * Getter for web output instance
754 * @return $webOutputInstance - Instance to class WebOutput
756 public final function getWebOutputInstance () {
757 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
758 return $webOutputInstance;
762 * Setter for database instance
764 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
767 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
768 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
772 * Getter for database layer
774 * @return $databaseInstance The database layer instance
776 public final function getDatabaseInstance () {
778 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
781 return $databaseInstance;
785 * Setter for compressor channel
787 * @param $compressorInstance An instance of CompressorChannel
790 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
791 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
795 * Getter for compressor channel
797 * @return $compressorInstance The compressor channel
799 public final function getCompressorChannel () {
800 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
801 return $compressorInstance;
805 * Private getter for language instance
807 * @return $langInstance An instance to the language sub-system
809 protected final function getLanguageInstance () {
810 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
811 return $langInstance;
815 * Setter for language instance
817 * @param $langInstance An instance to the language sub-system
819 * @see LanguageSystem
821 public final function setLanguageInstance (ManageableLanguage $langInstance) {
822 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
826 * Protected setter for user instance
828 * @param $userInstance An instance of a user class
831 protected final function setUserInstance (ManageableAccount $userInstance) {
832 $this->userInstance = $userInstance;
836 * Getter for user instance
838 * @return $userInstance An instance of a user class
840 public final function getUserInstance () {
841 return $this->userInstance;
845 * Setter for RNG instance
847 * @param $rngInstance An instance of a random number generator (RNG)
850 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
851 $this->rngInstance = $rngInstance;
855 * Getter for RNG instance
857 * @return $rngInstance An instance of a random number generator (RNG)
859 public final function getRngInstance () {
860 return $this->rngInstance;
864 * Setter for Cryptable instance
866 * @param $cryptoInstance An instance of a Cryptable class
869 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
870 $this->cryptoInstance = $cryptoInstance;
874 * Getter for Cryptable instance
876 * @return $cryptoInstance An instance of a Cryptable class
878 public final function getCryptoInstance () {
879 return $this->cryptoInstance;
883 * Setter for the list instance
885 * @param $listInstance A list of Listable
888 protected final function setListInstance (Listable $listInstance) {
889 $this->listInstance = $listInstance;
893 * Getter for the list instance
895 * @return $listInstance A list of Listable
897 protected final function getListInstance () {
898 return $this->listInstance;
902 * Setter for the menu instance
904 * @param $menuInstance A RenderableMenu instance
907 protected final function setMenuInstance (RenderableMenu $menuInstance) {
908 $this->menuInstance = $menuInstance;
912 * Getter for the menu instance
914 * @return $menuInstance A RenderableMenu instance
916 protected final function getMenuInstance () {
917 return $this->menuInstance;
921 * Setter for image instance
923 * @param $imageInstance An instance of an image
926 public final function setImageInstance (BaseImage $imageInstance) {
927 $this->imageInstance = $imageInstance;
931 * Getter for image instance
933 * @return $imageInstance An instance of an image
935 public final function getImageInstance () {
936 return $this->imageInstance;
940 * Setter for stacker instance
942 * @param $stackInstance An instance of an stacker
945 public final function setStackInstance (Stackable $stackInstance) {
946 $this->stackInstance = $stackInstance;
950 * Getter for stacker instance
952 * @return $stackInstance An instance of an stacker
954 public final function getStackInstance () {
955 return $this->stackInstance;
959 * Setter for compressor instance
961 * @param $compressorInstance An instance of an compressor
964 public final function setCompressorInstance (Compressor $compressorInstance) {
965 $this->compressorInstance = $compressorInstance;
969 * Getter for compressor instance
971 * @return $compressorInstance An instance of an compressor
973 public final function getCompressorInstance () {
974 return $this->compressorInstance;
978 * Setter for Parseable instance
980 * @param $parserInstance An instance of an Parseable
983 public final function setParserInstance (Parseable $parserInstance) {
984 $this->parserInstance = $parserInstance;
988 * Getter for Parseable instance
990 * @return $parserInstance An instance of an Parseable
992 public final function getParserInstance () {
993 return $this->parserInstance;
997 * Setter for DatabaseWrapper instance
999 * @param $wrapperInstance An instance of an DatabaseWrapper
1002 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1003 $this->wrapperInstance = $wrapperInstance;
1007 * Getter for DatabaseWrapper instance
1009 * @return $wrapperInstance An instance of an DatabaseWrapper
1011 public final function getWrapperInstance () {
1012 return $this->wrapperInstance;
1016 * Setter for helper instance
1018 * @param $helperInstance An instance of a helper class
1021 protected final function setHelperInstance (Helper $helperInstance) {
1022 $this->helperInstance = $helperInstance;
1026 * Getter for helper instance
1028 * @return $helperInstance An instance of a helper class
1030 public final function getHelperInstance () {
1031 return $this->helperInstance;
1035 * Getter for a InputStream instance
1037 * @param $inputStreamInstance The InputStream instance
1039 protected final function getInputStreamInstance () {
1040 return $this->inputStreamInstance;
1044 * Setter for a InputStream instance
1046 * @param $inputStreamInstance The InputStream instance
1049 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1050 $this->inputStreamInstance = $inputStreamInstance;
1054 * Getter for a OutputStream instance
1056 * @param $outputStreamInstance The OutputStream instance
1058 protected final function getOutputStreamInstance () {
1059 return $this->outputStreamInstance;
1063 * Setter for a OutputStream instance
1065 * @param $outputStreamInstance The OutputStream instance
1068 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1069 $this->outputStreamInstance = $outputStreamInstance;
1073 * Setter for handler instance
1075 * @param $handlerInstance An instance of a Handleable class
1078 protected final function setHandlerInstance (Handleable $handlerInstance) {
1079 $this->handlerInstance = $handlerInstance;
1083 * Getter for handler instance
1085 * @return $handlerInstance A Handleable instance
1087 protected final function getHandlerInstance () {
1088 return $this->handlerInstance;
1092 * Setter for visitor instance
1094 * @param $visitorInstance A Visitor instance
1097 protected final function setVisitorInstance (Visitor $visitorInstance) {
1098 $this->visitorInstance = $visitorInstance;
1102 * Getter for visitor instance
1104 * @return $visitorInstance A Visitor instance
1106 protected final function getVisitorInstance () {
1107 return $this->visitorInstance;
1111 * Setter for Iterator instance
1113 * @param $iteratorInstance An instance of an Iterator
1116 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1117 $this->iteratorInstance = $iteratorInstance;
1121 * Getter for Iterator instance
1123 * @return $iteratorInstance An instance of an Iterator
1125 public final function getIteratorInstance () {
1126 return $this->iteratorInstance;
1130 * Setter for FilePointer instance
1132 * @param $pointerInstance An instance of an FilePointer class
1135 protected final function setPointerInstance (FilePointer $pointerInstance) {
1136 $this->pointerInstance = $pointerInstance;
1140 * Getter for FilePointer instance
1142 * @return $pointerInstance An instance of an FilePointer class
1144 public final function getPointerInstance () {
1145 return $this->pointerInstance;
1149 * Unsets pointer instance which triggers a call of __destruct() if the
1150 * instance is still there. This is surely not fatal on already "closed"
1151 * file pointer instances.
1153 * I don't want to mess around with above setter by giving it a default
1154 * value NULL as setter should always explicitly only set (existing) object
1155 * instances and NULL is NULL.
1159 protected final function unsetPointerInstance () {
1160 // Simply it to NULL
1161 $this->pointerInstance = NULL;
1165 * Setter for Indexable instance
1167 * @param $indexInstance An instance of an Indexable class
1170 protected final function setIndexInstance (Indexable $indexInstance) {
1171 $this->indexInstance = $indexInstance;
1175 * Getter for Indexable instance
1177 * @return $indexInstance An instance of an Indexable class
1179 public final function getIndexInstance () {
1180 return $this->indexInstance;
1184 * Setter for Block instance
1186 * @param $blockInstance An instance of an Block class
1189 protected final function setBlockInstance (Block $blockInstance) {
1190 $this->blockInstance = $blockInstance;
1194 * Getter for Block instance
1196 * @return $blockInstance An instance of an Block class
1198 public final function getBlockInstance () {
1199 return $this->blockInstance;
1203 * Setter for FrameworkDirectory instance
1205 * @param $directoryInstance A FrameworkDirectory instance
1208 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1209 $this->directoryInstance = $directoryInstance;
1213 * Getter for FrameworkDirectory instance
1215 * @return $directoryInstance A FrameworkDirectory instance
1217 protected final function getDirectoryInstance () {
1218 return $this->directoryInstance;
1222 * Setter for state instance
1224 * @param $stateInstance A Stateable instance
1227 public final function setStateInstance (Stateable $stateInstance) {
1228 $this->stateInstance = $stateInstance;
1232 * Getter for state instance
1234 * @return $stateInstance A Stateable instance
1236 public final function getStateInstance () {
1237 return $this->stateInstance;
1241 * Setter for output instance
1243 * @param $outputInstance The debug output instance
1246 public final function setOutputInstance (OutputStreamer $outputInstance) {
1247 $this->outputInstance = $outputInstance;
1251 * Getter for output instance
1253 * @return $outputInstance The debug output instance
1255 public final function getOutputInstance () {
1256 return $this->outputInstance;
1260 * Setter for call-back instance
1262 * @param $callbackInstance An instance of a FrameworkInterface class
1265 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1266 $this->callbackInstance = $callbackInstance;
1270 * Getter for call-back instance
1272 * @return $callbackInstance An instance of a FrameworkInterface class
1274 protected final function getCallbackInstance () {
1275 return $this->callbackInstance;
1279 * Checks whether an object equals this object. You should overwrite this
1280 * method to implement own equality checks
1282 * @param $objectInstance An instance of a FrameworkInterface object
1283 * @return $equals Whether both objects equals
1285 public function equals (FrameworkInterface $objectInstance) {
1288 $this->__toString() == $objectInstance->__toString()
1290 $this->hashCode() == $objectInstance->hashCode()
1293 // Return the result
1298 * Generates a generic hash code of this class. You should really overwrite
1299 * this method with your own hash code generator code. But keep KISS in mind.
1301 * @return $hashCode A generic hash code respresenting this whole class
1303 public function hashCode () {
1305 return crc32($this->__toString());
1309 * Formats computer generated price values into human-understandable formats
1310 * with thousand and decimal separators.
1312 * @param $value The in computer format value for a price
1313 * @param $currency The currency symbol (use HTML-valid characters!)
1314 * @param $decNum Number of decimals after commata
1315 * @return $price The for the current language formated price string
1316 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1317 * thousands separator
1320 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1321 // Are all required attriutes set?
1322 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1323 // Throw an exception
1324 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1328 $value = (float) $value;
1330 // Reformat the US number
1331 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1333 // Return as string...
1338 * Appends a trailing slash to a string
1340 * @param $str A string (maybe) without trailing slash
1341 * @return $str A string with an auto-appended trailing slash
1343 public final function addMissingTrailingSlash ($str) {
1344 // Is there a trailing slash?
1345 if (substr($str, -1, 1) != '/') {
1349 // Return string with trailing slash
1354 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1355 * application helper instance (ApplicationHelper by default).
1357 * @param $applicationInstance An application helper instance or
1358 * null if we shall use the default
1359 * @return $templateInstance The template engine instance
1360 * @throws NullPointerException If the discovered application
1361 * instance is still null
1363 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1364 // Is the application instance set?
1365 if (is_null($applicationInstance)) {
1366 // Get the current instance
1367 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1370 if (is_null($applicationInstance)) {
1371 // Thrown an exception
1372 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1376 // Initialize the template engine
1377 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1379 // Return the prepared instance
1380 return $templateInstance;
1384 * Debugs this instance by putting out it's full content
1386 * @param $message Optional message to show in debug output
1389 public final function debugInstance ($message = '') {
1390 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1391 restore_error_handler();
1396 // Is a message set?
1397 if (!empty($message)) {
1398 // Construct message
1399 $content = sprintf('<div class="debug_message">
1401 </div>' . PHP_EOL, $message);
1404 // Generate the output
1405 $content .= sprintf('<pre>%s</pre>',
1408 print_r($this, true)
1414 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1417 <div class="debug_content">
1421 <div class="debug_include_list">
1424 $this->__toString(),
1426 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1431 * Replaces control characters with printable output
1433 * @param $str String with control characters
1434 * @return $str Replaced string
1436 protected function replaceControlCharacters ($str) {
1439 chr(13), '[r]', str_replace(
1440 chr(10), '[n]', str_replace(
1450 * Output a partial stub message for the caller method
1452 * @param $message An optional message to display
1455 protected function partialStub ($message = '') {
1457 $stubMessage = 'Partial stub!';
1459 // Is an extra message given?
1460 if (!empty($message)) {
1461 // Then add it as well
1462 $stubMessage .= ' Message: ' . $message;
1465 // Debug instance is there?
1466 if (!is_null($this->getDebugInstance())) {
1467 // Output stub message
1468 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1471 trigger_error($stubMessage);
1477 * Outputs a debug backtrace and stops further script execution
1479 * @param $message An optional message to output
1480 * @param $doExit Whether exit the program (true is default)
1483 public function debugBackTrace ($message = '', $doExit = true) {
1484 // Sorry, there is no other way getting this nice backtrace
1485 if (!empty($message)) {
1487 printf('Message: %s<br />' . PHP_EOL, $message);
1491 debug_print_backtrace();
1495 if ($doExit === true) {
1501 * Creates an instance of a debugger instance
1503 * @param $className Name of the class (currently unsupported)
1504 * @param $lineNumber Line number where the call was made
1505 * @return $debugInstance An instance of a debugger class
1506 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1508 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1509 // Is the instance set?
1510 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1511 // Init debug instance
1512 $debugInstance = NULL;
1516 // Get a debugger instance
1517 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1518 } catch (NullPointerException $e) {
1519 // Didn't work, no instance there
1520 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1523 // Empty string should be ignored and used for testing the middleware
1524 DebugMiddleware::getSelfInstance()->output('');
1526 // Set it in registry
1527 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1529 // Get instance from registry
1530 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1534 return $debugInstance;
1538 * Simple output of a message with line-break
1540 * @param $message Message to output
1543 public function outputLine ($message) {
1545 print($message . PHP_EOL);
1549 * Outputs a debug message whether to debug instance (should be set!) or
1550 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1551 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1553 * @param $message Message we shall send out...
1554 * @param $doPrint Whether print or die here (default: print)
1555 * @paran $stripTags Whether to strip tags (default: false)
1558 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1559 // Set debug instance to NULL
1560 $debugInstance = NULL;
1563 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1565 // Is function partialStub/__callStatic ?
1566 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1567 // Prepend class::function:line from 3rd element
1568 $message = sprintf('[%s::%s:%d]: %s',
1569 $backtrace[2]['class'],
1570 $backtrace[2]['function'],
1571 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1575 // Prepend class::function:line from 2nd element
1576 $message = sprintf('[%s::%s:%d]: %s',
1577 $backtrace[1]['class'],
1578 $backtrace[1]['function'],
1579 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1586 // Get debug instance
1587 $debugInstance = $this->getDebugInstance();
1588 } catch (NullPointerException $e) {
1589 // The debug instance is not set (yet)
1592 // Is the debug instance there?
1593 if (is_object($debugInstance)) {
1594 // Use debug output handler
1595 $debugInstance->output($message, $stripTags);
1597 if ($doPrint === false) {
1598 // Die here if not printed
1602 // Are debug times enabled?
1603 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1605 $message = $this->getPrintableExecutionTime() . $message;
1609 if ($doPrint === true) {
1611 $this->outputLine($message);
1620 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1622 * @param $str The string, what ever it is needs to be converted
1623 * @return $className Generated class name
1625 public static final function convertToClassName ($str) {
1629 // Convert all dashes in underscores
1630 $str = StringUtils::convertDashesToUnderscores($str);
1632 // Now use that underscores to get classname parts for hungarian style
1633 foreach (explode('_', $str) as $strPart) {
1634 // Make the class name part lower case and first upper case
1635 $className .= ucfirst(strtolower($strPart));
1638 // Return class name
1643 * Marks up the code by adding e.g. line numbers
1645 * @param $phpCode Unmarked PHP code
1646 * @return $markedCode Marked PHP code
1648 public function markupCode ($phpCode) {
1653 $errorArray = error_get_last();
1655 // Init the code with error message
1656 if (is_array($errorArray)) {
1658 $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>',
1659 basename($errorArray['file']),
1660 $errorArray['line'],
1661 $errorArray['message'],
1666 // Add line number to the code
1667 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1669 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1671 htmlentities($code, ENT_QUOTES)
1680 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1681 * beatiful for web-based front-ends. If null is given a message id
1682 * null_timestamp will be resolved and returned.
1684 * @param $timestamp Timestamp to prepare (filter) for display
1685 * @return $readable A readable timestamp
1687 public function doFilterFormatTimestamp ($timestamp) {
1688 // Default value to return
1691 // Is the timestamp null?
1692 if (is_null($timestamp)) {
1693 // Get a message string
1694 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1696 switch ($this->getLanguageInstance()->getLanguageCode()) {
1697 case 'de': // German format is a bit different to default
1698 // Split the GMT stamp up
1699 $dateTime = explode(' ', $timestamp );
1700 $dateArray = explode('-', $dateTime[0]);
1701 $timeArray = explode(':', $dateTime[1]);
1703 // Construct the timestamp
1704 $readable = sprintf(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('german_date_time'),
1714 default: // Default is pass-through
1715 $readable = $timestamp;
1725 * Filter a given number into a localized number
1727 * @param $value The raw value from e.g. database
1728 * @return $localized Localized value
1730 public function doFilterFormatNumber ($value) {
1731 // Generate it from config and localize dependencies
1732 switch ($this->getLanguageInstance()->getLanguageCode()) {
1733 case 'de': // German format is a bit different to default
1734 $localized = number_format($value, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals'), ',', '.');
1737 default: // US, etc.
1738 $localized = number_format($value, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals'), '.', ',');
1747 * "Getter" for databse entry
1749 * @return $entry An array with database entries
1750 * @throws NullPointerException If the database result is not found
1751 * @throws InvalidDatabaseResultException If the database result is invalid
1753 protected final function getDatabaseEntry () {
1754 // Is there an instance?
1755 if (!$this->getResultInstance() instanceof SearchableResult) {
1756 // Throw an exception here
1757 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1761 $this->getResultInstance()->rewind();
1763 // Do we have an entry?
1764 if ($this->getResultInstance()->valid() === false) {
1765 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
1766 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1770 $this->getResultInstance()->next();
1773 $entry = $this->getResultInstance()->current();
1780 * Getter for field name
1782 * @param $fieldName Field name which we shall get
1783 * @return $fieldValue Field value from the user
1784 * @throws NullPointerException If the result instance is null
1786 public final function getField ($fieldName) {
1787 // Default field value
1790 // Get result instance
1791 $resultInstance = $this->getResultInstance();
1793 // Is this instance null?
1794 if (is_null($resultInstance)) {
1795 // Then the user instance is no longer valid (expired cookies?)
1796 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1799 // Get current array
1800 $fieldArray = $resultInstance->current();
1801 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1803 // Convert dashes to underscore
1804 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
1806 // Does the field exist?
1807 if ($this->isFieldSet($fieldName)) {
1809 $fieldValue = $fieldArray[$fieldName2];
1810 } elseif (defined('DEVELOPER')) {
1811 // Missing field entry, may require debugging
1812 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
1814 // Missing field entry, may require debugging
1815 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
1823 * Checks if given field is set
1825 * @param $fieldName Field name to check
1826 * @return $isSet Whether the given field name is set
1827 * @throws NullPointerException If the result instance is null
1829 public function isFieldSet ($fieldName) {
1830 // Get result instance
1831 $resultInstance = $this->getResultInstance();
1833 // Is this instance null?
1834 if (is_null($resultInstance)) {
1835 // Then the user instance is no longer valid (expired cookies?)
1836 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1839 // Get current array
1840 $fieldArray = $resultInstance->current();
1841 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
1843 // Convert dashes to underscore
1844 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
1847 $isSet = isset($fieldArray[$fieldName]);
1854 * Flushs all pending updates to the database layer
1858 public function flushPendingUpdates () {
1859 // Get result instance
1860 $resultInstance = $this->getResultInstance();
1862 // Do we have data to update?
1863 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1864 // Get wrapper class name config entry
1865 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1867 // Create object instance
1868 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
1870 // Yes, then send the whole result to the database layer
1871 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1876 * Outputs a deprecation warning to the developer.
1878 * @param $message The message we shall output to the developer
1880 * @todo Write a logging mechanism for productive mode
1882 public function deprecationWarning ($message) {
1883 // Is developer mode active?
1884 if (defined('DEVELOPER')) {
1885 // Debug instance is there?
1886 if (!is_null($this->getDebugInstance())) {
1887 // Output stub message
1888 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
1891 trigger_error($message . "<br />\n");
1895 // @TODO Finish this part!
1896 $this->partialStub('Developer mode inactive. Message:' . $message);
1901 * Checks whether the given PHP extension is loaded
1903 * @param $phpExtension The PHP extension we shall check
1904 * @return $isLoaded Whether the PHP extension is loaded
1906 public final function isPhpExtensionLoaded ($phpExtension) {
1908 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1915 * "Getter" as a time() replacement but with milliseconds. You should use this
1916 * method instead of the encapsulated getimeofday() function.
1918 * @return $milliTime Timestamp with milliseconds
1920 public function getMilliTime () {
1921 // Get the time of day as float
1922 $milliTime = gettimeofday(true);
1929 * Idles (sleeps) for given milliseconds
1931 * @return $hasSlept Whether it goes fine
1933 public function idle ($milliSeconds) {
1934 // Sleep is fine by default
1937 // Idle so long with found function
1938 if (function_exists('time_sleep_until')) {
1939 // Get current time and add idle time
1940 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1942 // New PHP 5.1.0 function found, ignore errors
1943 $hasSlept = @time_sleep_until($sleepUntil);
1946 * My Sun station doesn't have that function even with latest PHP
1949 usleep($milliSeconds * 1000);
1956 * Converts a hexadecimal string, even with negative sign as first string to
1957 * a decimal number using BC functions.
1959 * This work is based on comment #86673 on php.net documentation page at:
1960 * <http://de.php.net/manual/en/function.dechex.php#86673>
1962 * @param $hex Hexadecimal string
1963 * @return $dec Decimal number
1965 protected function hex2dec ($hex) {
1966 // Convert to all lower-case
1967 $hex = strtolower($hex);
1969 // Detect sign (negative/positive numbers)
1971 if (substr($hex, 0, 1) == '-') {
1973 $hex = substr($hex, 1);
1976 // Decode the hexadecimal string into a decimal number
1978 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1979 $factor = self::$hexdec[substr($hex, $i, 1)];
1980 $dec = bcadd($dec, bcmul($factor, $e));
1983 // Return the decimal number
1984 return $sign . $dec;
1988 * Converts even very large decimal numbers, also signed, to a hexadecimal
1991 * This work is based on comment #97756 on php.net documentation page at:
1992 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1994 * @param $dec Decimal number, even with negative sign
1995 * @param $maxLength Optional maximum length of the string
1996 * @return $hex Hexadecimal string
1998 protected function dec2hex ($dec, $maxLength = 0) {
1999 // maxLength can be zero or devideable by 2
2000 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2002 // Detect sign (negative/positive numbers)
2009 // Encode the decimal number into a hexadecimal string
2012 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2014 } while ($dec >= 1);
2017 * Leading zeros are required for hex-decimal "numbers". In some
2018 * situations more leading zeros are wanted, so check for both
2021 if ($maxLength > 0) {
2022 // Prepend more zeros
2023 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2024 } elseif ((strlen($hex) % 2) != 0) {
2025 // Only make string's length dividable by 2
2029 // Return the hexadecimal string
2030 return $sign . $hex;
2034 * Converts a ASCII string (0 to 255) into a decimal number.
2036 * @param $asc The ASCII string to be converted
2037 * @return $dec Decimal number
2039 protected function asc2dec ($asc) {
2040 // Convert it into a hexadecimal number
2041 $hex = bin2hex($asc);
2043 // And back into a decimal number
2044 $dec = $this->hex2dec($hex);
2051 * Converts a decimal number into an ASCII string.
2053 * @param $dec Decimal number
2054 * @return $asc An ASCII string
2056 protected function dec2asc ($dec) {
2057 // First convert the number into a hexadecimal string
2058 $hex = $this->dec2hex($dec);
2060 // Then convert it into the ASCII string
2061 $asc = $this->hex2asc($hex);
2068 * Converts a hexadecimal number into an ASCII string. Negative numbers
2071 * @param $hex Hexadecimal string
2072 * @return $asc An ASCII string
2074 protected function hex2asc ($hex) {
2075 // Check for length, it must be devideable by 2
2076 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2077 assert((strlen($hex) % 2) == 0);
2081 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2082 // Get the decimal number of the chunk
2083 $part = hexdec(substr($hex, $idx, 2));
2085 // Add it to the final string
2089 // Return the final string
2094 * Checks whether the given encoded data was encoded with Base64
2096 * @param $encodedData Encoded data we shall check
2097 * @return $isBase64 Whether the encoded data is Base64
2099 protected function isBase64Encoded ($encodedData) {
2101 $isBase64 = (@base64_decode($encodedData, true) !== false);
2108 * Gets a cache key from Criteria instance
2110 * @param $criteriaInstance An instance of a Criteria class
2111 * @param $onlyKeys Only use these keys for a cache key
2112 * @return $cacheKey A cache key suitable for lookup/storage purposes
2114 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2116 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: criteriaInstance=' . $criteriaInstance->__toString() . ',onlyKeys()=' . count($onlyKeys) . ' - CALLED!');
2117 $cacheKey = sprintf('%s@%s',
2118 $this->__toString(),
2119 $criteriaInstance->getCacheKey($onlyKeys)
2123 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
2128 * Getter for startup time in miliseconds
2130 * @return $startupTime Startup time in miliseconds
2132 protected function getStartupTime () {
2133 return self::$startupTime;
2137 * "Getter" for a printable currently execution time in nice braces
2139 * @return $executionTime Current execution time in nice braces
2141 protected function getPrintableExecutionTime () {
2142 // Caculate the execution time
2143 $executionTime = microtime(true) - $this->getStartupTime();
2145 // Pack it in nice braces
2146 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2149 return $executionTime;
2153 * Hashes a given string with a simple but stronger hash function (no salt)
2154 * and hex-encode it.
2156 * @param $str The string to be hashed
2157 * @return $hash The hash from string $str
2159 public static final function hash ($str) {
2160 // Hash given string with (better secure) hasher
2161 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2168 * "Getter" for length of hash() output. This will be "cached" to speed up
2171 * @return $length Length of hash() output
2173 public static final function getHashLength () {
2175 if (is_null(self::$hashLength)) {
2176 // No, then hash a string and save its length.
2177 self::$hashLength = strlen(self::hash('abc123'));
2181 return self::$hashLength;
2185 * Checks whether the given number is really a number (only chars 0-9).
2187 * @param $num A string consisting only chars between 0 and 9
2188 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2189 * @param $assertMismatch Whether to assert mismatches
2190 * @return $ret The (hopefully) secured numbered value
2192 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2193 // Filter all numbers out
2194 $ret = preg_replace('/[^0123456789]/', '', $num);
2197 if ($castValue === true) {
2198 // Cast to biggest numeric type
2199 $ret = (double) $ret;
2202 // Assert only if requested
2203 if ($assertMismatch === true) {
2204 // Has the whole value changed?
2205 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2213 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2215 * @param $num A string consisting only chars between 0 and 9
2216 * @param $assertMismatch Whether to assert mismatches
2217 * @return $ret The (hopefully) secured hext-numbered value
2219 public function hexval ($num, $assertMismatch = false) {
2220 // Filter all numbers out
2221 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2223 // Assert only if requested
2224 if ($assertMismatch === true) {
2225 // Has the whole value changed?
2226 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2234 * Determines if an element is set in the generic array
2236 * @param $keyGroup Main group for the key
2237 * @param $subGroup Sub group for the key
2238 * @param $key Key to check
2239 * @param $element Element to check
2240 * @return $isset Whether the given key is set
2242 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2244 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2247 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2253 * Determines if a key is set in the generic array
2255 * @param $keyGroup Main group for the key
2256 * @param $subGroup Sub group for the key
2257 * @param $key Key to check
2258 * @return $isset Whether the given key is set
2260 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2262 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2265 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2273 * Determines if a group is set in the generic array
2275 * @param $keyGroup Main group
2276 * @param $subGroup Sub group
2277 * @return $isset Whether the given group is set
2279 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2281 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2284 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2291 * Getter for sub key group
2293 * @param $keyGroup Main key group
2294 * @param $subGroup Sub key group
2295 * @return $array An array with all array elements
2297 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2299 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2300 // No, then abort here
2301 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2306 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2309 return $this->genericArray[$keyGroup][$subGroup];
2313 * Unsets a given key in generic array
2315 * @param $keyGroup Main group for the key
2316 * @param $subGroup Sub group for the key
2317 * @param $key Key to unset
2320 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2322 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2325 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2329 * Unsets a given element in generic array
2331 * @param $keyGroup Main group for the key
2332 * @param $subGroup Sub group for the key
2333 * @param $key Key to unset
2334 * @param $element Element to unset
2337 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2339 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2342 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2346 * Append a string to a given generic array key
2348 * @param $keyGroup Main group for the key
2349 * @param $subGroup Sub group for the key
2350 * @param $key Key to unset
2351 * @param $value Value to add/append
2354 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2356 //* 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);
2358 // Is it already there?
2359 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2361 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2364 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2369 * Append a string to a given generic array element
2371 * @param $keyGroup Main group for the key
2372 * @param $subGroup Sub group for the key
2373 * @param $key Key to unset
2374 * @param $element Element to check
2375 * @param $value Value to add/append
2378 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2380 //* 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);
2382 // Is it already there?
2383 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2385 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2388 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2393 * Sets a string in a given generic array element
2395 * @param $keyGroup Main group for the key
2396 * @param $subGroup Sub group for the key
2397 * @param $key Key to unset
2398 * @param $element Element to check
2399 * @param $value Value to add/append
2402 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2404 //* 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);
2407 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2411 * Initializes given generic array group
2413 * @param $keyGroup Main group for the key
2414 * @param $subGroup Sub group for the key
2415 * @param $key Key to use
2416 * @param $forceInit Optionally force initialization
2419 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2421 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2423 // Is it already set?
2424 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2425 // Already initialized
2426 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2431 $this->genericArray[$keyGroup][$subGroup] = array();
2435 * Initializes given generic array key
2437 * @param $keyGroup Main group for the key
2438 * @param $subGroup Sub group for the key
2439 * @param $key Key to use
2440 * @param $forceInit Optionally force initialization
2443 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2445 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2447 // Is it already set?
2448 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2449 // Already initialized
2450 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2455 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2459 * Initializes given generic array element
2461 * @param $keyGroup Main group for the key
2462 * @param $subGroup Sub group for the key
2463 * @param $key Key to use
2464 * @param $element Element to use
2465 * @param $forceInit Optionally force initialization
2468 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2470 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2472 // Is it already set?
2473 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2474 // Already initialized
2475 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2480 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2484 * Pushes an element to a generic key
2486 * @param $keyGroup Main group for the key
2487 * @param $subGroup Sub group for the key
2488 * @param $key Key to use
2489 * @param $value Value to add/append
2490 * @return $count Number of array elements
2492 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2494 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2497 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2499 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2503 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2506 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2507 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2512 * Pushes an element to a generic array element
2514 * @param $keyGroup Main group for the key
2515 * @param $subGroup Sub group for the key
2516 * @param $key Key to use
2517 * @param $element Element to check
2518 * @param $value Value to add/append
2519 * @return $count Number of array elements
2521 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2523 //* 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));
2526 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2528 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2532 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2535 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2536 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2541 * Pops an element from a generic group
2543 * @param $keyGroup Main group for the key
2544 * @param $subGroup Sub group for the key
2545 * @param $key Key to unset
2546 * @return $value Last "popped" value
2548 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2550 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2553 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2555 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2560 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2563 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2564 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2569 * Shifts an element from a generic group
2571 * @param $keyGroup Main group for the key
2572 * @param $subGroup Sub group for the key
2573 * @param $key Key to unset
2574 * @return $value Last "popped" value
2576 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2578 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2581 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2583 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2588 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2591 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2592 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2597 * Count generic array group
2599 * @param $keyGroup Main group for the key
2600 * @return $count Count of given group
2602 protected final function countGenericArray ($keyGroup) {
2604 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2607 if (!isset($this->genericArray[$keyGroup])) {
2609 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2614 $count = count($this->genericArray[$keyGroup]);
2617 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2624 * Count generic array sub group
2626 * @param $keyGroup Main group for the key
2627 * @param $subGroup Sub group for the key
2628 * @return $count Count of given group
2630 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2632 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2635 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2637 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2642 $count = count($this->genericArray[$keyGroup][$subGroup]);
2645 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2652 * Count generic array elements
2654 * @param $keyGroup Main group for the key
2655 * @param $subGroup Sub group for the key
2656 * @para $key Key to count
2657 * @return $count Count of given key
2659 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2661 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2664 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2666 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2668 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2670 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2675 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2678 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2685 * Getter for whole generic group array
2687 * @param $keyGroup Key group to get
2688 * @return $array Whole generic array group
2690 protected final function getGenericArray ($keyGroup) {
2692 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2695 if (!isset($this->genericArray[$keyGroup])) {
2697 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2702 return $this->genericArray[$keyGroup];
2706 * Setter for generic array key
2708 * @param $keyGroup Key group to get
2709 * @param $subGroup Sub group for the key
2710 * @param $key Key to unset
2711 * @param $value Mixed value from generic array element
2714 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2716 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2719 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2723 * Getter for generic array key
2725 * @param $keyGroup Key group to get
2726 * @param $subGroup Sub group for the key
2727 * @param $key Key to unset
2728 * @return $value Mixed value from generic array element
2730 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2732 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2735 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2737 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2742 return $this->genericArray[$keyGroup][$subGroup][$key];
2746 * Sets a value in given generic array key/element
2748 * @param $keyGroup Main group for the key
2749 * @param $subGroup Sub group for the key
2750 * @param $key Key to set
2751 * @param $element Element to set
2752 * @param $value Value to set
2755 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2757 //* 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));
2760 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2764 * Getter for generic array element
2766 * @param $keyGroup Key group to get
2767 * @param $subGroup Sub group for the key
2768 * @param $key Key to look for
2769 * @param $element Element to look for
2770 * @return $value Mixed value from generic array element
2772 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2774 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2777 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2779 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2784 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2788 * Checks if a given sub group is valid (array)
2790 * @param $keyGroup Key group to get
2791 * @param $subGroup Sub group for the key
2792 * @return $isValid Whether given sub group is valid
2794 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2796 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2799 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2806 * Checks if a given key is valid (array)
2808 * @param $keyGroup Key group to get
2809 * @param $subGroup Sub group for the key
2810 * @param $key Key to check
2811 * @return $isValid Whether given sub group is valid
2813 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2815 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2818 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2825 * Initializes the web output instance
2829 protected function initWebOutputInstance () {
2830 // Get application instance
2831 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
2833 // Init web output instance
2834 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
2837 $this->setWebOutputInstance($outputInstance);
2841 * Translates boolean true to 'Y' and false to 'N'
2843 * @param $boolean Boolean value
2844 * @return $translated Translated boolean value
2846 public static final function translateBooleanToYesNo ($boolean) {
2847 // Make sure it is really boolean
2848 assert(is_bool($boolean));
2851 $translated = ($boolean === true) ? 'Y' : 'N';
2853 // ... and return it
2858 * Encodes raw data (almost any type) by "serializing" it and then pack it
2859 * into a "binary format".
2861 * @param $rawData Raw data (almost any type)
2862 * @return $encoded Encoded data
2864 protected function encodeData ($rawData) {
2865 // Make sure no objects or resources pass through
2866 assert(!is_object($rawData));
2867 assert(!is_resource($rawData));
2869 // First "serialize" it (json_encode() is faster than serialize())
2870 $encoded = $this->packString(json_encode($rawData));
2877 * Pack a string into a "binary format". Please execuse me that this is
2878 * widely undocumented. :-(
2880 * @param $str Unpacked string
2881 * @return $packed Packed string
2882 * @todo Improve documentation
2884 protected function packString ($str) {
2886 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
2888 // First compress the string (gzcompress is okay)
2889 $str = gzcompress($str);
2894 // And start the "encoding" loop
2895 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
2897 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
2898 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
2900 if (($idx + $i) <= strlen($str)) {
2901 $ord = ord(substr($str, ($idx + $i), 1));
2903 $add = $ord * pow(256, $factor);
2907 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
2911 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
2912 $r = $big & $this->packingData[$this->archArrayElement]['right'];
2914 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
2915 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
2921 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
2926 * Creates a full-qualified file name (FQFN) for given file name by adding
2927 * a configured temporary file path to it.
2929 * @param $infoInstance An instance of a SplFileInfo class
2930 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
2931 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
2932 * @throws FileIoException If the file cannot be written
2934 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
2936 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
2938 // Is the path writeable?
2939 if (!is_writable($basePath)) {
2940 // Path is write-protected
2941 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
2945 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
2948 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
2950 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
2954 return $tempInstance;
2958 * "Getter" for a printable state name
2960 * @return $stateName Name of the node's state in a printable format
2962 public final function getPrintableState () {
2963 // Default is 'null'
2964 $stateName = 'null';
2966 // Get the state instance
2967 $stateInstance = $this->getStateInstance();
2969 // Is it an instance of Stateable?
2970 if ($stateInstance instanceof Stateable) {
2971 // Then use that state name
2972 $stateName = $stateInstance->getStateName();