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\Index\Indexable;
30 use CoreFramework\Lists\Listable;
31 use CoreFramework\Loader\ClassLoader;
32 use CoreFramework\Manager\ManageableApplication;
33 use CoreFramework\Middleware\Compressor\CompressorChannel;
34 use CoreFramework\Middleware\Debug\DebugMiddleware;
35 use CoreFramework\Parser\Parseable;
36 use CoreFramework\Registry\Register;
37 use CoreFramework\Registry\Registry;
38 use CoreFramework\Resolver\Resolver;
39 use CoreFramework\Result\Database\CachedDatabaseResult;
40 use CoreFramework\Result\Search\SearchableResult;
41 use CoreFramework\Stacker\Stackable;
42 use CoreFramework\State\Stateable;
43 use CoreFramework\Stream\Input\InputStream;
44 use CoreFramework\Stream\Output\OutputStreamer;
45 use CoreFramework\Template\CompileableTemplate;
46 use CoreFramework\User\ManageableAccount;
47 use CoreFramework\Visitor\Visitor;
55 * The simulator system class is the super class of all other classes. This
56 * class handles saving of games etc.
58 * @author Roland Haeder <webmaster@shipsimu.org>
60 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
61 * @license GNU GPL 3.0 or any newer version
62 * @link http://www.shipsimu.org
64 * This program is free software: you can redistribute it and/or modify
65 * it under the terms of the GNU General Public License as published by
66 * the Free Software Foundation, either version 3 of the License, or
67 * (at your option) any later version.
69 * This program is distributed in the hope that it will be useful,
70 * but WITHOUT ANY WARRANTY; without even the implied warranty of
71 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
72 * GNU General Public License for more details.
74 * You should have received a copy of the GNU General Public License
75 * along with this program. If not, see <http://www.gnu.org/licenses/>.
77 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
79 * Length of output from hash()
81 private static $hashLength = NULL;
86 private $realClass = 'BaseFrameworkSystem';
89 * Search criteria instance
91 private $searchInstance = NULL;
94 * Update criteria instance
96 private $updateInstance = NULL;
99 * The file I/O instance for the template loader
101 private $fileIoInstance = NULL;
106 private $resolverInstance = NULL;
109 * Template engine instance
111 private $templateInstance = NULL;
114 * Database result instance
116 private $resultInstance = NULL;
119 * Instance for user class
121 private $userInstance = NULL;
124 * A controller instance
126 private $controllerInstance = NULL;
131 private $rngInstance = NULL;
134 * Instance of a crypto helper
136 private $cryptoInstance = NULL;
139 * Instance of an Iterator class
141 private $iteratorInstance = NULL;
144 * Instance of the list
146 private $listInstance = NULL;
151 private $menuInstance = NULL;
154 * Instance of the image
156 private $imageInstance = NULL;
159 * Instance of the stacker
161 private $stackInstance = NULL;
164 * A Compressor instance
166 private $compressorInstance = NULL;
169 * A Parseable instance
171 private $parserInstance = NULL;
174 * A database wrapper instance
176 private $databaseInstance = NULL;
179 * A helper instance for the form
181 private $helperInstance = NULL;
184 * An instance of a Source class
186 private $sourceInstance = NULL;
189 * An instance of a UrlSource class
191 private $urlSourceInstance = NULL;
194 * An instance of a InputStream class
196 private $inputStreamInstance = NULL;
199 * An instance of a OutputStream class
201 private $outputStreamInstance = NULL;
206 private $handlerInstance = NULL;
209 * Visitor handler instance
211 private $visitorInstance = NULL;
214 * An instance of a database wrapper class
216 private $wrapperInstance = NULL;
219 * An instance of a file I/O pointer class (not handler)
221 private $pointerInstance = NULL;
224 * An instance of an Indexable class
226 private $indexInstance = NULL;
229 * An instance of a Block class
231 private $blockInstance = NULL;
236 private $minableInstance = NULL;
239 * A FrameworkDirectory instance
241 private $directoryInstance = NULL;
244 * An instance of a communicator
246 private $communicatorInstance = NULL;
249 * The concrete output instance
251 private $outputInstance = NULL;
256 private $stateInstance = NULL;
259 * Thousands separator
261 private $thousands = '.'; // German
266 private $decimals = ','; // German
271 private $socketResource = false;
274 * Regular expression to use for validation
276 private $regularExpression = '';
281 private $packageData = array();
286 private $genericArray = array();
291 private $commandName = '';
296 private $controllerName = '';
299 * Array with bitmasks and such for pack/unpack methods to support both
300 * 32-bit and 64-bit systems
302 private $packingData = array(
305 'left' => 0xffff0000,
306 'right' => 0x0000ffff,
312 'left' => 0xffffffff00000000,
313 'right' => 0x00000000ffffffff,
320 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
322 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
324 private $archArrayElement = false;
326 /***********************
327 * Exception codes.... *
328 ***********************/
330 // @todo Try to clean these constants up
331 const EXCEPTION_IS_NULL_POINTER = 0x001;
332 const EXCEPTION_IS_NO_OBJECT = 0x002;
333 const EXCEPTION_IS_NO_ARRAY = 0x003;
334 const EXCEPTION_MISSING_METHOD = 0x004;
335 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
336 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
337 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
338 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
339 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
340 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
341 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
342 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
343 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
344 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
345 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
346 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
347 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
348 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
349 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
350 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
351 const EXCEPTION_PATH_NOT_FOUND = 0x015;
352 const EXCEPTION_INVALID_PATH_NAME = 0x016;
353 const EXCEPTION_READ_PROTECED_PATH = 0x017;
354 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
355 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
356 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
357 const EXCEPTION_INVALID_RESOURCE = 0x01b;
358 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
359 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
360 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
361 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
362 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
363 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
364 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
365 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
366 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
367 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
368 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
369 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
370 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
371 const EXCEPTION_INVALID_STRING = 0x029;
372 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
373 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
374 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
375 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
376 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
377 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
378 const EXCEPTION_MISSING_ELEMENT = 0x030;
379 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
380 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
381 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
382 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
383 const EXCEPTION_FATAL_ERROR = 0x035;
384 const EXCEPTION_FILE_NOT_FOUND = 0x036;
385 const EXCEPTION_ASSERTION_FAILED = 0x037;
386 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
387 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
388 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
389 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
390 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
391 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
392 const EXCEPTION_INVALID_SOCKET = 0x03e;
395 * Hexadecimal->Decimal translation array
397 private static $hexdec = array(
417 * Decimal->hexadecimal translation array
419 private static $dechex = array(
439 * Startup time in miliseconds
441 private static $startupTime = 0;
444 * Protected super constructor
446 * @param $className Name of the class
449 protected function __construct ($className) {
451 $this->setRealClass($className);
453 // Set configuration instance if no registry ...
454 if (!$this instanceof Register) {
455 // ... because registries doesn't need to be configured
456 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
459 // Is the startup time set? (0 cannot be true anymore)
460 if (self::$startupTime == 0) {
462 self::$startupTime = microtime(true);
466 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
470 * Destructor for all classes. You should not call this method on your own.
474 public function __destruct () {
475 // Flush any updated entries to the database
476 $this->flushPendingUpdates();
478 // Is this object already destroyed?
479 if ($this->__toString() != 'DestructedObject') {
480 // Destroy all informations about this class but keep some text about it alive
481 $this->setRealClass('DestructedObject');
482 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
483 // Already destructed object
484 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
488 // Do not call this twice
489 trigger_error(__METHOD__ . ': Called twice.');
495 * The __call() method where all non-implemented methods end up
497 * @param $methodName Name of the missing method
498 * @args $args Arguments passed to the method
501 public final function __call ($methodName, $args) {
502 return self::__callStatic($methodName, $args);
506 * The __callStatic() method where all non-implemented static methods end up
508 * @param $methodName Name of the missing method
509 * @args $args Arguments passed to the method
512 public static final function __callStatic ($methodName, $args) {
514 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
516 // Init argument string
519 // Is it NULL, empty or an array?
520 if (is_null($args)) {
522 $argsString = 'NULL';
523 } elseif (is_array($args)) {
527 // Some arguments are there
528 foreach ($args as $arg) {
529 // Add data about the argument
530 $argsString .= gettype($arg) . ':';
533 // Found a NULL argument
534 $argsString .= 'NULL';
535 } elseif (is_string($arg)) {
536 // Add length for strings
537 $argsString .= strlen($arg);
538 } elseif ((is_int($arg)) || (is_float($arg))) {
541 } elseif (is_array($arg)) {
542 // .. or size if array
543 $argsString .= count($arg);
544 } elseif (is_object($arg)) {
546 $reflection = new ReflectionClass($arg);
548 // Is an other object, maybe no __toString() available
549 $argsString .= $reflection->getName();
550 } elseif ($arg === true) {
551 // ... is boolean 'true'
552 $argsString .= 'true';
553 } elseif ($arg === false) {
554 // ... is boolean 'false'
555 $argsString .= 'false';
558 // Comma for next one
563 if (substr($argsString, -2, 1) == ',') {
564 $argsString = substr($argsString, 0, -2);
570 // Invalid arguments!
571 $argsString = '!INVALID:' . gettype($args) . '!';
574 // Output stub message
575 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
576 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
586 * Getter for $realClass
588 * @return $realClass The name of the real class (not BaseFrameworkSystem)
590 public function __toString () {
591 return $this->realClass;
595 * Magic method to catch setting of missing but set class fields/attributes
597 * @param $name Name of the field/attribute
598 * @param $value Value to store
601 public final function __set ($name, $value) {
602 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
605 print_r($value, true)
610 * Magic method to catch getting of missing fields/attributes
612 * @param $name Name of the field/attribute
615 public final function __get ($name) {
616 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
622 * Magic method to catch unsetting of missing fields/attributes
624 * @param $name Name of the field/attribute
627 public final function __unset ($name) {
628 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
634 * Magic method to catch object serialization
636 * @return $unsupported Unsupported method
637 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
639 public final function __sleep () {
640 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
644 * Magic method to catch object deserialization
646 * @return $unsupported Unsupported method
647 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
649 public final function __wakeup () {
650 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
654 * Magic method to catch calls when an object instance is called
656 * @return $unsupported Unsupported method
657 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
659 public final function __invoke () {
660 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
664 * Setter for the real class name
666 * @param $realClass Class name (string)
669 public final function setRealClass ($realClass) {
671 $this->realClass = (string) $realClass;
675 * Setter for database result instance
677 * @param $resultInstance An instance of a database result class
679 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
681 protected final function setResultInstance (SearchableResult $resultInstance) {
682 $this->resultInstance = $resultInstance;
686 * Getter for database result instance
688 * @return $resultInstance An instance of a database result class
690 public final function getResultInstance () {
691 return $this->resultInstance;
695 * Setter for template engine instances
697 * @param $templateInstance An instance of a template engine class
700 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
701 $this->templateInstance = $templateInstance;
705 * Getter for template engine instances
707 * @return $templateInstance An instance of a template engine class
709 protected final function getTemplateInstance () {
710 return $this->templateInstance;
714 * Setter for search instance
716 * @param $searchInstance Searchable criteria instance
719 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
720 $this->searchInstance = $searchInstance;
724 * Getter for search instance
726 * @return $searchInstance Searchable criteria instance
728 public final function getSearchInstance () {
729 return $this->searchInstance;
733 * Setter for update instance
735 * @param $updateInstance An instance of a LocalUpdateCriteria clase
738 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
739 $this->updateInstance = $updateInstance;
743 * Getter for update instance
745 * @return $updateInstance Updateable criteria instance
747 public final function getUpdateInstance () {
748 return $this->updateInstance;
752 * Setter for resolver instance
754 * @param $resolverInstance Instance of a command resolver class
757 public final function setResolverInstance (Resolver $resolverInstance) {
758 $this->resolverInstance = $resolverInstance;
762 * Getter for resolver instance
764 * @return $resolverInstance Instance of a command resolver class
766 public final function getResolverInstance () {
767 return $this->resolverInstance;
771 * Setter for language instance
773 * @param $configInstance The configuration instance which shall
774 * be FrameworkConfiguration
777 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
778 Registry::getRegistry()->addInstance('config', $configInstance);
782 * Getter for configuration instance
784 * @return $configInstance Configuration instance
786 public final function getConfigInstance () {
787 $configInstance = Registry::getRegistry()->getInstance('config');
788 return $configInstance;
792 * Setter for debug instance
794 * @param $debugInstance The instance for debug output class
797 public final function setDebugInstance (DebugMiddleware $debugInstance) {
798 Registry::getRegistry()->addInstance('debug', $debugInstance);
802 * Getter for debug instance
804 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
806 public final function getDebugInstance () {
807 // Get debug instance
808 $debugInstance = Registry::getRegistry()->getInstance('debug');
811 return $debugInstance;
815 * Setter for web output instance
817 * @param $webInstance The instance for web output class
820 public final function setWebOutputInstance (OutputStreamer $webInstance) {
821 Registry::getRegistry()->addInstance('web_output', $webInstance);
825 * Getter for web output instance
827 * @return $webOutputInstance - Instance to class WebOutput
829 public final function getWebOutputInstance () {
830 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
831 return $webOutputInstance;
835 * Setter for database instance
837 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
840 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
841 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
845 * Getter for database layer
847 * @return $databaseInstance The database layer instance
849 public final function getDatabaseInstance () {
851 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
854 return $databaseInstance;
858 * Setter for compressor channel
860 * @param $compressorInstance An instance of CompressorChannel
863 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
864 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
868 * Getter for compressor channel
870 * @return $compressorInstance The compressor channel
872 public final function getCompressorChannel () {
873 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
874 return $compressorInstance;
878 * Protected getter for a manageable application helper class
880 * @return $applicationInstance An instance of a manageable application helper class
882 protected final function getApplicationInstance () {
883 $applicationInstance = Registry::getRegistry()->getInstance('app');
884 return $applicationInstance;
888 * Setter for a manageable application helper class
890 * @param $applicationInstance An instance of a manageable application helper class
893 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
894 Registry::getRegistry()->addInstance('application', $applicationInstance);
898 * Private getter for language instance
900 * @return $langInstance An instance to the language sub-system
902 protected final function getLanguageInstance () {
903 $langInstance = Registry::getRegistry()->getInstance('language');
904 return $langInstance;
908 * Setter for language instance
910 * @param $langInstance An instance to the language sub-system
912 * @see LanguageSystem
914 public final function setLanguageInstance (ManageableLanguage $langInstance) {
915 Registry::getRegistry()->addInstance('language', $langInstance);
919 * Private getter for file IO instance
921 * @return $fileIoInstance An instance to the file I/O sub-system
923 protected final function getFileIoInstance () {
924 return $this->fileIoInstance;
928 * Setter for file I/O instance
930 * @param $fileIoInstance An instance to the file I/O sub-system
933 public final function setFileIoInstance (IoHandler $fileIoInstance) {
934 $this->fileIoInstance = $fileIoInstance;
938 * Protected setter for user instance
940 * @param $userInstance An instance of a user class
943 protected final function setUserInstance (ManageableAccount $userInstance) {
944 $this->userInstance = $userInstance;
948 * Getter for user instance
950 * @return $userInstance An instance of a user class
952 public final function getUserInstance () {
953 return $this->userInstance;
957 * Setter for controller instance (this surely breaks a bit the MVC patterm)
959 * @param $controllerInstance An instance of the controller
962 public final function setControllerInstance (Controller $controllerInstance) {
963 $this->controllerInstance = $controllerInstance;
967 * Getter for controller instance (this surely breaks a bit the MVC patterm)
969 * @return $controllerInstance An instance of the controller
971 public final function getControllerInstance () {
972 return $this->controllerInstance;
976 * Setter for RNG instance
978 * @param $rngInstance An instance of a random number generator (RNG)
981 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
982 $this->rngInstance = $rngInstance;
986 * Getter for RNG instance
988 * @return $rngInstance An instance of a random number generator (RNG)
990 public final function getRngInstance () {
991 return $this->rngInstance;
995 * Setter for Cryptable instance
997 * @param $cryptoInstance An instance of a Cryptable class
1000 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1001 $this->cryptoInstance = $cryptoInstance;
1005 * Getter for Cryptable instance
1007 * @return $cryptoInstance An instance of a Cryptable class
1009 public final function getCryptoInstance () {
1010 return $this->cryptoInstance;
1014 * Setter for the list instance
1016 * @param $listInstance A list of Listable
1019 protected final function setListInstance (Listable $listInstance) {
1020 $this->listInstance = $listInstance;
1024 * Getter for the list instance
1026 * @return $listInstance A list of Listable
1028 protected final function getListInstance () {
1029 return $this->listInstance;
1033 * Setter for the menu instance
1035 * @param $menuInstance A RenderableMenu instance
1038 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1039 $this->menuInstance = $menuInstance;
1043 * Getter for the menu instance
1045 * @return $menuInstance A RenderableMenu instance
1047 protected final function getMenuInstance () {
1048 return $this->menuInstance;
1052 * Setter for image instance
1054 * @param $imageInstance An instance of an image
1057 public final function setImageInstance (BaseImage $imageInstance) {
1058 $this->imageInstance = $imageInstance;
1062 * Getter for image instance
1064 * @return $imageInstance An instance of an image
1066 public final function getImageInstance () {
1067 return $this->imageInstance;
1071 * Setter for stacker instance
1073 * @param $stackInstance An instance of an stacker
1076 public final function setStackInstance (Stackable $stackInstance) {
1077 $this->stackInstance = $stackInstance;
1081 * Getter for stacker instance
1083 * @return $stackInstance An instance of an stacker
1085 public final function getStackInstance () {
1086 return $this->stackInstance;
1090 * Setter for compressor instance
1092 * @param $compressorInstance An instance of an compressor
1095 public final function setCompressorInstance (Compressor $compressorInstance) {
1096 $this->compressorInstance = $compressorInstance;
1100 * Getter for compressor instance
1102 * @return $compressorInstance An instance of an compressor
1104 public final function getCompressorInstance () {
1105 return $this->compressorInstance;
1109 * Setter for Parseable instance
1111 * @param $parserInstance An instance of an Parseable
1114 public final function setParserInstance (Parseable $parserInstance) {
1115 $this->parserInstance = $parserInstance;
1119 * Getter for Parseable instance
1121 * @return $parserInstance An instance of an Parseable
1123 public final function getParserInstance () {
1124 return $this->parserInstance;
1128 * Setter for DatabaseWrapper instance
1130 * @param $wrapperInstance An instance of an DatabaseWrapper
1133 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1134 $this->wrapperInstance = $wrapperInstance;
1138 * Getter for DatabaseWrapper instance
1140 * @return $wrapperInstance An instance of an DatabaseWrapper
1142 public final function getWrapperInstance () {
1143 return $this->wrapperInstance;
1147 * Setter for socket resource
1149 * @param $socketResource A valid socket resource
1152 public final function setSocketResource ($socketResource) {
1153 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1154 $this->socketResource = $socketResource;
1158 * Getter for socket resource
1160 * @return $socketResource A valid socket resource
1162 public final function getSocketResource () {
1163 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1164 return $this->socketResource;
1168 * Setter for regular expression
1170 * @param $regularExpression A valid regular expression
1173 public final function setRegularExpression ($regularExpression) {
1174 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1175 $this->regularExpression = $regularExpression;
1179 * Getter for regular expression
1181 * @return $regularExpression A valid regular expression
1183 public final function getRegularExpression () {
1184 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1185 return $this->regularExpression;
1189 * Setter for helper instance
1191 * @param $helperInstance An instance of a helper class
1194 protected final function setHelperInstance (Helper $helperInstance) {
1195 $this->helperInstance = $helperInstance;
1199 * Getter for helper instance
1201 * @return $helperInstance An instance of a helper class
1203 public final function getHelperInstance () {
1204 return $this->helperInstance;
1208 * Setter for a Source instance
1210 * @param $sourceInstance An instance of a Source class
1213 protected final function setSourceInstance (Source $sourceInstance) {
1214 $this->sourceInstance = $sourceInstance;
1218 * Getter for a Source instance
1220 * @return $sourceInstance An instance of a Source class
1222 protected final function getSourceInstance () {
1223 return $this->sourceInstance;
1227 * Setter for a UrlSource instance
1229 * @param $sourceInstance An instance of a UrlSource class
1232 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1233 $this->urlSourceInstance = $urlSourceInstance;
1237 * Getter for a UrlSource instance
1239 * @return $urlSourceInstance An instance of a UrlSource class
1241 protected final function getUrlSourceInstance () {
1242 return $this->urlSourceInstance;
1246 * Getter for a InputStream instance
1248 * @param $inputStreamInstance The InputStream instance
1250 protected final function getInputStreamInstance () {
1251 return $this->inputStreamInstance;
1255 * Setter for a InputStream instance
1257 * @param $inputStreamInstance The InputStream instance
1260 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1261 $this->inputStreamInstance = $inputStreamInstance;
1265 * Getter for a OutputStream instance
1267 * @param $outputStreamInstance The OutputStream instance
1269 protected final function getOutputStreamInstance () {
1270 return $this->outputStreamInstance;
1274 * Setter for a OutputStream instance
1276 * @param $outputStreamInstance The OutputStream instance
1279 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1280 $this->outputStreamInstance = $outputStreamInstance;
1284 * Setter for handler instance
1286 * @param $handlerInstance An instance of a Handleable class
1289 protected final function setHandlerInstance (Handleable $handlerInstance) {
1290 $this->handlerInstance = $handlerInstance;
1294 * Getter for handler instance
1296 * @return $handlerInstance A Handleable instance
1298 protected final function getHandlerInstance () {
1299 return $this->handlerInstance;
1303 * Setter for visitor instance
1305 * @param $visitorInstance A Visitor instance
1308 protected final function setVisitorInstance (Visitor $visitorInstance) {
1309 $this->visitorInstance = $visitorInstance;
1313 * Getter for visitor instance
1315 * @return $visitorInstance A Visitor instance
1317 protected final function getVisitorInstance () {
1318 return $this->visitorInstance;
1322 * Setter for raw package Data
1324 * @param $packageData Raw package Data
1327 public final function setPackageData (array $packageData) {
1328 $this->packageData = $packageData;
1332 * Getter for raw package Data
1334 * @return $packageData Raw package Data
1336 public function getPackageData () {
1337 return $this->packageData;
1342 * Setter for Iterator instance
1344 * @param $iteratorInstance An instance of an Iterator
1347 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1348 $this->iteratorInstance = $iteratorInstance;
1352 * Getter for Iterator instance
1354 * @return $iteratorInstance An instance of an Iterator
1356 public final function getIteratorInstance () {
1357 return $this->iteratorInstance;
1361 * Setter for FilePointer instance
1363 * @param $pointerInstance An instance of an FilePointer class
1366 protected final function setPointerInstance (FilePointer $pointerInstance) {
1367 $this->pointerInstance = $pointerInstance;
1371 * Getter for FilePointer instance
1373 * @return $pointerInstance An instance of an FilePointer class
1375 public final function getPointerInstance () {
1376 return $this->pointerInstance;
1380 * Unsets pointer instance which triggers a call of __destruct() if the
1381 * instance is still there. This is surely not fatal on already "closed"
1382 * file pointer instances.
1384 * I don't want to mess around with above setter by giving it a default
1385 * value NULL as setter should always explicitly only set (existing) object
1386 * instances and NULL is NULL.
1390 protected final function unsetPointerInstance () {
1391 // Simply it to NULL
1392 $this->pointerInstance = NULL;
1396 * Setter for Indexable instance
1398 * @param $indexInstance An instance of an Indexable class
1401 protected final function setIndexInstance (Indexable $indexInstance) {
1402 $this->indexInstance = $indexInstance;
1406 * Getter for Indexable instance
1408 * @return $indexInstance An instance of an Indexable class
1410 public final function getIndexInstance () {
1411 return $this->indexInstance;
1415 * Setter for Block instance
1417 * @param $blockInstance An instance of an Block class
1420 protected final function setBlockInstance (Block $blockInstance) {
1421 $this->blockInstance = $blockInstance;
1425 * Getter for Block instance
1427 * @return $blockInstance An instance of an Block class
1429 public final function getBlockInstance () {
1430 return $this->blockInstance;
1434 * Setter for Minable instance
1436 * @param $minableInstance A Minable instance
1439 protected final function setMinableInstance (Minable $minableInstance) {
1440 $this->minableInstance = $minableInstance;
1444 * Getter for minable instance
1446 * @return $minableInstance A Minable instance
1448 protected final function getMinableInstance () {
1449 return $this->minableInstance;
1453 * Setter for FrameworkDirectory instance
1455 * @param $directoryInstance A FrameworkDirectory instance
1458 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1459 $this->directoryInstance = $directoryInstance;
1463 * Getter for FrameworkDirectory instance
1465 * @return $directoryInstance A FrameworkDirectory instance
1467 protected final function getDirectoryInstance () {
1468 return $this->directoryInstance;
1472 * Getter for communicator instance
1474 * @return $communicatorInstance An instance of a Communicator class
1476 public final function getCommunicatorInstance () {
1477 return $this->communicatorInstance;
1481 * Setter for communicator instance
1483 * @param $communicatorInstance An instance of a Communicator class
1486 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1487 $this->communicatorInstance = $communicatorInstance;
1491 * Setter for state instance
1493 * @param $stateInstance A Stateable instance
1496 public final function setStateInstance (Stateable $stateInstance) {
1497 $this->stateInstance = $stateInstance;
1501 * Getter for state instance
1503 * @return $stateInstance A Stateable instance
1505 public final function getStateInstance () {
1506 return $this->stateInstance;
1510 * Setter for output instance
1512 * @param $outputInstance The debug output instance
1515 public final function setOutputInstance (OutputStreamer $outputInstance) {
1516 $this->outputInstance = $outputInstance;
1520 * Getter for output instance
1522 * @return $outputInstance The debug output instance
1524 public final function getOutputInstance () {
1525 return $this->outputInstance;
1529 * Setter for command name
1531 * @param $commandName Last validated command name
1534 protected final function setCommandName ($commandName) {
1535 $this->commandName = $commandName;
1539 * Getter for command name
1541 * @return $commandName Last validated command name
1543 protected final function getCommandName () {
1544 return $this->commandName;
1548 * Setter for controller name
1550 * @param $controllerName Last validated controller name
1553 protected final function setControllerName ($controllerName) {
1554 $this->controllerName = $controllerName;
1558 * Getter for controller name
1560 * @return $controllerName Last validated controller name
1562 protected final function getControllerName () {
1563 return $this->controllerName;
1567 * Checks whether an object equals this object. You should overwrite this
1568 * method to implement own equality checks
1570 * @param $objectInstance An instance of a FrameworkInterface object
1571 * @return $equals Whether both objects equals
1573 public function equals (FrameworkInterface $objectInstance) {
1576 $this->__toString() == $objectInstance->__toString()
1578 $this->hashCode() == $objectInstance->hashCode()
1581 // Return the result
1586 * Generates a generic hash code of this class. You should really overwrite
1587 * this method with your own hash code generator code. But keep KISS in mind.
1589 * @return $hashCode A generic hash code respresenting this whole class
1591 public function hashCode () {
1593 return crc32($this->__toString());
1597 * Formats computer generated price values into human-understandable formats
1598 * with thousand and decimal separators.
1600 * @param $value The in computer format value for a price
1601 * @param $currency The currency symbol (use HTML-valid characters!)
1602 * @param $decNum Number of decimals after commata
1603 * @return $price The for the current language formated price string
1604 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1605 * thousands separator
1608 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1609 // Are all required attriutes set?
1610 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1611 // Throw an exception
1612 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1616 $value = (float) $value;
1618 // Reformat the US number
1619 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1621 // Return as string...
1626 * Appends a trailing slash to a string
1628 * @param $str A string (maybe) without trailing slash
1629 * @return $str A string with an auto-appended trailing slash
1631 public final function addMissingTrailingSlash ($str) {
1632 // Is there a trailing slash?
1633 if (substr($str, -1, 1) != '/') {
1637 // Return string with trailing slash
1642 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1643 * application helper instance (ApplicationHelper by default).
1645 * @param $applicationInstance An application helper instance or
1646 * null if we shall use the default
1647 * @return $templateInstance The template engine instance
1648 * @throws NullPointerException If the discovered application
1649 * instance is still null
1651 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1652 // Is the application instance set?
1653 if (is_null($applicationInstance)) {
1654 // Get the current instance
1655 $applicationInstance = Registry::getRegistry()->getInstance('app');
1658 if (is_null($applicationInstance)) {
1659 // Thrown an exception
1660 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1664 // Initialize the template engine
1665 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1667 // Return the prepared instance
1668 return $templateInstance;
1672 * Debugs this instance by putting out it's full content
1674 * @param $message Optional message to show in debug output
1677 public final function debugInstance ($message = '') {
1678 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1679 restore_error_handler();
1684 // Is a message set?
1685 if (!empty($message)) {
1686 // Construct message
1687 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1690 // Generate the output
1691 $content .= sprintf('<pre>%s</pre>',
1694 print_r($this, true)
1700 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">%s debug output:</div><div class="debug_content">%s</div>Loaded includes: <div class="debug_include_list">%s</div>',
1701 $this->__toString(),
1703 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1708 * Replaces control characters with printable output
1710 * @param $str String with control characters
1711 * @return $str Replaced string
1713 protected function replaceControlCharacters ($str) {
1716 chr(13), '[r]', str_replace(
1717 chr(10), '[n]', str_replace(
1727 * Output a partial stub message for the caller method
1729 * @param $message An optional message to display
1732 protected function partialStub ($message = '') {
1733 // Get the backtrace
1734 $backtrace = debug_backtrace();
1736 // Generate the class::method string
1737 $methodName = 'UnknownClass->unknownMethod';
1738 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1739 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1742 // Construct the full message
1743 $stubMessage = sprintf('[%s]: Partial stub!',
1747 // Is the extra message given?
1748 if (!empty($message)) {
1749 // Then add it as well
1750 $stubMessage .= ' Message: ' . $message;
1753 // Debug instance is there?
1754 if (!is_null($this->getDebugInstance())) {
1755 // Output stub message
1756 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1759 trigger_error($stubMessage);
1765 * Outputs a debug backtrace and stops further script execution
1767 * @param $message An optional message to output
1768 * @param $doExit Whether exit the program (true is default)
1771 public function debugBackTrace ($message = '', $doExit = true) {
1772 // Sorry, there is no other way getting this nice backtrace
1773 if (!empty($message)) {
1775 printf('Message: %s<br />' . PHP_EOL, $message);
1779 debug_print_backtrace();
1783 if ($doExit === true) {
1789 * Creates an instance of a debugger instance
1791 * @param $className Name of the class (currently unsupported)
1792 * @param $lineNumber Line number where the call was made
1793 * @return $debugInstance An instance of a debugger class
1794 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1796 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1797 // Is the instance set?
1798 if (!Registry::getRegistry()->instanceExists('debug')) {
1799 // Init debug instance
1800 $debugInstance = NULL;
1804 // Get a debugger instance
1805 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1806 } catch (NullPointerException $e) {
1807 // Didn't work, no instance there
1808 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1811 // Empty string should be ignored and used for testing the middleware
1812 DebugMiddleware::getSelfInstance()->output('');
1814 // Set it in its own class. This will set it in the registry
1815 $debugInstance->setDebugInstance($debugInstance);
1817 // Get instance from registry
1818 $debugInstance = Registry::getRegistry()->getDebugInstance();
1822 return $debugInstance;
1826 * Simple output of a message with line-break
1828 * @param $message Message to output
1831 public function outputLine ($message) {
1833 print($message . PHP_EOL);
1837 * Outputs a debug message whether to debug instance (should be set!) or
1838 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1839 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1841 * @param $message Message we shall send out...
1842 * @param $doPrint Whether print or die here (default: print)
1843 * @paran $stripTags Whether to strip tags (default: false)
1846 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1847 // Set debug instance to NULL
1848 $debugInstance = NULL;
1852 // Get debug instance
1853 $debugInstance = $this->getDebugInstance();
1854 } catch (NullPointerException $e) {
1855 // The debug instance is not set (yet)
1858 // Is the debug instance there?
1859 if (is_object($debugInstance)) {
1860 // Use debug output handler
1861 $debugInstance->output($message, $stripTags);
1863 if ($doPrint === false) {
1864 // Die here if not printed
1868 // Are debug times enabled?
1869 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1871 $message = $this->getPrintableExecutionTime() . $message;
1875 if ($doPrint === true) {
1877 $this->outputLine($message);
1886 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1888 * @param $str The string, what ever it is needs to be converted
1889 * @return $className Generated class name
1891 public static final function convertToClassName ($str) {
1895 // Convert all dashes in underscores
1896 $str = self::convertDashesToUnderscores($str);
1898 // Now use that underscores to get classname parts for hungarian style
1899 foreach (explode('_', $str) as $strPart) {
1900 // Make the class name part lower case and first upper case
1901 $className .= ucfirst(strtolower($strPart));
1904 // Return class name
1909 * Converts dashes to underscores, e.g. useable for configuration entries
1911 * @param $str The string with maybe dashes inside
1912 * @return $str The converted string with no dashed, but underscores
1914 public static final function convertDashesToUnderscores ($str) {
1916 $str = str_replace('-', '_', $str);
1918 // Return converted string
1923 * Marks up the code by adding e.g. line numbers
1925 * @param $phpCode Unmarked PHP code
1926 * @return $markedCode Marked PHP code
1928 public function markupCode ($phpCode) {
1933 $errorArray = error_get_last();
1935 // Init the code with error message
1936 if (is_array($errorArray)) {
1938 $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>',
1939 basename($errorArray['file']),
1940 $errorArray['line'],
1941 $errorArray['message'],
1946 // Add line number to the code
1947 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1949 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1951 htmlentities($code, ENT_QUOTES)
1960 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1961 * beatiful for web-based front-ends. If null is given a message id
1962 * null_timestamp will be resolved and returned.
1964 * @param $timestamp Timestamp to prepare (filter) for display
1965 * @return $readable A readable timestamp
1967 public function doFilterFormatTimestamp ($timestamp) {
1968 // Default value to return
1971 // Is the timestamp null?
1972 if (is_null($timestamp)) {
1973 // Get a message string
1974 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1976 switch ($this->getLanguageInstance()->getLanguageCode()) {
1977 case 'de': // German format is a bit different to default
1978 // Split the GMT stamp up
1979 $dateTime = explode(' ', $timestamp );
1980 $dateArray = explode('-', $dateTime[0]);
1981 $timeArray = explode(':', $dateTime[1]);
1983 // Construct the timestamp
1984 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1994 default: // Default is pass-through
1995 $readable = $timestamp;
2005 * Filter a given number into a localized number
2007 * @param $value The raw value from e.g. database
2008 * @return $localized Localized value
2010 public function doFilterFormatNumber ($value) {
2011 // Generate it from config and localize dependencies
2012 switch ($this->getLanguageInstance()->getLanguageCode()) {
2013 case 'de': // German format is a bit different to default
2014 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2017 default: // US, etc.
2018 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2027 * "Getter" for databse entry
2029 * @return $entry An array with database entries
2030 * @throws NullPointerException If the database result is not found
2031 * @throws InvalidDatabaseResultException If the database result is invalid
2033 protected final function getDatabaseEntry () {
2034 // Is there an instance?
2035 if (!$this->getResultInstance() instanceof SearchableResult) {
2036 // Throw an exception here
2037 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2041 $this->getResultInstance()->rewind();
2043 // Do we have an entry?
2044 if ($this->getResultInstance()->valid() === false) {
2045 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2046 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2050 $this->getResultInstance()->next();
2053 $entry = $this->getResultInstance()->current();
2060 * Getter for field name
2062 * @param $fieldName Field name which we shall get
2063 * @return $fieldValue Field value from the user
2064 * @throws NullPointerException If the result instance is null
2066 public final function getField ($fieldName) {
2067 // Default field value
2070 // Get result instance
2071 $resultInstance = $this->getResultInstance();
2073 // Is this instance null?
2074 if (is_null($resultInstance)) {
2075 // Then the user instance is no longer valid (expired cookies?)
2076 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2079 // Get current array
2080 $fieldArray = $resultInstance->current();
2081 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2083 // Convert dashes to underscore
2084 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2086 // Does the field exist?
2087 if ($this->isFieldSet($fieldName)) {
2089 $fieldValue = $fieldArray[$fieldName2];
2090 } elseif (defined('DEVELOPER')) {
2091 // Missing field entry, may require debugging
2092 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2094 // Missing field entry, may require debugging
2095 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2103 * Checks if given field is set
2105 * @param $fieldName Field name to check
2106 * @return $isSet Whether the given field name is set
2107 * @throws NullPointerException If the result instance is null
2109 public function isFieldSet ($fieldName) {
2110 // Get result instance
2111 $resultInstance = $this->getResultInstance();
2113 // Is this instance null?
2114 if (is_null($resultInstance)) {
2115 // Then the user instance is no longer valid (expired cookies?)
2116 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2119 // Get current array
2120 $fieldArray = $resultInstance->current();
2121 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2123 // Convert dashes to underscore
2124 $fieldName = self::convertDashesToUnderscores($fieldName);
2127 $isSet = isset($fieldArray[$fieldName]);
2134 * Flushs all pending updates to the database layer
2138 public function flushPendingUpdates () {
2139 // Get result instance
2140 $resultInstance = $this->getResultInstance();
2142 // Do we have data to update?
2143 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2144 // Get wrapper class name config entry
2145 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2147 // Create object instance
2148 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2150 // Yes, then send the whole result to the database layer
2151 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2156 * Outputs a deprecation warning to the developer.
2158 * @param $message The message we shall output to the developer
2160 * @todo Write a logging mechanism for productive mode
2162 public function deprecationWarning ($message) {
2163 // Is developer mode active?
2164 if (defined('DEVELOPER')) {
2165 // Debug instance is there?
2166 if (!is_null($this->getDebugInstance())) {
2167 // Output stub message
2168 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2171 trigger_error($message . "<br />\n");
2175 // @TODO Finish this part!
2176 $this->partialStub('Developer mode inactive. Message:' . $message);
2181 * Checks whether the given PHP extension is loaded
2183 * @param $phpExtension The PHP extension we shall check
2184 * @return $isLoaded Whether the PHP extension is loaded
2186 public final function isPhpExtensionLoaded ($phpExtension) {
2188 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2195 * "Getter" as a time() replacement but with milliseconds. You should use this
2196 * method instead of the encapsulated getimeofday() function.
2198 * @return $milliTime Timestamp with milliseconds
2200 public function getMilliTime () {
2201 // Get the time of day as float
2202 $milliTime = gettimeofday(true);
2209 * Idles (sleeps) for given milliseconds
2211 * @return $hasSlept Whether it goes fine
2213 public function idle ($milliSeconds) {
2214 // Sleep is fine by default
2217 // Idle so long with found function
2218 if (function_exists('time_sleep_until')) {
2219 // Get current time and add idle time
2220 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2222 // New PHP 5.1.0 function found, ignore errors
2223 $hasSlept = @time_sleep_until($sleepUntil);
2226 * My Sun station doesn't have that function even with latest PHP
2229 usleep($milliSeconds * 1000);
2236 * Converts a hexadecimal string, even with negative sign as first string to
2237 * a decimal number using BC functions.
2239 * This work is based on comment #86673 on php.net documentation page at:
2240 * <http://de.php.net/manual/en/function.dechex.php#86673>
2242 * @param $hex Hexadecimal string
2243 * @return $dec Decimal number
2245 protected function hex2dec ($hex) {
2246 // Convert to all lower-case
2247 $hex = strtolower($hex);
2249 // Detect sign (negative/positive numbers)
2251 if (substr($hex, 0, 1) == '-') {
2253 $hex = substr($hex, 1);
2256 // Decode the hexadecimal string into a decimal number
2258 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2259 $factor = self::$hexdec[substr($hex, $i, 1)];
2260 $dec = bcadd($dec, bcmul($factor, $e));
2263 // Return the decimal number
2264 return $sign . $dec;
2268 * Converts even very large decimal numbers, also signed, to a hexadecimal
2271 * This work is based on comment #97756 on php.net documentation page at:
2272 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2274 * @param $dec Decimal number, even with negative sign
2275 * @param $maxLength Optional maximum length of the string
2276 * @return $hex Hexadecimal string
2278 protected function dec2hex ($dec, $maxLength = 0) {
2279 // maxLength can be zero or devideable by 2
2280 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2282 // Detect sign (negative/positive numbers)
2289 // Encode the decimal number into a hexadecimal string
2292 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2294 } while ($dec >= 1);
2297 * Leading zeros are required for hex-decimal "numbers". In some
2298 * situations more leading zeros are wanted, so check for both
2301 if ($maxLength > 0) {
2302 // Prepend more zeros
2303 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2304 } elseif ((strlen($hex) % 2) != 0) {
2305 // Only make string's length dividable by 2
2309 // Return the hexadecimal string
2310 return $sign . $hex;
2314 * Converts a ASCII string (0 to 255) into a decimal number.
2316 * @param $asc The ASCII string to be converted
2317 * @return $dec Decimal number
2319 protected function asc2dec ($asc) {
2320 // Convert it into a hexadecimal number
2321 $hex = bin2hex($asc);
2323 // And back into a decimal number
2324 $dec = $this->hex2dec($hex);
2331 * Converts a decimal number into an ASCII string.
2333 * @param $dec Decimal number
2334 * @return $asc An ASCII string
2336 protected function dec2asc ($dec) {
2337 // First convert the number into a hexadecimal string
2338 $hex = $this->dec2hex($dec);
2340 // Then convert it into the ASCII string
2341 $asc = $this->hex2asc($hex);
2348 * Converts a hexadecimal number into an ASCII string. Negative numbers
2351 * @param $hex Hexadecimal string
2352 * @return $asc An ASCII string
2354 protected function hex2asc ($hex) {
2355 // Check for length, it must be devideable by 2
2356 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2357 assert((strlen($hex) % 2) == 0);
2361 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2362 // Get the decimal number of the chunk
2363 $part = hexdec(substr($hex, $idx, 2));
2365 // Add it to the final string
2369 // Return the final string
2374 * Checks whether the given encoded data was encoded with Base64
2376 * @param $encodedData Encoded data we shall check
2377 * @return $isBase64 Whether the encoded data is Base64
2379 protected function isBase64Encoded ($encodedData) {
2381 $isBase64 = (@base64_decode($encodedData, true) !== false);
2388 * Gets a cache key from Criteria instance
2390 * @param $criteriaInstance An instance of a Criteria class
2391 * @param $onlyKeys Only use these keys for a cache key
2392 * @return $cacheKey A cache key suitable for lookup/storage purposes
2394 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2396 $cacheKey = sprintf('%s@%s',
2397 $this->__toString(),
2398 $criteriaInstance->getCacheKey($onlyKeys)
2402 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2407 * Getter for startup time in miliseconds
2409 * @return $startupTime Startup time in miliseconds
2411 protected function getStartupTime () {
2412 return self::$startupTime;
2416 * "Getter" for a printable currently execution time in nice braces
2418 * @return $executionTime Current execution time in nice braces
2420 protected function getPrintableExecutionTime () {
2421 // Caculate the execution time
2422 $executionTime = microtime(true) - $this->getStartupTime();
2424 // Pack it in nice braces
2425 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2428 return $executionTime;
2432 * Hashes a given string with a simple but stronger hash function (no salt)
2433 * and hex-encode it.
2435 * @param $str The string to be hashed
2436 * @return $hash The hash from string $str
2438 public static final function hash ($str) {
2439 // Hash given string with (better secure) hasher
2440 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2447 * "Getter" for length of hash() output. This will be "cached" to speed up
2450 * @return $length Length of hash() output
2452 public static final function getHashLength () {
2454 if (is_null(self::$hashLength)) {
2455 // No, then hash a string and save its length.
2456 self::$hashLength = strlen(self::hash('abc123'));
2460 return self::$hashLength;
2464 * Checks whether the given number is really a number (only chars 0-9).
2466 * @param $num A string consisting only chars between 0 and 9
2467 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2468 * @param $assertMismatch Whether to assert mismatches
2469 * @return $ret The (hopefully) secured numbered value
2471 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2472 // Filter all numbers out
2473 $ret = preg_replace('/[^0123456789]/', '', $num);
2476 if ($castValue === true) {
2477 // Cast to biggest numeric type
2478 $ret = (double) $ret;
2481 // Assert only if requested
2482 if ($assertMismatch === true) {
2483 // Has the whole value changed?
2484 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2492 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2494 * @param $num A string consisting only chars between 0 and 9
2495 * @param $assertMismatch Whether to assert mismatches
2496 * @return $ret The (hopefully) secured hext-numbered value
2498 public function hexval ($num, $assertMismatch = false) {
2499 // Filter all numbers out
2500 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2502 // Assert only if requested
2503 if ($assertMismatch === true) {
2504 // Has the whole value changed?
2505 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2513 * Determines if an element is set in the generic array
2515 * @param $keyGroup Main group for the key
2516 * @param $subGroup Sub group for the key
2517 * @param $key Key to check
2518 * @param $element Element to check
2519 * @return $isset Whether the given key is set
2521 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2523 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2526 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2532 * Determines if a key is set in the generic array
2534 * @param $keyGroup Main group for the key
2535 * @param $subGroup Sub group for the key
2536 * @param $key Key to check
2537 * @return $isset Whether the given key is set
2539 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2541 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2544 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2552 * Determines if a group is set in the generic array
2554 * @param $keyGroup Main group
2555 * @param $subGroup Sub group
2556 * @return $isset Whether the given group is set
2558 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2560 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2563 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2570 * Getter for sub key group
2572 * @param $keyGroup Main key group
2573 * @param $subGroup Sub key group
2574 * @return $array An array with all array elements
2576 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2578 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2579 // No, then abort here
2580 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2585 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2588 return $this->genericArray[$keyGroup][$subGroup];
2592 * Unsets a given key in generic array
2594 * @param $keyGroup Main group for the key
2595 * @param $subGroup Sub group for the key
2596 * @param $key Key to unset
2599 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2601 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2604 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2608 * Unsets a given element in generic array
2610 * @param $keyGroup Main group for the key
2611 * @param $subGroup Sub group for the key
2612 * @param $key Key to unset
2613 * @param $element Element to unset
2616 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2618 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2621 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2625 * Append a string to a given generic array key
2627 * @param $keyGroup Main group for the key
2628 * @param $subGroup Sub group for the key
2629 * @param $key Key to unset
2630 * @param $value Value to add/append
2633 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2635 //* 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);
2637 // Is it already there?
2638 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2640 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2643 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2648 * Append a string to a given generic array element
2650 * @param $keyGroup Main group for the key
2651 * @param $subGroup Sub group for the key
2652 * @param $key Key to unset
2653 * @param $element Element to check
2654 * @param $value Value to add/append
2657 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2659 //* 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);
2661 // Is it already there?
2662 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2664 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2667 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2672 * Sets a string in 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 setStringGenericArrayElement ($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);
2686 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2690 * Initializes given generic array group
2692 * @param $keyGroup Main group for the key
2693 * @param $subGroup Sub group for the key
2694 * @param $key Key to use
2695 * @param $forceInit Optionally force initialization
2698 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2700 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2702 // Is it already set?
2703 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2704 // Already initialized
2705 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2710 $this->genericArray[$keyGroup][$subGroup] = array();
2714 * Initializes given generic array key
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 initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2724 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2726 // Is it already set?
2727 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2728 // Already initialized
2729 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2734 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2738 * Initializes given generic array element
2740 * @param $keyGroup Main group for the key
2741 * @param $subGroup Sub group for the key
2742 * @param $key Key to use
2743 * @param $element Element to use
2744 * @param $forceInit Optionally force initialization
2747 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2749 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2751 // Is it already set?
2752 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2753 // Already initialized
2754 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2759 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2763 * Pushes an element to a generic key
2765 * @param $keyGroup Main group for the key
2766 * @param $subGroup Sub group for the key
2767 * @param $key Key to use
2768 * @param $value Value to add/append
2769 * @return $count Number of array elements
2771 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2773 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2776 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2778 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2782 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2785 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2786 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2791 * Pushes an element to a generic array element
2793 * @param $keyGroup Main group for the key
2794 * @param $subGroup Sub group for the key
2795 * @param $key Key to use
2796 * @param $element Element to check
2797 * @param $value Value to add/append
2798 * @return $count Number of array elements
2800 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2802 //* 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));
2805 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2807 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2811 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2814 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2815 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2820 * Pops an element from a generic group
2822 * @param $keyGroup Main group for the key
2823 * @param $subGroup Sub group for the key
2824 * @param $key Key to unset
2825 * @return $value Last "popped" value
2827 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2829 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2832 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2834 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2839 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2842 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2843 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2848 * Shifts an element from a generic group
2850 * @param $keyGroup Main group for the key
2851 * @param $subGroup Sub group for the key
2852 * @param $key Key to unset
2853 * @return $value Last "popped" value
2855 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2857 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2860 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2862 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2867 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2870 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2871 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2876 * Count generic array group
2878 * @param $keyGroup Main group for the key
2879 * @return $count Count of given group
2881 protected final function countGenericArray ($keyGroup) {
2883 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2886 if (!isset($this->genericArray[$keyGroup])) {
2888 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2893 $count = count($this->genericArray[$keyGroup]);
2896 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2903 * Count generic array sub group
2905 * @param $keyGroup Main group for the key
2906 * @param $subGroup Sub group for the key
2907 * @return $count Count of given group
2909 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2911 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2914 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2916 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2921 $count = count($this->genericArray[$keyGroup][$subGroup]);
2924 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2931 * Count generic array elements
2933 * @param $keyGroup Main group for the key
2934 * @param $subGroup Sub group for the key
2935 * @para $key Key to count
2936 * @return $count Count of given key
2938 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2940 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2943 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2945 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2947 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2949 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2954 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2957 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2964 * Getter for whole generic group array
2966 * @param $keyGroup Key group to get
2967 * @return $array Whole generic array group
2969 protected final function getGenericArray ($keyGroup) {
2971 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2974 if (!isset($this->genericArray[$keyGroup])) {
2976 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2981 return $this->genericArray[$keyGroup];
2985 * Setter for generic array key
2987 * @param $keyGroup Key group to get
2988 * @param $subGroup Sub group for the key
2989 * @param $key Key to unset
2990 * @param $value Mixed value from generic array element
2993 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2995 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2998 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3002 * Getter for generic array key
3004 * @param $keyGroup Key group to get
3005 * @param $subGroup Sub group for the key
3006 * @param $key Key to unset
3007 * @return $value Mixed value from generic array element
3009 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3011 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3014 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3016 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3021 return $this->genericArray[$keyGroup][$subGroup][$key];
3025 * Sets a value in given generic array key/element
3027 * @param $keyGroup Main group for the key
3028 * @param $subGroup Sub group for the key
3029 * @param $key Key to set
3030 * @param $element Element to set
3031 * @param $value Value to set
3034 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3036 //* 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));
3039 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3043 * Getter for generic array element
3045 * @param $keyGroup Key group to get
3046 * @param $subGroup Sub group for the key
3047 * @param $key Key to look for
3048 * @param $element Element to look for
3049 * @return $value Mixed value from generic array element
3051 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3053 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3056 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3058 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3063 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3067 * Checks if a given sub group is valid (array)
3069 * @param $keyGroup Key group to get
3070 * @param $subGroup Sub group for the key
3071 * @return $isValid Whether given sub group is valid
3073 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3075 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3078 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3085 * Checks if a given key is valid (array)
3087 * @param $keyGroup Key group to get
3088 * @param $subGroup Sub group for the key
3089 * @param $key Key to check
3090 * @return $isValid Whether given sub group is valid
3092 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3094 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3097 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3104 * Initializes the web output instance
3108 protected function initWebOutputInstance () {
3109 // Get application instance
3110 $applicationInstance = Registry::getRegistry()->getInstance('app');
3112 // Init web output instance
3113 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3116 $this->setWebOutputInstance($outputInstance);
3120 * Translates boolean true to 'Y' and false to 'N'
3122 * @param $boolean Boolean value
3123 * @return $translated Translated boolean value
3125 public static final function translateBooleanToYesNo ($boolean) {
3126 // Make sure it is really boolean
3127 assert(is_bool($boolean));
3130 $translated = ($boolean === true) ? 'Y' : 'N';
3132 // ... and return it
3137 * Encodes raw data (almost any type) by "serializing" it and then pack it
3138 * into a "binary format".
3140 * @param $rawData Raw data (almost any type)
3141 * @return $encoded Encoded data
3143 protected function encodeData ($rawData) {
3144 // Make sure no objects or resources pass through
3145 assert(!is_object($rawData));
3146 assert(!is_resource($rawData));
3148 // First "serialize" it (json_encode() is faster than serialize())
3149 $encoded = $this->packString(json_encode($rawData));
3156 * Pack a string into a "binary format". Please execuse me that this is
3157 * widely undocumented. :-(
3159 * @param $str Unpacked string
3160 * @return $packed Packed string
3161 * @todo Improve documentation
3163 protected function packString ($str) {
3165 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3167 // First compress the string (gzcompress is okay)
3168 $str = gzcompress($str);
3173 // And start the "encoding" loop
3174 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3176 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3177 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3179 if (($idx + $i) <= strlen($str)) {
3180 $ord = ord(substr($str, ($idx + $i), 1));
3182 $add = $ord * pow(256, $factor);
3186 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3190 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3191 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3193 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3194 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3200 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3205 * Creates a full-qualified file name (FQFN) for given file name by adding
3206 * a configured temporary file path to it.
3208 * @param $fileName Name for temporary file
3209 * @return $fqfn Full-qualified file name
3210 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3211 * @throws FileIoException If the file cannot be written
3213 protected static function createTempPathForFile ($fileName) {
3215 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3217 // Is the path writeable?
3218 if (!is_writable($basePath)) {
3219 // Path is write-protected
3220 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3224 $fqfn = $basePath . DIRECTORY_SEPARATOR . $fileName;
3227 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3229 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3237 * "Getter" for a printable state name
3239 * @return $stateName Name of the node's state in a printable format
3241 public final function getPrintableState () {
3242 // Default is 'null'
3243 $stateName = 'null';
3245 // Get the state instance
3246 $stateInstance = $this->getStateInstance();
3248 // Is it an instance of Stateable?
3249 if ($stateInstance instanceof Stateable) {
3250 // Then use that state name
3251 $stateName = $stateInstance->getStateName();