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 = '') {
1746 // Get the backtrace
1747 $backtrace = debug_backtrace();
1749 // Generate the class::method string
1750 $methodName = 'UnknownClass->unknownMethod';
1751 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1752 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1755 // Construct the full message
1756 $stubMessage = sprintf('[%s]: Partial stub!',
1760 // Is the extra message given?
1761 if (!empty($message)) {
1762 // Then add it as well
1763 $stubMessage .= ' Message: ' . $message;
1766 // Debug instance is there?
1767 if (!is_null($this->getDebugInstance())) {
1768 // Output stub message
1769 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1772 trigger_error($stubMessage);
1778 * Outputs a debug backtrace and stops further script execution
1780 * @param $message An optional message to output
1781 * @param $doExit Whether exit the program (true is default)
1784 public function debugBackTrace ($message = '', $doExit = true) {
1785 // Sorry, there is no other way getting this nice backtrace
1786 if (!empty($message)) {
1788 printf('Message: %s<br />' . PHP_EOL, $message);
1792 debug_print_backtrace();
1796 if ($doExit === true) {
1802 * Creates an instance of a debugger instance
1804 * @param $className Name of the class (currently unsupported)
1805 * @param $lineNumber Line number where the call was made
1806 * @return $debugInstance An instance of a debugger class
1807 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1809 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1810 // Is the instance set?
1811 if (!Registry::getRegistry()->instanceExists('debug')) {
1812 // Init debug instance
1813 $debugInstance = NULL;
1817 // Get a debugger instance
1818 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1819 } catch (NullPointerException $e) {
1820 // Didn't work, no instance there
1821 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1824 // Empty string should be ignored and used for testing the middleware
1825 DebugMiddleware::getSelfInstance()->output('');
1827 // Set it in its own class. This will set it in the registry
1828 $debugInstance->setDebugInstance($debugInstance);
1830 // Get instance from registry
1831 $debugInstance = Registry::getRegistry()->getDebugInstance();
1835 return $debugInstance;
1839 * Simple output of a message with line-break
1841 * @param $message Message to output
1844 public function outputLine ($message) {
1846 print($message . PHP_EOL);
1850 * Outputs a debug message whether to debug instance (should be set!) or
1851 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1852 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1854 * @param $message Message we shall send out...
1855 * @param $doPrint Whether print or die here (default: print)
1856 * @paran $stripTags Whether to strip tags (default: false)
1859 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1860 // Set debug instance to NULL
1861 $debugInstance = NULL;
1865 // Get debug instance
1866 $debugInstance = $this->getDebugInstance();
1867 } catch (NullPointerException $e) {
1868 // The debug instance is not set (yet)
1871 // Is the debug instance there?
1872 if (is_object($debugInstance)) {
1873 // Use debug output handler
1874 $debugInstance->output($message, $stripTags);
1876 if ($doPrint === false) {
1877 // Die here if not printed
1881 // Are debug times enabled?
1882 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1884 $message = $this->getPrintableExecutionTime() . $message;
1888 if ($doPrint === true) {
1890 $this->outputLine($message);
1899 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1901 * @param $str The string, what ever it is needs to be converted
1902 * @return $className Generated class name
1904 public static final function convertToClassName ($str) {
1908 // Convert all dashes in underscores
1909 $str = self::convertDashesToUnderscores($str);
1911 // Now use that underscores to get classname parts for hungarian style
1912 foreach (explode('_', $str) as $strPart) {
1913 // Make the class name part lower case and first upper case
1914 $className .= ucfirst(strtolower($strPart));
1917 // Return class name
1922 * Converts dashes to underscores, e.g. useable for configuration entries
1924 * @param $str The string with maybe dashes inside
1925 * @return $str The converted string with no dashed, but underscores
1927 public static final function convertDashesToUnderscores ($str) {
1929 $str = str_replace('-', '_', $str);
1931 // Return converted string
1936 * Marks up the code by adding e.g. line numbers
1938 * @param $phpCode Unmarked PHP code
1939 * @return $markedCode Marked PHP code
1941 public function markupCode ($phpCode) {
1946 $errorArray = error_get_last();
1948 // Init the code with error message
1949 if (is_array($errorArray)) {
1951 $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>',
1952 basename($errorArray['file']),
1953 $errorArray['line'],
1954 $errorArray['message'],
1959 // Add line number to the code
1960 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1962 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1964 htmlentities($code, ENT_QUOTES)
1973 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1974 * beatiful for web-based front-ends. If null is given a message id
1975 * null_timestamp will be resolved and returned.
1977 * @param $timestamp Timestamp to prepare (filter) for display
1978 * @return $readable A readable timestamp
1980 public function doFilterFormatTimestamp ($timestamp) {
1981 // Default value to return
1984 // Is the timestamp null?
1985 if (is_null($timestamp)) {
1986 // Get a message string
1987 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1989 switch ($this->getLanguageInstance()->getLanguageCode()) {
1990 case 'de': // German format is a bit different to default
1991 // Split the GMT stamp up
1992 $dateTime = explode(' ', $timestamp );
1993 $dateArray = explode('-', $dateTime[0]);
1994 $timeArray = explode(':', $dateTime[1]);
1996 // Construct the timestamp
1997 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2007 default: // Default is pass-through
2008 $readable = $timestamp;
2018 * Filter a given number into a localized number
2020 * @param $value The raw value from e.g. database
2021 * @return $localized Localized value
2023 public function doFilterFormatNumber ($value) {
2024 // Generate it from config and localize dependencies
2025 switch ($this->getLanguageInstance()->getLanguageCode()) {
2026 case 'de': // German format is a bit different to default
2027 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2030 default: // US, etc.
2031 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2040 * "Getter" for databse entry
2042 * @return $entry An array with database entries
2043 * @throws NullPointerException If the database result is not found
2044 * @throws InvalidDatabaseResultException If the database result is invalid
2046 protected final function getDatabaseEntry () {
2047 // Is there an instance?
2048 if (!$this->getResultInstance() instanceof SearchableResult) {
2049 // Throw an exception here
2050 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2054 $this->getResultInstance()->rewind();
2056 // Do we have an entry?
2057 if ($this->getResultInstance()->valid() === false) {
2058 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2059 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2063 $this->getResultInstance()->next();
2066 $entry = $this->getResultInstance()->current();
2073 * Getter for field name
2075 * @param $fieldName Field name which we shall get
2076 * @return $fieldValue Field value from the user
2077 * @throws NullPointerException If the result instance is null
2079 public final function getField ($fieldName) {
2080 // Default field value
2083 // Get result instance
2084 $resultInstance = $this->getResultInstance();
2086 // Is this instance null?
2087 if (is_null($resultInstance)) {
2088 // Then the user instance is no longer valid (expired cookies?)
2089 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2092 // Get current array
2093 $fieldArray = $resultInstance->current();
2094 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2096 // Convert dashes to underscore
2097 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2099 // Does the field exist?
2100 if ($this->isFieldSet($fieldName)) {
2102 $fieldValue = $fieldArray[$fieldName2];
2103 } elseif (defined('DEVELOPER')) {
2104 // Missing field entry, may require debugging
2105 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2107 // Missing field entry, may require debugging
2108 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2116 * Checks if given field is set
2118 * @param $fieldName Field name to check
2119 * @return $isSet Whether the given field name is set
2120 * @throws NullPointerException If the result instance is null
2122 public function isFieldSet ($fieldName) {
2123 // Get result instance
2124 $resultInstance = $this->getResultInstance();
2126 // Is this instance null?
2127 if (is_null($resultInstance)) {
2128 // Then the user instance is no longer valid (expired cookies?)
2129 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2132 // Get current array
2133 $fieldArray = $resultInstance->current();
2134 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2136 // Convert dashes to underscore
2137 $fieldName = self::convertDashesToUnderscores($fieldName);
2140 $isSet = isset($fieldArray[$fieldName]);
2147 * Flushs all pending updates to the database layer
2151 public function flushPendingUpdates () {
2152 // Get result instance
2153 $resultInstance = $this->getResultInstance();
2155 // Do we have data to update?
2156 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2157 // Get wrapper class name config entry
2158 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2160 // Create object instance
2161 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2163 // Yes, then send the whole result to the database layer
2164 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2169 * Outputs a deprecation warning to the developer.
2171 * @param $message The message we shall output to the developer
2173 * @todo Write a logging mechanism for productive mode
2175 public function deprecationWarning ($message) {
2176 // Is developer mode active?
2177 if (defined('DEVELOPER')) {
2178 // Debug instance is there?
2179 if (!is_null($this->getDebugInstance())) {
2180 // Output stub message
2181 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2184 trigger_error($message . "<br />\n");
2188 // @TODO Finish this part!
2189 $this->partialStub('Developer mode inactive. Message:' . $message);
2194 * Checks whether the given PHP extension is loaded
2196 * @param $phpExtension The PHP extension we shall check
2197 * @return $isLoaded Whether the PHP extension is loaded
2199 public final function isPhpExtensionLoaded ($phpExtension) {
2201 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2208 * "Getter" as a time() replacement but with milliseconds. You should use this
2209 * method instead of the encapsulated getimeofday() function.
2211 * @return $milliTime Timestamp with milliseconds
2213 public function getMilliTime () {
2214 // Get the time of day as float
2215 $milliTime = gettimeofday(true);
2222 * Idles (sleeps) for given milliseconds
2224 * @return $hasSlept Whether it goes fine
2226 public function idle ($milliSeconds) {
2227 // Sleep is fine by default
2230 // Idle so long with found function
2231 if (function_exists('time_sleep_until')) {
2232 // Get current time and add idle time
2233 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2235 // New PHP 5.1.0 function found, ignore errors
2236 $hasSlept = @time_sleep_until($sleepUntil);
2239 * My Sun station doesn't have that function even with latest PHP
2242 usleep($milliSeconds * 1000);
2249 * Converts a hexadecimal string, even with negative sign as first string to
2250 * a decimal number using BC functions.
2252 * This work is based on comment #86673 on php.net documentation page at:
2253 * <http://de.php.net/manual/en/function.dechex.php#86673>
2255 * @param $hex Hexadecimal string
2256 * @return $dec Decimal number
2258 protected function hex2dec ($hex) {
2259 // Convert to all lower-case
2260 $hex = strtolower($hex);
2262 // Detect sign (negative/positive numbers)
2264 if (substr($hex, 0, 1) == '-') {
2266 $hex = substr($hex, 1);
2269 // Decode the hexadecimal string into a decimal number
2271 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2272 $factor = self::$hexdec[substr($hex, $i, 1)];
2273 $dec = bcadd($dec, bcmul($factor, $e));
2276 // Return the decimal number
2277 return $sign . $dec;
2281 * Converts even very large decimal numbers, also signed, to a hexadecimal
2284 * This work is based on comment #97756 on php.net documentation page at:
2285 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2287 * @param $dec Decimal number, even with negative sign
2288 * @param $maxLength Optional maximum length of the string
2289 * @return $hex Hexadecimal string
2291 protected function dec2hex ($dec, $maxLength = 0) {
2292 // maxLength can be zero or devideable by 2
2293 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2295 // Detect sign (negative/positive numbers)
2302 // Encode the decimal number into a hexadecimal string
2305 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2307 } while ($dec >= 1);
2310 * Leading zeros are required for hex-decimal "numbers". In some
2311 * situations more leading zeros are wanted, so check for both
2314 if ($maxLength > 0) {
2315 // Prepend more zeros
2316 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2317 } elseif ((strlen($hex) % 2) != 0) {
2318 // Only make string's length dividable by 2
2322 // Return the hexadecimal string
2323 return $sign . $hex;
2327 * Converts a ASCII string (0 to 255) into a decimal number.
2329 * @param $asc The ASCII string to be converted
2330 * @return $dec Decimal number
2332 protected function asc2dec ($asc) {
2333 // Convert it into a hexadecimal number
2334 $hex = bin2hex($asc);
2336 // And back into a decimal number
2337 $dec = $this->hex2dec($hex);
2344 * Converts a decimal number into an ASCII string.
2346 * @param $dec Decimal number
2347 * @return $asc An ASCII string
2349 protected function dec2asc ($dec) {
2350 // First convert the number into a hexadecimal string
2351 $hex = $this->dec2hex($dec);
2353 // Then convert it into the ASCII string
2354 $asc = $this->hex2asc($hex);
2361 * Converts a hexadecimal number into an ASCII string. Negative numbers
2364 * @param $hex Hexadecimal string
2365 * @return $asc An ASCII string
2367 protected function hex2asc ($hex) {
2368 // Check for length, it must be devideable by 2
2369 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2370 assert((strlen($hex) % 2) == 0);
2374 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2375 // Get the decimal number of the chunk
2376 $part = hexdec(substr($hex, $idx, 2));
2378 // Add it to the final string
2382 // Return the final string
2387 * Checks whether the given encoded data was encoded with Base64
2389 * @param $encodedData Encoded data we shall check
2390 * @return $isBase64 Whether the encoded data is Base64
2392 protected function isBase64Encoded ($encodedData) {
2394 $isBase64 = (@base64_decode($encodedData, true) !== false);
2401 * Gets a cache key from Criteria instance
2403 * @param $criteriaInstance An instance of a Criteria class
2404 * @param $onlyKeys Only use these keys for a cache key
2405 * @return $cacheKey A cache key suitable for lookup/storage purposes
2407 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2409 $cacheKey = sprintf('%s@%s',
2410 $this->__toString(),
2411 $criteriaInstance->getCacheKey($onlyKeys)
2415 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2420 * Getter for startup time in miliseconds
2422 * @return $startupTime Startup time in miliseconds
2424 protected function getStartupTime () {
2425 return self::$startupTime;
2429 * "Getter" for a printable currently execution time in nice braces
2431 * @return $executionTime Current execution time in nice braces
2433 protected function getPrintableExecutionTime () {
2434 // Caculate the execution time
2435 $executionTime = microtime(true) - $this->getStartupTime();
2437 // Pack it in nice braces
2438 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2441 return $executionTime;
2445 * Hashes a given string with a simple but stronger hash function (no salt)
2446 * and hex-encode it.
2448 * @param $str The string to be hashed
2449 * @return $hash The hash from string $str
2451 public static final function hash ($str) {
2452 // Hash given string with (better secure) hasher
2453 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2460 * "Getter" for length of hash() output. This will be "cached" to speed up
2463 * @return $length Length of hash() output
2465 public static final function getHashLength () {
2467 if (is_null(self::$hashLength)) {
2468 // No, then hash a string and save its length.
2469 self::$hashLength = strlen(self::hash('abc123'));
2473 return self::$hashLength;
2477 * Checks whether the given number is really a number (only chars 0-9).
2479 * @param $num A string consisting only chars between 0 and 9
2480 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2481 * @param $assertMismatch Whether to assert mismatches
2482 * @return $ret The (hopefully) secured numbered value
2484 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2485 // Filter all numbers out
2486 $ret = preg_replace('/[^0123456789]/', '', $num);
2489 if ($castValue === true) {
2490 // Cast to biggest numeric type
2491 $ret = (double) $ret;
2494 // Assert only if requested
2495 if ($assertMismatch === true) {
2496 // Has the whole value changed?
2497 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2505 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2507 * @param $num A string consisting only chars between 0 and 9
2508 * @param $assertMismatch Whether to assert mismatches
2509 * @return $ret The (hopefully) secured hext-numbered value
2511 public function hexval ($num, $assertMismatch = false) {
2512 // Filter all numbers out
2513 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2515 // Assert only if requested
2516 if ($assertMismatch === true) {
2517 // Has the whole value changed?
2518 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2526 * Determines if an element is set in the generic array
2528 * @param $keyGroup Main group for the key
2529 * @param $subGroup Sub group for the key
2530 * @param $key Key to check
2531 * @param $element Element to check
2532 * @return $isset Whether the given key is set
2534 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2536 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2539 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2545 * Determines if a key is set in the generic array
2547 * @param $keyGroup Main group for the key
2548 * @param $subGroup Sub group for the key
2549 * @param $key Key to check
2550 * @return $isset Whether the given key is set
2552 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2554 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2557 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2565 * Determines if a group is set in the generic array
2567 * @param $keyGroup Main group
2568 * @param $subGroup Sub group
2569 * @return $isset Whether the given group is set
2571 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2573 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2576 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2583 * Getter for sub key group
2585 * @param $keyGroup Main key group
2586 * @param $subGroup Sub key group
2587 * @return $array An array with all array elements
2589 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2591 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2592 // No, then abort here
2593 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2598 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2601 return $this->genericArray[$keyGroup][$subGroup];
2605 * Unsets a given key in generic array
2607 * @param $keyGroup Main group for the key
2608 * @param $subGroup Sub group for the key
2609 * @param $key Key to unset
2612 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2614 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2617 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2621 * Unsets a given element in generic array
2623 * @param $keyGroup Main group for the key
2624 * @param $subGroup Sub group for the key
2625 * @param $key Key to unset
2626 * @param $element Element to unset
2629 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2631 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2634 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2638 * Append a string to a given generic array key
2640 * @param $keyGroup Main group for the key
2641 * @param $subGroup Sub group for the key
2642 * @param $key Key to unset
2643 * @param $value Value to add/append
2646 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2648 //* 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);
2650 // Is it already there?
2651 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2653 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2656 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2661 * Append a string to a given generic array element
2663 * @param $keyGroup Main group for the key
2664 * @param $subGroup Sub group for the key
2665 * @param $key Key to unset
2666 * @param $element Element to check
2667 * @param $value Value to add/append
2670 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2672 //* 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);
2674 // Is it already there?
2675 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2677 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2680 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2685 * Sets a string in a given generic array element
2687 * @param $keyGroup Main group for the key
2688 * @param $subGroup Sub group for the key
2689 * @param $key Key to unset
2690 * @param $element Element to check
2691 * @param $value Value to add/append
2694 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2696 //* 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);
2699 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2703 * Initializes given generic array group
2705 * @param $keyGroup Main group for the key
2706 * @param $subGroup Sub group for the key
2707 * @param $key Key to use
2708 * @param $forceInit Optionally force initialization
2711 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2713 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2715 // Is it already set?
2716 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2717 // Already initialized
2718 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2723 $this->genericArray[$keyGroup][$subGroup] = array();
2727 * Initializes given generic array key
2729 * @param $keyGroup Main group for the key
2730 * @param $subGroup Sub group for the key
2731 * @param $key Key to use
2732 * @param $forceInit Optionally force initialization
2735 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2737 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2739 // Is it already set?
2740 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2741 // Already initialized
2742 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2747 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2751 * Initializes given generic array element
2753 * @param $keyGroup Main group for the key
2754 * @param $subGroup Sub group for the key
2755 * @param $key Key to use
2756 * @param $element Element to use
2757 * @param $forceInit Optionally force initialization
2760 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2762 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2764 // Is it already set?
2765 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2766 // Already initialized
2767 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2772 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2776 * Pushes an element to a generic key
2778 * @param $keyGroup Main group for the key
2779 * @param $subGroup Sub group for the key
2780 * @param $key Key to use
2781 * @param $value Value to add/append
2782 * @return $count Number of array elements
2784 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2786 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2789 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2791 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2795 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2798 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2799 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2804 * Pushes an element to a generic array element
2806 * @param $keyGroup Main group for the key
2807 * @param $subGroup Sub group for the key
2808 * @param $key Key to use
2809 * @param $element Element to check
2810 * @param $value Value to add/append
2811 * @return $count Number of array elements
2813 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2815 //* 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));
2818 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2820 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2824 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2827 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2828 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2833 * Pops an element from a generic group
2835 * @param $keyGroup Main group for the key
2836 * @param $subGroup Sub group for the key
2837 * @param $key Key to unset
2838 * @return $value Last "popped" value
2840 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2842 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2845 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2847 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2852 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2855 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2856 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2861 * Shifts an element from a generic group
2863 * @param $keyGroup Main group for the key
2864 * @param $subGroup Sub group for the key
2865 * @param $key Key to unset
2866 * @return $value Last "popped" value
2868 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2870 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2873 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2875 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2880 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2883 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2884 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2889 * Count generic array group
2891 * @param $keyGroup Main group for the key
2892 * @return $count Count of given group
2894 protected final function countGenericArray ($keyGroup) {
2896 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2899 if (!isset($this->genericArray[$keyGroup])) {
2901 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2906 $count = count($this->genericArray[$keyGroup]);
2909 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2916 * Count generic array sub group
2918 * @param $keyGroup Main group for the key
2919 * @param $subGroup Sub group for the key
2920 * @return $count Count of given group
2922 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2924 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2927 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2929 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2934 $count = count($this->genericArray[$keyGroup][$subGroup]);
2937 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2944 * Count generic array elements
2946 * @param $keyGroup Main group for the key
2947 * @param $subGroup Sub group for the key
2948 * @para $key Key to count
2949 * @return $count Count of given key
2951 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2953 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2956 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2958 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2960 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2962 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2967 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2970 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2977 * Getter for whole generic group array
2979 * @param $keyGroup Key group to get
2980 * @return $array Whole generic array group
2982 protected final function getGenericArray ($keyGroup) {
2984 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2987 if (!isset($this->genericArray[$keyGroup])) {
2989 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2994 return $this->genericArray[$keyGroup];
2998 * Setter for generic array key
3000 * @param $keyGroup Key group to get
3001 * @param $subGroup Sub group for the key
3002 * @param $key Key to unset
3003 * @param $value Mixed value from generic array element
3006 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3008 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3011 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3015 * Getter for generic array key
3017 * @param $keyGroup Key group to get
3018 * @param $subGroup Sub group for the key
3019 * @param $key Key to unset
3020 * @return $value Mixed value from generic array element
3022 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3024 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3027 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3029 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3034 return $this->genericArray[$keyGroup][$subGroup][$key];
3038 * Sets a value in given generic array key/element
3040 * @param $keyGroup Main group for the key
3041 * @param $subGroup Sub group for the key
3042 * @param $key Key to set
3043 * @param $element Element to set
3044 * @param $value Value to set
3047 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3049 //* 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));
3052 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3056 * Getter for generic array element
3058 * @param $keyGroup Key group to get
3059 * @param $subGroup Sub group for the key
3060 * @param $key Key to look for
3061 * @param $element Element to look for
3062 * @return $value Mixed value from generic array element
3064 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3066 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3069 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3071 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3076 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3080 * Checks if a given sub group is valid (array)
3082 * @param $keyGroup Key group to get
3083 * @param $subGroup Sub group for the key
3084 * @return $isValid Whether given sub group is valid
3086 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3088 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3091 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3098 * Checks if a given key is valid (array)
3100 * @param $keyGroup Key group to get
3101 * @param $subGroup Sub group for the key
3102 * @param $key Key to check
3103 * @return $isValid Whether given sub group is valid
3105 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3107 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3110 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3117 * Initializes the web output instance
3121 protected function initWebOutputInstance () {
3122 // Get application instance
3123 $applicationInstance = Registry::getRegistry()->getInstance('app');
3125 // Init web output instance
3126 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3129 $this->setWebOutputInstance($outputInstance);
3133 * Translates boolean true to 'Y' and false to 'N'
3135 * @param $boolean Boolean value
3136 * @return $translated Translated boolean value
3138 public static final function translateBooleanToYesNo ($boolean) {
3139 // Make sure it is really boolean
3140 assert(is_bool($boolean));
3143 $translated = ($boolean === true) ? 'Y' : 'N';
3145 // ... and return it
3150 * Encodes raw data (almost any type) by "serializing" it and then pack it
3151 * into a "binary format".
3153 * @param $rawData Raw data (almost any type)
3154 * @return $encoded Encoded data
3156 protected function encodeData ($rawData) {
3157 // Make sure no objects or resources pass through
3158 assert(!is_object($rawData));
3159 assert(!is_resource($rawData));
3161 // First "serialize" it (json_encode() is faster than serialize())
3162 $encoded = $this->packString(json_encode($rawData));
3169 * Pack a string into a "binary format". Please execuse me that this is
3170 * widely undocumented. :-(
3172 * @param $str Unpacked string
3173 * @return $packed Packed string
3174 * @todo Improve documentation
3176 protected function packString ($str) {
3178 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3180 // First compress the string (gzcompress is okay)
3181 $str = gzcompress($str);
3186 // And start the "encoding" loop
3187 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3189 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3190 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3192 if (($idx + $i) <= strlen($str)) {
3193 $ord = ord(substr($str, ($idx + $i), 1));
3195 $add = $ord * pow(256, $factor);
3199 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3203 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3204 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3206 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3207 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3213 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3218 * Creates a full-qualified file name (FQFN) for given file name by adding
3219 * a configured temporary file path to it.
3221 * @param $fileName Name for temporary file
3222 * @return $fqfn Full-qualified file name
3223 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3224 * @throws FileIoException If the file cannot be written
3226 protected static function createTempPathForFile ($fileName) {
3228 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3230 // Is the path writeable?
3231 if (!is_writable($basePath)) {
3232 // Path is write-protected
3233 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3237 $fqfn = $basePath . DIRECTORY_SEPARATOR . $fileName;
3240 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3242 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3250 * "Getter" for a printable state name
3252 * @return $stateName Name of the node's state in a printable format
3254 public final function getPrintableState () {
3255 // Default is 'null'
3256 $stateName = 'null';
3258 // Get the state instance
3259 $stateInstance = $this->getStateInstance();
3261 // Is it an instance of Stateable?
3262 if ($stateInstance instanceof Stateable) {
3263 // Then use that state name
3264 $stateName = $stateInstance->getStateName();