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\Factory\Database\Wrapper\DatabaseWrapperFactory;
18 use CoreFramework\Factory\ObjectFactory;
19 use CoreFramework\Filesystem\Block;
20 use CoreFramework\Filesystem\FilePointer;
21 use CoreFramework\Filesystem\FrameworkDirectory;
22 use CoreFramework\Filesystem\PathWriteProtectedException;
23 use CoreFramework\Generic\FrameworkInterface;
24 use CoreFramework\Generic\NullPointerException;
25 use CoreFramework\Generic\UnsupportedOperationException;
26 use CoreFramework\Handler\Handleable;
27 use CoreFramework\Handler\Stream\IoHandler;
28 use CoreFramework\Index\Indexable;
29 use CoreFramework\Lists\Listable;
30 use CoreFramework\Loader\ClassLoader;
31 use CoreFramework\Manager\ManageableApplication;
32 use CoreFramework\Middleware\Compressor\CompressorChannel;
33 use CoreFramework\Middleware\Debug\DebugMiddleware;
34 use CoreFramework\Parser\Parseable;
35 use CoreFramework\Registry\Register;
36 use CoreFramework\Registry\Registry;
37 use CoreFramework\Resolver\Resolver;
38 use CoreFramework\Result\Database\CachedDatabaseResult;
39 use CoreFramework\Result\Search\SearchableResult;
40 use CoreFramework\Stacker\Stackable;
41 use CoreFramework\State\Stateable;
42 use CoreFramework\Stream\Output\OutputStreamer;
43 use CoreFramework\Template\CompileableTemplate;
44 use CoreFramework\User\ManageableAccount;
45 use CoreFramework\Visitor\Visitor;
53 * The simulator system class is the super class of all other classes. This
54 * class handles saving of games etc.
56 * @author Roland Haeder <webmaster@shipsimu.org>
58 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
59 * @license GNU GPL 3.0 or any newer version
60 * @link http://www.shipsimu.org
62 * This program is free software: you can redistribute it and/or modify
63 * it under the terms of the GNU General Public License as published by
64 * the Free Software Foundation, either version 3 of the License, or
65 * (at your option) any later version.
67 * This program is distributed in the hope that it will be useful,
68 * but WITHOUT ANY WARRANTY; without even the implied warranty of
69 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
70 * GNU General Public License for more details.
72 * You should have received a copy of the GNU General Public License
73 * along with this program. If not, see <http://www.gnu.org/licenses/>.
75 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
77 * Length of output from hash()
79 private static $hashLength = NULL;
84 private $realClass = 'BaseFrameworkSystem';
87 * Search criteria instance
89 private $searchInstance = NULL;
92 * Update criteria instance
94 private $updateInstance = NULL;
97 * The file I/O instance for the template loader
99 private $fileIoInstance = NULL;
104 private $resolverInstance = NULL;
107 * Template engine instance
109 private $templateInstance = NULL;
112 * Database result instance
114 private $resultInstance = NULL;
117 * Instance for user class
119 private $userInstance = NULL;
122 * A controller instance
124 private $controllerInstance = NULL;
129 private $rngInstance = NULL;
132 * Instance of a crypto helper
134 private $cryptoInstance = NULL;
137 * Instance of an Iterator class
139 private $iteratorInstance = NULL;
142 * Instance of the list
144 private $listInstance = NULL;
149 private $menuInstance = NULL;
152 * Instance of the image
154 private $imageInstance = NULL;
157 * Instance of the stacker
159 private $stackInstance = NULL;
162 * A Compressor instance
164 private $compressorInstance = NULL;
167 * A Parseable instance
169 private $parserInstance = NULL;
172 * A database wrapper instance
174 private $databaseInstance = NULL;
177 * A helper instance for the form
179 private $helperInstance = NULL;
182 * An instance of a Source class
184 private $sourceInstance = NULL;
187 * An instance of a UrlSource class
189 private $urlSourceInstance = NULL;
192 * An instance of a InputStream class
194 private $inputStreamInstance = NULL;
197 * An instance of a OutputStream class
199 private $outputStreamInstance = NULL;
204 private $handlerInstance = NULL;
207 * Visitor handler instance
209 private $visitorInstance = NULL;
214 private $dhtInstance = 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 * Thousands separator
264 private $thousands = '.'; // German
269 private $decimals = ','; // German
274 private $socketResource = false;
277 * Regular expression to use for validation
279 private $regularExpression = '';
284 private $packageData = array();
289 private $genericArray = array();
294 private $commandName = '';
299 private $controllerName = '';
302 * Array with bitmasks and such for pack/unpack methods to support both
303 * 32-bit and 64-bit systems
305 private $packingData = array(
308 'left' => 0xffff0000,
309 'right' => 0x0000ffff,
315 'left' => 0xffffffff00000000,
316 'right' => 0x00000000ffffffff,
323 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
325 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
327 private $archArrayElement = false;
329 /***********************
330 * Exception codes.... *
331 ***********************/
333 // @todo Try to clean these constants up
334 const EXCEPTION_IS_NULL_POINTER = 0x001;
335 const EXCEPTION_IS_NO_OBJECT = 0x002;
336 const EXCEPTION_IS_NO_ARRAY = 0x003;
337 const EXCEPTION_MISSING_METHOD = 0x004;
338 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
339 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
340 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
341 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
342 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
343 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
344 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
345 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
346 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
347 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
348 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
349 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
350 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
351 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
352 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
353 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
354 const EXCEPTION_PATH_NOT_FOUND = 0x015;
355 const EXCEPTION_INVALID_PATH_NAME = 0x016;
356 const EXCEPTION_READ_PROTECED_PATH = 0x017;
357 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
358 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
359 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
360 const EXCEPTION_INVALID_RESOURCE = 0x01b;
361 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
362 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
363 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
364 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
365 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
366 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
367 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
368 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
369 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
370 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
371 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
372 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
373 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
374 const EXCEPTION_INVALID_STRING = 0x029;
375 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
376 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
377 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
378 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
379 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
380 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
381 const EXCEPTION_MISSING_ELEMENT = 0x030;
382 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
383 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
384 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
385 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
386 const EXCEPTION_FATAL_ERROR = 0x035;
387 const EXCEPTION_FILE_NOT_FOUND = 0x036;
388 const EXCEPTION_ASSERTION_FAILED = 0x037;
389 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
390 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
391 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
392 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
393 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
394 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
395 const EXCEPTION_INVALID_SOCKET = 0x03e;
398 * Hexadecimal->Decimal translation array
400 private static $hexdec = array(
420 * Decimal->hexadecimal translation array
422 private static $dechex = array(
442 * Startup time in miliseconds
444 private static $startupTime = 0;
447 * Protected super constructor
449 * @param $className Name of the class
452 protected function __construct ($className) {
454 $this->setRealClass($className);
456 // Set configuration instance if no registry ...
457 if (!$this instanceof Register) {
458 // ... because registries doesn't need to be configured
459 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
462 // Is the startup time set? (0 cannot be true anymore)
463 if (self::$startupTime == 0) {
465 self::$startupTime = microtime(true);
469 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
473 * Destructor for all classes. You should not call this method on your own.
477 public function __destruct () {
478 // Flush any updated entries to the database
479 $this->flushPendingUpdates();
481 // Is this object already destroyed?
482 if ($this->__toString() != 'DestructedObject') {
483 // Destroy all informations about this class but keep some text about it alive
484 $this->setRealClass('DestructedObject');
485 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
486 // Already destructed object
487 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
491 // Do not call this twice
492 trigger_error(__METHOD__ . ': Called twice.');
498 * The __call() method where all non-implemented methods end up
500 * @param $methodName Name of the missing method
501 * @args $args Arguments passed to the method
504 public final function __call ($methodName, $args) {
505 return self::__callStatic($methodName, $args);
509 * The __callStatic() method where all non-implemented static methods end up
511 * @param $methodName Name of the missing method
512 * @args $args Arguments passed to the method
515 public static final function __callStatic ($methodName, $args) {
517 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
519 // Init argument string
522 // Is it NULL, empty or an array?
523 if (is_null($args)) {
525 $argsString = 'NULL';
526 } elseif (is_array($args)) {
530 // Some arguments are there
531 foreach ($args as $arg) {
532 // Add data about the argument
533 $argsString .= gettype($arg) . ':';
536 // Found a NULL argument
537 $argsString .= 'NULL';
538 } elseif (is_string($arg)) {
539 // Add length for strings
540 $argsString .= strlen($arg);
541 } elseif ((is_int($arg)) || (is_float($arg))) {
544 } elseif (is_array($arg)) {
545 // .. or size if array
546 $argsString .= count($arg);
547 } elseif (is_object($arg)) {
549 $reflection = new ReflectionClass($arg);
551 // Is an other object, maybe no __toString() available
552 $argsString .= $reflection->getName();
553 } elseif ($arg === true) {
554 // ... is boolean 'true'
555 $argsString .= 'true';
556 } elseif ($arg === false) {
557 // ... is boolean 'false'
558 $argsString .= 'false';
561 // Comma for next one
566 if (substr($argsString, -2, 1) == ',') {
567 $argsString = substr($argsString, 0, -2);
573 // Invalid arguments!
574 $argsString = '!INVALID:' . gettype($args) . '!';
577 // Output stub message
578 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
579 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
589 * Getter for $realClass
591 * @return $realClass The name of the real class (not BaseFrameworkSystem)
593 public function __toString () {
594 return $this->realClass;
598 * Magic method to catch setting of missing but set class fields/attributes
600 * @param $name Name of the field/attribute
601 * @param $value Value to store
604 public final function __set ($name, $value) {
605 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
608 print_r($value, true)
613 * Magic method to catch getting of missing fields/attributes
615 * @param $name Name of the field/attribute
618 public final function __get ($name) {
619 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
625 * Magic method to catch unsetting of missing fields/attributes
627 * @param $name Name of the field/attribute
630 public final function __unset ($name) {
631 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
637 * Magic method to catch object serialization
639 * @return $unsupported Unsupported method
640 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
642 public final function __sleep () {
643 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
647 * Magic method to catch object deserialization
649 * @return $unsupported Unsupported method
650 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
652 public final function __wakeup () {
653 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
657 * Magic method to catch calls when an object instance is called
659 * @return $unsupported Unsupported method
660 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
662 public final function __invoke () {
663 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
667 * Setter for the real class name
669 * @param $realClass Class name (string)
672 public final function setRealClass ($realClass) {
674 $this->realClass = (string) $realClass;
678 * Setter for database result instance
680 * @param $resultInstance An instance of a database result class
682 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
684 protected final function setResultInstance (SearchableResult $resultInstance) {
685 $this->resultInstance = $resultInstance;
689 * Getter for database result instance
691 * @return $resultInstance An instance of a database result class
693 public final function getResultInstance () {
694 return $this->resultInstance;
698 * Setter for template engine instances
700 * @param $templateInstance An instance of a template engine class
703 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
704 $this->templateInstance = $templateInstance;
708 * Getter for template engine instances
710 * @return $templateInstance An instance of a template engine class
712 protected final function getTemplateInstance () {
713 return $this->templateInstance;
717 * Setter for search instance
719 * @param $searchInstance Searchable criteria instance
722 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
723 $this->searchInstance = $searchInstance;
727 * Getter for search instance
729 * @return $searchInstance Searchable criteria instance
731 public final function getSearchInstance () {
732 return $this->searchInstance;
736 * Setter for update instance
738 * @param $updateInstance An instance of a LocalUpdateCriteria clase
741 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
742 $this->updateInstance = $updateInstance;
746 * Getter for update instance
748 * @return $updateInstance Updateable criteria instance
750 public final function getUpdateInstance () {
751 return $this->updateInstance;
755 * Setter for resolver instance
757 * @param $resolverInstance Instance of a command resolver class
760 public final function setResolverInstance (Resolver $resolverInstance) {
761 $this->resolverInstance = $resolverInstance;
765 * Getter for resolver instance
767 * @return $resolverInstance Instance of a command resolver class
769 public final function getResolverInstance () {
770 return $this->resolverInstance;
774 * Setter for language instance
776 * @param $configInstance The configuration instance which shall
777 * be FrameworkConfiguration
780 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
781 Registry::getRegistry()->addInstance('config', $configInstance);
785 * Getter for configuration instance
787 * @return $configInstance Configuration instance
789 public final function getConfigInstance () {
790 $configInstance = Registry::getRegistry()->getInstance('config');
791 return $configInstance;
795 * Setter for debug instance
797 * @param $debugInstance The instance for debug output class
800 public final function setDebugInstance (DebugMiddleware $debugInstance) {
801 Registry::getRegistry()->addInstance('debug', $debugInstance);
805 * Getter for debug instance
807 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
809 public final function getDebugInstance () {
810 // Get debug instance
811 $debugInstance = Registry::getRegistry()->getInstance('debug');
814 return $debugInstance;
818 * Setter for web output instance
820 * @param $webInstance The instance for web output class
823 public final function setWebOutputInstance (OutputStreamer $webInstance) {
824 Registry::getRegistry()->addInstance('web_output', $webInstance);
828 * Getter for web output instance
830 * @return $webOutputInstance - Instance to class WebOutput
832 public final function getWebOutputInstance () {
833 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
834 return $webOutputInstance;
838 * Setter for database instance
840 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
843 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
844 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
848 * Getter for database layer
850 * @return $databaseInstance The database layer instance
852 public final function getDatabaseInstance () {
854 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
857 return $databaseInstance;
861 * Setter for compressor channel
863 * @param $compressorInstance An instance of CompressorChannel
866 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
867 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
871 * Getter for compressor channel
873 * @return $compressorInstance The compressor channel
875 public final function getCompressorChannel () {
876 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
877 return $compressorInstance;
881 * Protected getter for a manageable application helper class
883 * @return $applicationInstance An instance of a manageable application helper class
885 protected final function getApplicationInstance () {
886 $applicationInstance = Registry::getRegistry()->getInstance('app');
887 return $applicationInstance;
891 * Setter for a manageable application helper class
893 * @param $applicationInstance An instance of a manageable application helper class
896 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
897 Registry::getRegistry()->addInstance('application', $applicationInstance);
901 * Private getter for language instance
903 * @return $langInstance An instance to the language sub-system
905 protected final function getLanguageInstance () {
906 $langInstance = Registry::getRegistry()->getInstance('language');
907 return $langInstance;
911 * Setter for language instance
913 * @param $langInstance An instance to the language sub-system
915 * @see LanguageSystem
917 public final function setLanguageInstance (ManageableLanguage $langInstance) {
918 Registry::getRegistry()->addInstance('language', $langInstance);
922 * Private getter for file IO instance
924 * @return $fileIoInstance An instance to the file I/O sub-system
926 protected final function getFileIoInstance () {
927 return $this->fileIoInstance;
931 * Setter for file I/O instance
933 * @param $fileIoInstance An instance to the file I/O sub-system
936 public final function setFileIoInstance (IoHandler $fileIoInstance) {
937 $this->fileIoInstance = $fileIoInstance;
941 * Protected setter for user instance
943 * @param $userInstance An instance of a user class
946 protected final function setUserInstance (ManageableAccount $userInstance) {
947 $this->userInstance = $userInstance;
951 * Getter for user instance
953 * @return $userInstance An instance of a user class
955 public final function getUserInstance () {
956 return $this->userInstance;
960 * Setter for controller instance (this surely breaks a bit the MVC patterm)
962 * @param $controllerInstance An instance of the controller
965 public final function setControllerInstance (Controller $controllerInstance) {
966 $this->controllerInstance = $controllerInstance;
970 * Getter for controller instance (this surely breaks a bit the MVC patterm)
972 * @return $controllerInstance An instance of the controller
974 public final function getControllerInstance () {
975 return $this->controllerInstance;
979 * Setter for RNG instance
981 * @param $rngInstance An instance of a random number generator (RNG)
984 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
985 $this->rngInstance = $rngInstance;
989 * Getter for RNG instance
991 * @return $rngInstance An instance of a random number generator (RNG)
993 public final function getRngInstance () {
994 return $this->rngInstance;
998 * Setter for Cryptable instance
1000 * @param $cryptoInstance An instance of a Cryptable class
1003 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1004 $this->cryptoInstance = $cryptoInstance;
1008 * Getter for Cryptable instance
1010 * @return $cryptoInstance An instance of a Cryptable class
1012 public final function getCryptoInstance () {
1013 return $this->cryptoInstance;
1017 * Setter for the list instance
1019 * @param $listInstance A list of Listable
1022 protected final function setListInstance (Listable $listInstance) {
1023 $this->listInstance = $listInstance;
1027 * Getter for the list instance
1029 * @return $listInstance A list of Listable
1031 protected final function getListInstance () {
1032 return $this->listInstance;
1036 * Setter for the menu instance
1038 * @param $menuInstance A RenderableMenu instance
1041 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1042 $this->menuInstance = $menuInstance;
1046 * Getter for the menu instance
1048 * @return $menuInstance A RenderableMenu instance
1050 protected final function getMenuInstance () {
1051 return $this->menuInstance;
1055 * Setter for image instance
1057 * @param $imageInstance An instance of an image
1060 public final function setImageInstance (BaseImage $imageInstance) {
1061 $this->imageInstance = $imageInstance;
1065 * Getter for image instance
1067 * @return $imageInstance An instance of an image
1069 public final function getImageInstance () {
1070 return $this->imageInstance;
1074 * Setter for stacker instance
1076 * @param $stackInstance An instance of an stacker
1079 public final function setStackInstance (Stackable $stackInstance) {
1080 $this->stackInstance = $stackInstance;
1084 * Getter for stacker instance
1086 * @return $stackInstance An instance of an stacker
1088 public final function getStackInstance () {
1089 return $this->stackInstance;
1093 * Setter for compressor instance
1095 * @param $compressorInstance An instance of an compressor
1098 public final function setCompressorInstance (Compressor $compressorInstance) {
1099 $this->compressorInstance = $compressorInstance;
1103 * Getter for compressor instance
1105 * @return $compressorInstance An instance of an compressor
1107 public final function getCompressorInstance () {
1108 return $this->compressorInstance;
1112 * Setter for Parseable instance
1114 * @param $parserInstance An instance of an Parseable
1117 public final function setParserInstance (Parseable $parserInstance) {
1118 $this->parserInstance = $parserInstance;
1122 * Getter for Parseable instance
1124 * @return $parserInstance An instance of an Parseable
1126 public final function getParserInstance () {
1127 return $this->parserInstance;
1131 * Setter for DatabaseWrapper instance
1133 * @param $wrapperInstance An instance of an DatabaseWrapper
1136 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1137 $this->wrapperInstance = $wrapperInstance;
1141 * Getter for DatabaseWrapper instance
1143 * @return $wrapperInstance An instance of an DatabaseWrapper
1145 public final function getWrapperInstance () {
1146 return $this->wrapperInstance;
1150 * Setter for socket resource
1152 * @param $socketResource A valid socket resource
1155 public final function setSocketResource ($socketResource) {
1156 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1157 $this->socketResource = $socketResource;
1161 * Getter for socket resource
1163 * @return $socketResource A valid socket resource
1165 public final function getSocketResource () {
1166 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1167 return $this->socketResource;
1171 * Setter for regular expression
1173 * @param $regularExpression A valid regular expression
1176 public final function setRegularExpression ($regularExpression) {
1177 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1178 $this->regularExpression = $regularExpression;
1182 * Getter for regular expression
1184 * @return $regularExpression A valid regular expression
1186 public final function getRegularExpression () {
1187 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1188 return $this->regularExpression;
1192 * Setter for helper instance
1194 * @param $helperInstance An instance of a helper class
1197 protected final function setHelperInstance (Helper $helperInstance) {
1198 $this->helperInstance = $helperInstance;
1202 * Getter for helper instance
1204 * @return $helperInstance An instance of a helper class
1206 public final function getHelperInstance () {
1207 return $this->helperInstance;
1211 * Setter for a Source instance
1213 * @param $sourceInstance An instance of a Source class
1216 protected final function setSourceInstance (Source $sourceInstance) {
1217 $this->sourceInstance = $sourceInstance;
1221 * Getter for a Source instance
1223 * @return $sourceInstance An instance of a Source class
1225 protected final function getSourceInstance () {
1226 return $this->sourceInstance;
1230 * Setter for a UrlSource instance
1232 * @param $sourceInstance An instance of a UrlSource class
1235 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1236 $this->urlSourceInstance = $urlSourceInstance;
1240 * Getter for a UrlSource instance
1242 * @return $urlSourceInstance An instance of a UrlSource class
1244 protected final function getUrlSourceInstance () {
1245 return $this->urlSourceInstance;
1249 * Getter for a InputStream instance
1251 * @param $inputStreamInstance The InputStream instance
1253 protected final function getInputStreamInstance () {
1254 return $this->inputStreamInstance;
1258 * Setter for a InputStream instance
1260 * @param $inputStreamInstance The InputStream instance
1263 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1264 $this->inputStreamInstance = $inputStreamInstance;
1268 * Getter for a OutputStream instance
1270 * @param $outputStreamInstance The OutputStream instance
1272 protected final function getOutputStreamInstance () {
1273 return $this->outputStreamInstance;
1277 * Setter for a OutputStream instance
1279 * @param $outputStreamInstance The OutputStream instance
1282 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1283 $this->outputStreamInstance = $outputStreamInstance;
1287 * Setter for handler instance
1289 * @param $handlerInstance An instance of a Handleable class
1292 protected final function setHandlerInstance (Handleable $handlerInstance) {
1293 $this->handlerInstance = $handlerInstance;
1297 * Getter for handler instance
1299 * @return $handlerInstance A Handleable instance
1301 protected final function getHandlerInstance () {
1302 return $this->handlerInstance;
1306 * Setter for visitor instance
1308 * @param $visitorInstance A Visitor instance
1311 protected final function setVisitorInstance (Visitor $visitorInstance) {
1312 $this->visitorInstance = $visitorInstance;
1316 * Getter for visitor instance
1318 * @return $visitorInstance A Visitor instance
1320 protected final function getVisitorInstance () {
1321 return $this->visitorInstance;
1325 * Setter for DHT instance
1327 * @param $dhtInstance A Distributable instance
1330 protected final function setDhtInstance (Distributable $dhtInstance) {
1331 $this->dhtInstance = $dhtInstance;
1335 * Getter for DHT instance
1337 * @return $dhtInstance A Distributable instance
1339 protected final function getDhtInstance () {
1340 return $this->dhtInstance;
1344 * Setter for raw package Data
1346 * @param $packageData Raw package Data
1349 public final function setPackageData (array $packageData) {
1350 $this->packageData = $packageData;
1354 * Getter for raw package Data
1356 * @return $packageData Raw package Data
1358 public function getPackageData () {
1359 return $this->packageData;
1364 * Setter for Iterator instance
1366 * @param $iteratorInstance An instance of an Iterator
1369 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1370 $this->iteratorInstance = $iteratorInstance;
1374 * Getter for Iterator instance
1376 * @return $iteratorInstance An instance of an Iterator
1378 public final function getIteratorInstance () {
1379 return $this->iteratorInstance;
1383 * Setter for FilePointer instance
1385 * @param $pointerInstance An instance of an FilePointer class
1388 protected final function setPointerInstance (FilePointer $pointerInstance) {
1389 $this->pointerInstance = $pointerInstance;
1393 * Getter for FilePointer instance
1395 * @return $pointerInstance An instance of an FilePointer class
1397 public final function getPointerInstance () {
1398 return $this->pointerInstance;
1402 * Unsets pointer instance which triggers a call of __destruct() if the
1403 * instance is still there. This is surely not fatal on already "closed"
1404 * file pointer instances.
1406 * I don't want to mess around with above setter by giving it a default
1407 * value NULL as setter should always explicitly only set (existing) object
1408 * instances and NULL is NULL.
1412 protected final function unsetPointerInstance () {
1413 // Simply it to NULL
1414 $this->pointerInstance = NULL;
1418 * Setter for Indexable instance
1420 * @param $indexInstance An instance of an Indexable class
1423 protected final function setIndexInstance (Indexable $indexInstance) {
1424 $this->indexInstance = $indexInstance;
1428 * Getter for Indexable instance
1430 * @return $indexInstance An instance of an Indexable class
1432 public final function getIndexInstance () {
1433 return $this->indexInstance;
1437 * Setter for Block instance
1439 * @param $blockInstance An instance of an Block class
1442 protected final function setBlockInstance (Block $blockInstance) {
1443 $this->blockInstance = $blockInstance;
1447 * Getter for Block instance
1449 * @return $blockInstance An instance of an Block class
1451 public final function getBlockInstance () {
1452 return $this->blockInstance;
1456 * Setter for Minable instance
1458 * @param $minableInstance A Minable instance
1461 protected final function setMinableInstance (Minable $minableInstance) {
1462 $this->minableInstance = $minableInstance;
1466 * Getter for minable instance
1468 * @return $minableInstance A Minable instance
1470 protected final function getMinableInstance () {
1471 return $this->minableInstance;
1475 * Setter for FrameworkDirectory instance
1477 * @param $directoryInstance A FrameworkDirectory instance
1480 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1481 $this->directoryInstance = $directoryInstance;
1485 * Getter for FrameworkDirectory instance
1487 * @return $directoryInstance A FrameworkDirectory instance
1489 protected final function getDirectoryInstance () {
1490 return $this->directoryInstance;
1494 * Getter for communicator instance
1496 * @return $communicatorInstance An instance of a Communicator class
1498 public final function getCommunicatorInstance () {
1499 return $this->communicatorInstance;
1503 * Setter for communicator instance
1505 * @param $communicatorInstance An instance of a Communicator class
1508 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1509 $this->communicatorInstance = $communicatorInstance;
1513 * Setter for state instance
1515 * @param $stateInstance A Stateable instance
1518 public final function setStateInstance (Stateable $stateInstance) {
1519 $this->stateInstance = $stateInstance;
1523 * Getter for state instance
1525 * @return $stateInstance A Stateable instance
1527 public final function getStateInstance () {
1528 return $this->stateInstance;
1532 * Setter for output instance
1534 * @param $outputInstance The debug output instance
1537 public final function setOutputInstance (OutputStreamer $outputInstance) {
1538 $this->outputInstance = $outputInstance;
1542 * Getter for output instance
1544 * @return $outputInstance The debug output instance
1546 public final function getOutputInstance () {
1547 return $this->outputInstance;
1551 * Setter for command name
1553 * @param $commandName Last validated command name
1556 protected final function setCommandName ($commandName) {
1557 $this->commandName = $commandName;
1561 * Getter for command name
1563 * @return $commandName Last validated command name
1565 protected final function getCommandName () {
1566 return $this->commandName;
1570 * Setter for controller name
1572 * @param $controllerName Last validated controller name
1575 protected final function setControllerName ($controllerName) {
1576 $this->controllerName = $controllerName;
1580 * Getter for controller name
1582 * @return $controllerName Last validated controller name
1584 protected final function getControllerName () {
1585 return $this->controllerName;
1589 * Checks whether an object equals this object. You should overwrite this
1590 * method to implement own equality checks
1592 * @param $objectInstance An instance of a FrameworkInterface object
1593 * @return $equals Whether both objects equals
1595 public function equals (FrameworkInterface $objectInstance) {
1598 $this->__toString() == $objectInstance->__toString()
1600 $this->hashCode() == $objectInstance->hashCode()
1603 // Return the result
1608 * Generates a generic hash code of this class. You should really overwrite
1609 * this method with your own hash code generator code. But keep KISS in mind.
1611 * @return $hashCode A generic hash code respresenting this whole class
1613 public function hashCode () {
1615 return crc32($this->__toString());
1619 * Formats computer generated price values into human-understandable formats
1620 * with thousand and decimal separators.
1622 * @param $value The in computer format value for a price
1623 * @param $currency The currency symbol (use HTML-valid characters!)
1624 * @param $decNum Number of decimals after commata
1625 * @return $price The for the current language formated price string
1626 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1627 * thousands separator
1630 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1631 // Are all required attriutes set?
1632 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1633 // Throw an exception
1634 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1638 $value = (float) $value;
1640 // Reformat the US number
1641 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1643 // Return as string...
1648 * Appends a trailing slash to a string
1650 * @param $str A string (maybe) without trailing slash
1651 * @return $str A string with an auto-appended trailing slash
1653 public final function addMissingTrailingSlash ($str) {
1654 // Is there a trailing slash?
1655 if (substr($str, -1, 1) != '/') {
1659 // Return string with trailing slash
1664 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1665 * application helper instance (ApplicationHelper by default).
1667 * @param $applicationInstance An application helper instance or
1668 * null if we shall use the default
1669 * @return $templateInstance The template engine instance
1670 * @throws NullPointerException If the discovered application
1671 * instance is still null
1673 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1674 // Is the application instance set?
1675 if (is_null($applicationInstance)) {
1676 // Get the current instance
1677 $applicationInstance = Registry::getRegistry()->getInstance('app');
1680 if (is_null($applicationInstance)) {
1681 // Thrown an exception
1682 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1686 // Initialize the template engine
1687 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1689 // Return the prepared instance
1690 return $templateInstance;
1694 * Debugs this instance by putting out it's full content
1696 * @param $message Optional message to show in debug output
1699 public final function debugInstance ($message = '') {
1700 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1701 restore_error_handler();
1706 // Is a message set?
1707 if (!empty($message)) {
1708 // Construct message
1709 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1712 // Generate the output
1713 $content .= sprintf('<pre>%s</pre>',
1716 print_r($this, true)
1722 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">%s debug output:</div><div class="debug_content">%s</div>Loaded includes: <div class="debug_include_list">%s</div>',
1723 $this->__toString(),
1725 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1730 * Replaces control characters with printable output
1732 * @param $str String with control characters
1733 * @return $str Replaced string
1735 protected function replaceControlCharacters ($str) {
1738 chr(13), '[r]', str_replace(
1739 chr(10), '[n]', str_replace(
1749 * Output a partial stub message for the caller method
1751 * @param $message An optional message to display
1754 protected function partialStub ($message = '') {
1755 // Get the backtrace
1756 $backtrace = debug_backtrace();
1758 // Generate the class::method string
1759 $methodName = 'UnknownClass->unknownMethod';
1760 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1761 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1764 // Construct the full message
1765 $stubMessage = sprintf('[%s]: Partial stub!',
1769 // Is the extra message given?
1770 if (!empty($message)) {
1771 // Then add it as well
1772 $stubMessage .= ' Message: ' . $message;
1775 // Debug instance is there?
1776 if (!is_null($this->getDebugInstance())) {
1777 // Output stub message
1778 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1781 trigger_error($stubMessage);
1787 * Outputs a debug backtrace and stops further script execution
1789 * @param $message An optional message to output
1790 * @param $doExit Whether exit the program (true is default)
1793 public function debugBackTrace ($message = '', $doExit = true) {
1794 // Sorry, there is no other way getting this nice backtrace
1795 if (!empty($message)) {
1797 printf('Message: %s<br />' . PHP_EOL, $message);
1801 debug_print_backtrace();
1805 if ($doExit === true) {
1811 * Creates an instance of a debugger instance
1813 * @param $className Name of the class (currently unsupported)
1814 * @param $lineNumber Line number where the call was made
1815 * @return $debugInstance An instance of a debugger class
1816 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1818 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1819 // Is the instance set?
1820 if (!Registry::getRegistry()->instanceExists('debug')) {
1821 // Init debug instance
1822 $debugInstance = NULL;
1826 // Get a debugger instance
1827 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1828 } catch (NullPointerException $e) {
1829 // Didn't work, no instance there
1830 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1833 // Empty string should be ignored and used for testing the middleware
1834 DebugMiddleware::getSelfInstance()->output('');
1836 // Set it in its own class. This will set it in the registry
1837 $debugInstance->setDebugInstance($debugInstance);
1839 // Get instance from registry
1840 $debugInstance = Registry::getRegistry()->getDebugInstance();
1844 return $debugInstance;
1848 * Simple output of a message with line-break
1850 * @param $message Message to output
1853 public function outputLine ($message) {
1855 print($message . PHP_EOL);
1859 * Outputs a debug message whether to debug instance (should be set!) or
1860 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1861 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1863 * @param $message Message we shall send out...
1864 * @param $doPrint Whether print or die here (default: print)
1865 * @paran $stripTags Whether to strip tags (default: false)
1868 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1869 // Set debug instance to NULL
1870 $debugInstance = NULL;
1874 // Get debug instance
1875 $debugInstance = $this->getDebugInstance();
1876 } catch (NullPointerException $e) {
1877 // The debug instance is not set (yet)
1880 // Is the debug instance there?
1881 if (is_object($debugInstance)) {
1882 // Use debug output handler
1883 $debugInstance->output($message, $stripTags);
1885 if ($doPrint === false) {
1886 // Die here if not printed
1890 // Are debug times enabled?
1891 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1893 $message = $this->getPrintableExecutionTime() . $message;
1897 if ($doPrint === true) {
1899 $this->outputLine($message);
1908 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1910 * @param $str The string, what ever it is needs to be converted
1911 * @return $className Generated class name
1913 public static final function convertToClassName ($str) {
1917 // Convert all dashes in underscores
1918 $str = self::convertDashesToUnderscores($str);
1920 // Now use that underscores to get classname parts for hungarian style
1921 foreach (explode('_', $str) as $strPart) {
1922 // Make the class name part lower case and first upper case
1923 $className .= ucfirst(strtolower($strPart));
1926 // Return class name
1931 * Converts dashes to underscores, e.g. useable for configuration entries
1933 * @param $str The string with maybe dashes inside
1934 * @return $str The converted string with no dashed, but underscores
1936 public static final function convertDashesToUnderscores ($str) {
1938 $str = str_replace('-', '_', $str);
1940 // Return converted string
1945 * Marks up the code by adding e.g. line numbers
1947 * @param $phpCode Unmarked PHP code
1948 * @return $markedCode Marked PHP code
1950 public function markupCode ($phpCode) {
1955 $errorArray = error_get_last();
1957 // Init the code with error message
1958 if (is_array($errorArray)) {
1960 $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>',
1961 basename($errorArray['file']),
1962 $errorArray['line'],
1963 $errorArray['message'],
1968 // Add line number to the code
1969 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1971 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1973 htmlentities($code, ENT_QUOTES)
1982 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1983 * beatiful for web-based front-ends. If null is given a message id
1984 * null_timestamp will be resolved and returned.
1986 * @param $timestamp Timestamp to prepare (filter) for display
1987 * @return $readable A readable timestamp
1989 public function doFilterFormatTimestamp ($timestamp) {
1990 // Default value to return
1993 // Is the timestamp null?
1994 if (is_null($timestamp)) {
1995 // Get a message string
1996 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1998 switch ($this->getLanguageInstance()->getLanguageCode()) {
1999 case 'de': // German format is a bit different to default
2000 // Split the GMT stamp up
2001 $dateTime = explode(' ', $timestamp );
2002 $dateArray = explode('-', $dateTime[0]);
2003 $timeArray = explode(':', $dateTime[1]);
2005 // Construct the timestamp
2006 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2016 default: // Default is pass-through
2017 $readable = $timestamp;
2027 * Filter a given number into a localized number
2029 * @param $value The raw value from e.g. database
2030 * @return $localized Localized value
2032 public function doFilterFormatNumber ($value) {
2033 // Generate it from config and localize dependencies
2034 switch ($this->getLanguageInstance()->getLanguageCode()) {
2035 case 'de': // German format is a bit different to default
2036 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2039 default: // US, etc.
2040 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2049 * "Getter" for databse entry
2051 * @return $entry An array with database entries
2052 * @throws NullPointerException If the database result is not found
2053 * @throws InvalidDatabaseResultException If the database result is invalid
2055 protected final function getDatabaseEntry () {
2056 // Is there an instance?
2057 if (!$this->getResultInstance() instanceof SearchableResult) {
2058 // Throw an exception here
2059 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2063 $this->getResultInstance()->rewind();
2065 // Do we have an entry?
2066 if ($this->getResultInstance()->valid() === false) {
2067 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2068 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2072 $this->getResultInstance()->next();
2075 $entry = $this->getResultInstance()->current();
2082 * Getter for field name
2084 * @param $fieldName Field name which we shall get
2085 * @return $fieldValue Field value from the user
2086 * @throws NullPointerException If the result instance is null
2088 public final function getField ($fieldName) {
2089 // Default field value
2092 // Get result instance
2093 $resultInstance = $this->getResultInstance();
2095 // Is this instance null?
2096 if (is_null($resultInstance)) {
2097 // Then the user instance is no longer valid (expired cookies?)
2098 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2101 // Get current array
2102 $fieldArray = $resultInstance->current();
2103 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2105 // Convert dashes to underscore
2106 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2108 // Does the field exist?
2109 if ($this->isFieldSet($fieldName)) {
2111 $fieldValue = $fieldArray[$fieldName2];
2112 } elseif (defined('DEVELOPER')) {
2113 // Missing field entry, may require debugging
2114 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2116 // Missing field entry, may require debugging
2117 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2125 * Checks if given field is set
2127 * @param $fieldName Field name to check
2128 * @return $isSet Whether the given field name is set
2129 * @throws NullPointerException If the result instance is null
2131 public function isFieldSet ($fieldName) {
2132 // Get result instance
2133 $resultInstance = $this->getResultInstance();
2135 // Is this instance null?
2136 if (is_null($resultInstance)) {
2137 // Then the user instance is no longer valid (expired cookies?)
2138 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2141 // Get current array
2142 $fieldArray = $resultInstance->current();
2143 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2145 // Convert dashes to underscore
2146 $fieldName = self::convertDashesToUnderscores($fieldName);
2149 $isSet = isset($fieldArray[$fieldName]);
2156 * Flushs all pending updates to the database layer
2160 public function flushPendingUpdates () {
2161 // Get result instance
2162 $resultInstance = $this->getResultInstance();
2164 // Do we have data to update?
2165 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2166 // Get wrapper class name config entry
2167 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2169 // Create object instance
2170 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2172 // Yes, then send the whole result to the database layer
2173 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2178 * Outputs a deprecation warning to the developer.
2180 * @param $message The message we shall output to the developer
2182 * @todo Write a logging mechanism for productive mode
2184 public function deprecationWarning ($message) {
2185 // Is developer mode active?
2186 if (defined('DEVELOPER')) {
2187 // Debug instance is there?
2188 if (!is_null($this->getDebugInstance())) {
2189 // Output stub message
2190 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2193 trigger_error($message . "<br />\n");
2197 // @TODO Finish this part!
2198 $this->partialStub('Developer mode inactive. Message:' . $message);
2203 * Checks whether the given PHP extension is loaded
2205 * @param $phpExtension The PHP extension we shall check
2206 * @return $isLoaded Whether the PHP extension is loaded
2208 public final function isPhpExtensionLoaded ($phpExtension) {
2210 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2217 * "Getter" as a time() replacement but with milliseconds. You should use this
2218 * method instead of the encapsulated getimeofday() function.
2220 * @return $milliTime Timestamp with milliseconds
2222 public function getMilliTime () {
2223 // Get the time of day as float
2224 $milliTime = gettimeofday(true);
2231 * Idles (sleeps) for given milliseconds
2233 * @return $hasSlept Whether it goes fine
2235 public function idle ($milliSeconds) {
2236 // Sleep is fine by default
2239 // Idle so long with found function
2240 if (function_exists('time_sleep_until')) {
2241 // Get current time and add idle time
2242 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2244 // New PHP 5.1.0 function found, ignore errors
2245 $hasSlept = @time_sleep_until($sleepUntil);
2248 * My Sun station doesn't have that function even with latest PHP
2251 usleep($milliSeconds * 1000);
2258 * Converts a hexadecimal string, even with negative sign as first string to
2259 * a decimal number using BC functions.
2261 * This work is based on comment #86673 on php.net documentation page at:
2262 * <http://de.php.net/manual/en/function.dechex.php#86673>
2264 * @param $hex Hexadecimal string
2265 * @return $dec Decimal number
2267 protected function hex2dec ($hex) {
2268 // Convert to all lower-case
2269 $hex = strtolower($hex);
2271 // Detect sign (negative/positive numbers)
2273 if (substr($hex, 0, 1) == '-') {
2275 $hex = substr($hex, 1);
2278 // Decode the hexadecimal string into a decimal number
2280 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2281 $factor = self::$hexdec[substr($hex, $i, 1)];
2282 $dec = bcadd($dec, bcmul($factor, $e));
2285 // Return the decimal number
2286 return $sign . $dec;
2290 * Converts even very large decimal numbers, also signed, to a hexadecimal
2293 * This work is based on comment #97756 on php.net documentation page at:
2294 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2296 * @param $dec Decimal number, even with negative sign
2297 * @param $maxLength Optional maximum length of the string
2298 * @return $hex Hexadecimal string
2300 protected function dec2hex ($dec, $maxLength = 0) {
2301 // maxLength can be zero or devideable by 2
2302 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2304 // Detect sign (negative/positive numbers)
2311 // Encode the decimal number into a hexadecimal string
2314 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2316 } while ($dec >= 1);
2319 * Leading zeros are required for hex-decimal "numbers". In some
2320 * situations more leading zeros are wanted, so check for both
2323 if ($maxLength > 0) {
2324 // Prepend more zeros
2325 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2326 } elseif ((strlen($hex) % 2) != 0) {
2327 // Only make string's length dividable by 2
2331 // Return the hexadecimal string
2332 return $sign . $hex;
2336 * Converts a ASCII string (0 to 255) into a decimal number.
2338 * @param $asc The ASCII string to be converted
2339 * @return $dec Decimal number
2341 protected function asc2dec ($asc) {
2342 // Convert it into a hexadecimal number
2343 $hex = bin2hex($asc);
2345 // And back into a decimal number
2346 $dec = $this->hex2dec($hex);
2353 * Converts a decimal number into an ASCII string.
2355 * @param $dec Decimal number
2356 * @return $asc An ASCII string
2358 protected function dec2asc ($dec) {
2359 // First convert the number into a hexadecimal string
2360 $hex = $this->dec2hex($dec);
2362 // Then convert it into the ASCII string
2363 $asc = $this->hex2asc($hex);
2370 * Converts a hexadecimal number into an ASCII string. Negative numbers
2373 * @param $hex Hexadecimal string
2374 * @return $asc An ASCII string
2376 protected function hex2asc ($hex) {
2377 // Check for length, it must be devideable by 2
2378 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2379 assert((strlen($hex) % 2) == 0);
2383 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2384 // Get the decimal number of the chunk
2385 $part = hexdec(substr($hex, $idx, 2));
2387 // Add it to the final string
2391 // Return the final string
2396 * Checks whether the given encoded data was encoded with Base64
2398 * @param $encodedData Encoded data we shall check
2399 * @return $isBase64 Whether the encoded data is Base64
2401 protected function isBase64Encoded ($encodedData) {
2403 $isBase64 = (@base64_decode($encodedData, true) !== false);
2410 * Gets a cache key from Criteria instance
2412 * @param $criteriaInstance An instance of a Criteria class
2413 * @param $onlyKeys Only use these keys for a cache key
2414 * @return $cacheKey A cache key suitable for lookup/storage purposes
2416 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2418 $cacheKey = sprintf('%s@%s',
2419 $this->__toString(),
2420 $criteriaInstance->getCacheKey($onlyKeys)
2424 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2429 * Getter for startup time in miliseconds
2431 * @return $startupTime Startup time in miliseconds
2433 protected function getStartupTime () {
2434 return self::$startupTime;
2438 * "Getter" for a printable currently execution time in nice braces
2440 * @return $executionTime Current execution time in nice braces
2442 protected function getPrintableExecutionTime () {
2443 // Caculate the execution time
2444 $executionTime = microtime(true) - $this->getStartupTime();
2446 // Pack it in nice braces
2447 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2450 return $executionTime;
2454 * Hashes a given string with a simple but stronger hash function (no salt)
2455 * and hex-encode it.
2457 * @param $str The string to be hashed
2458 * @return $hash The hash from string $str
2460 public static final function hash ($str) {
2461 // Hash given string with (better secure) hasher
2462 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2469 * "Getter" for length of hash() output. This will be "cached" to speed up
2472 * @return $length Length of hash() output
2474 public static final function getHashLength () {
2476 if (is_null(self::$hashLength)) {
2477 // No, then hash a string and save its length.
2478 self::$hashLength = strlen(self::hash('abc123'));
2482 return self::$hashLength;
2486 * Checks whether the given number is really a number (only chars 0-9).
2488 * @param $num A string consisting only chars between 0 and 9
2489 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2490 * @param $assertMismatch Whether to assert mismatches
2491 * @return $ret The (hopefully) secured numbered value
2493 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2494 // Filter all numbers out
2495 $ret = preg_replace('/[^0123456789]/', '', $num);
2498 if ($castValue === true) {
2499 // Cast to biggest numeric type
2500 $ret = (double) $ret;
2503 // Assert only if requested
2504 if ($assertMismatch === true) {
2505 // Has the whole value changed?
2506 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2514 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2516 * @param $num A string consisting only chars between 0 and 9
2517 * @param $assertMismatch Whether to assert mismatches
2518 * @return $ret The (hopefully) secured hext-numbered value
2520 public function hexval ($num, $assertMismatch = false) {
2521 // Filter all numbers out
2522 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2524 // Assert only if requested
2525 if ($assertMismatch === true) {
2526 // Has the whole value changed?
2527 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2535 * Determines if an element is set in the generic array
2537 * @param $keyGroup Main group for the key
2538 * @param $subGroup Sub group for the key
2539 * @param $key Key to check
2540 * @param $element Element to check
2541 * @return $isset Whether the given key is set
2543 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2545 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2548 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2554 * Determines if a key is set in the generic array
2556 * @param $keyGroup Main group for the key
2557 * @param $subGroup Sub group for the key
2558 * @param $key Key to check
2559 * @return $isset Whether the given key is set
2561 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2563 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2566 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2574 * Determines if a group is set in the generic array
2576 * @param $keyGroup Main group
2577 * @param $subGroup Sub group
2578 * @return $isset Whether the given group is set
2580 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2582 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2585 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2592 * Getter for sub key group
2594 * @param $keyGroup Main key group
2595 * @param $subGroup Sub key group
2596 * @return $array An array with all array elements
2598 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2600 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2601 // No, then abort here
2602 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2607 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2610 return $this->genericArray[$keyGroup][$subGroup];
2614 * Unsets a given key in generic array
2616 * @param $keyGroup Main group for the key
2617 * @param $subGroup Sub group for the key
2618 * @param $key Key to unset
2621 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2623 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2626 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2630 * Unsets a given element in generic array
2632 * @param $keyGroup Main group for the key
2633 * @param $subGroup Sub group for the key
2634 * @param $key Key to unset
2635 * @param $element Element to unset
2638 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2640 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2643 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2647 * Append a string to a given generic array key
2649 * @param $keyGroup Main group for the key
2650 * @param $subGroup Sub group for the key
2651 * @param $key Key to unset
2652 * @param $value Value to add/append
2655 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2657 //* 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);
2659 // Is it already there?
2660 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2662 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2665 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2670 * Append a string to a given generic array element
2672 * @param $keyGroup Main group for the key
2673 * @param $subGroup Sub group for the key
2674 * @param $key Key to unset
2675 * @param $element Element to check
2676 * @param $value Value to add/append
2679 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2681 //* 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);
2683 // Is it already there?
2684 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2686 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2689 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2694 * Sets a string in a given generic array element
2696 * @param $keyGroup Main group for the key
2697 * @param $subGroup Sub group for the key
2698 * @param $key Key to unset
2699 * @param $element Element to check
2700 * @param $value Value to add/append
2703 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2705 //* 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);
2708 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2712 * Initializes given generic array group
2714 * @param $keyGroup Main group for the key
2715 * @param $subGroup Sub group for the key
2716 * @param $key Key to use
2717 * @param $forceInit Optionally force initialization
2720 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2722 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2724 // Is it already set?
2725 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2726 // Already initialized
2727 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2732 $this->genericArray[$keyGroup][$subGroup] = array();
2736 * Initializes given generic array key
2738 * @param $keyGroup Main group for the key
2739 * @param $subGroup Sub group for the key
2740 * @param $key Key to use
2741 * @param $forceInit Optionally force initialization
2744 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2746 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2748 // Is it already set?
2749 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2750 // Already initialized
2751 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2756 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2760 * Initializes given generic array element
2762 * @param $keyGroup Main group for the key
2763 * @param $subGroup Sub group for the key
2764 * @param $key Key to use
2765 * @param $element Element to use
2766 * @param $forceInit Optionally force initialization
2769 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2771 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2773 // Is it already set?
2774 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2775 // Already initialized
2776 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2781 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2785 * Pushes an element to a generic key
2787 * @param $keyGroup Main group for the key
2788 * @param $subGroup Sub group for the key
2789 * @param $key Key to use
2790 * @param $value Value to add/append
2791 * @return $count Number of array elements
2793 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2795 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2798 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2800 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2804 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2807 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2808 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2813 * Pushes an element to a generic array element
2815 * @param $keyGroup Main group for the key
2816 * @param $subGroup Sub group for the key
2817 * @param $key Key to use
2818 * @param $element Element to check
2819 * @param $value Value to add/append
2820 * @return $count Number of array elements
2822 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2824 //* 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));
2827 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2829 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2833 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2836 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2837 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2842 * Pops an element from a generic group
2844 * @param $keyGroup Main group for the key
2845 * @param $subGroup Sub group for the key
2846 * @param $key Key to unset
2847 * @return $value Last "popped" value
2849 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2851 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2854 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2856 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2861 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2864 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2865 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2870 * Shifts an element from a generic group
2872 * @param $keyGroup Main group for the key
2873 * @param $subGroup Sub group for the key
2874 * @param $key Key to unset
2875 * @return $value Last "popped" value
2877 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2879 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2882 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2884 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2889 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2892 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2893 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2898 * Count generic array group
2900 * @param $keyGroup Main group for the key
2901 * @return $count Count of given group
2903 protected final function countGenericArray ($keyGroup) {
2905 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2908 if (!isset($this->genericArray[$keyGroup])) {
2910 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2915 $count = count($this->genericArray[$keyGroup]);
2918 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2925 * Count generic array sub group
2927 * @param $keyGroup Main group for the key
2928 * @param $subGroup Sub group for the key
2929 * @return $count Count of given group
2931 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2933 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2936 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2938 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2943 $count = count($this->genericArray[$keyGroup][$subGroup]);
2946 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2953 * Count generic array elements
2955 * @param $keyGroup Main group for the key
2956 * @param $subGroup Sub group for the key
2957 * @para $key Key to count
2958 * @return $count Count of given key
2960 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2962 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2965 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2967 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2969 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2971 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2976 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2979 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2986 * Getter for whole generic group array
2988 * @param $keyGroup Key group to get
2989 * @return $array Whole generic array group
2991 protected final function getGenericArray ($keyGroup) {
2993 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2996 if (!isset($this->genericArray[$keyGroup])) {
2998 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3003 return $this->genericArray[$keyGroup];
3007 * Setter for generic array key
3009 * @param $keyGroup Key group to get
3010 * @param $subGroup Sub group for the key
3011 * @param $key Key to unset
3012 * @param $value Mixed value from generic array element
3015 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3017 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3020 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3024 * Getter for generic array key
3026 * @param $keyGroup Key group to get
3027 * @param $subGroup Sub group for the key
3028 * @param $key Key to unset
3029 * @return $value Mixed value from generic array element
3031 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3033 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3036 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3038 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3043 return $this->genericArray[$keyGroup][$subGroup][$key];
3047 * Sets a value in given generic array key/element
3049 * @param $keyGroup Main group for the key
3050 * @param $subGroup Sub group for the key
3051 * @param $key Key to set
3052 * @param $element Element to set
3053 * @param $value Value to set
3056 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3058 //* 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));
3061 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3065 * Getter for generic array element
3067 * @param $keyGroup Key group to get
3068 * @param $subGroup Sub group for the key
3069 * @param $key Key to look for
3070 * @param $element Element to look for
3071 * @return $value Mixed value from generic array element
3073 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3075 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3078 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3080 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3085 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3089 * Checks if a given sub group is valid (array)
3091 * @param $keyGroup Key group to get
3092 * @param $subGroup Sub group for the key
3093 * @return $isValid Whether given sub group is valid
3095 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3097 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3100 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3107 * Checks if a given key is valid (array)
3109 * @param $keyGroup Key group to get
3110 * @param $subGroup Sub group for the key
3111 * @param $key Key to check
3112 * @return $isValid Whether given sub group is valid
3114 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3116 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3119 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3126 * Initializes the web output instance
3130 protected function initWebOutputInstance () {
3131 // Get application instance
3132 $applicationInstance = Registry::getRegistry()->getInstance('app');
3134 // Init web output instance
3135 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3138 $this->setWebOutputInstance($outputInstance);
3142 * Translates boolean true to 'Y' and false to 'N'
3144 * @param $boolean Boolean value
3145 * @return $translated Translated boolean value
3147 public static final function translateBooleanToYesNo ($boolean) {
3148 // Make sure it is really boolean
3149 assert(is_bool($boolean));
3152 $translated = ($boolean === true) ? 'Y' : 'N';
3154 // ... and return it
3159 * Encodes raw data (almost any type) by "serializing" it and then pack it
3160 * into a "binary format".
3162 * @param $rawData Raw data (almost any type)
3163 * @return $encoded Encoded data
3165 protected function encodeData ($rawData) {
3166 // Make sure no objects or resources pass through
3167 assert(!is_object($rawData));
3168 assert(!is_resource($rawData));
3170 // First "serialize" it (json_encode() is faster than serialize())
3171 $encoded = $this->packString(json_encode($rawData));
3178 * Pack a string into a "binary format". Please execuse me that this is
3179 * widely undocumented. :-(
3181 * @param $str Unpacked string
3182 * @return $packed Packed string
3183 * @todo Improve documentation
3185 protected function packString ($str) {
3187 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3189 // First compress the string (gzcompress is okay)
3190 $str = gzcompress($str);
3195 // And start the "encoding" loop
3196 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3198 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3199 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3201 if (($idx + $i) <= strlen($str)) {
3202 $ord = ord(substr($str, ($idx + $i), 1));
3204 $add = $ord * pow(256, $factor);
3208 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3212 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3213 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3215 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3216 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3222 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3227 * Creates a full-qualified file name (FQFN) for given file name by adding
3228 * a configured temporary file path to it.
3230 * @param $fileName Name for temporary file
3231 * @return $fqfn Full-qualified file name
3232 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3233 * @throws FileIoException If the file cannot be written
3235 protected static function createTempPathForFile ($fileName) {
3237 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3239 // Is the path writeable?
3240 if (!is_writable($basePath)) {
3241 // Path is write-protected
3242 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3246 $fqfn = $basePath . '/' . $fileName;
3249 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3251 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3259 * "Getter" for a printable state name
3261 * @return $stateName Name of the node's state in a printable format
3263 public final function getPrintableState () {
3264 // Default is 'null'
3265 $stateName = 'null';
3267 // Get the state instance
3268 $stateInstance = $this->getStateInstance();
3270 // Is it an instance of Stateable?
3271 if ($stateInstance instanceof Stateable) {
3272 // Then use that state name
3273 $stateName = $stateInstance->getStateName();