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 HandleableProtocol instance
174 private $protocolInstance = NULL;
177 * A database wrapper instance
179 private $databaseInstance = NULL;
182 * A helper instance for the form
184 private $helperInstance = NULL;
187 * An instance of a Source class
189 private $sourceInstance = NULL;
192 * An instance of a UrlSource class
194 private $urlSourceInstance = NULL;
197 * An instance of a InputStream class
199 private $inputStreamInstance = NULL;
202 * An instance of a OutputStream class
204 private $outputStreamInstance = NULL;
209 private $handlerInstance = NULL;
212 * Visitor handler instance
214 private $visitorInstance = NULL;
219 private $dhtInstance = NULL;
222 * An instance of a database wrapper class
224 private $wrapperInstance = NULL;
227 * An instance of a file I/O pointer class (not handler)
229 private $pointerInstance = NULL;
232 * An instance of an Indexable class
234 private $indexInstance = NULL;
237 * An instance of a Block class
239 private $blockInstance = NULL;
244 private $minableInstance = NULL;
247 * A FrameworkDirectory instance
249 private $directoryInstance = NULL;
252 * An instance of a communicator
254 private $communicatorInstance = NULL;
257 * The concrete output instance
259 private $outputInstance = NULL;
264 private $stateInstance = NULL;
267 * Thousands separator
269 private $thousands = '.'; // German
274 private $decimals = ','; // German
279 private $socketResource = false;
282 * Regular expression to use for validation
284 private $regularExpression = '';
289 private $packageData = array();
294 private $genericArray = array();
299 private $commandName = '';
304 private $controllerName = '';
307 * Name of used protocol
309 private $protocolName = 'invalid';
312 * Array with bitmasks and such for pack/unpack methods to support both
313 * 32-bit and 64-bit systems
315 private $packingData = array(
318 'left' => 0xffff0000,
319 'right' => 0x0000ffff,
325 'left' => 0xffffffff00000000,
326 'right' => 0x00000000ffffffff,
333 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
335 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
337 private $archArrayElement = false;
339 /***********************
340 * Exception codes.... *
341 ***********************/
343 // @todo Try to clean these constants up
344 const EXCEPTION_IS_NULL_POINTER = 0x001;
345 const EXCEPTION_IS_NO_OBJECT = 0x002;
346 const EXCEPTION_IS_NO_ARRAY = 0x003;
347 const EXCEPTION_MISSING_METHOD = 0x004;
348 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
349 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
350 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
351 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
352 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
353 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
354 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
355 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
356 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
357 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
358 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
359 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
360 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
361 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
362 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
363 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
364 const EXCEPTION_PATH_NOT_FOUND = 0x015;
365 const EXCEPTION_INVALID_PATH_NAME = 0x016;
366 const EXCEPTION_READ_PROTECED_PATH = 0x017;
367 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
368 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
369 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
370 const EXCEPTION_INVALID_RESOURCE = 0x01b;
371 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
372 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
373 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
374 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
375 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
376 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
377 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
378 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
379 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
380 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
381 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
382 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
383 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
384 const EXCEPTION_INVALID_STRING = 0x029;
385 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
386 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
387 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
388 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
389 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
390 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
391 const EXCEPTION_MISSING_ELEMENT = 0x030;
392 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
393 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
394 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
395 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
396 const EXCEPTION_FATAL_ERROR = 0x035;
397 const EXCEPTION_FILE_NOT_FOUND = 0x036;
398 const EXCEPTION_ASSERTION_FAILED = 0x037;
399 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
400 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
401 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
402 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
403 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
404 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
405 const EXCEPTION_INVALID_SOCKET = 0x03e;
408 * Hexadecimal->Decimal translation array
410 private static $hexdec = array(
430 * Decimal->hexadecimal translation array
432 private static $dechex = array(
452 * Startup time in miliseconds
454 private static $startupTime = 0;
457 * Protected super constructor
459 * @param $className Name of the class
462 protected function __construct ($className) {
464 $this->setRealClass($className);
466 // Set configuration instance if no registry ...
467 if (!$this instanceof Register) {
468 // ... because registries doesn't need to be configured
469 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
472 // Is the startup time set? (0 cannot be true anymore)
473 if (self::$startupTime == 0) {
475 self::$startupTime = microtime(true);
479 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
483 * Destructor for all classes. You should not call this method on your own.
487 public function __destruct () {
488 // Flush any updated entries to the database
489 $this->flushPendingUpdates();
491 // Is this object already destroyed?
492 if ($this->__toString() != 'DestructedObject') {
493 // Destroy all informations about this class but keep some text about it alive
494 $this->setRealClass('DestructedObject');
495 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
496 // Already destructed object
497 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
502 // Do not call this twice
503 trigger_error(__METHOD__ . ': Called twice.');
509 * The __call() method where all non-implemented methods end up
511 * @param $methodName Name of the missing method
512 * @args $args Arguments passed to the method
515 public final function __call ($methodName, $args) {
516 return self::__callStatic($methodName, $args);
520 * The __callStatic() method where all non-implemented static methods end up
522 * @param $methodName Name of the missing method
523 * @args $args Arguments passed to the method
526 public static final function __callStatic ($methodName, $args) {
528 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
530 // Init argument string
533 // Is it NULL, empty or an array?
534 if (is_null($args)) {
536 $argsString = 'NULL';
537 } elseif (is_array($args)) {
541 // Some arguments are there
542 foreach ($args as $arg) {
543 // Add data about the argument
544 $argsString .= gettype($arg) . ':';
547 // Found a NULL argument
548 $argsString .= 'NULL';
549 } elseif (is_string($arg)) {
550 // Add length for strings
551 $argsString .= strlen($arg);
552 } elseif ((is_int($arg)) || (is_float($arg))) {
555 } elseif (is_array($arg)) {
556 // .. or size if array
557 $argsString .= count($arg);
558 } elseif (is_object($arg)) {
560 $reflection = new ReflectionClass($arg);
562 // Is an other object, maybe no __toString() available
563 $argsString .= $reflection->getName();
564 } elseif ($arg === true) {
565 // ... is boolean 'true'
566 $argsString .= 'true';
567 } elseif ($arg === false) {
568 // ... is boolean 'false'
569 $argsString .= 'false';
572 // Comma for next one
577 if (substr($argsString, -2, 1) == ',') {
578 $argsString = substr($argsString, 0, -2);
584 // Invalid arguments!
585 $argsString = '!INVALID:' . gettype($args) . '!';
588 // Output stub message
589 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
590 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
600 * Getter for $realClass
602 * @return $realClass The name of the real class (not BaseFrameworkSystem)
604 public function __toString () {
605 return $this->realClass;
609 * Magic method to catch setting of missing but set class fields/attributes
611 * @param $name Name of the field/attribute
612 * @param $value Value to store
615 public final function __set ($name, $value) {
616 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
619 print_r($value, true)
624 * Magic method to catch getting of missing fields/attributes
626 * @param $name Name of the field/attribute
629 public final function __get ($name) {
630 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
636 * Magic method to catch unsetting of missing fields/attributes
638 * @param $name Name of the field/attribute
641 public final function __unset ($name) {
642 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
648 * Magic method to catch object serialization
650 * @return $unsupported Unsupported method
651 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
653 public final function __sleep () {
654 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
658 * Magic method to catch object deserialization
660 * @return $unsupported Unsupported method
661 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
663 public final function __wakeup () {
664 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
668 * Magic method to catch calls when an object instance is called
670 * @return $unsupported Unsupported method
671 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
673 public final function __invoke () {
674 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
678 * Setter for the real class name
680 * @param $realClass Class name (string)
683 public final function setRealClass ($realClass) {
685 $this->realClass = (string) $realClass;
689 * Setter for database result instance
691 * @param $resultInstance An instance of a database result class
693 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
695 protected final function setResultInstance (SearchableResult $resultInstance) {
696 $this->resultInstance = $resultInstance;
700 * Getter for database result instance
702 * @return $resultInstance An instance of a database result class
704 public final function getResultInstance () {
705 return $this->resultInstance;
709 * Setter for template engine instances
711 * @param $templateInstance An instance of a template engine class
714 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
715 $this->templateInstance = $templateInstance;
719 * Getter for template engine instances
721 * @return $templateInstance An instance of a template engine class
723 protected final function getTemplateInstance () {
724 return $this->templateInstance;
728 * Setter for search instance
730 * @param $searchInstance Searchable criteria instance
733 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
734 $this->searchInstance = $searchInstance;
738 * Getter for search instance
740 * @return $searchInstance Searchable criteria instance
742 public final function getSearchInstance () {
743 return $this->searchInstance;
747 * Setter for update instance
749 * @param $updateInstance An instance of a LocalUpdateCriteria clase
752 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
753 $this->updateInstance = $updateInstance;
757 * Getter for update instance
759 * @return $updateInstance Updateable criteria instance
761 public final function getUpdateInstance () {
762 return $this->updateInstance;
766 * Setter for resolver instance
768 * @param $resolverInstance Instance of a command resolver class
771 public final function setResolverInstance (Resolver $resolverInstance) {
772 $this->resolverInstance = $resolverInstance;
776 * Getter for resolver instance
778 * @return $resolverInstance Instance of a command resolver class
780 public final function getResolverInstance () {
781 return $this->resolverInstance;
785 * Setter for language instance
787 * @param $configInstance The configuration instance which shall
788 * be FrameworkConfiguration
791 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
792 Registry::getRegistry()->addInstance('config', $configInstance);
796 * Getter for configuration instance
798 * @return $configInstance Configuration instance
800 public final function getConfigInstance () {
801 $configInstance = Registry::getRegistry()->getInstance('config');
802 return $configInstance;
806 * Setter for debug instance
808 * @param $debugInstance The instance for debug output class
811 public final function setDebugInstance (DebugMiddleware $debugInstance) {
812 Registry::getRegistry()->addInstance('debug', $debugInstance);
816 * Getter for debug instance
818 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
820 public final function getDebugInstance () {
821 // Get debug instance
822 $debugInstance = Registry::getRegistry()->getInstance('debug');
825 return $debugInstance;
829 * Setter for web output instance
831 * @param $webInstance The instance for web output class
834 public final function setWebOutputInstance (OutputStreamer $webInstance) {
835 Registry::getRegistry()->addInstance('web_output', $webInstance);
839 * Getter for web output instance
841 * @return $webOutputInstance - Instance to class WebOutput
843 public final function getWebOutputInstance () {
844 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
845 return $webOutputInstance;
849 * Setter for database instance
851 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
854 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
855 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
859 * Getter for database layer
861 * @return $databaseInstance The database layer instance
863 public final function getDatabaseInstance () {
865 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
868 return $databaseInstance;
872 * Setter for compressor channel
874 * @param $compressorInstance An instance of CompressorChannel
877 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
878 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
882 * Getter for compressor channel
884 * @return $compressorInstance The compressor channel
886 public final function getCompressorChannel () {
887 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
888 return $compressorInstance;
892 * Protected getter for a manageable application helper class
894 * @return $applicationInstance An instance of a manageable application helper class
896 protected final function getApplicationInstance () {
897 $applicationInstance = Registry::getRegistry()->getInstance('app');
898 return $applicationInstance;
902 * Setter for a manageable application helper class
904 * @param $applicationInstance An instance of a manageable application helper class
907 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
908 Registry::getRegistry()->addInstance('application', $applicationInstance);
912 * Private getter for language instance
914 * @return $langInstance An instance to the language sub-system
916 protected final function getLanguageInstance () {
917 $langInstance = Registry::getRegistry()->getInstance('language');
918 return $langInstance;
922 * Setter for language instance
924 * @param $langInstance An instance to the language sub-system
926 * @see LanguageSystem
928 public final function setLanguageInstance (ManageableLanguage $langInstance) {
929 Registry::getRegistry()->addInstance('language', $langInstance);
933 * Private getter for file IO instance
935 * @return $fileIoInstance An instance to the file I/O sub-system
937 protected final function getFileIoInstance () {
938 return $this->fileIoInstance;
942 * Setter for file I/O instance
944 * @param $fileIoInstance An instance to the file I/O sub-system
947 public final function setFileIoInstance (IoHandler $fileIoInstance) {
948 $this->fileIoInstance = $fileIoInstance;
952 * Protected setter for user instance
954 * @param $userInstance An instance of a user class
957 protected final function setUserInstance (ManageableAccount $userInstance) {
958 $this->userInstance = $userInstance;
962 * Getter for user instance
964 * @return $userInstance An instance of a user class
966 public final function getUserInstance () {
967 return $this->userInstance;
971 * Setter for controller instance (this surely breaks a bit the MVC patterm)
973 * @param $controllerInstance An instance of the controller
976 public final function setControllerInstance (Controller $controllerInstance) {
977 $this->controllerInstance = $controllerInstance;
981 * Getter for controller instance (this surely breaks a bit the MVC patterm)
983 * @return $controllerInstance An instance of the controller
985 public final function getControllerInstance () {
986 return $this->controllerInstance;
990 * Setter for RNG instance
992 * @param $rngInstance An instance of a random number generator (RNG)
995 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
996 $this->rngInstance = $rngInstance;
1000 * Getter for RNG instance
1002 * @return $rngInstance An instance of a random number generator (RNG)
1004 public final function getRngInstance () {
1005 return $this->rngInstance;
1009 * Setter for Cryptable instance
1011 * @param $cryptoInstance An instance of a Cryptable class
1014 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1015 $this->cryptoInstance = $cryptoInstance;
1019 * Getter for Cryptable instance
1021 * @return $cryptoInstance An instance of a Cryptable class
1023 public final function getCryptoInstance () {
1024 return $this->cryptoInstance;
1028 * Setter for the list instance
1030 * @param $listInstance A list of Listable
1033 protected final function setListInstance (Listable $listInstance) {
1034 $this->listInstance = $listInstance;
1038 * Getter for the list instance
1040 * @return $listInstance A list of Listable
1042 protected final function getListInstance () {
1043 return $this->listInstance;
1047 * Setter for the menu instance
1049 * @param $menuInstance A RenderableMenu instance
1052 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1053 $this->menuInstance = $menuInstance;
1057 * Getter for the menu instance
1059 * @return $menuInstance A RenderableMenu instance
1061 protected final function getMenuInstance () {
1062 return $this->menuInstance;
1066 * Setter for image instance
1068 * @param $imageInstance An instance of an image
1071 public final function setImageInstance (BaseImage $imageInstance) {
1072 $this->imageInstance = $imageInstance;
1076 * Getter for image instance
1078 * @return $imageInstance An instance of an image
1080 public final function getImageInstance () {
1081 return $this->imageInstance;
1085 * Setter for stacker instance
1087 * @param $stackInstance An instance of an stacker
1090 public final function setStackInstance (Stackable $stackInstance) {
1091 $this->stackInstance = $stackInstance;
1095 * Getter for stacker instance
1097 * @return $stackInstance An instance of an stacker
1099 public final function getStackInstance () {
1100 return $this->stackInstance;
1104 * Setter for compressor instance
1106 * @param $compressorInstance An instance of an compressor
1109 public final function setCompressorInstance (Compressor $compressorInstance) {
1110 $this->compressorInstance = $compressorInstance;
1114 * Getter for compressor instance
1116 * @return $compressorInstance An instance of an compressor
1118 public final function getCompressorInstance () {
1119 return $this->compressorInstance;
1123 * Setter for Parseable instance
1125 * @param $parserInstance An instance of an Parseable
1128 public final function setParserInstance (Parseable $parserInstance) {
1129 $this->parserInstance = $parserInstance;
1133 * Getter for Parseable instance
1135 * @return $parserInstance An instance of an Parseable
1137 public final function getParserInstance () {
1138 return $this->parserInstance;
1142 * Setter for HandleableProtocol instance
1144 * @param $protocolInstance An instance of an HandleableProtocol
1147 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1148 $this->protocolInstance = $protocolInstance;
1152 * Getter for HandleableProtocol instance
1154 * @return $protocolInstance An instance of an HandleableProtocol
1156 public final function getProtocolInstance () {
1157 return $this->protocolInstance;
1161 * Setter for DatabaseWrapper instance
1163 * @param $wrapperInstance An instance of an DatabaseWrapper
1166 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1167 $this->wrapperInstance = $wrapperInstance;
1171 * Getter for DatabaseWrapper instance
1173 * @return $wrapperInstance An instance of an DatabaseWrapper
1175 public final function getWrapperInstance () {
1176 return $this->wrapperInstance;
1180 * Setter for socket resource
1182 * @param $socketResource A valid socket resource
1185 public final function setSocketResource ($socketResource) {
1186 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1187 $this->socketResource = $socketResource;
1191 * Getter for socket resource
1193 * @return $socketResource A valid socket resource
1195 public final function getSocketResource () {
1196 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1197 return $this->socketResource;
1201 * Setter for regular expression
1203 * @param $regularExpression A valid regular expression
1206 public final function setRegularExpression ($regularExpression) {
1207 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1208 $this->regularExpression = $regularExpression;
1212 * Getter for regular expression
1214 * @return $regularExpression A valid regular expression
1216 public final function getRegularExpression () {
1217 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1218 return $this->regularExpression;
1222 * Setter for helper instance
1224 * @param $helperInstance An instance of a helper class
1227 protected final function setHelperInstance (Helper $helperInstance) {
1228 $this->helperInstance = $helperInstance;
1232 * Getter for helper instance
1234 * @return $helperInstance An instance of a helper class
1236 public final function getHelperInstance () {
1237 return $this->helperInstance;
1241 * Setter for a Source instance
1243 * @param $sourceInstance An instance of a Source class
1246 protected final function setSourceInstance (Source $sourceInstance) {
1247 $this->sourceInstance = $sourceInstance;
1251 * Getter for a Source instance
1253 * @return $sourceInstance An instance of a Source class
1255 protected final function getSourceInstance () {
1256 return $this->sourceInstance;
1260 * Setter for a UrlSource instance
1262 * @param $sourceInstance An instance of a UrlSource class
1265 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1266 $this->urlSourceInstance = $urlSourceInstance;
1270 * Getter for a UrlSource instance
1272 * @return $urlSourceInstance An instance of a UrlSource class
1274 protected final function getUrlSourceInstance () {
1275 return $this->urlSourceInstance;
1279 * Getter for a InputStream instance
1281 * @param $inputStreamInstance The InputStream instance
1283 protected final function getInputStreamInstance () {
1284 return $this->inputStreamInstance;
1288 * Setter for a InputStream instance
1290 * @param $inputStreamInstance The InputStream instance
1293 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1294 $this->inputStreamInstance = $inputStreamInstance;
1298 * Getter for a OutputStream instance
1300 * @param $outputStreamInstance The OutputStream instance
1302 protected final function getOutputStreamInstance () {
1303 return $this->outputStreamInstance;
1307 * Setter for a OutputStream instance
1309 * @param $outputStreamInstance The OutputStream instance
1312 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1313 $this->outputStreamInstance = $outputStreamInstance;
1317 * Setter for handler instance
1319 * @param $handlerInstance An instance of a Handleable class
1322 protected final function setHandlerInstance (Handleable $handlerInstance) {
1323 $this->handlerInstance = $handlerInstance;
1327 * Getter for handler instance
1329 * @return $handlerInstance A Handleable instance
1331 protected final function getHandlerInstance () {
1332 return $this->handlerInstance;
1336 * Setter for visitor instance
1338 * @param $visitorInstance A Visitor instance
1341 protected final function setVisitorInstance (Visitor $visitorInstance) {
1342 $this->visitorInstance = $visitorInstance;
1346 * Getter for visitor instance
1348 * @return $visitorInstance A Visitor instance
1350 protected final function getVisitorInstance () {
1351 return $this->visitorInstance;
1355 * Setter for DHT instance
1357 * @param $dhtInstance A Distributable instance
1360 protected final function setDhtInstance (Distributable $dhtInstance) {
1361 $this->dhtInstance = $dhtInstance;
1365 * Getter for DHT instance
1367 * @return $dhtInstance A Distributable instance
1369 protected final function getDhtInstance () {
1370 return $this->dhtInstance;
1374 * Setter for raw package Data
1376 * @param $packageData Raw package Data
1379 public final function setPackageData (array $packageData) {
1380 $this->packageData = $packageData;
1384 * Getter for raw package Data
1386 * @return $packageData Raw package Data
1388 public function getPackageData () {
1389 return $this->packageData;
1394 * Setter for Iterator instance
1396 * @param $iteratorInstance An instance of an Iterator
1399 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1400 $this->iteratorInstance = $iteratorInstance;
1404 * Getter for Iterator instance
1406 * @return $iteratorInstance An instance of an Iterator
1408 public final function getIteratorInstance () {
1409 return $this->iteratorInstance;
1413 * Setter for FilePointer instance
1415 * @param $pointerInstance An instance of an FilePointer class
1418 protected final function setPointerInstance (FilePointer $pointerInstance) {
1419 $this->pointerInstance = $pointerInstance;
1423 * Getter for FilePointer instance
1425 * @return $pointerInstance An instance of an FilePointer class
1427 public final function getPointerInstance () {
1428 return $this->pointerInstance;
1432 * Unsets pointer instance which triggers a call of __destruct() if the
1433 * instance is still there. This is surely not fatal on already "closed"
1434 * file pointer instances.
1436 * I don't want to mess around with above setter by giving it a default
1437 * value NULL as setter should always explicitly only set (existing) object
1438 * instances and NULL is NULL.
1442 protected final function unsetPointerInstance () {
1443 // Simply it to NULL
1444 $this->pointerInstance = NULL;
1448 * Setter for Indexable instance
1450 * @param $indexInstance An instance of an Indexable class
1453 protected final function setIndexInstance (Indexable $indexInstance) {
1454 $this->indexInstance = $indexInstance;
1458 * Getter for Indexable instance
1460 * @return $indexInstance An instance of an Indexable class
1462 public final function getIndexInstance () {
1463 return $this->indexInstance;
1467 * Setter for Block instance
1469 * @param $blockInstance An instance of an Block class
1472 protected final function setBlockInstance (Block $blockInstance) {
1473 $this->blockInstance = $blockInstance;
1477 * Getter for Block instance
1479 * @return $blockInstance An instance of an Block class
1481 public final function getBlockInstance () {
1482 return $this->blockInstance;
1486 * Setter for Minable instance
1488 * @param $minableInstance A Minable instance
1491 protected final function setMinableInstance (Minable $minableInstance) {
1492 $this->minableInstance = $minableInstance;
1496 * Getter for minable instance
1498 * @return $minableInstance A Minable instance
1500 protected final function getMinableInstance () {
1501 return $this->minableInstance;
1505 * Setter for FrameworkDirectory instance
1507 * @param $directoryInstance A FrameworkDirectory instance
1510 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1511 $this->directoryInstance = $directoryInstance;
1515 * Getter for FrameworkDirectory instance
1517 * @return $directoryInstance A FrameworkDirectory instance
1519 protected final function getDirectoryInstance () {
1520 return $this->directoryInstance;
1524 * Getter for communicator instance
1526 * @return $communicatorInstance An instance of a Communicator class
1528 public final function getCommunicatorInstance () {
1529 return $this->communicatorInstance;
1533 * Setter for communicator instance
1535 * @param $communicatorInstance An instance of a Communicator class
1538 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1539 $this->communicatorInstance = $communicatorInstance;
1543 * Setter for state instance
1545 * @param $stateInstance A Stateable instance
1548 public final function setStateInstance (Stateable $stateInstance) {
1549 $this->stateInstance = $stateInstance;
1553 * Getter for state instance
1555 * @return $stateInstance A Stateable instance
1557 public final function getStateInstance () {
1558 return $this->stateInstance;
1562 * Setter for output instance
1564 * @param $outputInstance The debug output instance
1567 public final function setOutputInstance (OutputStreamer $outputInstance) {
1568 $this->outputInstance = $outputInstance;
1572 * Getter for output instance
1574 * @return $outputInstance The debug output instance
1576 public final function getOutputInstance () {
1577 return $this->outputInstance;
1581 * Setter for command name
1583 * @param $commandName Last validated command name
1586 protected final function setCommandName ($commandName) {
1587 $this->commandName = $commandName;
1591 * Getter for command name
1593 * @return $commandName Last validated command name
1595 protected final function getCommandName () {
1596 return $this->commandName;
1600 * Setter for controller name
1602 * @param $controllerName Last validated controller name
1605 protected final function setControllerName ($controllerName) {
1606 $this->controllerName = $controllerName;
1610 * Getter for controller name
1612 * @return $controllerName Last validated controller name
1614 protected final function getControllerName () {
1615 return $this->controllerName;
1619 * Getter for protocol name
1621 * @return $protocolName Name of used protocol
1623 public final function getProtocolName () {
1624 return $this->protocolName;
1628 * Setter for protocol name
1630 * @param $protocolName Name of used protocol
1633 protected final function setProtocolName ($protocolName) {
1634 $this->protocolName = $protocolName;
1638 * Checks whether an object equals this object. You should overwrite this
1639 * method to implement own equality checks
1641 * @param $objectInstance An instance of a FrameworkInterface object
1642 * @return $equals Whether both objects equals
1644 public function equals (FrameworkInterface $objectInstance) {
1647 $this->__toString() == $objectInstance->__toString()
1649 $this->hashCode() == $objectInstance->hashCode()
1652 // Return the result
1657 * Generates a generic hash code of this class. You should really overwrite
1658 * this method with your own hash code generator code. But keep KISS in mind.
1660 * @return $hashCode A generic hash code respresenting this whole class
1662 public function hashCode () {
1664 return crc32($this->__toString());
1668 * Formats computer generated price values into human-understandable formats
1669 * with thousand and decimal separators.
1671 * @param $value The in computer format value for a price
1672 * @param $currency The currency symbol (use HTML-valid characters!)
1673 * @param $decNum Number of decimals after commata
1674 * @return $price The for the current language formated price string
1675 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1676 * thousands separator
1679 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1680 // Are all required attriutes set?
1681 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1682 // Throw an exception
1683 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1687 $value = (float) $value;
1689 // Reformat the US number
1690 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1692 // Return as string...
1697 * Appends a trailing slash to a string
1699 * @param $str A string (maybe) without trailing slash
1700 * @return $str A string with an auto-appended trailing slash
1702 public final function addMissingTrailingSlash ($str) {
1703 // Is there a trailing slash?
1704 if (substr($str, -1, 1) != '/') {
1708 // Return string with trailing slash
1713 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1714 * application helper instance (ApplicationHelper by default).
1716 * @param $applicationInstance An application helper instance or
1717 * null if we shall use the default
1718 * @return $templateInstance The template engine instance
1719 * @throws NullPointerException If the discovered application
1720 * instance is still null
1722 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1723 // Is the application instance set?
1724 if (is_null($applicationInstance)) {
1725 // Get the current instance
1726 $applicationInstance = Registry::getRegistry()->getInstance('app');
1729 if (is_null($applicationInstance)) {
1730 // Thrown an exception
1731 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1735 // Initialize the template engine
1736 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1738 // Return the prepared instance
1739 return $templateInstance;
1743 * Debugs this instance by putting out it's full content
1745 * @param $message Optional message to show in debug output
1748 public final function debugInstance ($message = '') {
1749 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1750 restore_error_handler();
1755 // Is a message set?
1756 if (!empty($message)) {
1757 // Construct message
1758 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1761 // Generate the output
1762 $content .= sprintf('<pre>%s</pre>',
1765 print_r($this, true)
1771 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>',
1772 $this->__toString(),
1774 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1779 * Replaces control characters with printable output
1781 * @param $str String with control characters
1782 * @return $str Replaced string
1784 protected function replaceControlCharacters ($str) {
1787 chr(13), '[r]', str_replace(
1788 chr(10), '[n]', str_replace(
1798 * Output a partial stub message for the caller method
1800 * @param $message An optional message to display
1803 protected function partialStub ($message = '') {
1804 // Get the backtrace
1805 $backtrace = debug_backtrace();
1807 // Generate the class::method string
1808 $methodName = 'UnknownClass->unknownMethod';
1809 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1810 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1813 // Construct the full message
1814 $stubMessage = sprintf('[%s:] Partial stub!',
1818 // Is the extra message given?
1819 if (!empty($message)) {
1820 // Then add it as well
1821 $stubMessage .= ' Message: ' . $message;
1824 // Debug instance is there?
1825 if (!is_null($this->getDebugInstance())) {
1826 // Output stub message
1827 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1830 trigger_error($stubMessage);
1836 * Outputs a debug backtrace and stops further script execution
1838 * @param $message An optional message to output
1839 * @param $doExit Whether exit the program (true is default)
1842 public function debugBackTrace ($message = '', $doExit = true) {
1843 // Sorry, there is no other way getting this nice backtrace
1844 if (!empty($message)) {
1846 printf('Message: %s<br />' . PHP_EOL, $message);
1850 debug_print_backtrace();
1854 if ($doExit === true) {
1860 * Creates an instance of a debugger instance
1862 * @param $className Name of the class (currently unsupported)
1863 * @param $lineNumber Line number where the call was made
1864 * @return $debugInstance An instance of a debugger class
1865 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1867 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1868 // Is the instance set?
1869 if (!Registry::getRegistry()->instanceExists('debug')) {
1870 // Init debug instance
1871 $debugInstance = NULL;
1875 // Get a debugger instance
1876 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1877 } catch (NullPointerException $e) {
1878 // Didn't work, no instance there
1879 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1882 // Empty string should be ignored and used for testing the middleware
1883 DebugMiddleware::getSelfInstance()->output('');
1885 // Set it in its own class. This will set it in the registry
1886 $debugInstance->setDebugInstance($debugInstance);
1888 // Get instance from registry
1889 $debugInstance = Registry::getRegistry()->getDebugInstance();
1893 return $debugInstance;
1897 * Simple output of a message with line-break
1899 * @param $message Message to output
1902 public function outputLine ($message) {
1904 print($message . PHP_EOL);
1908 * Outputs a debug message whether to debug instance (should be set!) or
1909 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1910 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1912 * @param $message Message we shall send out...
1913 * @param $doPrint Whether print or die here (default: print)
1914 * @paran $stripTags Whether to strip tags (default: false)
1917 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1918 // Set debug instance to NULL
1919 $debugInstance = NULL;
1923 // Get debug instance
1924 $debugInstance = $this->getDebugInstance();
1925 } catch (NullPointerException $e) {
1926 // The debug instance is not set (yet)
1929 // Is the debug instance there?
1930 if (is_object($debugInstance)) {
1931 // Use debug output handler
1932 $debugInstance->output($message, $stripTags);
1934 if ($doPrint === false) {
1935 // Die here if not printed
1939 // Are debug times enabled?
1940 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1942 $message = $this->getPrintableExecutionTime() . $message;
1946 if ($doPrint === true) {
1948 $this->outputLine($message);
1957 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1959 * @param $str The string, what ever it is needs to be converted
1960 * @return $className Generated class name
1962 public static final function convertToClassName ($str) {
1966 // Convert all dashes in underscores
1967 $str = self::convertDashesToUnderscores($str);
1969 // Now use that underscores to get classname parts for hungarian style
1970 foreach (explode('_', $str) as $strPart) {
1971 // Make the class name part lower case and first upper case
1972 $className .= ucfirst(strtolower($strPart));
1975 // Return class name
1980 * Converts dashes to underscores, e.g. useable for configuration entries
1982 * @param $str The string with maybe dashes inside
1983 * @return $str The converted string with no dashed, but underscores
1985 public static final function convertDashesToUnderscores ($str) {
1987 $str = str_replace('-', '_', $str);
1989 // Return converted string
1994 * Marks up the code by adding e.g. line numbers
1996 * @param $phpCode Unmarked PHP code
1997 * @return $markedCode Marked PHP code
1999 public function markupCode ($phpCode) {
2004 $errorArray = error_get_last();
2006 // Init the code with error message
2007 if (is_array($errorArray)) {
2009 $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>',
2010 basename($errorArray['file']),
2011 $errorArray['line'],
2012 $errorArray['message'],
2017 // Add line number to the code
2018 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2020 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2022 htmlentities($code, ENT_QUOTES)
2031 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2032 * beatiful for web-based front-ends. If null is given a message id
2033 * null_timestamp will be resolved and returned.
2035 * @param $timestamp Timestamp to prepare (filter) for display
2036 * @return $readable A readable timestamp
2038 public function doFilterFormatTimestamp ($timestamp) {
2039 // Default value to return
2042 // Is the timestamp null?
2043 if (is_null($timestamp)) {
2044 // Get a message string
2045 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2047 switch ($this->getLanguageInstance()->getLanguageCode()) {
2048 case 'de': // German format is a bit different to default
2049 // Split the GMT stamp up
2050 $dateTime = explode(' ', $timestamp );
2051 $dateArray = explode('-', $dateTime[0]);
2052 $timeArray = explode(':', $dateTime[1]);
2054 // Construct the timestamp
2055 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2065 default: // Default is pass-through
2066 $readable = $timestamp;
2076 * Filter a given number into a localized number
2078 * @param $value The raw value from e.g. database
2079 * @return $localized Localized value
2081 public function doFilterFormatNumber ($value) {
2082 // Generate it from config and localize dependencies
2083 switch ($this->getLanguageInstance()->getLanguageCode()) {
2084 case 'de': // German format is a bit different to default
2085 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2088 default: // US, etc.
2089 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2098 * "Getter" for databse entry
2100 * @return $entry An array with database entries
2101 * @throws NullPointerException If the database result is not found
2102 * @throws InvalidDatabaseResultException If the database result is invalid
2104 protected final function getDatabaseEntry () {
2105 // Is there an instance?
2106 if (!$this->getResultInstance() instanceof SearchableResult) {
2107 // Throw an exception here
2108 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2112 $this->getResultInstance()->rewind();
2114 // Do we have an entry?
2115 if ($this->getResultInstance()->valid() === false) {
2116 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2117 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2121 $this->getResultInstance()->next();
2124 $entry = $this->getResultInstance()->current();
2131 * Getter for field name
2133 * @param $fieldName Field name which we shall get
2134 * @return $fieldValue Field value from the user
2135 * @throws NullPointerException If the result instance is null
2137 public final function getField ($fieldName) {
2138 // Default field value
2141 // Get result instance
2142 $resultInstance = $this->getResultInstance();
2144 // Is this instance null?
2145 if (is_null($resultInstance)) {
2146 // Then the user instance is no longer valid (expired cookies?)
2147 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2150 // Get current array
2151 $fieldArray = $resultInstance->current();
2152 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2154 // Convert dashes to underscore
2155 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2157 // Does the field exist?
2158 if ($this->isFieldSet($fieldName)) {
2160 $fieldValue = $fieldArray[$fieldName2];
2161 } elseif (defined('DEVELOPER')) {
2162 // Missing field entry, may require debugging
2163 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2165 // Missing field entry, may require debugging
2166 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2174 * Checks if given field is set
2176 * @param $fieldName Field name to check
2177 * @return $isSet Whether the given field name is set
2178 * @throws NullPointerException If the result instance is null
2180 public function isFieldSet ($fieldName) {
2181 // Get result instance
2182 $resultInstance = $this->getResultInstance();
2184 // Is this instance null?
2185 if (is_null($resultInstance)) {
2186 // Then the user instance is no longer valid (expired cookies?)
2187 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2190 // Get current array
2191 $fieldArray = $resultInstance->current();
2192 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2194 // Convert dashes to underscore
2195 $fieldName = self::convertDashesToUnderscores($fieldName);
2198 $isSet = isset($fieldArray[$fieldName]);
2205 * Flushs all pending updates to the database layer
2209 public function flushPendingUpdates () {
2210 // Get result instance
2211 $resultInstance = $this->getResultInstance();
2213 // Do we have data to update?
2214 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2215 // Get wrapper class name config entry
2216 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2218 // Create object instance
2219 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2221 // Yes, then send the whole result to the database layer
2222 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2227 * Outputs a deprecation warning to the developer.
2229 * @param $message The message we shall output to the developer
2231 * @todo Write a logging mechanism for productive mode
2233 public function deprecationWarning ($message) {
2234 // Is developer mode active?
2235 if (defined('DEVELOPER')) {
2236 // Debug instance is there?
2237 if (!is_null($this->getDebugInstance())) {
2238 // Output stub message
2239 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2242 trigger_error($message . "<br />\n");
2246 // @TODO Finish this part!
2247 $this->partialStub('Developer mode inactive. Message:' . $message);
2252 * Checks whether the given PHP extension is loaded
2254 * @param $phpExtension The PHP extension we shall check
2255 * @return $isLoaded Whether the PHP extension is loaded
2257 public final function isPhpExtensionLoaded ($phpExtension) {
2259 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2266 * "Getter" as a time() replacement but with milliseconds. You should use this
2267 * method instead of the encapsulated getimeofday() function.
2269 * @return $milliTime Timestamp with milliseconds
2271 public function getMilliTime () {
2272 // Get the time of day as float
2273 $milliTime = gettimeofday(true);
2280 * Idles (sleeps) for given milliseconds
2282 * @return $hasSlept Whether it goes fine
2284 public function idle ($milliSeconds) {
2285 // Sleep is fine by default
2288 // Idle so long with found function
2289 if (function_exists('time_sleep_until')) {
2290 // Get current time and add idle time
2291 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2293 // New PHP 5.1.0 function found, ignore errors
2294 $hasSlept = @time_sleep_until($sleepUntil);
2297 * My Sun station doesn't have that function even with latest PHP
2300 usleep($milliSeconds * 1000);
2307 * Converts a hexadecimal string, even with negative sign as first string to
2308 * a decimal number using BC functions.
2310 * This work is based on comment #86673 on php.net documentation page at:
2311 * <http://de.php.net/manual/en/function.dechex.php#86673>
2313 * @param $hex Hexadecimal string
2314 * @return $dec Decimal number
2316 protected function hex2dec ($hex) {
2317 // Convert to all lower-case
2318 $hex = strtolower($hex);
2320 // Detect sign (negative/positive numbers)
2322 if (substr($hex, 0, 1) == '-') {
2324 $hex = substr($hex, 1);
2327 // Decode the hexadecimal string into a decimal number
2329 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2330 $factor = self::$hexdec[substr($hex, $i, 1)];
2331 $dec = bcadd($dec, bcmul($factor, $e));
2334 // Return the decimal number
2335 return $sign . $dec;
2339 * Converts even very large decimal numbers, also signed, to a hexadecimal
2342 * This work is based on comment #97756 on php.net documentation page at:
2343 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2345 * @param $dec Decimal number, even with negative sign
2346 * @param $maxLength Optional maximum length of the string
2347 * @return $hex Hexadecimal string
2349 protected function dec2hex ($dec, $maxLength = 0) {
2350 // maxLength can be zero or devideable by 2
2351 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2353 // Detect sign (negative/positive numbers)
2360 // Encode the decimal number into a hexadecimal string
2363 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2365 } while ($dec >= 1);
2368 * Leading zeros are required for hex-decimal "numbers". In some
2369 * situations more leading zeros are wanted, so check for both
2372 if ($maxLength > 0) {
2373 // Prepend more zeros
2374 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2375 } elseif ((strlen($hex) % 2) != 0) {
2376 // Only make string's length dividable by 2
2380 // Return the hexadecimal string
2381 return $sign . $hex;
2385 * Converts a ASCII string (0 to 255) into a decimal number.
2387 * @param $asc The ASCII string to be converted
2388 * @return $dec Decimal number
2390 protected function asc2dec ($asc) {
2391 // Convert it into a hexadecimal number
2392 $hex = bin2hex($asc);
2394 // And back into a decimal number
2395 $dec = $this->hex2dec($hex);
2402 * Converts a decimal number into an ASCII string.
2404 * @param $dec Decimal number
2405 * @return $asc An ASCII string
2407 protected function dec2asc ($dec) {
2408 // First convert the number into a hexadecimal string
2409 $hex = $this->dec2hex($dec);
2411 // Then convert it into the ASCII string
2412 $asc = $this->hex2asc($hex);
2419 * Converts a hexadecimal number into an ASCII string. Negative numbers
2422 * @param $hex Hexadecimal string
2423 * @return $asc An ASCII string
2425 protected function hex2asc ($hex) {
2426 // Check for length, it must be devideable by 2
2427 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2428 assert((strlen($hex) % 2) == 0);
2432 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2433 // Get the decimal number of the chunk
2434 $part = hexdec(substr($hex, $idx, 2));
2436 // Add it to the final string
2440 // Return the final string
2445 * Checks whether the given encoded data was encoded with Base64
2447 * @param $encodedData Encoded data we shall check
2448 * @return $isBase64 Whether the encoded data is Base64
2450 protected function isBase64Encoded ($encodedData) {
2452 $isBase64 = (@base64_decode($encodedData, true) !== false);
2459 * Gets a cache key from Criteria instance
2461 * @param $criteriaInstance An instance of a Criteria class
2462 * @param $onlyKeys Only use these keys for a cache key
2463 * @return $cacheKey A cache key suitable for lookup/storage purposes
2465 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2467 $cacheKey = sprintf('%s@%s',
2468 $this->__toString(),
2469 $criteriaInstance->getCacheKey($onlyKeys)
2473 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2478 * Getter for startup time in miliseconds
2480 * @return $startupTime Startup time in miliseconds
2482 protected function getStartupTime () {
2483 return self::$startupTime;
2487 * "Getter" for a printable currently execution time in nice braces
2489 * @return $executionTime Current execution time in nice braces
2491 protected function getPrintableExecutionTime () {
2492 // Caculate the execution time
2493 $executionTime = microtime(true) - $this->getStartupTime();
2495 // Pack it in nice braces
2496 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2499 return $executionTime;
2503 * Hashes a given string with a simple but stronger hash function (no salt)
2504 * and hex-encode it.
2506 * @param $str The string to be hashed
2507 * @return $hash The hash from string $str
2509 public static final function hash ($str) {
2510 // Hash given string with (better secure) hasher
2511 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2518 * "Getter" for length of hash() output. This will be "cached" to speed up
2521 * @return $length Length of hash() output
2523 public static final function getHashLength () {
2525 if (is_null(self::$hashLength)) {
2526 // No, then hash a string and save its length.
2527 self::$hashLength = strlen(self::hash('abc123'));
2531 return self::$hashLength;
2535 * Checks whether the given number is really a number (only chars 0-9).
2537 * @param $num A string consisting only chars between 0 and 9
2538 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2539 * @param $assertMismatch Whether to assert mismatches
2540 * @return $ret The (hopefully) secured numbered value
2542 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2543 // Filter all numbers out
2544 $ret = preg_replace('/[^0123456789]/', '', $num);
2547 if ($castValue === true) {
2548 // Cast to biggest numeric type
2549 $ret = (double) $ret;
2552 // Assert only if requested
2553 if ($assertMismatch === true) {
2554 // Has the whole value changed?
2555 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2563 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2565 * @param $num A string consisting only chars between 0 and 9
2566 * @param $assertMismatch Whether to assert mismatches
2567 * @return $ret The (hopefully) secured hext-numbered value
2569 public function hexval ($num, $assertMismatch = false) {
2570 // Filter all numbers out
2571 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2573 // Assert only if requested
2574 if ($assertMismatch === true) {
2575 // Has the whole value changed?
2576 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2584 * Determines if an element is set in the generic array
2586 * @param $keyGroup Main group for the key
2587 * @param $subGroup Sub group for the key
2588 * @param $key Key to check
2589 * @param $element Element to check
2590 * @return $isset Whether the given key is set
2592 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2594 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2597 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2603 * Determines if a key is set in the generic array
2605 * @param $keyGroup Main group for the key
2606 * @param $subGroup Sub group for the key
2607 * @param $key Key to check
2608 * @return $isset Whether the given key is set
2610 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2612 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2615 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2623 * Determines if a group is set in the generic array
2625 * @param $keyGroup Main group
2626 * @param $subGroup Sub group
2627 * @return $isset Whether the given group is set
2629 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2631 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2634 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2641 * Getter for sub key group
2643 * @param $keyGroup Main key group
2644 * @param $subGroup Sub key group
2645 * @return $array An array with all array elements
2647 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2649 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2650 // No, then abort here
2651 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2656 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2659 return $this->genericArray[$keyGroup][$subGroup];
2663 * Unsets a given key in generic array
2665 * @param $keyGroup Main group for the key
2666 * @param $subGroup Sub group for the key
2667 * @param $key Key to unset
2670 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2672 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2675 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2679 * Unsets a given element in generic array
2681 * @param $keyGroup Main group for the key
2682 * @param $subGroup Sub group for the key
2683 * @param $key Key to unset
2684 * @param $element Element to unset
2687 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2689 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2692 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2696 * Append a string to a given generic array key
2698 * @param $keyGroup Main group for the key
2699 * @param $subGroup Sub group for the key
2700 * @param $key Key to unset
2701 * @param $value Value to add/append
2704 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2706 //* 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);
2708 // Is it already there?
2709 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2711 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2714 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2719 * Append a string to a given generic array element
2721 * @param $keyGroup Main group for the key
2722 * @param $subGroup Sub group for the key
2723 * @param $key Key to unset
2724 * @param $element Element to check
2725 * @param $value Value to add/append
2728 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2730 //* 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);
2732 // Is it already there?
2733 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2735 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2738 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2743 * Sets a string in a given generic array element
2745 * @param $keyGroup Main group for the key
2746 * @param $subGroup Sub group for the key
2747 * @param $key Key to unset
2748 * @param $element Element to check
2749 * @param $value Value to add/append
2752 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2754 //* 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);
2757 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2761 * Initializes given generic array group
2763 * @param $keyGroup Main group for the key
2764 * @param $subGroup Sub group for the key
2765 * @param $key Key to use
2766 * @param $forceInit Optionally force initialization
2769 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2771 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2773 // Is it already set?
2774 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2775 // Already initialized
2776 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2781 $this->genericArray[$keyGroup][$subGroup] = array();
2785 * Initializes given generic array 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 $forceInit Optionally force initialization
2793 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2795 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2797 // Is it already set?
2798 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2799 // Already initialized
2800 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2805 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2809 * Initializes given generic array element
2811 * @param $keyGroup Main group for the key
2812 * @param $subGroup Sub group for the key
2813 * @param $key Key to use
2814 * @param $element Element to use
2815 * @param $forceInit Optionally force initialization
2818 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2820 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2822 // Is it already set?
2823 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2824 // Already initialized
2825 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2830 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2834 * Pushes an element to a generic key
2836 * @param $keyGroup Main group for the key
2837 * @param $subGroup Sub group for the key
2838 * @param $key Key to use
2839 * @param $value Value to add/append
2840 * @return $count Number of array elements
2842 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2844 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2847 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2849 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2853 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2856 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2857 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2862 * Pushes an element to a generic array element
2864 * @param $keyGroup Main group for the key
2865 * @param $subGroup Sub group for the key
2866 * @param $key Key to use
2867 * @param $element Element to check
2868 * @param $value Value to add/append
2869 * @return $count Number of array elements
2871 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2873 //* 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));
2876 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2878 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2882 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2885 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2886 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2891 * Pops an element from a generic group
2893 * @param $keyGroup Main group for the key
2894 * @param $subGroup Sub group for the key
2895 * @param $key Key to unset
2896 * @return $value Last "popped" value
2898 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2900 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2903 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2905 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2910 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2913 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2914 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2919 * Shifts an element from a generic group
2921 * @param $keyGroup Main group for the key
2922 * @param $subGroup Sub group for the key
2923 * @param $key Key to unset
2924 * @return $value Last "popped" value
2926 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2928 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2931 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2933 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2938 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2941 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2942 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2947 * Count generic array group
2949 * @param $keyGroup Main group for the key
2950 * @return $count Count of given group
2952 protected final function countGenericArray ($keyGroup) {
2954 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2957 if (!isset($this->genericArray[$keyGroup])) {
2959 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2964 $count = count($this->genericArray[$keyGroup]);
2967 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2974 * Count generic array sub group
2976 * @param $keyGroup Main group for the key
2977 * @param $subGroup Sub group for the key
2978 * @return $count Count of given group
2980 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2982 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2985 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2987 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2992 $count = count($this->genericArray[$keyGroup][$subGroup]);
2995 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3002 * Count generic array elements
3004 * @param $keyGroup Main group for the key
3005 * @param $subGroup Sub group for the key
3006 * @para $key Key to count
3007 * @return $count Count of given key
3009 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3011 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3014 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3016 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3018 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3020 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3025 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3028 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3035 * Getter for whole generic group array
3037 * @param $keyGroup Key group to get
3038 * @return $array Whole generic array group
3040 protected final function getGenericArray ($keyGroup) {
3042 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3045 if (!isset($this->genericArray[$keyGroup])) {
3047 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3052 return $this->genericArray[$keyGroup];
3056 * Setter for generic array key
3058 * @param $keyGroup Key group to get
3059 * @param $subGroup Sub group for the key
3060 * @param $key Key to unset
3061 * @param $value Mixed value from generic array element
3064 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3066 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3069 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3073 * Getter for generic array key
3075 * @param $keyGroup Key group to get
3076 * @param $subGroup Sub group for the key
3077 * @param $key Key to unset
3078 * @return $value Mixed value from generic array element
3080 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3082 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3085 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3087 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3092 return $this->genericArray[$keyGroup][$subGroup][$key];
3096 * Sets a value in given generic array key/element
3098 * @param $keyGroup Main group for the key
3099 * @param $subGroup Sub group for the key
3100 * @param $key Key to set
3101 * @param $element Element to set
3102 * @param $value Value to set
3105 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3107 //* 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));
3110 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3114 * Getter for generic array element
3116 * @param $keyGroup Key group to get
3117 * @param $subGroup Sub group for the key
3118 * @param $key Key to look for
3119 * @param $element Element to look for
3120 * @return $value Mixed value from generic array element
3122 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3124 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3127 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3129 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3134 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3138 * Checks if a given sub group is valid (array)
3140 * @param $keyGroup Key group to get
3141 * @param $subGroup Sub group for the key
3142 * @return $isValid Whether given sub group is valid
3144 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3146 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3149 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3156 * Checks if a given key is valid (array)
3158 * @param $keyGroup Key group to get
3159 * @param $subGroup Sub group for the key
3160 * @param $key Key to check
3161 * @return $isValid Whether given sub group is valid
3163 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3165 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3168 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3175 * Initializes the web output instance
3179 protected function initWebOutputInstance () {
3180 // Get application instance
3181 $applicationInstance = Registry::getRegistry()->getInstance('app');
3183 // Init web output instance
3184 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3187 $this->setWebOutputInstance($outputInstance);
3191 * Translates boolean true to 'Y' and false to 'N'
3193 * @param $boolean Boolean value
3194 * @return $translated Translated boolean value
3196 public static final function translateBooleanToYesNo ($boolean) {
3197 // Make sure it is really boolean
3198 assert(is_bool($boolean));
3201 $translated = ($boolean === true) ? 'Y' : 'N';
3203 // ... and return it
3208 * Encodes raw data (almost any type) by "serializing" it and then pack it
3209 * into a "binary format".
3211 * @param $rawData Raw data (almost any type)
3212 * @return $encoded Encoded data
3214 protected function encodeData ($rawData) {
3215 // Make sure no objects or resources pass through
3216 assert(!is_object($rawData));
3217 assert(!is_resource($rawData));
3219 // First "serialize" it (json_encode() is faster than serialize())
3220 $encoded = $this->packString(json_encode($rawData));
3227 * Pack a string into a "binary format". Please execuse me that this is
3228 * widely undocumented. :-(
3230 * @param $str Unpacked string
3231 * @return $packed Packed string
3232 * @todo Improve documentation
3234 protected function packString ($str) {
3236 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3238 // First compress the string (gzcompress is okay)
3239 $str = gzcompress($str);
3244 // And start the "encoding" loop
3245 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3247 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3248 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3250 if (($idx + $i) <= strlen($str)) {
3251 $ord = ord(substr($str, ($idx + $i), 1));
3253 $add = $ord * pow(256, $factor);
3257 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3261 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3262 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3264 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3265 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3271 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3276 * Creates a full-qualified file name (FQFN) for given file name by adding
3277 * a configured temporary file path to it.
3279 * @param $fileName Name for temporary file
3280 * @return $fqfn Full-qualified file name
3281 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3282 * @throws FileIoException If the file cannot be written
3284 protected static function createTempPathForFile ($fileName) {
3286 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3288 // Is the path writeable?
3289 if (!is_writable($basePath)) {
3290 // Path is write-protected
3291 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3295 $fqfn = $basePath . '/' . $fileName;
3298 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3300 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3308 * "Getter" for a printable state name
3310 * @return $stateName Name of the node's state in a printable format
3312 public final function getPrintableState () {
3313 // Default is 'null'
3314 $stateName = 'null';
3316 // Get the state instance
3317 $stateInstance = $this->getStateInstance();
3319 // Is it an instance of Stateable?
3320 if ($stateInstance instanceof Stateable) {
3321 // Then use that state name
3322 $stateName = $stateInstance->getStateName();