3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\Compressor\Compressor;
8 use CoreFramework\Configuration\FrameworkConfiguration;
9 use CoreFramework\Connection\Database\DatabaseConnection;
10 use CoreFramework\Controller\Controller;
11 use CoreFramework\Criteria\Criteria;
12 use CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use CoreFramework\Crypto\Cryptable;
15 use CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use CoreFramework\Database\Frontend\DatabaseWrapper;
17 use CoreFramework\EntryPoint\ApplicationEntryPoint;
18 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
19 use CoreFramework\Factory\ObjectFactory;
20 use CoreFramework\Filesystem\Block;
21 use CoreFramework\Filesystem\FilePointer;
22 use CoreFramework\Filesystem\FrameworkDirectory;
23 use CoreFramework\Filesystem\PathWriteProtectedException;
24 use CoreFramework\Generic\FrameworkInterface;
25 use CoreFramework\Generic\NullPointerException;
26 use CoreFramework\Generic\UnsupportedOperationException;
27 use CoreFramework\Handler\Handleable;
28 use CoreFramework\Handler\Stream\IoHandler;
29 use CoreFramework\Helper\Helper;
30 use CoreFramework\Index\Indexable;
31 use CoreFramework\Lists\Listable;
32 use CoreFramework\Loader\ClassLoader;
33 use CoreFramework\Manager\ManageableApplication;
34 use CoreFramework\Middleware\Compressor\CompressorChannel;
35 use CoreFramework\Middleware\Debug\DebugMiddleware;
36 use CoreFramework\Parser\Parseable;
37 use CoreFramework\Registry\Register;
38 use CoreFramework\Registry\Registry;
39 use CoreFramework\Resolver\Resolver;
40 use CoreFramework\Result\Database\CachedDatabaseResult;
41 use CoreFramework\Result\Search\SearchableResult;
42 use CoreFramework\Stacker\Stackable;
43 use CoreFramework\State\Stateable;
44 use CoreFramework\Stream\Input\InputStream;
45 use CoreFramework\Stream\Output\OutputStreamer;
46 use CoreFramework\Stream\Output\OutputStream;
47 use CoreFramework\Template\CompileableTemplate;
48 use CoreFramework\User\ManageableAccount;
49 use CoreFramework\Visitor\Visitor;
57 * The simulator system class is the super class of all other classes. This
58 * class handles saving of games etc.
60 * @author Roland Haeder <webmaster@shipsimu.org>
62 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
63 * @license GNU GPL 3.0 or any newer version
64 * @link http://www.shipsimu.org
66 * This program is free software: you can redistribute it and/or modify
67 * it under the terms of the GNU General Public License as published by
68 * the Free Software Foundation, either version 3 of the License, or
69 * (at your option) any later version.
71 * This program is distributed in the hope that it will be useful,
72 * but WITHOUT ANY WARRANTY; without even the implied warranty of
73 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
74 * GNU General Public License for more details.
76 * You should have received a copy of the GNU General Public License
77 * along with this program. If not, see <http://www.gnu.org/licenses/>.
79 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
81 * Length of output from hash()
83 private static $hashLength = NULL;
88 private $realClass = 'BaseFrameworkSystem';
91 * Search criteria instance
93 private $searchInstance = NULL;
96 * Update criteria instance
98 private $updateInstance = NULL;
101 * The file I/O instance for the template loader
103 private $fileIoInstance = NULL;
108 private $resolverInstance = NULL;
111 * Template engine instance
113 private $templateInstance = NULL;
116 * Database result instance
118 private $resultInstance = NULL;
121 * Instance for user class
123 private $userInstance = NULL;
126 * A controller instance
128 private $controllerInstance = NULL;
133 private $rngInstance = NULL;
136 * Instance of a crypto helper
138 private $cryptoInstance = NULL;
141 * Instance of an Iterator class
143 private $iteratorInstance = NULL;
146 * Instance of the list
148 private $listInstance = NULL;
153 private $menuInstance = NULL;
156 * Instance of the image
158 private $imageInstance = NULL;
161 * Instance of the stacker
163 private $stackInstance = NULL;
166 * A Compressor instance
168 private $compressorInstance = NULL;
171 * A Parseable instance
173 private $parserInstance = NULL;
176 * A database wrapper instance
178 private $databaseInstance = NULL;
181 * A helper instance for the form
183 private $helperInstance = NULL;
186 * An instance of a Source class
188 private $sourceInstance = NULL;
191 * An instance of a UrlSource class
193 private $urlSourceInstance = NULL;
196 * An instance of a InputStream class
198 private $inputStreamInstance = NULL;
201 * An instance of a OutputStream class
203 private $outputStreamInstance = NULL;
208 private $handlerInstance = NULL;
211 * Visitor handler instance
213 private $visitorInstance = NULL;
216 * An instance of a database wrapper class
218 private $wrapperInstance = NULL;
221 * An instance of a file I/O pointer class (not handler)
223 private $pointerInstance = NULL;
226 * An instance of an Indexable class
228 private $indexInstance = NULL;
231 * An instance of a Block class
233 private $blockInstance = NULL;
238 private $minableInstance = NULL;
241 * A FrameworkDirectory instance
243 private $directoryInstance = NULL;
246 * An instance of a communicator
248 private $communicatorInstance = NULL;
251 * The concrete output instance
253 private $outputInstance = NULL;
258 private $stateInstance = NULL;
261 * Registry instance (implementing Register)
263 private $registryInstance = NULL;
266 * Thousands separator
268 private $thousands = '.'; // German
273 private $decimals = ','; // German
278 private $socketResource = false;
281 * Regular expression to use for validation
283 private $regularExpression = '';
288 private $packageData = array();
293 private $genericArray = array();
298 private $commandName = '';
303 private $controllerName = '';
306 * Array with bitmasks and such for pack/unpack methods to support both
307 * 32-bit and 64-bit systems
309 private $packingData = array(
312 'left' => 0xffff0000,
313 'right' => 0x0000ffff,
319 'left' => 0xffffffff00000000,
320 'right' => 0x00000000ffffffff,
327 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
329 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
331 private $archArrayElement = false;
333 /***********************
334 * Exception codes.... *
335 ***********************/
337 // @todo Try to clean these constants up
338 const EXCEPTION_IS_NULL_POINTER = 0x001;
339 const EXCEPTION_IS_NO_OBJECT = 0x002;
340 const EXCEPTION_IS_NO_ARRAY = 0x003;
341 const EXCEPTION_MISSING_METHOD = 0x004;
342 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
343 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
344 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
345 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
346 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
347 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
348 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
349 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
350 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
351 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
352 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
353 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
354 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
355 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
356 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
357 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
358 const EXCEPTION_PATH_NOT_FOUND = 0x015;
359 const EXCEPTION_INVALID_PATH_NAME = 0x016;
360 const EXCEPTION_READ_PROTECED_PATH = 0x017;
361 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
362 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
363 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
364 const EXCEPTION_INVALID_RESOURCE = 0x01b;
365 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
366 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
367 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
368 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
369 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
370 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
371 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
372 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
373 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
374 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
375 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
376 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
377 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
378 const EXCEPTION_INVALID_STRING = 0x029;
379 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
380 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
381 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
382 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
383 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
384 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
385 const EXCEPTION_MISSING_ELEMENT = 0x030;
386 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
387 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
388 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
389 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
390 const EXCEPTION_FATAL_ERROR = 0x035;
391 const EXCEPTION_FILE_NOT_FOUND = 0x036;
392 const EXCEPTION_ASSERTION_FAILED = 0x037;
393 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
394 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
395 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
396 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
397 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
398 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
399 const EXCEPTION_INVALID_SOCKET = 0x03e;
402 * Hexadecimal->Decimal translation array
404 private static $hexdec = array(
424 * Decimal->hexadecimal translation array
426 private static $dechex = array(
446 * Startup time in miliseconds
448 private static $startupTime = 0;
451 * Protected super constructor
453 * @param $className Name of the class
456 protected function __construct ($className) {
458 $this->setRealClass($className);
460 // Set configuration instance if no registry ...
461 if (!$this instanceof Register) {
462 // ... because registries doesn't need to be configured
463 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
466 // Is the startup time set? (0 cannot be true anymore)
467 if (self::$startupTime == 0) {
469 self::$startupTime = microtime(true);
473 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
477 * Destructor for all classes. You should not call this method on your own.
481 public function __destruct () {
482 // Flush any updated entries to the database
483 $this->flushPendingUpdates();
485 // Is this object already destroyed?
486 if ($this->__toString() != 'DestructedObject') {
487 // Destroy all informations about this class but keep some text about it alive
488 $this->setRealClass('DestructedObject');
489 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
490 // Already destructed object
491 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
495 // Do not call this twice
496 trigger_error(__METHOD__ . ': Called twice.');
502 * The __call() method where all non-implemented methods end up
504 * @param $methodName Name of the missing method
505 * @args $args Arguments passed to the method
508 public final function __call ($methodName, $args) {
509 return self::__callStatic($methodName, $args);
513 * The __callStatic() method where all non-implemented static methods end up
515 * @param $methodName Name of the missing method
516 * @args $args Arguments passed to the method
519 public static final function __callStatic ($methodName, $args) {
521 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
523 // Init argument string
526 // Is it NULL, empty or an array?
527 if (is_null($args)) {
529 $argsString = 'NULL';
530 } elseif (is_array($args)) {
534 // Some arguments are there
535 foreach ($args as $arg) {
536 // Add data about the argument
537 $argsString .= gettype($arg) . ':';
540 // Found a NULL argument
541 $argsString .= 'NULL';
542 } elseif (is_string($arg)) {
543 // Add length for strings
544 $argsString .= strlen($arg);
545 } elseif ((is_int($arg)) || (is_float($arg))) {
548 } elseif (is_array($arg)) {
549 // .. or size if array
550 $argsString .= count($arg);
551 } elseif (is_object($arg)) {
553 $reflection = new ReflectionClass($arg);
555 // Is an other object, maybe no __toString() available
556 $argsString .= $reflection->getName();
557 } elseif ($arg === true) {
558 // ... is boolean 'true'
559 $argsString .= 'true';
560 } elseif ($arg === false) {
561 // ... is boolean 'false'
562 $argsString .= 'false';
565 // Comma for next one
570 if (substr($argsString, -2, 1) == ',') {
571 $argsString = substr($argsString, 0, -2);
577 // Invalid arguments!
578 $argsString = '!INVALID:' . gettype($args) . '!';
581 // Output stub message
582 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
583 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
593 * Getter for $realClass
595 * @return $realClass The name of the real class (not BaseFrameworkSystem)
597 public function __toString () {
598 return $this->realClass;
602 * Magic method to catch setting of missing but set class fields/attributes
604 * @param $name Name of the field/attribute
605 * @param $value Value to store
608 public final function __set ($name, $value) {
609 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
612 print_r($value, true)
617 * Magic method to catch getting of missing fields/attributes
619 * @param $name Name of the field/attribute
622 public final function __get ($name) {
623 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
629 * Magic method to catch unsetting of missing fields/attributes
631 * @param $name Name of the field/attribute
634 public final function __unset ($name) {
635 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
641 * Magic method to catch object serialization
643 * @return $unsupported Unsupported method
644 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
646 public final function __sleep () {
647 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
651 * Magic method to catch object deserialization
653 * @return $unsupported Unsupported method
654 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
656 public final function __wakeup () {
657 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
661 * Magic method to catch calls when an object instance is called
663 * @return $unsupported Unsupported method
664 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
666 public final function __invoke () {
667 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
671 * Setter for the real class name
673 * @param $realClass Class name (string)
676 public final function setRealClass ($realClass) {
678 $this->realClass = (string) $realClass;
682 * Setter for database result instance
684 * @param $resultInstance An instance of a database result class
686 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
688 protected final function setResultInstance (SearchableResult $resultInstance) {
689 $this->resultInstance = $resultInstance;
693 * Getter for database result instance
695 * @return $resultInstance An instance of a database result class
697 public final function getResultInstance () {
698 return $this->resultInstance;
702 * Setter for template engine instances
704 * @param $templateInstance An instance of a template engine class
707 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
708 $this->templateInstance = $templateInstance;
712 * Getter for template engine instances
714 * @return $templateInstance An instance of a template engine class
716 protected final function getTemplateInstance () {
717 return $this->templateInstance;
721 * Setter for search instance
723 * @param $searchInstance Searchable criteria instance
726 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
727 $this->searchInstance = $searchInstance;
731 * Getter for search instance
733 * @return $searchInstance Searchable criteria instance
735 public final function getSearchInstance () {
736 return $this->searchInstance;
740 * Setter for update instance
742 * @param $updateInstance An instance of a LocalUpdateCriteria clase
745 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
746 $this->updateInstance = $updateInstance;
750 * Getter for update instance
752 * @return $updateInstance Updateable criteria instance
754 public final function getUpdateInstance () {
755 return $this->updateInstance;
759 * Setter for resolver instance
761 * @param $resolverInstance Instance of a command resolver class
764 public final function setResolverInstance (Resolver $resolverInstance) {
765 $this->resolverInstance = $resolverInstance;
769 * Getter for resolver instance
771 * @return $resolverInstance Instance of a command resolver class
773 public final function getResolverInstance () {
774 return $this->resolverInstance;
778 * Setter for language instance
780 * @param $configInstance The configuration instance which shall
781 * be FrameworkConfiguration
784 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
785 Registry::getRegistry()->addInstance('config', $configInstance);
789 * Getter for configuration instance
791 * @return $configInstance Configuration instance
793 public final function getConfigInstance () {
794 $configInstance = Registry::getRegistry()->getInstance('config');
795 return $configInstance;
799 * Setter for debug instance
801 * @param $debugInstance The instance for debug output class
804 public final function setDebugInstance (DebugMiddleware $debugInstance) {
805 Registry::getRegistry()->addInstance('debug', $debugInstance);
809 * Getter for debug instance
811 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
813 public final function getDebugInstance () {
814 // Get debug instance
815 $debugInstance = Registry::getRegistry()->getInstance('debug');
818 return $debugInstance;
822 * Setter for web output instance
824 * @param $webInstance The instance for web output class
827 public final function setWebOutputInstance (OutputStreamer $webInstance) {
828 Registry::getRegistry()->addInstance('web_output', $webInstance);
832 * Getter for web output instance
834 * @return $webOutputInstance - Instance to class WebOutput
836 public final function getWebOutputInstance () {
837 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
838 return $webOutputInstance;
842 * Setter for database instance
844 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
847 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
848 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
852 * Getter for database layer
854 * @return $databaseInstance The database layer instance
856 public final function getDatabaseInstance () {
858 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
861 return $databaseInstance;
865 * Setter for compressor channel
867 * @param $compressorInstance An instance of CompressorChannel
870 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
871 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
875 * Getter for compressor channel
877 * @return $compressorInstance The compressor channel
879 public final function getCompressorChannel () {
880 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
881 return $compressorInstance;
885 * Protected getter for a manageable application helper class
887 * @return $applicationInstance An instance of a manageable application helper class
889 protected final function getApplicationInstance () {
890 $applicationInstance = Registry::getRegistry()->getInstance('app');
891 return $applicationInstance;
895 * Setter for a manageable application helper class
897 * @param $applicationInstance An instance of a manageable application helper class
900 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
901 Registry::getRegistry()->addInstance('application', $applicationInstance);
905 * Private getter for language instance
907 * @return $langInstance An instance to the language sub-system
909 protected final function getLanguageInstance () {
910 $langInstance = Registry::getRegistry()->getInstance('language');
911 return $langInstance;
915 * Setter for language instance
917 * @param $langInstance An instance to the language sub-system
919 * @see LanguageSystem
921 public final function setLanguageInstance (ManageableLanguage $langInstance) {
922 Registry::getRegistry()->addInstance('language', $langInstance);
926 * Private getter for file IO instance
928 * @return $fileIoInstance An instance to the file I/O sub-system
930 protected final function getFileIoInstance () {
931 return $this->fileIoInstance;
935 * Setter for file I/O instance
937 * @param $fileIoInstance An instance to the file I/O sub-system
940 public final function setFileIoInstance (IoHandler $fileIoInstance) {
941 $this->fileIoInstance = $fileIoInstance;
945 * Protected setter for user instance
947 * @param $userInstance An instance of a user class
950 protected final function setUserInstance (ManageableAccount $userInstance) {
951 $this->userInstance = $userInstance;
955 * Getter for user instance
957 * @return $userInstance An instance of a user class
959 public final function getUserInstance () {
960 return $this->userInstance;
964 * Setter for controller instance (this surely breaks a bit the MVC patterm)
966 * @param $controllerInstance An instance of the controller
969 public final function setControllerInstance (Controller $controllerInstance) {
970 $this->controllerInstance = $controllerInstance;
974 * Getter for controller instance (this surely breaks a bit the MVC patterm)
976 * @return $controllerInstance An instance of the controller
978 public final function getControllerInstance () {
979 return $this->controllerInstance;
983 * Setter for RNG instance
985 * @param $rngInstance An instance of a random number generator (RNG)
988 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
989 $this->rngInstance = $rngInstance;
993 * Getter for RNG instance
995 * @return $rngInstance An instance of a random number generator (RNG)
997 public final function getRngInstance () {
998 return $this->rngInstance;
1002 * Setter for Cryptable instance
1004 * @param $cryptoInstance An instance of a Cryptable class
1007 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1008 $this->cryptoInstance = $cryptoInstance;
1012 * Getter for Cryptable instance
1014 * @return $cryptoInstance An instance of a Cryptable class
1016 public final function getCryptoInstance () {
1017 return $this->cryptoInstance;
1021 * Setter for the list instance
1023 * @param $listInstance A list of Listable
1026 protected final function setListInstance (Listable $listInstance) {
1027 $this->listInstance = $listInstance;
1031 * Getter for the list instance
1033 * @return $listInstance A list of Listable
1035 protected final function getListInstance () {
1036 return $this->listInstance;
1040 * Setter for the menu instance
1042 * @param $menuInstance A RenderableMenu instance
1045 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1046 $this->menuInstance = $menuInstance;
1050 * Getter for the menu instance
1052 * @return $menuInstance A RenderableMenu instance
1054 protected final function getMenuInstance () {
1055 return $this->menuInstance;
1059 * Setter for image instance
1061 * @param $imageInstance An instance of an image
1064 public final function setImageInstance (BaseImage $imageInstance) {
1065 $this->imageInstance = $imageInstance;
1069 * Getter for image instance
1071 * @return $imageInstance An instance of an image
1073 public final function getImageInstance () {
1074 return $this->imageInstance;
1078 * Setter for stacker instance
1080 * @param $stackInstance An instance of an stacker
1083 public final function setStackInstance (Stackable $stackInstance) {
1084 $this->stackInstance = $stackInstance;
1088 * Getter for stacker instance
1090 * @return $stackInstance An instance of an stacker
1092 public final function getStackInstance () {
1093 return $this->stackInstance;
1097 * Setter for compressor instance
1099 * @param $compressorInstance An instance of an compressor
1102 public final function setCompressorInstance (Compressor $compressorInstance) {
1103 $this->compressorInstance = $compressorInstance;
1107 * Getter for compressor instance
1109 * @return $compressorInstance An instance of an compressor
1111 public final function getCompressorInstance () {
1112 return $this->compressorInstance;
1116 * Setter for Parseable instance
1118 * @param $parserInstance An instance of an Parseable
1121 public final function setParserInstance (Parseable $parserInstance) {
1122 $this->parserInstance = $parserInstance;
1126 * Getter for Parseable instance
1128 * @return $parserInstance An instance of an Parseable
1130 public final function getParserInstance () {
1131 return $this->parserInstance;
1135 * Setter for DatabaseWrapper instance
1137 * @param $wrapperInstance An instance of an DatabaseWrapper
1140 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1141 $this->wrapperInstance = $wrapperInstance;
1145 * Getter for DatabaseWrapper instance
1147 * @return $wrapperInstance An instance of an DatabaseWrapper
1149 public final function getWrapperInstance () {
1150 return $this->wrapperInstance;
1154 * Setter for socket resource
1156 * @param $socketResource A valid socket resource
1159 public final function setSocketResource ($socketResource) {
1160 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1161 $this->socketResource = $socketResource;
1165 * Getter for socket resource
1167 * @return $socketResource A valid socket resource
1169 public final function getSocketResource () {
1170 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1171 return $this->socketResource;
1175 * Setter for regular expression
1177 * @param $regularExpression A valid regular expression
1180 public final function setRegularExpression ($regularExpression) {
1181 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1182 $this->regularExpression = $regularExpression;
1186 * Getter for regular expression
1188 * @return $regularExpression A valid regular expression
1190 public final function getRegularExpression () {
1191 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1192 return $this->regularExpression;
1196 * Setter for helper instance
1198 * @param $helperInstance An instance of a helper class
1201 protected final function setHelperInstance (Helper $helperInstance) {
1202 $this->helperInstance = $helperInstance;
1206 * Getter for helper instance
1208 * @return $helperInstance An instance of a helper class
1210 public final function getHelperInstance () {
1211 return $this->helperInstance;
1215 * Setter for a Source instance
1217 * @param $sourceInstance An instance of a Source class
1220 protected final function setSourceInstance (Source $sourceInstance) {
1221 $this->sourceInstance = $sourceInstance;
1225 * Getter for a Source instance
1227 * @return $sourceInstance An instance of a Source class
1229 protected final function getSourceInstance () {
1230 return $this->sourceInstance;
1234 * Setter for a UrlSource instance
1236 * @param $sourceInstance An instance of a UrlSource class
1239 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1240 $this->urlSourceInstance = $urlSourceInstance;
1244 * Getter for a UrlSource instance
1246 * @return $urlSourceInstance An instance of a UrlSource class
1248 protected final function getUrlSourceInstance () {
1249 return $this->urlSourceInstance;
1253 * Getter for a InputStream instance
1255 * @param $inputStreamInstance The InputStream instance
1257 protected final function getInputStreamInstance () {
1258 return $this->inputStreamInstance;
1262 * Setter for a InputStream instance
1264 * @param $inputStreamInstance The InputStream instance
1267 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1268 $this->inputStreamInstance = $inputStreamInstance;
1272 * Getter for a OutputStream instance
1274 * @param $outputStreamInstance The OutputStream instance
1276 protected final function getOutputStreamInstance () {
1277 return $this->outputStreamInstance;
1281 * Setter for a OutputStream instance
1283 * @param $outputStreamInstance The OutputStream instance
1286 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1287 $this->outputStreamInstance = $outputStreamInstance;
1291 * Setter for handler instance
1293 * @param $handlerInstance An instance of a Handleable class
1296 protected final function setHandlerInstance (Handleable $handlerInstance) {
1297 $this->handlerInstance = $handlerInstance;
1301 * Getter for handler instance
1303 * @return $handlerInstance A Handleable instance
1305 protected final function getHandlerInstance () {
1306 return $this->handlerInstance;
1310 * Setter for visitor instance
1312 * @param $visitorInstance A Visitor instance
1315 protected final function setVisitorInstance (Visitor $visitorInstance) {
1316 $this->visitorInstance = $visitorInstance;
1320 * Getter for visitor instance
1322 * @return $visitorInstance A Visitor instance
1324 protected final function getVisitorInstance () {
1325 return $this->visitorInstance;
1329 * Setter for raw package Data
1331 * @param $packageData Raw package Data
1334 public final function setPackageData (array $packageData) {
1335 $this->packageData = $packageData;
1339 * Getter for raw package Data
1341 * @return $packageData Raw package Data
1343 public function getPackageData () {
1344 return $this->packageData;
1349 * Setter for Iterator instance
1351 * @param $iteratorInstance An instance of an Iterator
1354 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1355 $this->iteratorInstance = $iteratorInstance;
1359 * Getter for Iterator instance
1361 * @return $iteratorInstance An instance of an Iterator
1363 public final function getIteratorInstance () {
1364 return $this->iteratorInstance;
1368 * Setter for FilePointer instance
1370 * @param $pointerInstance An instance of an FilePointer class
1373 protected final function setPointerInstance (FilePointer $pointerInstance) {
1374 $this->pointerInstance = $pointerInstance;
1378 * Getter for FilePointer instance
1380 * @return $pointerInstance An instance of an FilePointer class
1382 public final function getPointerInstance () {
1383 return $this->pointerInstance;
1387 * Unsets pointer instance which triggers a call of __destruct() if the
1388 * instance is still there. This is surely not fatal on already "closed"
1389 * file pointer instances.
1391 * I don't want to mess around with above setter by giving it a default
1392 * value NULL as setter should always explicitly only set (existing) object
1393 * instances and NULL is NULL.
1397 protected final function unsetPointerInstance () {
1398 // Simply it to NULL
1399 $this->pointerInstance = NULL;
1403 * Setter for Indexable instance
1405 * @param $indexInstance An instance of an Indexable class
1408 protected final function setIndexInstance (Indexable $indexInstance) {
1409 $this->indexInstance = $indexInstance;
1413 * Getter for Indexable instance
1415 * @return $indexInstance An instance of an Indexable class
1417 public final function getIndexInstance () {
1418 return $this->indexInstance;
1422 * Setter for Block instance
1424 * @param $blockInstance An instance of an Block class
1427 protected final function setBlockInstance (Block $blockInstance) {
1428 $this->blockInstance = $blockInstance;
1432 * Getter for Block instance
1434 * @return $blockInstance An instance of an Block class
1436 public final function getBlockInstance () {
1437 return $this->blockInstance;
1441 * Setter for Minable instance
1443 * @param $minableInstance A Minable instance
1446 protected final function setMinableInstance (Minable $minableInstance) {
1447 $this->minableInstance = $minableInstance;
1451 * Getter for minable instance
1453 * @return $minableInstance A Minable instance
1455 protected final function getMinableInstance () {
1456 return $this->minableInstance;
1460 * Setter for FrameworkDirectory instance
1462 * @param $directoryInstance A FrameworkDirectory instance
1465 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1466 $this->directoryInstance = $directoryInstance;
1470 * Getter for FrameworkDirectory instance
1472 * @return $directoryInstance A FrameworkDirectory instance
1474 protected final function getDirectoryInstance () {
1475 return $this->directoryInstance;
1479 * Getter for communicator instance
1481 * @return $communicatorInstance An instance of a Communicator class
1483 public final function getCommunicatorInstance () {
1484 return $this->communicatorInstance;
1488 * Setter for communicator instance
1490 * @param $communicatorInstance An instance of a Communicator class
1493 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1494 $this->communicatorInstance = $communicatorInstance;
1498 * Setter for state instance
1500 * @param $stateInstance A Stateable instance
1503 public final function setStateInstance (Stateable $stateInstance) {
1504 $this->stateInstance = $stateInstance;
1508 * Getter for state instance
1510 * @return $stateInstance A Stateable instance
1512 public final function getStateInstance () {
1513 return $this->stateInstance;
1517 * Setter for output instance
1519 * @param $outputInstance The debug output instance
1522 public final function setOutputInstance (OutputStreamer $outputInstance) {
1523 $this->outputInstance = $outputInstance;
1527 * Getter for output instance
1529 * @return $outputInstance The debug output instance
1531 public final function getOutputInstance () {
1532 return $this->outputInstance;
1536 * Setter for registry instance
1538 * @param $registryInstance An instance of a Register class
1541 protected final function setRegistryInstance (Register $registryInstance) {
1542 $this->registryInstance = $registryInstance;
1546 * Getter for registry instance
1548 * @return $registryInstance The debug registry instance
1550 public final function getRegistryInstance () {
1551 return $this->registryInstance;
1555 * Setter for command name
1557 * @param $commandName Last validated command name
1560 protected final function setCommandName ($commandName) {
1561 $this->commandName = $commandName;
1565 * Getter for command name
1567 * @return $commandName Last validated command name
1569 protected final function getCommandName () {
1570 return $this->commandName;
1574 * Setter for controller name
1576 * @param $controllerName Last validated controller name
1579 protected final function setControllerName ($controllerName) {
1580 $this->controllerName = $controllerName;
1584 * Getter for controller name
1586 * @return $controllerName Last validated controller name
1588 protected final function getControllerName () {
1589 return $this->controllerName;
1593 * Checks whether an object equals this object. You should overwrite this
1594 * method to implement own equality checks
1596 * @param $objectInstance An instance of a FrameworkInterface object
1597 * @return $equals Whether both objects equals
1599 public function equals (FrameworkInterface $objectInstance) {
1602 $this->__toString() == $objectInstance->__toString()
1604 $this->hashCode() == $objectInstance->hashCode()
1607 // Return the result
1612 * Generates a generic hash code of this class. You should really overwrite
1613 * this method with your own hash code generator code. But keep KISS in mind.
1615 * @return $hashCode A generic hash code respresenting this whole class
1617 public function hashCode () {
1619 return crc32($this->__toString());
1623 * Formats computer generated price values into human-understandable formats
1624 * with thousand and decimal separators.
1626 * @param $value The in computer format value for a price
1627 * @param $currency The currency symbol (use HTML-valid characters!)
1628 * @param $decNum Number of decimals after commata
1629 * @return $price The for the current language formated price string
1630 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1631 * thousands separator
1634 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1635 // Are all required attriutes set?
1636 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1637 // Throw an exception
1638 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1642 $value = (float) $value;
1644 // Reformat the US number
1645 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1647 // Return as string...
1652 * Appends a trailing slash to a string
1654 * @param $str A string (maybe) without trailing slash
1655 * @return $str A string with an auto-appended trailing slash
1657 public final function addMissingTrailingSlash ($str) {
1658 // Is there a trailing slash?
1659 if (substr($str, -1, 1) != '/') {
1663 // Return string with trailing slash
1668 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1669 * application helper instance (ApplicationHelper by default).
1671 * @param $applicationInstance An application helper instance or
1672 * null if we shall use the default
1673 * @return $templateInstance The template engine instance
1674 * @throws NullPointerException If the discovered application
1675 * instance is still null
1677 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1678 // Is the application instance set?
1679 if (is_null($applicationInstance)) {
1680 // Get the current instance
1681 $applicationInstance = Registry::getRegistry()->getInstance('app');
1684 if (is_null($applicationInstance)) {
1685 // Thrown an exception
1686 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1690 // Initialize the template engine
1691 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1693 // Return the prepared instance
1694 return $templateInstance;
1698 * Debugs this instance by putting out it's full content
1700 * @param $message Optional message to show in debug output
1703 public final function debugInstance ($message = '') {
1704 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1705 restore_error_handler();
1710 // Is a message set?
1711 if (!empty($message)) {
1712 // Construct message
1713 $content = sprintf('<div class="debug_message">
1715 </div>' . PHP_EOL, $message);
1718 // Generate the output
1719 $content .= sprintf('<pre>%s</pre>',
1722 print_r($this, true)
1728 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">
1731 <div class="debug_content">
1735 <div class="debug_include_list">
1738 $this->__toString(),
1740 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1745 * Replaces control characters with printable output
1747 * @param $str String with control characters
1748 * @return $str Replaced string
1750 protected function replaceControlCharacters ($str) {
1753 chr(13), '[r]', str_replace(
1754 chr(10), '[n]', str_replace(
1764 * Output a partial stub message for the caller method
1766 * @param $message An optional message to display
1769 protected function partialStub ($message = '') {
1771 $stubMessage = 'Partial Stub!';
1773 // Is the extra message given?
1774 if (!empty($message)) {
1775 // Then add it as well
1776 $stubMessage .= ' Message: ' . $message;
1779 // Debug instance is there?
1780 if (!is_null($this->getDebugInstance())) {
1781 // Output stub message
1782 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1785 trigger_error($stubMessage);
1791 * Outputs a debug backtrace and stops further script execution
1793 * @param $message An optional message to output
1794 * @param $doExit Whether exit the program (true is default)
1797 public function debugBackTrace ($message = '', $doExit = true) {
1798 // Sorry, there is no other way getting this nice backtrace
1799 if (!empty($message)) {
1801 printf('Message: %s<br />' . PHP_EOL, $message);
1805 debug_print_backtrace();
1809 if ($doExit === true) {
1815 * Creates an instance of a debugger instance
1817 * @param $className Name of the class (currently unsupported)
1818 * @param $lineNumber Line number where the call was made
1819 * @return $debugInstance An instance of a debugger class
1820 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1822 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1823 // Is the instance set?
1824 if (!Registry::getRegistry()->instanceExists('debug')) {
1825 // Init debug instance
1826 $debugInstance = NULL;
1830 // Get a debugger instance
1831 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1832 } catch (NullPointerException $e) {
1833 // Didn't work, no instance there
1834 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1837 // Empty string should be ignored and used for testing the middleware
1838 DebugMiddleware::getSelfInstance()->output('');
1840 // Set it in registry
1841 Registry::getRegistry()->addInstance('debug', $debugInstance);
1843 // Get instance from registry
1844 $debugInstance = Registry::getRegistry()->getInstance('debug');
1848 return $debugInstance;
1852 * Simple output of a message with line-break
1854 * @param $message Message to output
1857 public function outputLine ($message) {
1859 print($message . PHP_EOL);
1863 * Outputs a debug message whether to debug instance (should be set!) or
1864 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1865 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1867 * @param $message Message we shall send out...
1868 * @param $doPrint Whether print or die here (default: print)
1869 * @paran $stripTags Whether to strip tags (default: false)
1872 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1873 // Set debug instance to NULL
1874 $debugInstance = NULL;
1877 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1879 // Is function partialStub/__callStatic ?
1880 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1881 // Prepend class::function:line from 3rd element
1882 $message = sprintf('[%s::%s:%d]: %s',
1883 $backtrace[2]['class'],
1884 $backtrace[2]['function'],
1885 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1889 // Prepend class::function:line from 2nd element
1890 $message = sprintf('[%s::%s:%d]: %s',
1891 $backtrace[1]['class'],
1892 $backtrace[1]['function'],
1893 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1900 // Get debug instance
1901 $debugInstance = $this->getDebugInstance();
1902 } catch (NullPointerException $e) {
1903 // The debug instance is not set (yet)
1906 // Is the debug instance there?
1907 if (is_object($debugInstance)) {
1908 // Use debug output handler
1909 $debugInstance->output($message, $stripTags);
1911 if ($doPrint === false) {
1912 // Die here if not printed
1916 // Are debug times enabled?
1917 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1919 $message = $this->getPrintableExecutionTime() . $message;
1923 if ($doPrint === true) {
1925 $this->outputLine($message);
1934 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1936 * @param $str The string, what ever it is needs to be converted
1937 * @return $className Generated class name
1939 public static final function convertToClassName ($str) {
1943 // Convert all dashes in underscores
1944 $str = self::convertDashesToUnderscores($str);
1946 // Now use that underscores to get classname parts for hungarian style
1947 foreach (explode('_', $str) as $strPart) {
1948 // Make the class name part lower case and first upper case
1949 $className .= ucfirst(strtolower($strPart));
1952 // Return class name
1957 * Converts dashes to underscores, e.g. useable for configuration entries
1959 * @param $str The string with maybe dashes inside
1960 * @return $str The converted string with no dashed, but underscores
1962 public static final function convertDashesToUnderscores ($str) {
1964 $str = str_replace('-', '_', $str);
1966 // Return converted string
1971 * Marks up the code by adding e.g. line numbers
1973 * @param $phpCode Unmarked PHP code
1974 * @return $markedCode Marked PHP code
1976 public function markupCode ($phpCode) {
1981 $errorArray = error_get_last();
1983 // Init the code with error message
1984 if (is_array($errorArray)) {
1986 $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>',
1987 basename($errorArray['file']),
1988 $errorArray['line'],
1989 $errorArray['message'],
1994 // Add line number to the code
1995 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1997 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1999 htmlentities($code, ENT_QUOTES)
2008 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2009 * beatiful for web-based front-ends. If null is given a message id
2010 * null_timestamp will be resolved and returned.
2012 * @param $timestamp Timestamp to prepare (filter) for display
2013 * @return $readable A readable timestamp
2015 public function doFilterFormatTimestamp ($timestamp) {
2016 // Default value to return
2019 // Is the timestamp null?
2020 if (is_null($timestamp)) {
2021 // Get a message string
2022 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2024 switch ($this->getLanguageInstance()->getLanguageCode()) {
2025 case 'de': // German format is a bit different to default
2026 // Split the GMT stamp up
2027 $dateTime = explode(' ', $timestamp );
2028 $dateArray = explode('-', $dateTime[0]);
2029 $timeArray = explode(':', $dateTime[1]);
2031 // Construct the timestamp
2032 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2042 default: // Default is pass-through
2043 $readable = $timestamp;
2053 * Filter a given number into a localized number
2055 * @param $value The raw value from e.g. database
2056 * @return $localized Localized value
2058 public function doFilterFormatNumber ($value) {
2059 // Generate it from config and localize dependencies
2060 switch ($this->getLanguageInstance()->getLanguageCode()) {
2061 case 'de': // German format is a bit different to default
2062 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2065 default: // US, etc.
2066 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2075 * "Getter" for databse entry
2077 * @return $entry An array with database entries
2078 * @throws NullPointerException If the database result is not found
2079 * @throws InvalidDatabaseResultException If the database result is invalid
2081 protected final function getDatabaseEntry () {
2082 // Is there an instance?
2083 if (!$this->getResultInstance() instanceof SearchableResult) {
2084 // Throw an exception here
2085 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2089 $this->getResultInstance()->rewind();
2091 // Do we have an entry?
2092 if ($this->getResultInstance()->valid() === false) {
2093 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2094 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2098 $this->getResultInstance()->next();
2101 $entry = $this->getResultInstance()->current();
2108 * Getter for field name
2110 * @param $fieldName Field name which we shall get
2111 * @return $fieldValue Field value from the user
2112 * @throws NullPointerException If the result instance is null
2114 public final function getField ($fieldName) {
2115 // Default field value
2118 // Get result instance
2119 $resultInstance = $this->getResultInstance();
2121 // Is this instance null?
2122 if (is_null($resultInstance)) {
2123 // Then the user instance is no longer valid (expired cookies?)
2124 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2127 // Get current array
2128 $fieldArray = $resultInstance->current();
2129 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2131 // Convert dashes to underscore
2132 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2134 // Does the field exist?
2135 if ($this->isFieldSet($fieldName)) {
2137 $fieldValue = $fieldArray[$fieldName2];
2138 } elseif (defined('DEVELOPER')) {
2139 // Missing field entry, may require debugging
2140 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2142 // Missing field entry, may require debugging
2143 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2151 * Checks if given field is set
2153 * @param $fieldName Field name to check
2154 * @return $isSet Whether the given field name is set
2155 * @throws NullPointerException If the result instance is null
2157 public function isFieldSet ($fieldName) {
2158 // Get result instance
2159 $resultInstance = $this->getResultInstance();
2161 // Is this instance null?
2162 if (is_null($resultInstance)) {
2163 // Then the user instance is no longer valid (expired cookies?)
2164 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2167 // Get current array
2168 $fieldArray = $resultInstance->current();
2169 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2171 // Convert dashes to underscore
2172 $fieldName = self::convertDashesToUnderscores($fieldName);
2175 $isSet = isset($fieldArray[$fieldName]);
2182 * Flushs all pending updates to the database layer
2186 public function flushPendingUpdates () {
2187 // Get result instance
2188 $resultInstance = $this->getResultInstance();
2190 // Do we have data to update?
2191 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2192 // Get wrapper class name config entry
2193 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2195 // Create object instance
2196 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2198 // Yes, then send the whole result to the database layer
2199 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2204 * Outputs a deprecation warning to the developer.
2206 * @param $message The message we shall output to the developer
2208 * @todo Write a logging mechanism for productive mode
2210 public function deprecationWarning ($message) {
2211 // Is developer mode active?
2212 if (defined('DEVELOPER')) {
2213 // Debug instance is there?
2214 if (!is_null($this->getDebugInstance())) {
2215 // Output stub message
2216 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2219 trigger_error($message . "<br />\n");
2223 // @TODO Finish this part!
2224 $this->partialStub('Developer mode inactive. Message:' . $message);
2229 * Checks whether the given PHP extension is loaded
2231 * @param $phpExtension The PHP extension we shall check
2232 * @return $isLoaded Whether the PHP extension is loaded
2234 public final function isPhpExtensionLoaded ($phpExtension) {
2236 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2243 * "Getter" as a time() replacement but with milliseconds. You should use this
2244 * method instead of the encapsulated getimeofday() function.
2246 * @return $milliTime Timestamp with milliseconds
2248 public function getMilliTime () {
2249 // Get the time of day as float
2250 $milliTime = gettimeofday(true);
2257 * Idles (sleeps) for given milliseconds
2259 * @return $hasSlept Whether it goes fine
2261 public function idle ($milliSeconds) {
2262 // Sleep is fine by default
2265 // Idle so long with found function
2266 if (function_exists('time_sleep_until')) {
2267 // Get current time and add idle time
2268 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2270 // New PHP 5.1.0 function found, ignore errors
2271 $hasSlept = @time_sleep_until($sleepUntil);
2274 * My Sun station doesn't have that function even with latest PHP
2277 usleep($milliSeconds * 1000);
2284 * Converts a hexadecimal string, even with negative sign as first string to
2285 * a decimal number using BC functions.
2287 * This work is based on comment #86673 on php.net documentation page at:
2288 * <http://de.php.net/manual/en/function.dechex.php#86673>
2290 * @param $hex Hexadecimal string
2291 * @return $dec Decimal number
2293 protected function hex2dec ($hex) {
2294 // Convert to all lower-case
2295 $hex = strtolower($hex);
2297 // Detect sign (negative/positive numbers)
2299 if (substr($hex, 0, 1) == '-') {
2301 $hex = substr($hex, 1);
2304 // Decode the hexadecimal string into a decimal number
2306 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2307 $factor = self::$hexdec[substr($hex, $i, 1)];
2308 $dec = bcadd($dec, bcmul($factor, $e));
2311 // Return the decimal number
2312 return $sign . $dec;
2316 * Converts even very large decimal numbers, also signed, to a hexadecimal
2319 * This work is based on comment #97756 on php.net documentation page at:
2320 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2322 * @param $dec Decimal number, even with negative sign
2323 * @param $maxLength Optional maximum length of the string
2324 * @return $hex Hexadecimal string
2326 protected function dec2hex ($dec, $maxLength = 0) {
2327 // maxLength can be zero or devideable by 2
2328 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2330 // Detect sign (negative/positive numbers)
2337 // Encode the decimal number into a hexadecimal string
2340 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2342 } while ($dec >= 1);
2345 * Leading zeros are required for hex-decimal "numbers". In some
2346 * situations more leading zeros are wanted, so check for both
2349 if ($maxLength > 0) {
2350 // Prepend more zeros
2351 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2352 } elseif ((strlen($hex) % 2) != 0) {
2353 // Only make string's length dividable by 2
2357 // Return the hexadecimal string
2358 return $sign . $hex;
2362 * Converts a ASCII string (0 to 255) into a decimal number.
2364 * @param $asc The ASCII string to be converted
2365 * @return $dec Decimal number
2367 protected function asc2dec ($asc) {
2368 // Convert it into a hexadecimal number
2369 $hex = bin2hex($asc);
2371 // And back into a decimal number
2372 $dec = $this->hex2dec($hex);
2379 * Converts a decimal number into an ASCII string.
2381 * @param $dec Decimal number
2382 * @return $asc An ASCII string
2384 protected function dec2asc ($dec) {
2385 // First convert the number into a hexadecimal string
2386 $hex = $this->dec2hex($dec);
2388 // Then convert it into the ASCII string
2389 $asc = $this->hex2asc($hex);
2396 * Converts a hexadecimal number into an ASCII string. Negative numbers
2399 * @param $hex Hexadecimal string
2400 * @return $asc An ASCII string
2402 protected function hex2asc ($hex) {
2403 // Check for length, it must be devideable by 2
2404 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2405 assert((strlen($hex) % 2) == 0);
2409 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2410 // Get the decimal number of the chunk
2411 $part = hexdec(substr($hex, $idx, 2));
2413 // Add it to the final string
2417 // Return the final string
2422 * Checks whether the given encoded data was encoded with Base64
2424 * @param $encodedData Encoded data we shall check
2425 * @return $isBase64 Whether the encoded data is Base64
2427 protected function isBase64Encoded ($encodedData) {
2429 $isBase64 = (@base64_decode($encodedData, true) !== false);
2436 * Gets a cache key from Criteria instance
2438 * @param $criteriaInstance An instance of a Criteria class
2439 * @param $onlyKeys Only use these keys for a cache key
2440 * @return $cacheKey A cache key suitable for lookup/storage purposes
2442 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2444 $cacheKey = sprintf('%s@%s',
2445 $this->__toString(),
2446 $criteriaInstance->getCacheKey($onlyKeys)
2450 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2455 * Getter for startup time in miliseconds
2457 * @return $startupTime Startup time in miliseconds
2459 protected function getStartupTime () {
2460 return self::$startupTime;
2464 * "Getter" for a printable currently execution time in nice braces
2466 * @return $executionTime Current execution time in nice braces
2468 protected function getPrintableExecutionTime () {
2469 // Caculate the execution time
2470 $executionTime = microtime(true) - $this->getStartupTime();
2472 // Pack it in nice braces
2473 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2476 return $executionTime;
2480 * Hashes a given string with a simple but stronger hash function (no salt)
2481 * and hex-encode it.
2483 * @param $str The string to be hashed
2484 * @return $hash The hash from string $str
2486 public static final function hash ($str) {
2487 // Hash given string with (better secure) hasher
2488 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2495 * "Getter" for length of hash() output. This will be "cached" to speed up
2498 * @return $length Length of hash() output
2500 public static final function getHashLength () {
2502 if (is_null(self::$hashLength)) {
2503 // No, then hash a string and save its length.
2504 self::$hashLength = strlen(self::hash('abc123'));
2508 return self::$hashLength;
2512 * Checks whether the given number is really a number (only chars 0-9).
2514 * @param $num A string consisting only chars between 0 and 9
2515 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2516 * @param $assertMismatch Whether to assert mismatches
2517 * @return $ret The (hopefully) secured numbered value
2519 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2520 // Filter all numbers out
2521 $ret = preg_replace('/[^0123456789]/', '', $num);
2524 if ($castValue === true) {
2525 // Cast to biggest numeric type
2526 $ret = (double) $ret;
2529 // Assert only if requested
2530 if ($assertMismatch === true) {
2531 // Has the whole value changed?
2532 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2540 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2542 * @param $num A string consisting only chars between 0 and 9
2543 * @param $assertMismatch Whether to assert mismatches
2544 * @return $ret The (hopefully) secured hext-numbered value
2546 public function hexval ($num, $assertMismatch = false) {
2547 // Filter all numbers out
2548 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2550 // Assert only if requested
2551 if ($assertMismatch === true) {
2552 // Has the whole value changed?
2553 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2561 * Determines if an element is set in the generic array
2563 * @param $keyGroup Main group for the key
2564 * @param $subGroup Sub group for the key
2565 * @param $key Key to check
2566 * @param $element Element to check
2567 * @return $isset Whether the given key is set
2569 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2571 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2574 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2580 * Determines if a key is set in the generic array
2582 * @param $keyGroup Main group for the key
2583 * @param $subGroup Sub group for the key
2584 * @param $key Key to check
2585 * @return $isset Whether the given key is set
2587 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2589 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2592 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2600 * Determines if a group is set in the generic array
2602 * @param $keyGroup Main group
2603 * @param $subGroup Sub group
2604 * @return $isset Whether the given group is set
2606 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2608 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2611 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2618 * Getter for sub key group
2620 * @param $keyGroup Main key group
2621 * @param $subGroup Sub key group
2622 * @return $array An array with all array elements
2624 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2626 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2627 // No, then abort here
2628 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2633 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2636 return $this->genericArray[$keyGroup][$subGroup];
2640 * Unsets a given key in generic array
2642 * @param $keyGroup Main group for the key
2643 * @param $subGroup Sub group for the key
2644 * @param $key Key to unset
2647 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2649 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2652 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2656 * Unsets a given element in generic array
2658 * @param $keyGroup Main group for the key
2659 * @param $subGroup Sub group for the key
2660 * @param $key Key to unset
2661 * @param $element Element to unset
2664 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2666 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2669 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2673 * Append a string to a given generic array key
2675 * @param $keyGroup Main group for the key
2676 * @param $subGroup Sub group for the key
2677 * @param $key Key to unset
2678 * @param $value Value to add/append
2681 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2683 //* 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);
2685 // Is it already there?
2686 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2688 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2691 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2696 * Append a string to a given generic array element
2698 * @param $keyGroup Main group for the key
2699 * @param $subGroup Sub group for the key
2700 * @param $key Key to unset
2701 * @param $element Element to check
2702 * @param $value Value to add/append
2705 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2707 //* 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);
2709 // Is it already there?
2710 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2712 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2715 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2720 * Sets a string in a given generic array element
2722 * @param $keyGroup Main group for the key
2723 * @param $subGroup Sub group for the key
2724 * @param $key Key to unset
2725 * @param $element Element to check
2726 * @param $value Value to add/append
2729 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2731 //* 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);
2734 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2738 * Initializes given generic array group
2740 * @param $keyGroup Main group for the key
2741 * @param $subGroup Sub group for the key
2742 * @param $key Key to use
2743 * @param $forceInit Optionally force initialization
2746 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2748 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2750 // Is it already set?
2751 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2752 // Already initialized
2753 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2758 $this->genericArray[$keyGroup][$subGroup] = array();
2762 * Initializes given generic array key
2764 * @param $keyGroup Main group for the key
2765 * @param $subGroup Sub group for the key
2766 * @param $key Key to use
2767 * @param $forceInit Optionally force initialization
2770 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2772 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2774 // Is it already set?
2775 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2776 // Already initialized
2777 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2782 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2786 * Initializes given generic array element
2788 * @param $keyGroup Main group for the key
2789 * @param $subGroup Sub group for the key
2790 * @param $key Key to use
2791 * @param $element Element to use
2792 * @param $forceInit Optionally force initialization
2795 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2797 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2799 // Is it already set?
2800 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2801 // Already initialized
2802 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2807 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2811 * Pushes an element to a generic key
2813 * @param $keyGroup Main group for the key
2814 * @param $subGroup Sub group for the key
2815 * @param $key Key to use
2816 * @param $value Value to add/append
2817 * @return $count Number of array elements
2819 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2821 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2824 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2826 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2830 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2833 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2834 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2839 * Pushes an element to a generic array element
2841 * @param $keyGroup Main group for the key
2842 * @param $subGroup Sub group for the key
2843 * @param $key Key to use
2844 * @param $element Element to check
2845 * @param $value Value to add/append
2846 * @return $count Number of array elements
2848 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2850 //* 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));
2853 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2855 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2859 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2862 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2863 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2868 * Pops an element from a generic group
2870 * @param $keyGroup Main group for the key
2871 * @param $subGroup Sub group for the key
2872 * @param $key Key to unset
2873 * @return $value Last "popped" value
2875 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2877 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2880 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2882 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2887 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2890 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2891 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2896 * Shifts an element from a generic group
2898 * @param $keyGroup Main group for the key
2899 * @param $subGroup Sub group for the key
2900 * @param $key Key to unset
2901 * @return $value Last "popped" value
2903 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2905 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2908 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2910 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2915 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2918 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2919 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2924 * Count generic array group
2926 * @param $keyGroup Main group for the key
2927 * @return $count Count of given group
2929 protected final function countGenericArray ($keyGroup) {
2931 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2934 if (!isset($this->genericArray[$keyGroup])) {
2936 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2941 $count = count($this->genericArray[$keyGroup]);
2944 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2951 * Count generic array sub group
2953 * @param $keyGroup Main group for the key
2954 * @param $subGroup Sub group for the key
2955 * @return $count Count of given group
2957 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2959 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2962 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2964 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2969 $count = count($this->genericArray[$keyGroup][$subGroup]);
2972 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2979 * Count generic array elements
2981 * @param $keyGroup Main group for the key
2982 * @param $subGroup Sub group for the key
2983 * @para $key Key to count
2984 * @return $count Count of given key
2986 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2988 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2991 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2993 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2995 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2997 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3002 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3005 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3012 * Getter for whole generic group array
3014 * @param $keyGroup Key group to get
3015 * @return $array Whole generic array group
3017 protected final function getGenericArray ($keyGroup) {
3019 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3022 if (!isset($this->genericArray[$keyGroup])) {
3024 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3029 return $this->genericArray[$keyGroup];
3033 * Setter for generic array key
3035 * @param $keyGroup Key group to get
3036 * @param $subGroup Sub group for the key
3037 * @param $key Key to unset
3038 * @param $value Mixed value from generic array element
3041 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3043 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3046 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3050 * Getter for generic array key
3052 * @param $keyGroup Key group to get
3053 * @param $subGroup Sub group for the key
3054 * @param $key Key to unset
3055 * @return $value Mixed value from generic array element
3057 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3059 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3062 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3064 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3069 return $this->genericArray[$keyGroup][$subGroup][$key];
3073 * Sets a value in given generic array key/element
3075 * @param $keyGroup Main group for the key
3076 * @param $subGroup Sub group for the key
3077 * @param $key Key to set
3078 * @param $element Element to set
3079 * @param $value Value to set
3082 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3084 //* 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));
3087 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3091 * Getter for generic array element
3093 * @param $keyGroup Key group to get
3094 * @param $subGroup Sub group for the key
3095 * @param $key Key to look for
3096 * @param $element Element to look for
3097 * @return $value Mixed value from generic array element
3099 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3101 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3104 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3106 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3111 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3115 * Checks if a given sub group is valid (array)
3117 * @param $keyGroup Key group to get
3118 * @param $subGroup Sub group for the key
3119 * @return $isValid Whether given sub group is valid
3121 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3123 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3126 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3133 * Checks if a given key is valid (array)
3135 * @param $keyGroup Key group to get
3136 * @param $subGroup Sub group for the key
3137 * @param $key Key to check
3138 * @return $isValid Whether given sub group is valid
3140 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3142 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3145 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3152 * Initializes the web output instance
3156 protected function initWebOutputInstance () {
3157 // Get application instance
3158 $applicationInstance = Registry::getRegistry()->getInstance('app');
3160 // Init web output instance
3161 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3164 $this->setWebOutputInstance($outputInstance);
3168 * Translates boolean true to 'Y' and false to 'N'
3170 * @param $boolean Boolean value
3171 * @return $translated Translated boolean value
3173 public static final function translateBooleanToYesNo ($boolean) {
3174 // Make sure it is really boolean
3175 assert(is_bool($boolean));
3178 $translated = ($boolean === true) ? 'Y' : 'N';
3180 // ... and return it
3185 * Encodes raw data (almost any type) by "serializing" it and then pack it
3186 * into a "binary format".
3188 * @param $rawData Raw data (almost any type)
3189 * @return $encoded Encoded data
3191 protected function encodeData ($rawData) {
3192 // Make sure no objects or resources pass through
3193 assert(!is_object($rawData));
3194 assert(!is_resource($rawData));
3196 // First "serialize" it (json_encode() is faster than serialize())
3197 $encoded = $this->packString(json_encode($rawData));
3204 * Pack a string into a "binary format". Please execuse me that this is
3205 * widely undocumented. :-(
3207 * @param $str Unpacked string
3208 * @return $packed Packed string
3209 * @todo Improve documentation
3211 protected function packString ($str) {
3213 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3215 // First compress the string (gzcompress is okay)
3216 $str = gzcompress($str);
3221 // And start the "encoding" loop
3222 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3224 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3225 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3227 if (($idx + $i) <= strlen($str)) {
3228 $ord = ord(substr($str, ($idx + $i), 1));
3230 $add = $ord * pow(256, $factor);
3234 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3238 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3239 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3241 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3242 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3248 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3253 * Creates a full-qualified file name (FQFN) for given file name by adding
3254 * a configured temporary file path to it.
3256 * @param $fileName Name for temporary file
3257 * @return $fqfn Full-qualified file name
3258 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3259 * @throws FileIoException If the file cannot be written
3261 protected static function createTempPathForFile ($fileName) {
3263 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3265 // Is the path writeable?
3266 if (!is_writable($basePath)) {
3267 // Path is write-protected
3268 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3272 $fqfn = $basePath . DIRECTORY_SEPARATOR . $fileName;
3275 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3277 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3285 * "Getter" for a printable state name
3287 * @return $stateName Name of the node's state in a printable format
3289 public final function getPrintableState () {
3290 // Default is 'null'
3291 $stateName = 'null';
3293 // Get the state instance
3294 $stateInstance = $this->getStateInstance();
3296 // Is it an instance of Stateable?
3297 if ($stateInstance instanceof Stateable) {
3298 // Then use that state name
3299 $stateName = $stateInstance->getStateName();