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 * Thousands separator
263 private $thousands = '.'; // German
268 private $decimals = ','; // German
273 private $socketResource = false;
276 * Regular expression to use for validation
278 private $regularExpression = '';
283 private $packageData = array();
288 private $genericArray = array();
293 private $commandName = '';
298 private $controllerName = '';
301 * Array with bitmasks and such for pack/unpack methods to support both
302 * 32-bit and 64-bit systems
304 private $packingData = array(
307 'left' => 0xffff0000,
308 'right' => 0x0000ffff,
314 'left' => 0xffffffff00000000,
315 'right' => 0x00000000ffffffff,
322 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
324 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
326 private $archArrayElement = false;
328 /***********************
329 * Exception codes.... *
330 ***********************/
332 // @todo Try to clean these constants up
333 const EXCEPTION_IS_NULL_POINTER = 0x001;
334 const EXCEPTION_IS_NO_OBJECT = 0x002;
335 const EXCEPTION_IS_NO_ARRAY = 0x003;
336 const EXCEPTION_MISSING_METHOD = 0x004;
337 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
338 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
339 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
340 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
341 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
342 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
343 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
344 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
345 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
346 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
347 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
348 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
349 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
350 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
351 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
352 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
353 const EXCEPTION_PATH_NOT_FOUND = 0x015;
354 const EXCEPTION_INVALID_PATH_NAME = 0x016;
355 const EXCEPTION_READ_PROTECED_PATH = 0x017;
356 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
357 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
358 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
359 const EXCEPTION_INVALID_RESOURCE = 0x01b;
360 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
361 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
362 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
363 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
364 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
365 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
366 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
367 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
368 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
369 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
370 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
371 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
372 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
373 const EXCEPTION_INVALID_STRING = 0x029;
374 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
375 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
376 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
377 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
378 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
379 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
380 const EXCEPTION_MISSING_ELEMENT = 0x030;
381 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
382 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
383 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
384 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
385 const EXCEPTION_FATAL_ERROR = 0x035;
386 const EXCEPTION_FILE_NOT_FOUND = 0x036;
387 const EXCEPTION_ASSERTION_FAILED = 0x037;
388 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
389 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
390 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
391 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
392 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
393 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
394 const EXCEPTION_INVALID_SOCKET = 0x03e;
397 * Hexadecimal->Decimal translation array
399 private static $hexdec = array(
419 * Decimal->hexadecimal translation array
421 private static $dechex = array(
441 * Startup time in miliseconds
443 private static $startupTime = 0;
446 * Protected super constructor
448 * @param $className Name of the class
451 protected function __construct ($className) {
453 $this->setRealClass($className);
455 // Set configuration instance if no registry ...
456 if (!$this instanceof Register) {
457 // ... because registries doesn't need to be configured
458 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
461 // Is the startup time set? (0 cannot be true anymore)
462 if (self::$startupTime == 0) {
464 self::$startupTime = microtime(true);
468 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
472 * Destructor for all classes. You should not call this method on your own.
476 public function __destruct () {
477 // Flush any updated entries to the database
478 $this->flushPendingUpdates();
480 // Is this object already destroyed?
481 if ($this->__toString() != 'DestructedObject') {
482 // Destroy all informations about this class but keep some text about it alive
483 $this->setRealClass('DestructedObject');
484 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
485 // Already destructed object
486 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
490 // Do not call this twice
491 trigger_error(__METHOD__ . ': Called twice.');
497 * The __call() method where all non-implemented methods end up
499 * @param $methodName Name of the missing method
500 * @args $args Arguments passed to the method
503 public final function __call ($methodName, $args) {
504 return self::__callStatic($methodName, $args);
508 * The __callStatic() method where all non-implemented static methods end up
510 * @param $methodName Name of the missing method
511 * @args $args Arguments passed to the method
514 public static final function __callStatic ($methodName, $args) {
516 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
518 // Init argument string
521 // Is it NULL, empty or an array?
522 if (is_null($args)) {
524 $argsString = 'NULL';
525 } elseif (is_array($args)) {
529 // Some arguments are there
530 foreach ($args as $arg) {
531 // Add data about the argument
532 $argsString .= gettype($arg) . ':';
535 // Found a NULL argument
536 $argsString .= 'NULL';
537 } elseif (is_string($arg)) {
538 // Add length for strings
539 $argsString .= strlen($arg);
540 } elseif ((is_int($arg)) || (is_float($arg))) {
543 } elseif (is_array($arg)) {
544 // .. or size if array
545 $argsString .= count($arg);
546 } elseif (is_object($arg)) {
548 $reflection = new ReflectionClass($arg);
550 // Is an other object, maybe no __toString() available
551 $argsString .= $reflection->getName();
552 } elseif ($arg === true) {
553 // ... is boolean 'true'
554 $argsString .= 'true';
555 } elseif ($arg === false) {
556 // ... is boolean 'false'
557 $argsString .= 'false';
560 // Comma for next one
565 if (substr($argsString, -2, 1) == ',') {
566 $argsString = substr($argsString, 0, -2);
572 // Invalid arguments!
573 $argsString = '!INVALID:' . gettype($args) . '!';
576 // Output stub message
577 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
578 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
588 * Getter for $realClass
590 * @return $realClass The name of the real class (not BaseFrameworkSystem)
592 public function __toString () {
593 return $this->realClass;
597 * Magic method to catch setting of missing but set class fields/attributes
599 * @param $name Name of the field/attribute
600 * @param $value Value to store
603 public final function __set ($name, $value) {
604 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
607 print_r($value, true)
612 * Magic method to catch getting of missing fields/attributes
614 * @param $name Name of the field/attribute
617 public final function __get ($name) {
618 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
624 * Magic method to catch unsetting of missing fields/attributes
626 * @param $name Name of the field/attribute
629 public final function __unset ($name) {
630 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
636 * Magic method to catch object serialization
638 * @return $unsupported Unsupported method
639 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
641 public final function __sleep () {
642 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
646 * Magic method to catch object deserialization
648 * @return $unsupported Unsupported method
649 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
651 public final function __wakeup () {
652 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
656 * Magic method to catch calls when an object instance is called
658 * @return $unsupported Unsupported method
659 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
661 public final function __invoke () {
662 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
666 * Setter for the real class name
668 * @param $realClass Class name (string)
671 public final function setRealClass ($realClass) {
673 $this->realClass = (string) $realClass;
677 * Setter for database result instance
679 * @param $resultInstance An instance of a database result class
681 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
683 protected final function setResultInstance (SearchableResult $resultInstance) {
684 $this->resultInstance = $resultInstance;
688 * Getter for database result instance
690 * @return $resultInstance An instance of a database result class
692 public final function getResultInstance () {
693 return $this->resultInstance;
697 * Setter for template engine instances
699 * @param $templateInstance An instance of a template engine class
702 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
703 $this->templateInstance = $templateInstance;
707 * Getter for template engine instances
709 * @return $templateInstance An instance of a template engine class
711 protected final function getTemplateInstance () {
712 return $this->templateInstance;
716 * Setter for search instance
718 * @param $searchInstance Searchable criteria instance
721 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
722 $this->searchInstance = $searchInstance;
726 * Getter for search instance
728 * @return $searchInstance Searchable criteria instance
730 public final function getSearchInstance () {
731 return $this->searchInstance;
735 * Setter for update instance
737 * @param $updateInstance An instance of a LocalUpdateCriteria clase
740 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
741 $this->updateInstance = $updateInstance;
745 * Getter for update instance
747 * @return $updateInstance Updateable criteria instance
749 public final function getUpdateInstance () {
750 return $this->updateInstance;
754 * Setter for resolver instance
756 * @param $resolverInstance Instance of a command resolver class
759 public final function setResolverInstance (Resolver $resolverInstance) {
760 $this->resolverInstance = $resolverInstance;
764 * Getter for resolver instance
766 * @return $resolverInstance Instance of a command resolver class
768 public final function getResolverInstance () {
769 return $this->resolverInstance;
773 * Setter for language instance
775 * @param $configInstance The configuration instance which shall
776 * be FrameworkConfiguration
779 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
780 Registry::getRegistry()->addInstance('config', $configInstance);
784 * Getter for configuration instance
786 * @return $configInstance Configuration instance
788 public final function getConfigInstance () {
789 $configInstance = Registry::getRegistry()->getInstance('config');
790 return $configInstance;
794 * Setter for debug instance
796 * @param $debugInstance The instance for debug output class
799 public final function setDebugInstance (DebugMiddleware $debugInstance) {
800 Registry::getRegistry()->addInstance('debug', $debugInstance);
804 * Getter for debug instance
806 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
808 public final function getDebugInstance () {
809 // Get debug instance
810 $debugInstance = Registry::getRegistry()->getInstance('debug');
813 return $debugInstance;
817 * Setter for web output instance
819 * @param $webInstance The instance for web output class
822 public final function setWebOutputInstance (OutputStreamer $webInstance) {
823 Registry::getRegistry()->addInstance('web_output', $webInstance);
827 * Getter for web output instance
829 * @return $webOutputInstance - Instance to class WebOutput
831 public final function getWebOutputInstance () {
832 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
833 return $webOutputInstance;
837 * Setter for database instance
839 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
842 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
843 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
847 * Getter for database layer
849 * @return $databaseInstance The database layer instance
851 public final function getDatabaseInstance () {
853 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
856 return $databaseInstance;
860 * Setter for compressor channel
862 * @param $compressorInstance An instance of CompressorChannel
865 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
866 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
870 * Getter for compressor channel
872 * @return $compressorInstance The compressor channel
874 public final function getCompressorChannel () {
875 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
876 return $compressorInstance;
880 * Protected getter for a manageable application helper class
882 * @return $applicationInstance An instance of a manageable application helper class
884 protected final function getApplicationInstance () {
885 $applicationInstance = Registry::getRegistry()->getInstance('app');
886 return $applicationInstance;
890 * Setter for a manageable application helper class
892 * @param $applicationInstance An instance of a manageable application helper class
895 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
896 Registry::getRegistry()->addInstance('application', $applicationInstance);
900 * Private getter for language instance
902 * @return $langInstance An instance to the language sub-system
904 protected final function getLanguageInstance () {
905 $langInstance = Registry::getRegistry()->getInstance('language');
906 return $langInstance;
910 * Setter for language instance
912 * @param $langInstance An instance to the language sub-system
914 * @see LanguageSystem
916 public final function setLanguageInstance (ManageableLanguage $langInstance) {
917 Registry::getRegistry()->addInstance('language', $langInstance);
921 * Private getter for file IO instance
923 * @return $fileIoInstance An instance to the file I/O sub-system
925 protected final function getFileIoInstance () {
926 return $this->fileIoInstance;
930 * Setter for file I/O instance
932 * @param $fileIoInstance An instance to the file I/O sub-system
935 public final function setFileIoInstance (IoHandler $fileIoInstance) {
936 $this->fileIoInstance = $fileIoInstance;
940 * Protected setter for user instance
942 * @param $userInstance An instance of a user class
945 protected final function setUserInstance (ManageableAccount $userInstance) {
946 $this->userInstance = $userInstance;
950 * Getter for user instance
952 * @return $userInstance An instance of a user class
954 public final function getUserInstance () {
955 return $this->userInstance;
959 * Setter for controller instance (this surely breaks a bit the MVC patterm)
961 * @param $controllerInstance An instance of the controller
964 public final function setControllerInstance (Controller $controllerInstance) {
965 $this->controllerInstance = $controllerInstance;
969 * Getter for controller instance (this surely breaks a bit the MVC patterm)
971 * @return $controllerInstance An instance of the controller
973 public final function getControllerInstance () {
974 return $this->controllerInstance;
978 * Setter for RNG instance
980 * @param $rngInstance An instance of a random number generator (RNG)
983 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
984 $this->rngInstance = $rngInstance;
988 * Getter for RNG instance
990 * @return $rngInstance An instance of a random number generator (RNG)
992 public final function getRngInstance () {
993 return $this->rngInstance;
997 * Setter for Cryptable instance
999 * @param $cryptoInstance An instance of a Cryptable class
1002 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1003 $this->cryptoInstance = $cryptoInstance;
1007 * Getter for Cryptable instance
1009 * @return $cryptoInstance An instance of a Cryptable class
1011 public final function getCryptoInstance () {
1012 return $this->cryptoInstance;
1016 * Setter for the list instance
1018 * @param $listInstance A list of Listable
1021 protected final function setListInstance (Listable $listInstance) {
1022 $this->listInstance = $listInstance;
1026 * Getter for the list instance
1028 * @return $listInstance A list of Listable
1030 protected final function getListInstance () {
1031 return $this->listInstance;
1035 * Setter for the menu instance
1037 * @param $menuInstance A RenderableMenu instance
1040 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1041 $this->menuInstance = $menuInstance;
1045 * Getter for the menu instance
1047 * @return $menuInstance A RenderableMenu instance
1049 protected final function getMenuInstance () {
1050 return $this->menuInstance;
1054 * Setter for image instance
1056 * @param $imageInstance An instance of an image
1059 public final function setImageInstance (BaseImage $imageInstance) {
1060 $this->imageInstance = $imageInstance;
1064 * Getter for image instance
1066 * @return $imageInstance An instance of an image
1068 public final function getImageInstance () {
1069 return $this->imageInstance;
1073 * Setter for stacker instance
1075 * @param $stackInstance An instance of an stacker
1078 public final function setStackInstance (Stackable $stackInstance) {
1079 $this->stackInstance = $stackInstance;
1083 * Getter for stacker instance
1085 * @return $stackInstance An instance of an stacker
1087 public final function getStackInstance () {
1088 return $this->stackInstance;
1092 * Setter for compressor instance
1094 * @param $compressorInstance An instance of an compressor
1097 public final function setCompressorInstance (Compressor $compressorInstance) {
1098 $this->compressorInstance = $compressorInstance;
1102 * Getter for compressor instance
1104 * @return $compressorInstance An instance of an compressor
1106 public final function getCompressorInstance () {
1107 return $this->compressorInstance;
1111 * Setter for Parseable instance
1113 * @param $parserInstance An instance of an Parseable
1116 public final function setParserInstance (Parseable $parserInstance) {
1117 $this->parserInstance = $parserInstance;
1121 * Getter for Parseable instance
1123 * @return $parserInstance An instance of an Parseable
1125 public final function getParserInstance () {
1126 return $this->parserInstance;
1130 * Setter for DatabaseWrapper instance
1132 * @param $wrapperInstance An instance of an DatabaseWrapper
1135 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1136 $this->wrapperInstance = $wrapperInstance;
1140 * Getter for DatabaseWrapper instance
1142 * @return $wrapperInstance An instance of an DatabaseWrapper
1144 public final function getWrapperInstance () {
1145 return $this->wrapperInstance;
1149 * Setter for socket resource
1151 * @param $socketResource A valid socket resource
1154 public final function setSocketResource ($socketResource) {
1155 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1156 $this->socketResource = $socketResource;
1160 * Getter for socket resource
1162 * @return $socketResource A valid socket resource
1164 public final function getSocketResource () {
1165 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1166 return $this->socketResource;
1170 * Setter for regular expression
1172 * @param $regularExpression A valid regular expression
1175 public final function setRegularExpression ($regularExpression) {
1176 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1177 $this->regularExpression = $regularExpression;
1181 * Getter for regular expression
1183 * @return $regularExpression A valid regular expression
1185 public final function getRegularExpression () {
1186 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1187 return $this->regularExpression;
1191 * Setter for helper instance
1193 * @param $helperInstance An instance of a helper class
1196 protected final function setHelperInstance (Helper $helperInstance) {
1197 $this->helperInstance = $helperInstance;
1201 * Getter for helper instance
1203 * @return $helperInstance An instance of a helper class
1205 public final function getHelperInstance () {
1206 return $this->helperInstance;
1210 * Setter for a Source instance
1212 * @param $sourceInstance An instance of a Source class
1215 protected final function setSourceInstance (Source $sourceInstance) {
1216 $this->sourceInstance = $sourceInstance;
1220 * Getter for a Source instance
1222 * @return $sourceInstance An instance of a Source class
1224 protected final function getSourceInstance () {
1225 return $this->sourceInstance;
1229 * Setter for a UrlSource instance
1231 * @param $sourceInstance An instance of a UrlSource class
1234 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1235 $this->urlSourceInstance = $urlSourceInstance;
1239 * Getter for a UrlSource instance
1241 * @return $urlSourceInstance An instance of a UrlSource class
1243 protected final function getUrlSourceInstance () {
1244 return $this->urlSourceInstance;
1248 * Getter for a InputStream instance
1250 * @param $inputStreamInstance The InputStream instance
1252 protected final function getInputStreamInstance () {
1253 return $this->inputStreamInstance;
1257 * Setter for a InputStream instance
1259 * @param $inputStreamInstance The InputStream instance
1262 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1263 $this->inputStreamInstance = $inputStreamInstance;
1267 * Getter for a OutputStream instance
1269 * @param $outputStreamInstance The OutputStream instance
1271 protected final function getOutputStreamInstance () {
1272 return $this->outputStreamInstance;
1276 * Setter for a OutputStream instance
1278 * @param $outputStreamInstance The OutputStream instance
1281 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1282 $this->outputStreamInstance = $outputStreamInstance;
1286 * Setter for handler instance
1288 * @param $handlerInstance An instance of a Handleable class
1291 protected final function setHandlerInstance (Handleable $handlerInstance) {
1292 $this->handlerInstance = $handlerInstance;
1296 * Getter for handler instance
1298 * @return $handlerInstance A Handleable instance
1300 protected final function getHandlerInstance () {
1301 return $this->handlerInstance;
1305 * Setter for visitor instance
1307 * @param $visitorInstance A Visitor instance
1310 protected final function setVisitorInstance (Visitor $visitorInstance) {
1311 $this->visitorInstance = $visitorInstance;
1315 * Getter for visitor instance
1317 * @return $visitorInstance A Visitor instance
1319 protected final function getVisitorInstance () {
1320 return $this->visitorInstance;
1324 * Setter for raw package Data
1326 * @param $packageData Raw package Data
1329 public final function setPackageData (array $packageData) {
1330 $this->packageData = $packageData;
1334 * Getter for raw package Data
1336 * @return $packageData Raw package Data
1338 public function getPackageData () {
1339 return $this->packageData;
1344 * Setter for Iterator instance
1346 * @param $iteratorInstance An instance of an Iterator
1349 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1350 $this->iteratorInstance = $iteratorInstance;
1354 * Getter for Iterator instance
1356 * @return $iteratorInstance An instance of an Iterator
1358 public final function getIteratorInstance () {
1359 return $this->iteratorInstance;
1363 * Setter for FilePointer instance
1365 * @param $pointerInstance An instance of an FilePointer class
1368 protected final function setPointerInstance (FilePointer $pointerInstance) {
1369 $this->pointerInstance = $pointerInstance;
1373 * Getter for FilePointer instance
1375 * @return $pointerInstance An instance of an FilePointer class
1377 public final function getPointerInstance () {
1378 return $this->pointerInstance;
1382 * Unsets pointer instance which triggers a call of __destruct() if the
1383 * instance is still there. This is surely not fatal on already "closed"
1384 * file pointer instances.
1386 * I don't want to mess around with above setter by giving it a default
1387 * value NULL as setter should always explicitly only set (existing) object
1388 * instances and NULL is NULL.
1392 protected final function unsetPointerInstance () {
1393 // Simply it to NULL
1394 $this->pointerInstance = NULL;
1398 * Setter for Indexable instance
1400 * @param $indexInstance An instance of an Indexable class
1403 protected final function setIndexInstance (Indexable $indexInstance) {
1404 $this->indexInstance = $indexInstance;
1408 * Getter for Indexable instance
1410 * @return $indexInstance An instance of an Indexable class
1412 public final function getIndexInstance () {
1413 return $this->indexInstance;
1417 * Setter for Block instance
1419 * @param $blockInstance An instance of an Block class
1422 protected final function setBlockInstance (Block $blockInstance) {
1423 $this->blockInstance = $blockInstance;
1427 * Getter for Block instance
1429 * @return $blockInstance An instance of an Block class
1431 public final function getBlockInstance () {
1432 return $this->blockInstance;
1436 * Setter for Minable instance
1438 * @param $minableInstance A Minable instance
1441 protected final function setMinableInstance (Minable $minableInstance) {
1442 $this->minableInstance = $minableInstance;
1446 * Getter for minable instance
1448 * @return $minableInstance A Minable instance
1450 protected final function getMinableInstance () {
1451 return $this->minableInstance;
1455 * Setter for FrameworkDirectory instance
1457 * @param $directoryInstance A FrameworkDirectory instance
1460 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1461 $this->directoryInstance = $directoryInstance;
1465 * Getter for FrameworkDirectory instance
1467 * @return $directoryInstance A FrameworkDirectory instance
1469 protected final function getDirectoryInstance () {
1470 return $this->directoryInstance;
1474 * Getter for communicator instance
1476 * @return $communicatorInstance An instance of a Communicator class
1478 public final function getCommunicatorInstance () {
1479 return $this->communicatorInstance;
1483 * Setter for communicator instance
1485 * @param $communicatorInstance An instance of a Communicator class
1488 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1489 $this->communicatorInstance = $communicatorInstance;
1493 * Setter for state instance
1495 * @param $stateInstance A Stateable instance
1498 public final function setStateInstance (Stateable $stateInstance) {
1499 $this->stateInstance = $stateInstance;
1503 * Getter for state instance
1505 * @return $stateInstance A Stateable instance
1507 public final function getStateInstance () {
1508 return $this->stateInstance;
1512 * Setter for output instance
1514 * @param $outputInstance The debug output instance
1517 public final function setOutputInstance (OutputStreamer $outputInstance) {
1518 $this->outputInstance = $outputInstance;
1522 * Getter for output instance
1524 * @return $outputInstance The debug output instance
1526 public final function getOutputInstance () {
1527 return $this->outputInstance;
1531 * Setter for command name
1533 * @param $commandName Last validated command name
1536 protected final function setCommandName ($commandName) {
1537 $this->commandName = $commandName;
1541 * Getter for command name
1543 * @return $commandName Last validated command name
1545 protected final function getCommandName () {
1546 return $this->commandName;
1550 * Setter for controller name
1552 * @param $controllerName Last validated controller name
1555 protected final function setControllerName ($controllerName) {
1556 $this->controllerName = $controllerName;
1560 * Getter for controller name
1562 * @return $controllerName Last validated controller name
1564 protected final function getControllerName () {
1565 return $this->controllerName;
1569 * Checks whether an object equals this object. You should overwrite this
1570 * method to implement own equality checks
1572 * @param $objectInstance An instance of a FrameworkInterface object
1573 * @return $equals Whether both objects equals
1575 public function equals (FrameworkInterface $objectInstance) {
1578 $this->__toString() == $objectInstance->__toString()
1580 $this->hashCode() == $objectInstance->hashCode()
1583 // Return the result
1588 * Generates a generic hash code of this class. You should really overwrite
1589 * this method with your own hash code generator code. But keep KISS in mind.
1591 * @return $hashCode A generic hash code respresenting this whole class
1593 public function hashCode () {
1595 return crc32($this->__toString());
1599 * Formats computer generated price values into human-understandable formats
1600 * with thousand and decimal separators.
1602 * @param $value The in computer format value for a price
1603 * @param $currency The currency symbol (use HTML-valid characters!)
1604 * @param $decNum Number of decimals after commata
1605 * @return $price The for the current language formated price string
1606 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1607 * thousands separator
1610 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1611 // Are all required attriutes set?
1612 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1613 // Throw an exception
1614 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1618 $value = (float) $value;
1620 // Reformat the US number
1621 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1623 // Return as string...
1628 * Appends a trailing slash to a string
1630 * @param $str A string (maybe) without trailing slash
1631 * @return $str A string with an auto-appended trailing slash
1633 public final function addMissingTrailingSlash ($str) {
1634 // Is there a trailing slash?
1635 if (substr($str, -1, 1) != '/') {
1639 // Return string with trailing slash
1644 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1645 * application helper instance (ApplicationHelper by default).
1647 * @param $applicationInstance An application helper instance or
1648 * null if we shall use the default
1649 * @return $templateInstance The template engine instance
1650 * @throws NullPointerException If the discovered application
1651 * instance is still null
1653 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1654 // Is the application instance set?
1655 if (is_null($applicationInstance)) {
1656 // Get the current instance
1657 $applicationInstance = Registry::getRegistry()->getInstance('app');
1660 if (is_null($applicationInstance)) {
1661 // Thrown an exception
1662 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1666 // Initialize the template engine
1667 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1669 // Return the prepared instance
1670 return $templateInstance;
1674 * Debugs this instance by putting out it's full content
1676 * @param $message Optional message to show in debug output
1679 public final function debugInstance ($message = '') {
1680 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1681 restore_error_handler();
1686 // Is a message set?
1687 if (!empty($message)) {
1688 // Construct message
1689 $content = sprintf('<div class="debug_message">
1691 </div>' . PHP_EOL, $message);
1694 // Generate the output
1695 $content .= sprintf('<pre>%s</pre>',
1698 print_r($this, true)
1704 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">
1707 <div class="debug_content">
1711 <div class="debug_include_list">
1714 $this->__toString(),
1716 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1721 * Replaces control characters with printable output
1723 * @param $str String with control characters
1724 * @return $str Replaced string
1726 protected function replaceControlCharacters ($str) {
1729 chr(13), '[r]', str_replace(
1730 chr(10), '[n]', str_replace(
1740 * Output a partial stub message for the caller method
1742 * @param $message An optional message to display
1745 protected function partialStub ($message = '') {
1747 $stubMessage = 'Partial Stub!';
1749 // Is the extra message given?
1750 if (!empty($message)) {
1751 // Then add it as well
1752 $stubMessage .= ' Message: ' . $message;
1755 // Debug instance is there?
1756 if (!is_null($this->getDebugInstance())) {
1757 // Output stub message
1758 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1761 trigger_error($stubMessage);
1767 * Outputs a debug backtrace and stops further script execution
1769 * @param $message An optional message to output
1770 * @param $doExit Whether exit the program (true is default)
1773 public function debugBackTrace ($message = '', $doExit = true) {
1774 // Sorry, there is no other way getting this nice backtrace
1775 if (!empty($message)) {
1777 printf('Message: %s<br />' . PHP_EOL, $message);
1781 debug_print_backtrace();
1785 if ($doExit === true) {
1791 * Creates an instance of a debugger instance
1793 * @param $className Name of the class (currently unsupported)
1794 * @param $lineNumber Line number where the call was made
1795 * @return $debugInstance An instance of a debugger class
1796 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1798 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1799 // Is the instance set?
1800 if (!Registry::getRegistry()->instanceExists('debug')) {
1801 // Init debug instance
1802 $debugInstance = NULL;
1806 // Get a debugger instance
1807 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1808 } catch (NullPointerException $e) {
1809 // Didn't work, no instance there
1810 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1813 // Empty string should be ignored and used for testing the middleware
1814 DebugMiddleware::getSelfInstance()->output('');
1816 // Set it in registry
1817 Registry::getRegistry()->addInstance('debug', $debugInstance);
1819 // Get instance from registry
1820 $debugInstance = Registry::getRegistry()->getInstance('debug');
1824 return $debugInstance;
1828 * Simple output of a message with line-break
1830 * @param $message Message to output
1833 public function outputLine ($message) {
1835 print($message . PHP_EOL);
1839 * Outputs a debug message whether to debug instance (should be set!) or
1840 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1841 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1843 * @param $message Message we shall send out...
1844 * @param $doPrint Whether print or die here (default: print)
1845 * @paran $stripTags Whether to strip tags (default: false)
1848 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1849 // Set debug instance to NULL
1850 $debugInstance = NULL;
1853 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1855 // Is function partialStub/__callStatic ?
1856 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1857 // Prepend class::function:line from 3rd element
1858 $message = sprintf('[%s::%s:%d]: %s',
1859 $backtrace[2]['class'],
1860 $backtrace[2]['function'],
1861 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1865 // Prepend class::function:line from 2nd element
1866 $message = sprintf('[%s::%s:%d]: %s',
1867 $backtrace[1]['class'],
1868 $backtrace[1]['function'],
1869 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1876 // Get debug instance
1877 $debugInstance = $this->getDebugInstance();
1878 } catch (NullPointerException $e) {
1879 // The debug instance is not set (yet)
1882 // Is the debug instance there?
1883 if (is_object($debugInstance)) {
1884 // Use debug output handler
1885 $debugInstance->output($message, $stripTags);
1887 if ($doPrint === false) {
1888 // Die here if not printed
1892 // Are debug times enabled?
1893 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1895 $message = $this->getPrintableExecutionTime() . $message;
1899 if ($doPrint === true) {
1901 $this->outputLine($message);
1910 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1912 * @param $str The string, what ever it is needs to be converted
1913 * @return $className Generated class name
1915 public static final function convertToClassName ($str) {
1919 // Convert all dashes in underscores
1920 $str = self::convertDashesToUnderscores($str);
1922 // Now use that underscores to get classname parts for hungarian style
1923 foreach (explode('_', $str) as $strPart) {
1924 // Make the class name part lower case and first upper case
1925 $className .= ucfirst(strtolower($strPart));
1928 // Return class name
1933 * Converts dashes to underscores, e.g. useable for configuration entries
1935 * @param $str The string with maybe dashes inside
1936 * @return $str The converted string with no dashed, but underscores
1938 public static final function convertDashesToUnderscores ($str) {
1940 $str = str_replace('-', '_', $str);
1942 // Return converted string
1947 * Marks up the code by adding e.g. line numbers
1949 * @param $phpCode Unmarked PHP code
1950 * @return $markedCode Marked PHP code
1952 public function markupCode ($phpCode) {
1957 $errorArray = error_get_last();
1959 // Init the code with error message
1960 if (is_array($errorArray)) {
1962 $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>',
1963 basename($errorArray['file']),
1964 $errorArray['line'],
1965 $errorArray['message'],
1970 // Add line number to the code
1971 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1973 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1975 htmlentities($code, ENT_QUOTES)
1984 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1985 * beatiful for web-based front-ends. If null is given a message id
1986 * null_timestamp will be resolved and returned.
1988 * @param $timestamp Timestamp to prepare (filter) for display
1989 * @return $readable A readable timestamp
1991 public function doFilterFormatTimestamp ($timestamp) {
1992 // Default value to return
1995 // Is the timestamp null?
1996 if (is_null($timestamp)) {
1997 // Get a message string
1998 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2000 switch ($this->getLanguageInstance()->getLanguageCode()) {
2001 case 'de': // German format is a bit different to default
2002 // Split the GMT stamp up
2003 $dateTime = explode(' ', $timestamp );
2004 $dateArray = explode('-', $dateTime[0]);
2005 $timeArray = explode(':', $dateTime[1]);
2007 // Construct the timestamp
2008 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2018 default: // Default is pass-through
2019 $readable = $timestamp;
2029 * Filter a given number into a localized number
2031 * @param $value The raw value from e.g. database
2032 * @return $localized Localized value
2034 public function doFilterFormatNumber ($value) {
2035 // Generate it from config and localize dependencies
2036 switch ($this->getLanguageInstance()->getLanguageCode()) {
2037 case 'de': // German format is a bit different to default
2038 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2041 default: // US, etc.
2042 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2051 * "Getter" for databse entry
2053 * @return $entry An array with database entries
2054 * @throws NullPointerException If the database result is not found
2055 * @throws InvalidDatabaseResultException If the database result is invalid
2057 protected final function getDatabaseEntry () {
2058 // Is there an instance?
2059 if (!$this->getResultInstance() instanceof SearchableResult) {
2060 // Throw an exception here
2061 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2065 $this->getResultInstance()->rewind();
2067 // Do we have an entry?
2068 if ($this->getResultInstance()->valid() === false) {
2069 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2070 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2074 $this->getResultInstance()->next();
2077 $entry = $this->getResultInstance()->current();
2084 * Getter for field name
2086 * @param $fieldName Field name which we shall get
2087 * @return $fieldValue Field value from the user
2088 * @throws NullPointerException If the result instance is null
2090 public final function getField ($fieldName) {
2091 // Default field value
2094 // Get result instance
2095 $resultInstance = $this->getResultInstance();
2097 // Is this instance null?
2098 if (is_null($resultInstance)) {
2099 // Then the user instance is no longer valid (expired cookies?)
2100 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2103 // Get current array
2104 $fieldArray = $resultInstance->current();
2105 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2107 // Convert dashes to underscore
2108 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2110 // Does the field exist?
2111 if ($this->isFieldSet($fieldName)) {
2113 $fieldValue = $fieldArray[$fieldName2];
2114 } elseif (defined('DEVELOPER')) {
2115 // Missing field entry, may require debugging
2116 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2118 // Missing field entry, may require debugging
2119 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2127 * Checks if given field is set
2129 * @param $fieldName Field name to check
2130 * @return $isSet Whether the given field name is set
2131 * @throws NullPointerException If the result instance is null
2133 public function isFieldSet ($fieldName) {
2134 // Get result instance
2135 $resultInstance = $this->getResultInstance();
2137 // Is this instance null?
2138 if (is_null($resultInstance)) {
2139 // Then the user instance is no longer valid (expired cookies?)
2140 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2143 // Get current array
2144 $fieldArray = $resultInstance->current();
2145 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2147 // Convert dashes to underscore
2148 $fieldName = self::convertDashesToUnderscores($fieldName);
2151 $isSet = isset($fieldArray[$fieldName]);
2158 * Flushs all pending updates to the database layer
2162 public function flushPendingUpdates () {
2163 // Get result instance
2164 $resultInstance = $this->getResultInstance();
2166 // Do we have data to update?
2167 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2168 // Get wrapper class name config entry
2169 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2171 // Create object instance
2172 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2174 // Yes, then send the whole result to the database layer
2175 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2180 * Outputs a deprecation warning to the developer.
2182 * @param $message The message we shall output to the developer
2184 * @todo Write a logging mechanism for productive mode
2186 public function deprecationWarning ($message) {
2187 // Is developer mode active?
2188 if (defined('DEVELOPER')) {
2189 // Debug instance is there?
2190 if (!is_null($this->getDebugInstance())) {
2191 // Output stub message
2192 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2195 trigger_error($message . "<br />\n");
2199 // @TODO Finish this part!
2200 $this->partialStub('Developer mode inactive. Message:' . $message);
2205 * Checks whether the given PHP extension is loaded
2207 * @param $phpExtension The PHP extension we shall check
2208 * @return $isLoaded Whether the PHP extension is loaded
2210 public final function isPhpExtensionLoaded ($phpExtension) {
2212 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2219 * "Getter" as a time() replacement but with milliseconds. You should use this
2220 * method instead of the encapsulated getimeofday() function.
2222 * @return $milliTime Timestamp with milliseconds
2224 public function getMilliTime () {
2225 // Get the time of day as float
2226 $milliTime = gettimeofday(true);
2233 * Idles (sleeps) for given milliseconds
2235 * @return $hasSlept Whether it goes fine
2237 public function idle ($milliSeconds) {
2238 // Sleep is fine by default
2241 // Idle so long with found function
2242 if (function_exists('time_sleep_until')) {
2243 // Get current time and add idle time
2244 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2246 // New PHP 5.1.0 function found, ignore errors
2247 $hasSlept = @time_sleep_until($sleepUntil);
2250 * My Sun station doesn't have that function even with latest PHP
2253 usleep($milliSeconds * 1000);
2260 * Converts a hexadecimal string, even with negative sign as first string to
2261 * a decimal number using BC functions.
2263 * This work is based on comment #86673 on php.net documentation page at:
2264 * <http://de.php.net/manual/en/function.dechex.php#86673>
2266 * @param $hex Hexadecimal string
2267 * @return $dec Decimal number
2269 protected function hex2dec ($hex) {
2270 // Convert to all lower-case
2271 $hex = strtolower($hex);
2273 // Detect sign (negative/positive numbers)
2275 if (substr($hex, 0, 1) == '-') {
2277 $hex = substr($hex, 1);
2280 // Decode the hexadecimal string into a decimal number
2282 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2283 $factor = self::$hexdec[substr($hex, $i, 1)];
2284 $dec = bcadd($dec, bcmul($factor, $e));
2287 // Return the decimal number
2288 return $sign . $dec;
2292 * Converts even very large decimal numbers, also signed, to a hexadecimal
2295 * This work is based on comment #97756 on php.net documentation page at:
2296 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2298 * @param $dec Decimal number, even with negative sign
2299 * @param $maxLength Optional maximum length of the string
2300 * @return $hex Hexadecimal string
2302 protected function dec2hex ($dec, $maxLength = 0) {
2303 // maxLength can be zero or devideable by 2
2304 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2306 // Detect sign (negative/positive numbers)
2313 // Encode the decimal number into a hexadecimal string
2316 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2318 } while ($dec >= 1);
2321 * Leading zeros are required for hex-decimal "numbers". In some
2322 * situations more leading zeros are wanted, so check for both
2325 if ($maxLength > 0) {
2326 // Prepend more zeros
2327 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2328 } elseif ((strlen($hex) % 2) != 0) {
2329 // Only make string's length dividable by 2
2333 // Return the hexadecimal string
2334 return $sign . $hex;
2338 * Converts a ASCII string (0 to 255) into a decimal number.
2340 * @param $asc The ASCII string to be converted
2341 * @return $dec Decimal number
2343 protected function asc2dec ($asc) {
2344 // Convert it into a hexadecimal number
2345 $hex = bin2hex($asc);
2347 // And back into a decimal number
2348 $dec = $this->hex2dec($hex);
2355 * Converts a decimal number into an ASCII string.
2357 * @param $dec Decimal number
2358 * @return $asc An ASCII string
2360 protected function dec2asc ($dec) {
2361 // First convert the number into a hexadecimal string
2362 $hex = $this->dec2hex($dec);
2364 // Then convert it into the ASCII string
2365 $asc = $this->hex2asc($hex);
2372 * Converts a hexadecimal number into an ASCII string. Negative numbers
2375 * @param $hex Hexadecimal string
2376 * @return $asc An ASCII string
2378 protected function hex2asc ($hex) {
2379 // Check for length, it must be devideable by 2
2380 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2381 assert((strlen($hex) % 2) == 0);
2385 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2386 // Get the decimal number of the chunk
2387 $part = hexdec(substr($hex, $idx, 2));
2389 // Add it to the final string
2393 // Return the final string
2398 * Checks whether the given encoded data was encoded with Base64
2400 * @param $encodedData Encoded data we shall check
2401 * @return $isBase64 Whether the encoded data is Base64
2403 protected function isBase64Encoded ($encodedData) {
2405 $isBase64 = (@base64_decode($encodedData, true) !== false);
2412 * Gets a cache key from Criteria instance
2414 * @param $criteriaInstance An instance of a Criteria class
2415 * @param $onlyKeys Only use these keys for a cache key
2416 * @return $cacheKey A cache key suitable for lookup/storage purposes
2418 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2420 $cacheKey = sprintf('%s@%s',
2421 $this->__toString(),
2422 $criteriaInstance->getCacheKey($onlyKeys)
2426 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2431 * Getter for startup time in miliseconds
2433 * @return $startupTime Startup time in miliseconds
2435 protected function getStartupTime () {
2436 return self::$startupTime;
2440 * "Getter" for a printable currently execution time in nice braces
2442 * @return $executionTime Current execution time in nice braces
2444 protected function getPrintableExecutionTime () {
2445 // Caculate the execution time
2446 $executionTime = microtime(true) - $this->getStartupTime();
2448 // Pack it in nice braces
2449 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2452 return $executionTime;
2456 * Hashes a given string with a simple but stronger hash function (no salt)
2457 * and hex-encode it.
2459 * @param $str The string to be hashed
2460 * @return $hash The hash from string $str
2462 public static final function hash ($str) {
2463 // Hash given string with (better secure) hasher
2464 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2471 * "Getter" for length of hash() output. This will be "cached" to speed up
2474 * @return $length Length of hash() output
2476 public static final function getHashLength () {
2478 if (is_null(self::$hashLength)) {
2479 // No, then hash a string and save its length.
2480 self::$hashLength = strlen(self::hash('abc123'));
2484 return self::$hashLength;
2488 * Checks whether the given number is really a number (only chars 0-9).
2490 * @param $num A string consisting only chars between 0 and 9
2491 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2492 * @param $assertMismatch Whether to assert mismatches
2493 * @return $ret The (hopefully) secured numbered value
2495 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2496 // Filter all numbers out
2497 $ret = preg_replace('/[^0123456789]/', '', $num);
2500 if ($castValue === true) {
2501 // Cast to biggest numeric type
2502 $ret = (double) $ret;
2505 // Assert only if requested
2506 if ($assertMismatch === true) {
2507 // Has the whole value changed?
2508 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2516 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2518 * @param $num A string consisting only chars between 0 and 9
2519 * @param $assertMismatch Whether to assert mismatches
2520 * @return $ret The (hopefully) secured hext-numbered value
2522 public function hexval ($num, $assertMismatch = false) {
2523 // Filter all numbers out
2524 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2526 // Assert only if requested
2527 if ($assertMismatch === true) {
2528 // Has the whole value changed?
2529 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2537 * Determines if an element is set in the generic array
2539 * @param $keyGroup Main group for the key
2540 * @param $subGroup Sub group for the key
2541 * @param $key Key to check
2542 * @param $element Element to check
2543 * @return $isset Whether the given key is set
2545 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2547 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2550 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2556 * Determines if a key is set in the generic array
2558 * @param $keyGroup Main group for the key
2559 * @param $subGroup Sub group for the key
2560 * @param $key Key to check
2561 * @return $isset Whether the given key is set
2563 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2565 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2568 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2576 * Determines if a group is set in the generic array
2578 * @param $keyGroup Main group
2579 * @param $subGroup Sub group
2580 * @return $isset Whether the given group is set
2582 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2584 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2587 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2594 * Getter for sub key group
2596 * @param $keyGroup Main key group
2597 * @param $subGroup Sub key group
2598 * @return $array An array with all array elements
2600 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2602 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2603 // No, then abort here
2604 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2609 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2612 return $this->genericArray[$keyGroup][$subGroup];
2616 * Unsets a given key in generic array
2618 * @param $keyGroup Main group for the key
2619 * @param $subGroup Sub group for the key
2620 * @param $key Key to unset
2623 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2625 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2628 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2632 * Unsets a given element in generic array
2634 * @param $keyGroup Main group for the key
2635 * @param $subGroup Sub group for the key
2636 * @param $key Key to unset
2637 * @param $element Element to unset
2640 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2642 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2645 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2649 * Append a string to a given generic array key
2651 * @param $keyGroup Main group for the key
2652 * @param $subGroup Sub group for the key
2653 * @param $key Key to unset
2654 * @param $value Value to add/append
2657 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2659 //* 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);
2661 // Is it already there?
2662 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2664 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2667 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2672 * Append a string to a given generic array element
2674 * @param $keyGroup Main group for the key
2675 * @param $subGroup Sub group for the key
2676 * @param $key Key to unset
2677 * @param $element Element to check
2678 * @param $value Value to add/append
2681 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2683 //* 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);
2685 // Is it already there?
2686 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2688 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2691 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2696 * Sets a string in 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 setStringGenericArrayElement ($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);
2710 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2714 * Initializes given generic array group
2716 * @param $keyGroup Main group for the key
2717 * @param $subGroup Sub group for the key
2718 * @param $key Key to use
2719 * @param $forceInit Optionally force initialization
2722 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2724 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2726 // Is it already set?
2727 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2728 // Already initialized
2729 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2734 $this->genericArray[$keyGroup][$subGroup] = array();
2738 * Initializes given generic array key
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 initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2748 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2750 // Is it already set?
2751 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2752 // Already initialized
2753 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2758 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2762 * Initializes given generic array element
2764 * @param $keyGroup Main group for the key
2765 * @param $subGroup Sub group for the key
2766 * @param $key Key to use
2767 * @param $element Element to use
2768 * @param $forceInit Optionally force initialization
2771 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2773 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2775 // Is it already set?
2776 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2777 // Already initialized
2778 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2783 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2787 * Pushes an element to a generic key
2789 * @param $keyGroup Main group for the key
2790 * @param $subGroup Sub group for the key
2791 * @param $key Key to use
2792 * @param $value Value to add/append
2793 * @return $count Number of array elements
2795 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2797 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2800 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2802 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2806 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2809 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2810 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2815 * Pushes an element to a generic array element
2817 * @param $keyGroup Main group for the key
2818 * @param $subGroup Sub group for the key
2819 * @param $key Key to use
2820 * @param $element Element to check
2821 * @param $value Value to add/append
2822 * @return $count Number of array elements
2824 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2826 //* 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));
2829 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2831 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2835 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2838 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2839 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2844 * Pops an element from a generic group
2846 * @param $keyGroup Main group for the key
2847 * @param $subGroup Sub group for the key
2848 * @param $key Key to unset
2849 * @return $value Last "popped" value
2851 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2853 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2856 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2858 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2863 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2866 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2867 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2872 * Shifts an element from a generic group
2874 * @param $keyGroup Main group for the key
2875 * @param $subGroup Sub group for the key
2876 * @param $key Key to unset
2877 * @return $value Last "popped" value
2879 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2881 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2884 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2886 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2891 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2894 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2895 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2900 * Count generic array group
2902 * @param $keyGroup Main group for the key
2903 * @return $count Count of given group
2905 protected final function countGenericArray ($keyGroup) {
2907 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2910 if (!isset($this->genericArray[$keyGroup])) {
2912 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2917 $count = count($this->genericArray[$keyGroup]);
2920 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2927 * Count generic array sub group
2929 * @param $keyGroup Main group for the key
2930 * @param $subGroup Sub group for the key
2931 * @return $count Count of given group
2933 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2935 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2938 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2940 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2945 $count = count($this->genericArray[$keyGroup][$subGroup]);
2948 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2955 * Count generic array elements
2957 * @param $keyGroup Main group for the key
2958 * @param $subGroup Sub group for the key
2959 * @para $key Key to count
2960 * @return $count Count of given key
2962 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2964 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2967 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2969 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2971 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2973 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2978 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2981 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2988 * Getter for whole generic group array
2990 * @param $keyGroup Key group to get
2991 * @return $array Whole generic array group
2993 protected final function getGenericArray ($keyGroup) {
2995 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2998 if (!isset($this->genericArray[$keyGroup])) {
3000 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3005 return $this->genericArray[$keyGroup];
3009 * Setter for generic array key
3011 * @param $keyGroup Key group to get
3012 * @param $subGroup Sub group for the key
3013 * @param $key Key to unset
3014 * @param $value Mixed value from generic array element
3017 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3019 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3022 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3026 * Getter for generic array key
3028 * @param $keyGroup Key group to get
3029 * @param $subGroup Sub group for the key
3030 * @param $key Key to unset
3031 * @return $value Mixed value from generic array element
3033 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3035 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3038 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3040 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3045 return $this->genericArray[$keyGroup][$subGroup][$key];
3049 * Sets a value in given generic array key/element
3051 * @param $keyGroup Main group for the key
3052 * @param $subGroup Sub group for the key
3053 * @param $key Key to set
3054 * @param $element Element to set
3055 * @param $value Value to set
3058 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3060 //* 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));
3063 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3067 * Getter for generic array element
3069 * @param $keyGroup Key group to get
3070 * @param $subGroup Sub group for the key
3071 * @param $key Key to look for
3072 * @param $element Element to look for
3073 * @return $value Mixed value from generic array element
3075 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3077 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3080 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3082 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3087 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3091 * Checks if a given sub group is valid (array)
3093 * @param $keyGroup Key group to get
3094 * @param $subGroup Sub group for the key
3095 * @return $isValid Whether given sub group is valid
3097 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3099 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3102 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3109 * Checks if a given key is valid (array)
3111 * @param $keyGroup Key group to get
3112 * @param $subGroup Sub group for the key
3113 * @param $key Key to check
3114 * @return $isValid Whether given sub group is valid
3116 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3118 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3121 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3128 * Initializes the web output instance
3132 protected function initWebOutputInstance () {
3133 // Get application instance
3134 $applicationInstance = Registry::getRegistry()->getInstance('app');
3136 // Init web output instance
3137 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3140 $this->setWebOutputInstance($outputInstance);
3144 * Translates boolean true to 'Y' and false to 'N'
3146 * @param $boolean Boolean value
3147 * @return $translated Translated boolean value
3149 public static final function translateBooleanToYesNo ($boolean) {
3150 // Make sure it is really boolean
3151 assert(is_bool($boolean));
3154 $translated = ($boolean === true) ? 'Y' : 'N';
3156 // ... and return it
3161 * Encodes raw data (almost any type) by "serializing" it and then pack it
3162 * into a "binary format".
3164 * @param $rawData Raw data (almost any type)
3165 * @return $encoded Encoded data
3167 protected function encodeData ($rawData) {
3168 // Make sure no objects or resources pass through
3169 assert(!is_object($rawData));
3170 assert(!is_resource($rawData));
3172 // First "serialize" it (json_encode() is faster than serialize())
3173 $encoded = $this->packString(json_encode($rawData));
3180 * Pack a string into a "binary format". Please execuse me that this is
3181 * widely undocumented. :-(
3183 * @param $str Unpacked string
3184 * @return $packed Packed string
3185 * @todo Improve documentation
3187 protected function packString ($str) {
3189 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3191 // First compress the string (gzcompress is okay)
3192 $str = gzcompress($str);
3197 // And start the "encoding" loop
3198 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3200 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3201 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3203 if (($idx + $i) <= strlen($str)) {
3204 $ord = ord(substr($str, ($idx + $i), 1));
3206 $add = $ord * pow(256, $factor);
3210 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3214 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3215 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3217 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3218 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3224 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3229 * Creates a full-qualified file name (FQFN) for given file name by adding
3230 * a configured temporary file path to it.
3232 * @param $fileName Name for temporary file
3233 * @return $fqfn Full-qualified file name
3234 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3235 * @throws FileIoException If the file cannot be written
3237 protected static function createTempPathForFile ($fileName) {
3239 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3241 // Is the path writeable?
3242 if (!is_writable($basePath)) {
3243 // Path is write-protected
3244 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3248 $fqfn = $basePath . DIRECTORY_SEPARATOR . $fileName;
3251 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3253 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3261 * "Getter" for a printable state name
3263 * @return $stateName Name of the node's state in a printable format
3265 public final function getPrintableState () {
3266 // Default is 'null'
3267 $stateName = 'null';
3269 // Get the state instance
3270 $stateInstance = $this->getStateInstance();
3272 // Is it an instance of Stateable?
3273 if ($stateInstance instanceof Stateable) {
3274 // Then use that state name
3275 $stateName = $stateInstance->getStateName();