3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFranework\Controller\Controller;
8 use CoreFramework\Factory\ObjectFactory;
9 use CoreFramework\Generic\FrameworkInterface;
10 use CoreFramework\Generic\NullPointerException;
11 use CoreFramework\Handler\Stream\IoHandler;
12 use CoreFramework\Loader\ClassLoader;
13 use CoreFramework\Manager\ManageableApplication;
14 use CoreFramework\Middleware\Debug\DebugMiddleware;
15 use CoreFramework\Registry\Register;
16 use CoreFramework\Registry\Registry;
17 use CoreFramework\Request\Requestable;
18 use CoreFramework\Resolver\Resolver;
19 use CoreFramework\Response\Responseable;
20 use CoreFramework\Stream\Output\OutputStreamer;
21 use CoreFramework\Template\CompileableTemplate;
27 * The simulator system class is the super class of all other classes. This
28 * class handles saving of games etc.
30 * @author Roland Haeder <webmaster@shipsimu.org>
32 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
33 * @license GNU GPL 3.0 or any newer version
34 * @link http://www.shipsimu.org
36 * This program is free software: you can redistribute it and/or modify
37 * it under the terms of the GNU General Public License as published by
38 * the Free Software Foundation, either version 3 of the License, or
39 * (at your option) any later version.
41 * This program is distributed in the hope that it will be useful,
42 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 * GNU General Public License for more details.
46 * You should have received a copy of the GNU General Public License
47 * along with this program. If not, see <http://www.gnu.org/licenses/>.
49 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
51 * Length of output from hash()
53 private static $hashLength = NULL;
58 private $realClass = 'BaseFrameworkSystem';
61 * Instance of a Requestable class
63 private $requestInstance = NULL;
66 * Instance of a Responseable class
68 private $responseInstance = NULL;
71 * Search criteria instance
73 private $searchInstance = NULL;
76 * Update criteria instance
78 private $updateInstance = NULL;
81 * The file I/O instance for the template loader
83 private $fileIoInstance = NULL;
88 private $resolverInstance = NULL;
91 * Template engine instance
93 private $templateInstance = NULL;
96 * Database result instance
98 private $resultInstance = NULL;
101 * Instance for user class
103 private $userInstance = NULL;
106 * A controller instance
108 private $controllerInstance = NULL;
113 private $rngInstance = NULL;
116 * Instance of a crypto helper
118 private $cryptoInstance = NULL;
121 * Instance of an Iterator class
123 private $iteratorInstance = NULL;
126 * Instance of the list
128 private $listInstance = NULL;
133 private $menuInstance = NULL;
136 * Instance of the image
138 private $imageInstance = NULL;
141 * Instance of the stacker
143 private $stackInstance = NULL;
146 * A Compressor instance
148 private $compressorInstance = NULL;
151 * A Parseable instance
153 private $parserInstance = NULL;
156 * A HandleableProtocol instance
158 private $protocolInstance = NULL;
161 * A database wrapper instance
163 private $databaseInstance = NULL;
166 * A helper instance for the form
168 private $helperInstance = NULL;
171 * An instance of a Source class
173 private $sourceInstance = NULL;
176 * An instance of a UrlSource class
178 private $urlSourceInstance = NULL;
181 * An instance of a InputStream class
183 private $inputStreamInstance = NULL;
186 * An instance of a OutputStream class
188 private $outputStreamInstance = NULL;
191 * Networkable handler instance
193 private $handlerInstance = NULL;
196 * Visitor handler instance
198 private $visitorInstance = NULL;
203 private $dhtInstance = NULL;
206 * An instance of a database wrapper class
208 private $wrapperInstance = NULL;
211 * An instance of a file I/O pointer class (not handler)
213 private $pointerInstance = NULL;
216 * An instance of an Indexable class
218 private $indexInstance = NULL;
221 * An instance of a Block class
223 private $blockInstance = NULL;
228 private $minableInstance = NULL;
231 * A FrameworkDirectory instance
233 private $directoryInstance = NULL;
238 private $listenerInstance = NULL;
241 * An instance of a communicator
243 private $communicatorInstance = NULL;
246 * The concrete output instance
248 private $outputInstance = NULL;
253 private $stateInstance = NULL;
256 * Thousands separator
258 private $thousands = '.'; // German
263 private $decimals = ','; // German
268 private $socketResource = FALSE;
271 * Regular expression to use for validation
273 private $regularExpression = '';
278 private $packageData = array();
283 private $genericArray = array();
288 private $commandName = '';
293 private $controllerName = '';
296 * Name of used protocol
298 private $protocolName = 'invalid';
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;
396 * Hexadecimal->Decimal translation array
398 private static $hexdec = array(
418 * Decimal->hexadecimal translation array
420 private static $dechex = array(
440 * Startup time in miliseconds
442 private static $startupTime = 0;
445 * Protected super constructor
447 * @param $className Name of the class
450 protected function __construct ($className) {
452 $this->setRealClass($className);
454 // Set configuration instance if no registry ...
455 if (!$this instanceof Register) {
456 // ... because registries doesn't need to be configured
457 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
460 // Is the startup time set? (0 cannot be TRUE anymore)
461 if (self::$startupTime == 0) {
463 self::$startupTime = microtime(TRUE);
467 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
471 * Destructor for all classes. You should not call this method on your own.
475 public function __destruct () {
476 // Flush any updated entries to the database
477 $this->flushPendingUpdates();
479 // Is this object already destroyed?
480 if ($this->__toString() != 'DestructedObject') {
481 // Destroy all informations about this class but keep some text about it alive
482 $this->setRealClass('DestructedObject');
483 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
484 // Already destructed object
485 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] 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 Searchable criteria instance
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('application');
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 * Setter for request instance
902 * @param $requestInstance An instance of a Requestable class
905 public final function setRequestInstance (Requestable $requestInstance) {
906 $this->requestInstance = $requestInstance;
910 * Getter for request instance
912 * @return $requestInstance An instance of a Requestable class
914 public final function getRequestInstance () {
915 return $this->requestInstance;
919 * Setter for response instance
921 * @param $responseInstance An instance of a Responseable class
924 public final function setResponseInstance (Responseable $responseInstance) {
925 $this->responseInstance = $responseInstance;
929 * Getter for response instance
931 * @return $responseInstance An instance of a Responseable class
933 public final function getResponseInstance () {
934 return $this->responseInstance;
938 * Private getter for language instance
940 * @return $langInstance An instance to the language sub-system
942 protected final function getLanguageInstance () {
943 $langInstance = Registry::getRegistry()->getInstance('language');
944 return $langInstance;
948 * Setter for language instance
950 * @param $langInstance An instance to the language sub-system
952 * @see LanguageSystem
954 public final function setLanguageInstance (ManageableLanguage $langInstance) {
955 Registry::getRegistry()->addInstance('language', $langInstance);
959 * Private getter for file IO instance
961 * @return $fileIoInstance An instance to the file I/O sub-system
963 protected final function getFileIoInstance () {
964 return $this->fileIoInstance;
968 * Setter for file I/O instance
970 * @param $fileIoInstance An instance to the file I/O sub-system
973 public final function setFileIoInstance (IoHandler $fileIoInstance) {
974 $this->fileIoInstance = $fileIoInstance;
978 * Protected setter for user instance
980 * @param $userInstance An instance of a user class
983 protected final function setUserInstance (ManageableAccount $userInstance) {
984 $this->userInstance = $userInstance;
988 * Getter for user instance
990 * @return $userInstance An instance of a user class
992 public final function getUserInstance () {
993 return $this->userInstance;
997 * Setter for controller instance (this surely breaks a bit the MVC patterm)
999 * @param $controllerInstance An instance of the controller
1002 public final function setControllerInstance (Controller $controllerInstance) {
1003 $this->controllerInstance = $controllerInstance;
1007 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1009 * @return $controllerInstance An instance of the controller
1011 public final function getControllerInstance () {
1012 return $this->controllerInstance;
1016 * Setter for RNG instance
1018 * @param $rngInstance An instance of a random number generator (RNG)
1021 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1022 $this->rngInstance = $rngInstance;
1026 * Getter for RNG instance
1028 * @return $rngInstance An instance of a random number generator (RNG)
1030 public final function getRngInstance () {
1031 return $this->rngInstance;
1035 * Setter for Cryptable instance
1037 * @param $cryptoInstance An instance of a Cryptable class
1040 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1041 $this->cryptoInstance = $cryptoInstance;
1045 * Getter for Cryptable instance
1047 * @return $cryptoInstance An instance of a Cryptable class
1049 public final function getCryptoInstance () {
1050 return $this->cryptoInstance;
1054 * Setter for the list instance
1056 * @param $listInstance A list of Listable
1059 protected final function setListInstance (Listable $listInstance) {
1060 $this->listInstance = $listInstance;
1064 * Getter for the list instance
1066 * @return $listInstance A list of Listable
1068 protected final function getListInstance () {
1069 return $this->listInstance;
1073 * Setter for the menu instance
1075 * @param $menuInstance A RenderableMenu instance
1078 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1079 $this->menuInstance = $menuInstance;
1083 * Getter for the menu instance
1085 * @return $menuInstance A RenderableMenu instance
1087 protected final function getMenuInstance () {
1088 return $this->menuInstance;
1092 * Setter for image instance
1094 * @param $imageInstance An instance of an image
1097 public final function setImageInstance (BaseImage $imageInstance) {
1098 $this->imageInstance = $imageInstance;
1102 * Getter for image instance
1104 * @return $imageInstance An instance of an image
1106 public final function getImageInstance () {
1107 return $this->imageInstance;
1111 * Setter for stacker instance
1113 * @param $stackInstance An instance of an stacker
1116 public final function setStackInstance (Stackable $stackInstance) {
1117 $this->stackInstance = $stackInstance;
1121 * Getter for stacker instance
1123 * @return $stackInstance An instance of an stacker
1125 public final function getStackInstance () {
1126 return $this->stackInstance;
1130 * Setter for compressor instance
1132 * @param $compressorInstance An instance of an compressor
1135 public final function setCompressorInstance (Compressor $compressorInstance) {
1136 $this->compressorInstance = $compressorInstance;
1140 * Getter for compressor instance
1142 * @return $compressorInstance An instance of an compressor
1144 public final function getCompressorInstance () {
1145 return $this->compressorInstance;
1149 * Setter for Parseable instance
1151 * @param $parserInstance An instance of an Parseable
1154 public final function setParserInstance (Parseable $parserInstance) {
1155 $this->parserInstance = $parserInstance;
1159 * Getter for Parseable instance
1161 * @return $parserInstance An instance of an Parseable
1163 public final function getParserInstance () {
1164 return $this->parserInstance;
1168 * Setter for HandleableProtocol instance
1170 * @param $protocolInstance An instance of an HandleableProtocol
1173 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1174 $this->protocolInstance = $protocolInstance;
1178 * Getter for HandleableProtocol instance
1180 * @return $protocolInstance An instance of an HandleableProtocol
1182 public final function getProtocolInstance () {
1183 return $this->protocolInstance;
1187 * Setter for DatabaseWrapper instance
1189 * @param $wrapperInstance An instance of an DatabaseWrapper
1192 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1193 $this->wrapperInstance = $wrapperInstance;
1197 * Getter for DatabaseWrapper instance
1199 * @return $wrapperInstance An instance of an DatabaseWrapper
1201 public final function getWrapperInstance () {
1202 return $this->wrapperInstance;
1206 * Setter for socket resource
1208 * @param $socketResource A valid socket resource
1211 public final function setSocketResource ($socketResource) {
1212 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1213 $this->socketResource = $socketResource;
1217 * Getter for socket resource
1219 * @return $socketResource A valid socket resource
1221 public final function getSocketResource () {
1222 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1223 return $this->socketResource;
1227 * Setter for regular expression
1229 * @param $regularExpression A valid regular expression
1232 public final function setRegularExpression ($regularExpression) {
1233 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1234 $this->regularExpression = $regularExpression;
1238 * Getter for regular expression
1240 * @return $regularExpression A valid regular expression
1242 public final function getRegularExpression () {
1243 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1244 return $this->regularExpression;
1248 * Setter for helper instance
1250 * @param $helperInstance An instance of a helper class
1253 protected final function setHelperInstance (Helper $helperInstance) {
1254 $this->helperInstance = $helperInstance;
1258 * Getter for helper instance
1260 * @return $helperInstance An instance of a helper class
1262 public final function getHelperInstance () {
1263 return $this->helperInstance;
1267 * Setter for a Source instance
1269 * @param $sourceInstance An instance of a Source class
1272 protected final function setSourceInstance (Source $sourceInstance) {
1273 $this->sourceInstance = $sourceInstance;
1277 * Getter for a Source instance
1279 * @return $sourceInstance An instance of a Source class
1281 protected final function getSourceInstance () {
1282 return $this->sourceInstance;
1286 * Setter for a UrlSource instance
1288 * @param $sourceInstance An instance of a UrlSource class
1291 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1292 $this->urlSourceInstance = $urlSourceInstance;
1296 * Getter for a UrlSource instance
1298 * @return $urlSourceInstance An instance of a UrlSource class
1300 protected final function getUrlSourceInstance () {
1301 return $this->urlSourceInstance;
1305 * Getter for a InputStream instance
1307 * @param $inputStreamInstance The InputStream instance
1309 protected final function getInputStreamInstance () {
1310 return $this->inputStreamInstance;
1314 * Setter for a InputStream instance
1316 * @param $inputStreamInstance The InputStream instance
1319 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1320 $this->inputStreamInstance = $inputStreamInstance;
1324 * Getter for a OutputStream instance
1326 * @param $outputStreamInstance The OutputStream instance
1328 protected final function getOutputStreamInstance () {
1329 return $this->outputStreamInstance;
1333 * Setter for a OutputStream instance
1335 * @param $outputStreamInstance The OutputStream instance
1338 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1339 $this->outputStreamInstance = $outputStreamInstance;
1343 * Setter for handler instance
1345 * @param $handlerInstance An instance of a Handleable class
1348 protected final function setHandlerInstance (Handleable $handlerInstance) {
1349 $this->handlerInstance = $handlerInstance;
1353 * Getter for handler instance
1355 * @return $handlerInstance A Networkable instance
1357 protected final function getHandlerInstance () {
1358 return $this->handlerInstance;
1362 * Setter for visitor instance
1364 * @param $visitorInstance A Visitor instance
1367 protected final function setVisitorInstance (Visitor $visitorInstance) {
1368 $this->visitorInstance = $visitorInstance;
1372 * Getter for visitor instance
1374 * @return $visitorInstance A Visitor instance
1376 protected final function getVisitorInstance () {
1377 return $this->visitorInstance;
1381 * Setter for DHT instance
1383 * @param $dhtInstance A Distributable instance
1386 protected final function setDhtInstance (Distributable $dhtInstance) {
1387 $this->dhtInstance = $dhtInstance;
1391 * Getter for DHT instance
1393 * @return $dhtInstance A Distributable instance
1395 protected final function getDhtInstance () {
1396 return $this->dhtInstance;
1400 * Setter for raw package Data
1402 * @param $packageData Raw package Data
1405 public final function setPackageData (array $packageData) {
1406 $this->packageData = $packageData;
1410 * Getter for raw package Data
1412 * @return $packageData Raw package Data
1414 public function getPackageData () {
1415 return $this->packageData;
1420 * Setter for Iterator instance
1422 * @param $iteratorInstance An instance of an Iterator
1425 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1426 $this->iteratorInstance = $iteratorInstance;
1430 * Getter for Iterator instance
1432 * @return $iteratorInstance An instance of an Iterator
1434 public final function getIteratorInstance () {
1435 return $this->iteratorInstance;
1439 * Setter for FilePointer instance
1441 * @param $pointerInstance An instance of an FilePointer class
1444 protected final function setPointerInstance (FilePointer $pointerInstance) {
1445 $this->pointerInstance = $pointerInstance;
1449 * Getter for FilePointer instance
1451 * @return $pointerInstance An instance of an FilePointer class
1453 public final function getPointerInstance () {
1454 return $this->pointerInstance;
1458 * Unsets pointer instance which triggers a call of __destruct() if the
1459 * instance is still there. This is surely not fatal on already "closed"
1460 * file pointer instances.
1462 * I don't want to mess around with above setter by giving it a default
1463 * value NULL as setter should always explicitly only set (existing) object
1464 * instances and NULL is NULL.
1468 protected final function unsetPointerInstance () {
1469 // Simply it to NULL
1470 $this->pointerInstance = NULL;
1474 * Setter for Indexable instance
1476 * @param $indexInstance An instance of an Indexable class
1479 protected final function setIndexInstance (Indexable $indexInstance) {
1480 $this->indexInstance = $indexInstance;
1484 * Getter for Indexable instance
1486 * @return $indexInstance An instance of an Indexable class
1488 public final function getIndexInstance () {
1489 return $this->indexInstance;
1493 * Setter for Block instance
1495 * @param $blockInstance An instance of an Block class
1498 protected final function setBlockInstance (Block $blockInstance) {
1499 $this->blockInstance = $blockInstance;
1503 * Getter for Block instance
1505 * @return $blockInstance An instance of an Block class
1507 public final function getBlockInstance () {
1508 return $this->blockInstance;
1512 * Setter for Minable instance
1514 * @param $minableInstance A Minable instance
1517 protected final function setMinableInstance (Minable $minableInstance) {
1518 $this->minableInstance = $minableInstance;
1522 * Getter for minable instance
1524 * @return $minableInstance A Minable instance
1526 protected final function getMinableInstance () {
1527 return $this->minableInstance;
1531 * Setter for FrameworkDirectory instance
1533 * @param $directoryInstance A FrameworkDirectoryPointer instance
1536 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1537 $this->directoryInstance = $directoryInstance;
1541 * Getter for FrameworkDirectory instance
1543 * @return $directoryInstance A FrameworkDirectory instance
1545 protected final function getDirectoryInstance () {
1546 return $this->directoryInstance;
1550 * Setter for listener instance
1552 * @param $listenerInstance A Listenable instance
1555 protected final function setListenerInstance (Listenable $listenerInstance) {
1556 $this->listenerInstance = $listenerInstance;
1560 * Getter for listener instance
1562 * @return $listenerInstance A Listenable instance
1564 protected final function getListenerInstance () {
1565 return $this->listenerInstance;
1569 * Getter for communicator instance
1571 * @return $communicatorInstance An instance of a Communicator class
1573 public final function getCommunicatorInstance () {
1574 return $this->communicatorInstance;
1578 * Setter for communicator instance
1580 * @param $communicatorInstance An instance of a Communicator class
1583 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1584 $this->communicatorInstance = $communicatorInstance;
1588 * Setter for state instance
1590 * @param $stateInstance A Stateable instance
1593 public final function setStateInstance (Stateable $stateInstance) {
1594 $this->stateInstance = $stateInstance;
1598 * Getter for state instance
1600 * @return $stateInstance A Stateable instance
1602 public final function getStateInstance () {
1603 return $this->stateInstance;
1607 * Setter for output instance
1609 * @param $outputInstance The debug output instance
1612 public final function setOutputInstance (OutputStreamer $outputInstance) {
1613 $this->outputInstance = $outputInstance;
1617 * Getter for output instance
1619 * @return $outputInstance The debug output instance
1621 public final function getOutputInstance () {
1622 return $this->outputInstance;
1626 * Setter for command name
1628 * @param $commandName Last validated command name
1631 protected final function setCommandName ($commandName) {
1632 $this->commandName = $commandName;
1636 * Getter for command name
1638 * @return $commandName Last validated command name
1640 protected final function getCommandName () {
1641 return $this->commandName;
1645 * Setter for controller name
1647 * @param $controllerName Last validated controller name
1650 protected final function setControllerName ($controllerName) {
1651 $this->controllerName = $controllerName;
1655 * Getter for controller name
1657 * @return $controllerName Last validated controller name
1659 protected final function getControllerName () {
1660 return $this->controllerName;
1664 * Getter for protocol name
1666 * @return $protocolName Name of used protocol
1668 public final function getProtocolName () {
1669 return $this->protocolName;
1673 * Setter for protocol name
1675 * @param $protocolName Name of used protocol
1678 protected final function setProtocolName ($protocolName) {
1679 $this->protocolName = $protocolName;
1683 * Checks whether an object equals this object. You should overwrite this
1684 * method to implement own equality checks
1686 * @param $objectInstance An instance of a FrameworkInterface object
1687 * @return $equals Whether both objects equals
1689 public function equals (FrameworkInterface $objectInstance) {
1692 $this->__toString() == $objectInstance->__toString()
1694 $this->hashCode() == $objectInstance->hashCode()
1697 // Return the result
1702 * Generates a generic hash code of this class. You should really overwrite
1703 * this method with your own hash code generator code. But keep KISS in mind.
1705 * @return $hashCode A generic hash code respresenting this whole class
1707 public function hashCode () {
1709 return crc32($this->__toString());
1713 * Formats computer generated price values into human-understandable formats
1714 * with thousand and decimal separators.
1716 * @param $value The in computer format value for a price
1717 * @param $currency The currency symbol (use HTML-valid characters!)
1718 * @param $decNum Number of decimals after commata
1719 * @return $price The for the current language formated price string
1720 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1721 * thousands separator
1724 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1725 // Are all required attriutes set?
1726 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1727 // Throw an exception
1728 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1732 $value = (float) $value;
1734 // Reformat the US number
1735 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1737 // Return as string...
1742 * Appends a trailing slash to a string
1744 * @param $str A string (maybe) without trailing slash
1745 * @return $str A string with an auto-appended trailing slash
1747 public final function addMissingTrailingSlash ($str) {
1748 // Is there a trailing slash?
1749 if (substr($str, -1, 1) != '/') {
1753 // Return string with trailing slash
1758 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1759 * application helper instance (ApplicationHelper by default).
1761 * @param $applicationInstance An application helper instance or
1762 * null if we shall use the default
1763 * @return $templateInstance The template engine instance
1764 * @throws NullPointerException If the discovered application
1765 * instance is still null
1767 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1768 // Is the application instance set?
1769 if (is_null($applicationInstance)) {
1770 // Get the current instance
1771 $applicationInstance = $this->getApplicationInstance();
1774 if (is_null($applicationInstance)) {
1775 // Thrown an exception
1776 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1780 // Initialize the template engine
1781 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1783 // Return the prepared instance
1784 return $templateInstance;
1788 * Debugs this instance by putting out it's full content
1790 * @param $message Optional message to show in debug output
1793 public final function debugInstance ($message = '') {
1794 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1795 restore_error_handler();
1800 // Is a message set?
1801 if (!empty($message)) {
1802 // Construct message
1803 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1806 // Generate the output
1807 $content .= sprintf('<pre>%s</pre>',
1810 print_r($this, TRUE)
1816 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>',
1817 $this->__toString(),
1819 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1824 * Replaces control characters with printable output
1826 * @param $str String with control characters
1827 * @return $str Replaced string
1829 protected function replaceControlCharacters ($str) {
1832 chr(13), '[r]', str_replace(
1833 chr(10), '[n]', str_replace(
1843 * Output a partial stub message for the caller method
1845 * @param $message An optional message to display
1848 protected function partialStub ($message = '') {
1849 // Get the backtrace
1850 $backtrace = debug_backtrace();
1852 // Generate the class::method string
1853 $methodName = 'UnknownClass->unknownMethod';
1854 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1855 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1858 // Construct the full message
1859 $stubMessage = sprintf('[%s:] Partial stub!',
1863 // Is the extra message given?
1864 if (!empty($message)) {
1865 // Then add it as well
1866 $stubMessage .= ' Message: ' . $message;
1869 // Debug instance is there?
1870 if (!is_null($this->getDebugInstance())) {
1871 // Output stub message
1872 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1875 trigger_error($stubMessage);
1881 * Outputs a debug backtrace and stops further script execution
1883 * @param $message An optional message to output
1884 * @param $doExit Whether exit the program (TRUE is default)
1887 public function debugBackTrace ($message = '', $doExit = TRUE) {
1888 // Sorry, there is no other way getting this nice backtrace
1889 if (!empty($message)) {
1891 printf('Message: %s<br />' . PHP_EOL, $message);
1895 debug_print_backtrace();
1899 if ($doExit === TRUE) {
1905 * Creates an instance of a debugger instance
1907 * @param $className Name of the class (currently unsupported)
1908 * @param $lineNumber Line number where the call was made
1909 * @return $debugInstance An instance of a debugger class
1910 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1912 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1913 // Is the instance set?
1914 if (!Registry::getRegistry()->instanceExists('debug')) {
1915 // Init debug instance
1916 $debugInstance = NULL;
1920 // Get a debugger instance
1921 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1922 } catch (NullPointerException $e) {
1923 // Didn't work, no instance there
1924 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1927 // Empty string should be ignored and used for testing the middleware
1928 DebugMiddleware::getSelfInstance()->output('');
1930 // Set it in its own class. This will set it in the registry
1931 $debugInstance->setDebugInstance($debugInstance);
1933 // Get instance from registry
1934 $debugInstance = Registry::getRegistry()->getDebugInstance();
1938 return $debugInstance;
1942 * Simple output of a message with line-break
1944 * @param $message Message to output
1947 public function outputLine ($message) {
1949 print($message . PHP_EOL);
1953 * Outputs a debug message whether to debug instance (should be set!) or
1954 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1955 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1957 * @param $message Message we shall send out...
1958 * @param $doPrint Whether print or die here (default: print)
1959 * @paran $stripTags Whether to strip tags (default: FALSE)
1962 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1963 // Set debug instance to NULL
1964 $debugInstance = NULL;
1968 // Get debug instance
1969 $debugInstance = $this->getDebugInstance();
1970 } catch (NullPointerException $e) {
1971 // The debug instance is not set (yet)
1974 // Is the debug instance there?
1975 if (is_object($debugInstance)) {
1976 // Use debug output handler
1977 $debugInstance->output($message, $stripTags);
1979 if ($doPrint === FALSE) {
1980 // Die here if not printed
1984 // Are debug times enabled?
1985 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1987 $message = $this->getPrintableExecutionTime() . $message;
1991 if ($doPrint === TRUE) {
1993 $this->outputLine($message);
2002 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2004 * @param $str The string, what ever it is needs to be converted
2005 * @return $className Generated class name
2007 public static final function convertToClassName ($str) {
2011 // Convert all dashes in underscores
2012 $str = self::convertDashesToUnderscores($str);
2014 // Now use that underscores to get classname parts for hungarian style
2015 foreach (explode('_', $str) as $strPart) {
2016 // Make the class name part lower case and first upper case
2017 $className .= ucfirst(strtolower($strPart));
2020 // Return class name
2025 * Converts dashes to underscores, e.g. useable for configuration entries
2027 * @param $str The string with maybe dashes inside
2028 * @return $str The converted string with no dashed, but underscores
2030 public static final function convertDashesToUnderscores ($str) {
2032 $str = str_replace('-', '_', $str);
2034 // Return converted string
2039 * Marks up the code by adding e.g. line numbers
2041 * @param $phpCode Unmarked PHP code
2042 * @return $markedCode Marked PHP code
2044 public function markupCode ($phpCode) {
2049 $errorArray = error_get_last();
2051 // Init the code with error message
2052 if (is_array($errorArray)) {
2054 $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>',
2055 basename($errorArray['file']),
2056 $errorArray['line'],
2057 $errorArray['message'],
2062 // Add line number to the code
2063 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2065 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2067 htmlentities($code, ENT_QUOTES)
2076 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2077 * beatiful for web-based front-ends. If null is given a message id
2078 * null_timestamp will be resolved and returned.
2080 * @param $timestamp Timestamp to prepare (filter) for display
2081 * @return $readable A readable timestamp
2083 public function doFilterFormatTimestamp ($timestamp) {
2084 // Default value to return
2087 // Is the timestamp null?
2088 if (is_null($timestamp)) {
2089 // Get a message string
2090 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2092 switch ($this->getLanguageInstance()->getLanguageCode()) {
2093 case 'de': // German format is a bit different to default
2094 // Split the GMT stamp up
2095 $dateTime = explode(' ', $timestamp );
2096 $dateArray = explode('-', $dateTime[0]);
2097 $timeArray = explode(':', $dateTime[1]);
2099 // Construct the timestamp
2100 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2110 default: // Default is pass-through
2111 $readable = $timestamp;
2121 * Filter a given number into a localized number
2123 * @param $value The raw value from e.g. database
2124 * @return $localized Localized value
2126 public function doFilterFormatNumber ($value) {
2127 // Generate it from config and localize dependencies
2128 switch ($this->getLanguageInstance()->getLanguageCode()) {
2129 case 'de': // German format is a bit different to default
2130 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2133 default: // US, etc.
2134 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2143 * "Getter" for databse entry
2145 * @return $entry An array with database entries
2146 * @throws NullPointerException If the database result is not found
2147 * @throws InvalidDatabaseResultException If the database result is invalid
2149 protected final function getDatabaseEntry () {
2150 // Is there an instance?
2151 if (!$this->getResultInstance() instanceof SearchableResult) {
2152 // Throw an exception here
2153 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2157 $this->getResultInstance()->rewind();
2159 // Do we have an entry?
2160 if ($this->getResultInstance()->valid() === FALSE) {
2161 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2162 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2166 $this->getResultInstance()->next();
2169 $entry = $this->getResultInstance()->current();
2176 * Getter for field name
2178 * @param $fieldName Field name which we shall get
2179 * @return $fieldValue Field value from the user
2180 * @throws NullPointerException If the result instance is null
2182 public final function getField ($fieldName) {
2183 // Default field value
2186 // Get result instance
2187 $resultInstance = $this->getResultInstance();
2189 // Is this instance null?
2190 if (is_null($resultInstance)) {
2191 // Then the user instance is no longer valid (expired cookies?)
2192 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2195 // Get current array
2196 $fieldArray = $resultInstance->current();
2197 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2199 // Convert dashes to underscore
2200 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2202 // Does the field exist?
2203 if ($this->isFieldSet($fieldName)) {
2205 $fieldValue = $fieldArray[$fieldName2];
2206 } elseif (defined('DEVELOPER')) {
2207 // Missing field entry, may require debugging
2208 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2210 // Missing field entry, may require debugging
2211 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2219 * Checks if given field is set
2221 * @param $fieldName Field name to check
2222 * @return $isSet Whether the given field name is set
2223 * @throws NullPointerException If the result instance is null
2225 public function isFieldSet ($fieldName) {
2226 // Get result instance
2227 $resultInstance = $this->getResultInstance();
2229 // Is this instance null?
2230 if (is_null($resultInstance)) {
2231 // Then the user instance is no longer valid (expired cookies?)
2232 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2235 // Get current array
2236 $fieldArray = $resultInstance->current();
2237 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2239 // Convert dashes to underscore
2240 $fieldName = self::convertDashesToUnderscores($fieldName);
2243 $isSet = isset($fieldArray[$fieldName]);
2250 * Flushs all pending updates to the database layer
2254 public function flushPendingUpdates () {
2255 // Get result instance
2256 $resultInstance = $this->getResultInstance();
2258 // Do we have data to update?
2259 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2260 // Get wrapper class name config entry
2261 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2263 // Create object instance
2264 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2266 // Yes, then send the whole result to the database layer
2267 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2272 * Outputs a deprecation warning to the developer.
2274 * @param $message The message we shall output to the developer
2276 * @todo Write a logging mechanism for productive mode
2278 public function deprecationWarning ($message) {
2279 // Is developer mode active?
2280 if (defined('DEVELOPER')) {
2281 // Debug instance is there?
2282 if (!is_null($this->getDebugInstance())) {
2283 // Output stub message
2284 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2287 trigger_error($message . "<br />\n");
2291 // @TODO Finish this part!
2292 $this->partialStub('Developer mode inactive. Message:' . $message);
2297 * Checks whether the given PHP extension is loaded
2299 * @param $phpExtension The PHP extension we shall check
2300 * @return $isLoaded Whether the PHP extension is loaded
2302 public final function isPhpExtensionLoaded ($phpExtension) {
2304 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2311 * "Getter" as a time() replacement but with milliseconds. You should use this
2312 * method instead of the encapsulated getimeofday() function.
2314 * @return $milliTime Timestamp with milliseconds
2316 public function getMilliTime () {
2317 // Get the time of day as float
2318 $milliTime = gettimeofday(TRUE);
2325 * Idles (sleeps) for given milliseconds
2327 * @return $hasSlept Whether it goes fine
2329 public function idle ($milliSeconds) {
2330 // Sleep is fine by default
2333 // Idle so long with found function
2334 if (function_exists('time_sleep_until')) {
2335 // Get current time and add idle time
2336 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2338 // New PHP 5.1.0 function found, ignore errors
2339 $hasSlept = @time_sleep_until($sleepUntil);
2342 * My Sun station doesn't have that function even with latest PHP
2345 usleep($milliSeconds * 1000);
2352 * Converts a hexadecimal string, even with negative sign as first string to
2353 * a decimal number using BC functions.
2355 * This work is based on comment #86673 on php.net documentation page at:
2356 * <http://de.php.net/manual/en/function.dechex.php#86673>
2358 * @param $hex Hexadecimal string
2359 * @return $dec Decimal number
2361 protected function hex2dec ($hex) {
2362 // Convert to all lower-case
2363 $hex = strtolower($hex);
2365 // Detect sign (negative/positive numbers)
2367 if (substr($hex, 0, 1) == '-') {
2369 $hex = substr($hex, 1);
2372 // Decode the hexadecimal string into a decimal number
2374 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2375 $factor = self::$hexdec[substr($hex, $i, 1)];
2376 $dec = bcadd($dec, bcmul($factor, $e));
2379 // Return the decimal number
2380 return $sign . $dec;
2384 * Converts even very large decimal numbers, also signed, to a hexadecimal
2387 * This work is based on comment #97756 on php.net documentation page at:
2388 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2390 * @param $dec Decimal number, even with negative sign
2391 * @param $maxLength Optional maximum length of the string
2392 * @return $hex Hexadecimal string
2394 protected function dec2hex ($dec, $maxLength = 0) {
2395 // maxLength can be zero or devideable by 2
2396 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2398 // Detect sign (negative/positive numbers)
2405 // Encode the decimal number into a hexadecimal string
2408 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2410 } while ($dec >= 1);
2413 * Leading zeros are required for hex-decimal "numbers". In some
2414 * situations more leading zeros are wanted, so check for both
2417 if ($maxLength > 0) {
2418 // Prepend more zeros
2419 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2420 } elseif ((strlen($hex) % 2) != 0) {
2421 // Only make string's length dividable by 2
2425 // Return the hexadecimal string
2426 return $sign . $hex;
2430 * Converts a ASCII string (0 to 255) into a decimal number.
2432 * @param $asc The ASCII string to be converted
2433 * @return $dec Decimal number
2435 protected function asc2dec ($asc) {
2436 // Convert it into a hexadecimal number
2437 $hex = bin2hex($asc);
2439 // And back into a decimal number
2440 $dec = $this->hex2dec($hex);
2447 * Converts a decimal number into an ASCII string.
2449 * @param $dec Decimal number
2450 * @return $asc An ASCII string
2452 protected function dec2asc ($dec) {
2453 // First convert the number into a hexadecimal string
2454 $hex = $this->dec2hex($dec);
2456 // Then convert it into the ASCII string
2457 $asc = $this->hex2asc($hex);
2464 * Converts a hexadecimal number into an ASCII string. Negative numbers
2467 * @param $hex Hexadecimal string
2468 * @return $asc An ASCII string
2470 protected function hex2asc ($hex) {
2471 // Check for length, it must be devideable by 2
2472 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2473 assert((strlen($hex) % 2) == 0);
2477 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2478 // Get the decimal number of the chunk
2479 $part = hexdec(substr($hex, $idx, 2));
2481 // Add it to the final string
2485 // Return the final string
2490 * Checks whether the given encoded data was encoded with Base64
2492 * @param $encodedData Encoded data we shall check
2493 * @return $isBase64 Whether the encoded data is Base64
2495 protected function isBase64Encoded ($encodedData) {
2497 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2504 * "Getter" to get response/request type from analysis of the system.
2506 * @return $responseType Analyzed response type
2508 protected static function getResponseTypeFromSystem () {
2509 // Default is console
2510 $responseType = 'console';
2512 // Is 'HTTP_HOST' set?
2513 if (isset($_SERVER['HTTP_HOST'])) {
2515 * Then it is a HTML response/request as RSS and so on may be
2516 * transfered over HTTP as well.
2518 $responseType = 'html';
2522 return $responseType;
2526 * Gets a cache key from Criteria instance
2528 * @param $criteriaInstance An instance of a Criteria class
2529 * @param $onlyKeys Only use these keys for a cache key
2530 * @return $cacheKey A cache key suitable for lookup/storage purposes
2532 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2534 $cacheKey = sprintf('%s@%s',
2535 $this->__toString(),
2536 $criteriaInstance->getCacheKey($onlyKeys)
2540 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2545 * Getter for startup time in miliseconds
2547 * @return $startupTime Startup time in miliseconds
2549 protected function getStartupTime () {
2550 return self::$startupTime;
2554 * "Getter" for a printable currently execution time in nice braces
2556 * @return $executionTime Current execution time in nice braces
2558 protected function getPrintableExecutionTime () {
2559 // Caculate the execution time
2560 $executionTime = microtime(TRUE) - $this->getStartupTime();
2562 // Pack it in nice braces
2563 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2566 return $executionTime;
2570 * Hashes a given string with a simple but stronger hash function (no salt)
2571 * and hex-encode it.
2573 * @param $str The string to be hashed
2574 * @return $hash The hash from string $str
2576 public static final function hash ($str) {
2577 // Hash given string with (better secure) hasher
2578 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2585 * "Getter" for length of hash() output. This will be "cached" to speed up
2588 * @return $length Length of hash() output
2590 public static final function getHashLength () {
2592 if (is_null(self::$hashLength)) {
2593 // No, then hash a string and save its length.
2594 self::$hashLength = strlen(self::hash('abc123'));
2598 return self::$hashLength;
2602 * Checks whether the given number is really a number (only chars 0-9).
2604 * @param $num A string consisting only chars between 0 and 9
2605 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2606 * @param $assertMismatch Whether to assert mismatches
2607 * @return $ret The (hopefully) secured numbered value
2609 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2610 // Filter all numbers out
2611 $ret = preg_replace('/[^0123456789]/', '', $num);
2614 if ($castValue === TRUE) {
2615 // Cast to biggest numeric type
2616 $ret = (double) $ret;
2619 // Assert only if requested
2620 if ($assertMismatch === TRUE) {
2621 // Has the whole value changed?
2622 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2630 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2632 * @param $num A string consisting only chars between 0 and 9
2633 * @param $assertMismatch Whether to assert mismatches
2634 * @return $ret The (hopefully) secured hext-numbered value
2636 public function hexval ($num, $assertMismatch = FALSE) {
2637 // Filter all numbers out
2638 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2640 // Assert only if requested
2641 if ($assertMismatch === TRUE) {
2642 // Has the whole value changed?
2643 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2651 * Checks whether start/end marker are set
2653 * @param $data Data to be checked
2654 * @return $isset Whether start/end marker are set
2656 public final function ifStartEndMarkersSet ($data) {
2658 $isset = ((substr($data, 0, strlen(BaseRawDataHandler::STREAM_START_MARKER)) == BaseRawDataHandler::STREAM_START_MARKER) && (substr($data, -1 * strlen(BaseRawDataHandler::STREAM_END_MARKER), strlen(BaseRawDataHandler::STREAM_END_MARKER)) == BaseRawDataHandler::STREAM_END_MARKER));
2660 // ... and return it
2665 * Determines if an element is set in the generic array
2667 * @param $keyGroup Main group for the key
2668 * @param $subGroup Sub group for the key
2669 * @param $key Key to check
2670 * @param $element Element to check
2671 * @return $isset Whether the given key is set
2673 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2675 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2678 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2684 * Determines if a key is set in the generic array
2686 * @param $keyGroup Main group for the key
2687 * @param $subGroup Sub group for the key
2688 * @param $key Key to check
2689 * @return $isset Whether the given key is set
2691 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2693 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2696 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2704 * Determines if a group is set in the generic array
2706 * @param $keyGroup Main group
2707 * @param $subGroup Sub group
2708 * @return $isset Whether the given group is set
2710 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2712 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2715 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2722 * Getter for sub key group
2724 * @param $keyGroup Main key group
2725 * @param $subGroup Sub key group
2726 * @return $array An array with all array elements
2728 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2730 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2731 // No, then abort here
2732 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2737 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2740 return $this->genericArray[$keyGroup][$subGroup];
2744 * Unsets a given key in generic array
2746 * @param $keyGroup Main group for the key
2747 * @param $subGroup Sub group for the key
2748 * @param $key Key to unset
2751 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2753 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2756 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2760 * Unsets a given element in generic array
2762 * @param $keyGroup Main group for the key
2763 * @param $subGroup Sub group for the key
2764 * @param $key Key to unset
2765 * @param $element Element to unset
2768 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2770 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2773 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2777 * Append a string to a given generic array key
2779 * @param $keyGroup Main group for the key
2780 * @param $subGroup Sub group for the key
2781 * @param $key Key to unset
2782 * @param $value Value to add/append
2785 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2787 //* 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);
2789 // Is it already there?
2790 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2792 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2795 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2800 * Append a string to a given generic array element
2802 * @param $keyGroup Main group for the key
2803 * @param $subGroup Sub group for the key
2804 * @param $key Key to unset
2805 * @param $element Element to check
2806 * @param $value Value to add/append
2809 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2811 //* 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);
2813 // Is it already there?
2814 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2816 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2819 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2824 * Sets a string in a given generic array element
2826 * @param $keyGroup Main group for the key
2827 * @param $subGroup Sub group for the key
2828 * @param $key Key to unset
2829 * @param $element Element to check
2830 * @param $value Value to add/append
2833 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2835 //* 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);
2838 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2842 * Initializes given generic array group
2844 * @param $keyGroup Main group for the key
2845 * @param $subGroup Sub group for the key
2846 * @param $key Key to use
2847 * @param $forceInit Optionally force initialization
2850 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2852 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2854 // Is it already set?
2855 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2856 // Already initialized
2857 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2862 $this->genericArray[$keyGroup][$subGroup] = array();
2866 * Initializes given generic array key
2868 * @param $keyGroup Main group for the key
2869 * @param $subGroup Sub group for the key
2870 * @param $key Key to use
2871 * @param $forceInit Optionally force initialization
2874 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2876 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2878 // Is it already set?
2879 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2880 // Already initialized
2881 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2886 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2890 * Initializes given generic array element
2892 * @param $keyGroup Main group for the key
2893 * @param $subGroup Sub group for the key
2894 * @param $key Key to use
2895 * @param $element Element to use
2896 * @param $forceInit Optionally force initialization
2899 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2901 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2903 // Is it already set?
2904 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2905 // Already initialized
2906 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2911 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2915 * Pushes an element to a generic key
2917 * @param $keyGroup Main group for the key
2918 * @param $subGroup Sub group for the key
2919 * @param $key Key to use
2920 * @param $value Value to add/append
2921 * @return $count Number of array elements
2923 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2925 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2928 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2930 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2934 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2937 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2938 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2943 * Pushes an element to a generic array element
2945 * @param $keyGroup Main group for the key
2946 * @param $subGroup Sub group for the key
2947 * @param $key Key to use
2948 * @param $element Element to check
2949 * @param $value Value to add/append
2950 * @return $count Number of array elements
2952 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2954 //* 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));
2957 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2959 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2963 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2966 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2967 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2972 * Pops an element from a generic group
2974 * @param $keyGroup Main group for the key
2975 * @param $subGroup Sub group for the key
2976 * @param $key Key to unset
2977 * @return $value Last "popped" value
2979 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2981 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2984 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2986 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2991 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2994 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2995 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3000 * Shifts an element from a generic group
3002 * @param $keyGroup Main group for the key
3003 * @param $subGroup Sub group for the key
3004 * @param $key Key to unset
3005 * @return $value Last "popped" value
3007 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3009 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3012 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3014 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3019 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3022 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3023 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3028 * Count generic array group
3030 * @param $keyGroup Main group for the key
3031 * @return $count Count of given group
3033 protected final function countGenericArray ($keyGroup) {
3035 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3038 if (!isset($this->genericArray[$keyGroup])) {
3040 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3045 $count = count($this->genericArray[$keyGroup]);
3048 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3055 * Count generic array sub group
3057 * @param $keyGroup Main group for the key
3058 * @param $subGroup Sub group for the key
3059 * @return $count Count of given group
3061 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3063 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3066 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3068 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3073 $count = count($this->genericArray[$keyGroup][$subGroup]);
3076 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3083 * Count generic array elements
3085 * @param $keyGroup Main group for the key
3086 * @param $subGroup Sub group for the key
3087 * @para $key Key to count
3088 * @return $count Count of given key
3090 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3092 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3095 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3097 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3099 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3101 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3106 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3109 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3116 * Getter for whole generic group array
3118 * @param $keyGroup Key group to get
3119 * @return $array Whole generic array group
3121 protected final function getGenericArray ($keyGroup) {
3123 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3126 if (!isset($this->genericArray[$keyGroup])) {
3128 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3133 return $this->genericArray[$keyGroup];
3137 * Setter for generic array key
3139 * @param $keyGroup Key group to get
3140 * @param $subGroup Sub group for the key
3141 * @param $key Key to unset
3142 * @param $value Mixed value from generic array element
3145 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3147 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3150 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3154 * Getter for generic array key
3156 * @param $keyGroup Key group to get
3157 * @param $subGroup Sub group for the key
3158 * @param $key Key to unset
3159 * @return $value Mixed value from generic array element
3161 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3163 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3166 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3168 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3173 return $this->genericArray[$keyGroup][$subGroup][$key];
3177 * Sets a value in given generic array key/element
3179 * @param $keyGroup Main group for the key
3180 * @param $subGroup Sub group for the key
3181 * @param $key Key to set
3182 * @param $element Element to set
3183 * @param $value Value to set
3186 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3188 //* 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));
3191 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3195 * Getter for generic array element
3197 * @param $keyGroup Key group to get
3198 * @param $subGroup Sub group for the key
3199 * @param $key Key to look for
3200 * @param $element Element to look for
3201 * @return $value Mixed value from generic array element
3203 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3205 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3208 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3210 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3215 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3219 * Checks if a given sub group is valid (array)
3221 * @param $keyGroup Key group to get
3222 * @param $subGroup Sub group for the key
3223 * @return $isValid Whether given sub group is valid
3225 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3227 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3230 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3237 * Checks if a given key is valid (array)
3239 * @param $keyGroup Key group to get
3240 * @param $subGroup Sub group for the key
3241 * @param $key Key to check
3242 * @return $isValid Whether given sub group is valid
3244 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3246 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3249 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3256 * Initializes the web output instance
3260 protected function initWebOutputInstance () {
3261 // Get application instance
3262 $applicationInstance = Registry::getRegistry()->getInstance('app');
3264 // Is this a response instance?
3265 if ($this instanceof Responseable) {
3266 // Then set it in application instance
3267 $applicationInstance->setResponseInstance($this);
3270 // Init web output instance
3271 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3274 $this->setWebOutputInstance($outputInstance);
3278 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3280 * @param $boolean Boolean value
3281 * @return $translated Translated boolean value
3283 public static final function translateBooleanToYesNo ($boolean) {
3284 // Make sure it is really boolean
3285 assert(is_bool($boolean));
3288 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3290 // ... and return it
3295 * Encodes raw data (almost any type) by "serializing" it and then pack it
3296 * into a "binary format".
3298 * @param $rawData Raw data (almost any type)
3299 * @return $encoded Encoded data
3301 protected function encodeData ($rawData) {
3302 // Make sure no objects or resources pass through
3303 assert(!is_object($rawData));
3304 assert(!is_resource($rawData));
3306 // First "serialize" it (json_encode() is faster than serialize())
3307 $encoded = $this->packString(json_encode($rawData));
3314 * Pack a string into a "binary format". Please execuse me that this is
3315 * widely undocumented. :-(
3317 * @param $str Unpacked string
3318 * @return $packed Packed string
3319 * @todo Improve documentation
3321 protected function packString ($str) {
3323 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3325 // First compress the string (gzcompress is okay)
3326 $str = gzcompress($str);
3331 // And start the "encoding" loop
3332 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3334 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3335 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3337 if (($idx + $i) <= strlen($str)) {
3338 $ord = ord(substr($str, ($idx + $i), 1));
3340 $add = $ord * pow(256, $factor);
3344 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3348 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3349 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3351 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3352 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3358 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3363 * Checks whether the given file/path is in open_basedir(). This does not
3364 * gurantee that the file is actually readable and/or writeable. If you need
3365 * such gurantee then please use isReadableFile() instead.
3367 * @param $filePathName Name of the file/path to be checked
3368 * @return $isReachable Whether it is within open_basedir()
3370 protected static function isReachableFilePath ($filePathName) {
3371 // Is not reachable by default
3372 $isReachable = FALSE;
3374 // Get open_basedir parameter
3375 $openBaseDir = ini_get('open_basedir');
3378 if (!empty($openBaseDir)) {
3379 // Check all entries
3380 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3381 // Check on existence
3382 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3384 $isReachable = TRUE;
3388 // If open_basedir is not set, all is allowed
3389 $isReachable = TRUE;
3393 return $isReachable;
3397 * Checks whether the give file is within open_basedir() (done by
3398 * isReachableFilePath()), is actually a file and is readable.
3400 * @param $fileName Name of the file to be checked
3401 * @return $isReadable Whether the file is readable (and therefor exists)
3403 public static function isReadableFile ($fileName) {
3404 // Default is not readable
3405 $isReadable = FALSE;
3407 // Is within parameters, so check if it is a file and readable
3408 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3415 * Creates a full-qualified file name (FQFN) for given file name by adding
3416 * a configured temporary file path to it.
3418 * @param $fileName Name for temporary file
3419 * @return $fqfn Full-qualified file name
3420 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3421 * @throws FileIoException If the file cannot be written
3423 protected static function createTempPathForFile ($fileName) {
3425 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3427 // Is the path writeable?
3428 if (!is_writable($basePath)) {
3429 // Path is write-protected
3430 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3434 $fqfn = $basePath . '/' . $fileName;
3437 if (!self::isReachableFilePath($fqfn)) {
3439 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3447 * "Getter" for a printable state name
3449 * @return $stateName Name of the node's state in a printable format
3451 public final function getPrintableState () {
3452 // Default is 'null'
3453 $stateName = 'null';
3455 // Get the state instance
3456 $stateInstance = $this->getStateInstance();
3458 // Is it an instance of Stateable?
3459 if ($stateInstance instanceof Stateable) {
3460 // Then use that state name
3461 $stateName = $stateInstance->getStateName();
3469 * Handles socket error for given socket resource and peer data. This method
3470 * validates $socketResource if it is a valid resource (see is_resource())
3471 * but assumes valid data in array $recipientData, except that
3472 * count($recipientData) is always 2.
3474 * @param $method Value of __METHOD__ from calling method
3475 * @param $line Value of __LINE__ from calling method
3476 * @param $socketResource A valid socket resource
3477 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3479 * @throws InvalidSocketException If $socketResource is no socket resource
3480 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3481 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3483 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3484 // This method handles only socket resources
3485 if (!is_resource($socketResource)) {
3486 // No resource, abort here
3487 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3490 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3491 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3492 assert(isset($socketData[0]));
3493 assert(isset($socketData[1]));
3495 // Get error code for first validation (0 is not an error)
3496 $errorCode = socket_last_error($socketResource);
3498 // If the error code is zero, someone called this method without an error
3499 if ($errorCode == 0) {
3500 // No error detected (or previously cleared outside this method)
3501 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3504 // Get handler (method) name
3505 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3507 // Call-back the error handler method
3508 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3510 // Finally clear the error because it has been handled
3511 socket_clear_error($socketResource);