3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Compressor\Compressor;
7 use CoreFramework\Configuration\FrameworkConfiguration;
8 use CoreFramework\Connection\Database\DatabaseConnection;
9 use CoreFramework\Controller\Controller;
10 use CoreFramework\Criteria\Criteria;
11 use CoreFramework\Criteria\Local\LocalSearchCriteria;
12 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
13 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
14 use CoreFramework\Factory\ObjectFactory;
15 use CoreFramework\Filesystem\Block;
16 use CoreFramework\Filesystem\FilePointer;
17 use CoreFramework\Filesystem\FrameworkDirectory;
18 use CoreFramework\Generic\FrameworkInterface;
19 use CoreFramework\Generic\NullPointerException;
20 use CoreFramework\Handler\Stream\IoHandler;
21 use CoreFramework\Lists\Listable;
22 use CoreFramework\Loader\ClassLoader;
23 use CoreFramework\Manager\ManageableApplication;
24 use CoreFramework\Middleware\Compressor\CompressorChannel;
25 use CoreFramework\Middleware\Debug\DebugMiddleware;
26 use CoreFramework\Parser\Parseable;
27 use CoreFramework\Registry\Register;
28 use CoreFramework\Registry\Registry;
29 use CoreFramework\Request\Requestable;
30 use CoreFramework\Resolver\Resolver;
31 use CoreFramework\Result\Database\CachedDatabaseResult;
32 use CoreFramework\Result\Search\SearchableResult;
33 use CoreFramework\Response\Responseable;
34 use CoreFramework\Stream\Output\OutputStreamer;
35 use CoreFramework\Template\CompileableTemplate;
36 use CoreFramework\User\ManageableAccount;
37 use CoreFramework\Visitor\Visitor;
38 use CoreFramework\Wrapper\Database\DatabaseWrapper;
45 * The simulator system class is the super class of all other classes. This
46 * class handles saving of games etc.
48 * @author Roland Haeder <webmaster@shipsimu.org>
50 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
51 * @license GNU GPL 3.0 or any newer version
52 * @link http://www.shipsimu.org
54 * This program is free software: you can redistribute it and/or modify
55 * it under the terms of the GNU General Public License as published by
56 * the Free Software Foundation, either version 3 of the License, or
57 * (at your option) any later version.
59 * This program is distributed in the hope that it will be useful,
60 * but WITHOUT ANY WARRANTY; without even the implied warranty of
61 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
62 * GNU General Public License for more details.
64 * You should have received a copy of the GNU General Public License
65 * along with this program. If not, see <http://www.gnu.org/licenses/>.
67 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
69 * Length of output from hash()
71 private static $hashLength = NULL;
76 private $realClass = 'BaseFrameworkSystem';
79 * Instance of a Requestable class
81 private $requestInstance = NULL;
84 * Instance of a Responseable class
86 private $responseInstance = NULL;
89 * Search criteria instance
91 private $searchInstance = NULL;
94 * Update criteria instance
96 private $updateInstance = NULL;
99 * The file I/O instance for the template loader
101 private $fileIoInstance = NULL;
106 private $resolverInstance = NULL;
109 * Template engine instance
111 private $templateInstance = NULL;
114 * Database result instance
116 private $resultInstance = NULL;
119 * Instance for user class
121 private $userInstance = NULL;
124 * A controller instance
126 private $controllerInstance = NULL;
131 private $rngInstance = NULL;
134 * Instance of a crypto helper
136 private $cryptoInstance = NULL;
139 * Instance of an Iterator class
141 private $iteratorInstance = NULL;
144 * Instance of the list
146 private $listInstance = NULL;
151 private $menuInstance = NULL;
154 * Instance of the image
156 private $imageInstance = NULL;
159 * Instance of the stacker
161 private $stackInstance = NULL;
164 * A Compressor instance
166 private $compressorInstance = NULL;
169 * A Parseable instance
171 private $parserInstance = NULL;
174 * A HandleableProtocol instance
176 private $protocolInstance = NULL;
179 * A database wrapper instance
181 private $databaseInstance = NULL;
184 * A helper instance for the form
186 private $helperInstance = NULL;
189 * An instance of a Source class
191 private $sourceInstance = NULL;
194 * An instance of a UrlSource class
196 private $urlSourceInstance = NULL;
199 * An instance of a InputStream class
201 private $inputStreamInstance = NULL;
204 * An instance of a OutputStream class
206 private $outputStreamInstance = NULL;
209 * Networkable handler instance
211 private $handlerInstance = NULL;
214 * Visitor handler instance
216 private $visitorInstance = NULL;
221 private $dhtInstance = NULL;
224 * An instance of a database wrapper class
226 private $wrapperInstance = NULL;
229 * An instance of a file I/O pointer class (not handler)
231 private $pointerInstance = NULL;
234 * An instance of an Indexable class
236 private $indexInstance = NULL;
239 * An instance of a Block class
241 private $blockInstance = NULL;
246 private $minableInstance = NULL;
249 * A FrameworkDirectory instance
251 private $directoryInstance = NULL;
256 private $listenerInstance = NULL;
259 * An instance of a communicator
261 private $communicatorInstance = NULL;
264 * The concrete output instance
266 private $outputInstance = NULL;
271 private $stateInstance = NULL;
274 * Thousands separator
276 private $thousands = '.'; // German
281 private $decimals = ','; // German
286 private $socketResource = FALSE;
289 * Regular expression to use for validation
291 private $regularExpression = '';
296 private $packageData = array();
301 private $genericArray = array();
306 private $commandName = '';
311 private $controllerName = '';
314 * Name of used protocol
316 private $protocolName = 'invalid';
319 * Array with bitmasks and such for pack/unpack methods to support both
320 * 32-bit and 64-bit systems
322 private $packingData = array(
325 'left' => 0xffff0000,
326 'right' => 0x0000ffff,
332 'left' => 0xffffffff00000000,
333 'right' => 0x00000000ffffffff,
340 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
342 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
344 private $archArrayElement = FALSE;
346 /***********************
347 * Exception codes.... *
348 ***********************/
350 // @todo Try to clean these constants up
351 const EXCEPTION_IS_NULL_POINTER = 0x001;
352 const EXCEPTION_IS_NO_OBJECT = 0x002;
353 const EXCEPTION_IS_NO_ARRAY = 0x003;
354 const EXCEPTION_MISSING_METHOD = 0x004;
355 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
356 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
357 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
358 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
359 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
360 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
361 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
362 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
363 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
364 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
365 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
366 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
367 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
368 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
369 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
370 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
371 const EXCEPTION_PATH_NOT_FOUND = 0x015;
372 const EXCEPTION_INVALID_PATH_NAME = 0x016;
373 const EXCEPTION_READ_PROTECED_PATH = 0x017;
374 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
375 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
376 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
377 const EXCEPTION_INVALID_RESOURCE = 0x01b;
378 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
379 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
380 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
381 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
382 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
383 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
384 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
385 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
386 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
387 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
388 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
389 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
390 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
391 const EXCEPTION_INVALID_STRING = 0x029;
392 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
393 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
394 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
395 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
396 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
397 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
398 const EXCEPTION_MISSING_ELEMENT = 0x030;
399 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
400 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
401 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
402 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
403 const EXCEPTION_FATAL_ERROR = 0x035;
404 const EXCEPTION_FILE_NOT_FOUND = 0x036;
405 const EXCEPTION_ASSERTION_FAILED = 0x037;
406 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
407 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
408 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
409 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
410 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
411 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
414 * Hexadecimal->Decimal translation array
416 private static $hexdec = array(
436 * Decimal->hexadecimal translation array
438 private static $dechex = array(
458 * Startup time in miliseconds
460 private static $startupTime = 0;
463 * Protected super constructor
465 * @param $className Name of the class
468 protected function __construct ($className) {
470 $this->setRealClass($className);
472 // Set configuration instance if no registry ...
473 if (!$this instanceof Register) {
474 // ... because registries doesn't need to be configured
475 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
478 // Is the startup time set? (0 cannot be TRUE anymore)
479 if (self::$startupTime == 0) {
481 self::$startupTime = microtime(TRUE);
485 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
489 * Destructor for all classes. You should not call this method on your own.
493 public function __destruct () {
494 // Flush any updated entries to the database
495 $this->flushPendingUpdates();
497 // Is this object already destroyed?
498 if ($this->__toString() != 'DestructedObject') {
499 // Destroy all informations about this class but keep some text about it alive
500 $this->setRealClass('DestructedObject');
501 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
502 // Already destructed object
503 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
508 // Do not call this twice
509 trigger_error(__METHOD__ . ': Called twice.');
515 * The __call() method where all non-implemented methods end up
517 * @param $methodName Name of the missing method
518 * @args $args Arguments passed to the method
521 public final function __call ($methodName, $args) {
522 return self::__callStatic($methodName, $args);
526 * The __callStatic() method where all non-implemented static methods end up
528 * @param $methodName Name of the missing method
529 * @args $args Arguments passed to the method
532 public static final function __callStatic ($methodName, $args) {
534 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
536 // Init argument string
539 // Is it NULL, empty or an array?
540 if (is_null($args)) {
542 $argsString = 'NULL';
543 } elseif (is_array($args)) {
547 // Some arguments are there
548 foreach ($args as $arg) {
549 // Add data about the argument
550 $argsString .= gettype($arg) . ':';
553 // Found a NULL argument
554 $argsString .= 'NULL';
555 } elseif (is_string($arg)) {
556 // Add length for strings
557 $argsString .= strlen($arg);
558 } elseif ((is_int($arg)) || (is_float($arg))) {
561 } elseif (is_array($arg)) {
562 // .. or size if array
563 $argsString .= count($arg);
564 } elseif (is_object($arg)) {
566 $reflection = new ReflectionClass($arg);
568 // Is an other object, maybe no __toString() available
569 $argsString .= $reflection->getName();
570 } elseif ($arg === TRUE) {
571 // ... is boolean 'TRUE'
572 $argsString .= 'TRUE';
573 } elseif ($arg === FALSE) {
574 // ... is boolean 'FALSE'
575 $argsString .= 'FALSE';
578 // Comma for next one
583 if (substr($argsString, -2, 1) == ',') {
584 $argsString = substr($argsString, 0, -2);
590 // Invalid arguments!
591 $argsString = '!INVALID:' . gettype($args) . '!';
594 // Output stub message
595 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
596 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
606 * Getter for $realClass
608 * @return $realClass The name of the real class (not BaseFrameworkSystem)
610 public function __toString () {
611 return $this->realClass;
615 * Magic method to catch setting of missing but set class fields/attributes
617 * @param $name Name of the field/attribute
618 * @param $value Value to store
621 public final function __set ($name, $value) {
622 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
625 print_r($value, TRUE)
630 * Magic method to catch getting of missing fields/attributes
632 * @param $name Name of the field/attribute
635 public final function __get ($name) {
636 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
642 * Magic method to catch unsetting of missing fields/attributes
644 * @param $name Name of the field/attribute
647 public final function __unset ($name) {
648 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
654 * Magic method to catch object serialization
656 * @return $unsupported Unsupported method
657 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
659 public final function __sleep () {
660 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
664 * Magic method to catch object deserialization
666 * @return $unsupported Unsupported method
667 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
669 public final function __wakeup () {
670 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
674 * Magic method to catch calls when an object instance is called
676 * @return $unsupported Unsupported method
677 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
679 public final function __invoke () {
680 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
684 * Setter for the real class name
686 * @param $realClass Class name (string)
689 public final function setRealClass ($realClass) {
691 $this->realClass = (string) $realClass;
695 * Setter for database result instance
697 * @param $resultInstance An instance of a database result class
699 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
701 protected final function setResultInstance (SearchableResult $resultInstance) {
702 $this->resultInstance = $resultInstance;
706 * Getter for database result instance
708 * @return $resultInstance An instance of a database result class
710 public final function getResultInstance () {
711 return $this->resultInstance;
715 * Setter for template engine instances
717 * @param $templateInstance An instance of a template engine class
720 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
721 $this->templateInstance = $templateInstance;
725 * Getter for template engine instances
727 * @return $templateInstance An instance of a template engine class
729 protected final function getTemplateInstance () {
730 return $this->templateInstance;
734 * Setter for search instance
736 * @param $searchInstance Searchable criteria instance
739 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
740 $this->searchInstance = $searchInstance;
744 * Getter for search instance
746 * @return $searchInstance Searchable criteria instance
748 public final function getSearchInstance () {
749 return $this->searchInstance;
753 * Setter for update instance
755 * @param $updateInstance An instance of a LocalUpdateCriteria clase
758 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
759 $this->updateInstance = $updateInstance;
763 * Getter for update instance
765 * @return $updateInstance Updateable criteria instance
767 public final function getUpdateInstance () {
768 return $this->updateInstance;
772 * Setter for resolver instance
774 * @param $resolverInstance Instance of a command resolver class
777 public final function setResolverInstance (Resolver $resolverInstance) {
778 $this->resolverInstance = $resolverInstance;
782 * Getter for resolver instance
784 * @return $resolverInstance Instance of a command resolver class
786 public final function getResolverInstance () {
787 return $this->resolverInstance;
791 * Setter for language instance
793 * @param $configInstance The configuration instance which shall
794 * be FrameworkConfiguration
797 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
798 Registry::getRegistry()->addInstance('config', $configInstance);
802 * Getter for configuration instance
804 * @return $configInstance Configuration instance
806 public final function getConfigInstance () {
807 $configInstance = Registry::getRegistry()->getInstance('config');
808 return $configInstance;
812 * Setter for debug instance
814 * @param $debugInstance The instance for debug output class
817 public final function setDebugInstance (DebugMiddleware $debugInstance) {
818 Registry::getRegistry()->addInstance('debug', $debugInstance);
822 * Getter for debug instance
824 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
826 public final function getDebugInstance () {
827 // Get debug instance
828 $debugInstance = Registry::getRegistry()->getInstance('debug');
831 return $debugInstance;
835 * Setter for web output instance
837 * @param $webInstance The instance for web output class
840 public final function setWebOutputInstance (OutputStreamer $webInstance) {
841 Registry::getRegistry()->addInstance('web_output', $webInstance);
845 * Getter for web output instance
847 * @return $webOutputInstance - Instance to class WebOutput
849 public final function getWebOutputInstance () {
850 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
851 return $webOutputInstance;
855 * Setter for database instance
857 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
860 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
861 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
865 * Getter for database layer
867 * @return $databaseInstance The database layer instance
869 public final function getDatabaseInstance () {
871 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
874 return $databaseInstance;
878 * Setter for compressor channel
880 * @param $compressorInstance An instance of CompressorChannel
883 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
884 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
888 * Getter for compressor channel
890 * @return $compressorInstance The compressor channel
892 public final function getCompressorChannel () {
893 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
894 return $compressorInstance;
898 * Protected getter for a manageable application helper class
900 * @return $applicationInstance An instance of a manageable application helper class
902 protected final function getApplicationInstance () {
903 $applicationInstance = Registry::getRegistry()->getInstance('application');
904 return $applicationInstance;
908 * Setter for a manageable application helper class
910 * @param $applicationInstance An instance of a manageable application helper class
913 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
914 Registry::getRegistry()->addInstance('application', $applicationInstance);
918 * Setter for request instance
920 * @param $requestInstance An instance of a Requestable class
923 public final function setRequestInstance (Requestable $requestInstance) {
924 $this->requestInstance = $requestInstance;
928 * Getter for request instance
930 * @return $requestInstance An instance of a Requestable class
932 public final function getRequestInstance () {
933 return $this->requestInstance;
937 * Setter for response instance
939 * @param $responseInstance An instance of a Responseable class
942 public final function setResponseInstance (Responseable $responseInstance) {
943 $this->responseInstance = $responseInstance;
947 * Getter for response instance
949 * @return $responseInstance An instance of a Responseable class
951 public final function getResponseInstance () {
952 return $this->responseInstance;
956 * Private getter for language instance
958 * @return $langInstance An instance to the language sub-system
960 protected final function getLanguageInstance () {
961 $langInstance = Registry::getRegistry()->getInstance('language');
962 return $langInstance;
966 * Setter for language instance
968 * @param $langInstance An instance to the language sub-system
970 * @see LanguageSystem
972 public final function setLanguageInstance (ManageableLanguage $langInstance) {
973 Registry::getRegistry()->addInstance('language', $langInstance);
977 * Private getter for file IO instance
979 * @return $fileIoInstance An instance to the file I/O sub-system
981 protected final function getFileIoInstance () {
982 return $this->fileIoInstance;
986 * Setter for file I/O instance
988 * @param $fileIoInstance An instance to the file I/O sub-system
991 public final function setFileIoInstance (IoHandler $fileIoInstance) {
992 $this->fileIoInstance = $fileIoInstance;
996 * Protected setter for user instance
998 * @param $userInstance An instance of a user class
1001 protected final function setUserInstance (ManageableAccount $userInstance) {
1002 $this->userInstance = $userInstance;
1006 * Getter for user instance
1008 * @return $userInstance An instance of a user class
1010 public final function getUserInstance () {
1011 return $this->userInstance;
1015 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1017 * @param $controllerInstance An instance of the controller
1020 public final function setControllerInstance (Controller $controllerInstance) {
1021 $this->controllerInstance = $controllerInstance;
1025 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1027 * @return $controllerInstance An instance of the controller
1029 public final function getControllerInstance () {
1030 return $this->controllerInstance;
1034 * Setter for RNG instance
1036 * @param $rngInstance An instance of a random number generator (RNG)
1039 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1040 $this->rngInstance = $rngInstance;
1044 * Getter for RNG instance
1046 * @return $rngInstance An instance of a random number generator (RNG)
1048 public final function getRngInstance () {
1049 return $this->rngInstance;
1053 * Setter for Cryptable instance
1055 * @param $cryptoInstance An instance of a Cryptable class
1058 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1059 $this->cryptoInstance = $cryptoInstance;
1063 * Getter for Cryptable instance
1065 * @return $cryptoInstance An instance of a Cryptable class
1067 public final function getCryptoInstance () {
1068 return $this->cryptoInstance;
1072 * Setter for the list instance
1074 * @param $listInstance A list of Listable
1077 protected final function setListInstance (Listable $listInstance) {
1078 $this->listInstance = $listInstance;
1082 * Getter for the list instance
1084 * @return $listInstance A list of Listable
1086 protected final function getListInstance () {
1087 return $this->listInstance;
1091 * Setter for the menu instance
1093 * @param $menuInstance A RenderableMenu instance
1096 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1097 $this->menuInstance = $menuInstance;
1101 * Getter for the menu instance
1103 * @return $menuInstance A RenderableMenu instance
1105 protected final function getMenuInstance () {
1106 return $this->menuInstance;
1110 * Setter for image instance
1112 * @param $imageInstance An instance of an image
1115 public final function setImageInstance (BaseImage $imageInstance) {
1116 $this->imageInstance = $imageInstance;
1120 * Getter for image instance
1122 * @return $imageInstance An instance of an image
1124 public final function getImageInstance () {
1125 return $this->imageInstance;
1129 * Setter for stacker instance
1131 * @param $stackInstance An instance of an stacker
1134 public final function setStackInstance (Stackable $stackInstance) {
1135 $this->stackInstance = $stackInstance;
1139 * Getter for stacker instance
1141 * @return $stackInstance An instance of an stacker
1143 public final function getStackInstance () {
1144 return $this->stackInstance;
1148 * Setter for compressor instance
1150 * @param $compressorInstance An instance of an compressor
1153 public final function setCompressorInstance (Compressor $compressorInstance) {
1154 $this->compressorInstance = $compressorInstance;
1158 * Getter for compressor instance
1160 * @return $compressorInstance An instance of an compressor
1162 public final function getCompressorInstance () {
1163 return $this->compressorInstance;
1167 * Setter for Parseable instance
1169 * @param $parserInstance An instance of an Parseable
1172 public final function setParserInstance (Parseable $parserInstance) {
1173 $this->parserInstance = $parserInstance;
1177 * Getter for Parseable instance
1179 * @return $parserInstance An instance of an Parseable
1181 public final function getParserInstance () {
1182 return $this->parserInstance;
1186 * Setter for HandleableProtocol instance
1188 * @param $protocolInstance An instance of an HandleableProtocol
1191 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1192 $this->protocolInstance = $protocolInstance;
1196 * Getter for HandleableProtocol instance
1198 * @return $protocolInstance An instance of an HandleableProtocol
1200 public final function getProtocolInstance () {
1201 return $this->protocolInstance;
1205 * Setter for DatabaseWrapper instance
1207 * @param $wrapperInstance An instance of an DatabaseWrapper
1210 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1211 $this->wrapperInstance = $wrapperInstance;
1215 * Getter for DatabaseWrapper instance
1217 * @return $wrapperInstance An instance of an DatabaseWrapper
1219 public final function getWrapperInstance () {
1220 return $this->wrapperInstance;
1224 * Setter for socket resource
1226 * @param $socketResource A valid socket resource
1229 public final function setSocketResource ($socketResource) {
1230 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1231 $this->socketResource = $socketResource;
1235 * Getter for socket resource
1237 * @return $socketResource A valid socket resource
1239 public final function getSocketResource () {
1240 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1241 return $this->socketResource;
1245 * Setter for regular expression
1247 * @param $regularExpression A valid regular expression
1250 public final function setRegularExpression ($regularExpression) {
1251 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1252 $this->regularExpression = $regularExpression;
1256 * Getter for regular expression
1258 * @return $regularExpression A valid regular expression
1260 public final function getRegularExpression () {
1261 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1262 return $this->regularExpression;
1266 * Setter for helper instance
1268 * @param $helperInstance An instance of a helper class
1271 protected final function setHelperInstance (Helper $helperInstance) {
1272 $this->helperInstance = $helperInstance;
1276 * Getter for helper instance
1278 * @return $helperInstance An instance of a helper class
1280 public final function getHelperInstance () {
1281 return $this->helperInstance;
1285 * Setter for a Source instance
1287 * @param $sourceInstance An instance of a Source class
1290 protected final function setSourceInstance (Source $sourceInstance) {
1291 $this->sourceInstance = $sourceInstance;
1295 * Getter for a Source instance
1297 * @return $sourceInstance An instance of a Source class
1299 protected final function getSourceInstance () {
1300 return $this->sourceInstance;
1304 * Setter for a UrlSource instance
1306 * @param $sourceInstance An instance of a UrlSource class
1309 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1310 $this->urlSourceInstance = $urlSourceInstance;
1314 * Getter for a UrlSource instance
1316 * @return $urlSourceInstance An instance of a UrlSource class
1318 protected final function getUrlSourceInstance () {
1319 return $this->urlSourceInstance;
1323 * Getter for a InputStream instance
1325 * @param $inputStreamInstance The InputStream instance
1327 protected final function getInputStreamInstance () {
1328 return $this->inputStreamInstance;
1332 * Setter for a InputStream instance
1334 * @param $inputStreamInstance The InputStream instance
1337 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1338 $this->inputStreamInstance = $inputStreamInstance;
1342 * Getter for a OutputStream instance
1344 * @param $outputStreamInstance The OutputStream instance
1346 protected final function getOutputStreamInstance () {
1347 return $this->outputStreamInstance;
1351 * Setter for a OutputStream instance
1353 * @param $outputStreamInstance The OutputStream instance
1356 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1357 $this->outputStreamInstance = $outputStreamInstance;
1361 * Setter for handler instance
1363 * @param $handlerInstance An instance of a Handleable class
1366 protected final function setHandlerInstance (Handleable $handlerInstance) {
1367 $this->handlerInstance = $handlerInstance;
1371 * Getter for handler instance
1373 * @return $handlerInstance A Networkable instance
1375 protected final function getHandlerInstance () {
1376 return $this->handlerInstance;
1380 * Setter for visitor instance
1382 * @param $visitorInstance A Visitor instance
1385 protected final function setVisitorInstance (Visitor $visitorInstance) {
1386 $this->visitorInstance = $visitorInstance;
1390 * Getter for visitor instance
1392 * @return $visitorInstance A Visitor instance
1394 protected final function getVisitorInstance () {
1395 return $this->visitorInstance;
1399 * Setter for DHT instance
1401 * @param $dhtInstance A Distributable instance
1404 protected final function setDhtInstance (Distributable $dhtInstance) {
1405 $this->dhtInstance = $dhtInstance;
1409 * Getter for DHT instance
1411 * @return $dhtInstance A Distributable instance
1413 protected final function getDhtInstance () {
1414 return $this->dhtInstance;
1418 * Setter for raw package Data
1420 * @param $packageData Raw package Data
1423 public final function setPackageData (array $packageData) {
1424 $this->packageData = $packageData;
1428 * Getter for raw package Data
1430 * @return $packageData Raw package Data
1432 public function getPackageData () {
1433 return $this->packageData;
1438 * Setter for Iterator instance
1440 * @param $iteratorInstance An instance of an Iterator
1443 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1444 $this->iteratorInstance = $iteratorInstance;
1448 * Getter for Iterator instance
1450 * @return $iteratorInstance An instance of an Iterator
1452 public final function getIteratorInstance () {
1453 return $this->iteratorInstance;
1457 * Setter for FilePointer instance
1459 * @param $pointerInstance An instance of an FilePointer class
1462 protected final function setPointerInstance (FilePointer $pointerInstance) {
1463 $this->pointerInstance = $pointerInstance;
1467 * Getter for FilePointer instance
1469 * @return $pointerInstance An instance of an FilePointer class
1471 public final function getPointerInstance () {
1472 return $this->pointerInstance;
1476 * Unsets pointer instance which triggers a call of __destruct() if the
1477 * instance is still there. This is surely not fatal on already "closed"
1478 * file pointer instances.
1480 * I don't want to mess around with above setter by giving it a default
1481 * value NULL as setter should always explicitly only set (existing) object
1482 * instances and NULL is NULL.
1486 protected final function unsetPointerInstance () {
1487 // Simply it to NULL
1488 $this->pointerInstance = NULL;
1492 * Setter for Indexable instance
1494 * @param $indexInstance An instance of an Indexable class
1497 protected final function setIndexInstance (Indexable $indexInstance) {
1498 $this->indexInstance = $indexInstance;
1502 * Getter for Indexable instance
1504 * @return $indexInstance An instance of an Indexable class
1506 public final function getIndexInstance () {
1507 return $this->indexInstance;
1511 * Setter for Block instance
1513 * @param $blockInstance An instance of an Block class
1516 protected final function setBlockInstance (Block $blockInstance) {
1517 $this->blockInstance = $blockInstance;
1521 * Getter for Block instance
1523 * @return $blockInstance An instance of an Block class
1525 public final function getBlockInstance () {
1526 return $this->blockInstance;
1530 * Setter for Minable instance
1532 * @param $minableInstance A Minable instance
1535 protected final function setMinableInstance (Minable $minableInstance) {
1536 $this->minableInstance = $minableInstance;
1540 * Getter for minable instance
1542 * @return $minableInstance A Minable instance
1544 protected final function getMinableInstance () {
1545 return $this->minableInstance;
1549 * Setter for FrameworkDirectory instance
1551 * @param $directoryInstance A FrameworkDirectory instance
1554 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1555 $this->directoryInstance = $directoryInstance;
1559 * Getter for FrameworkDirectory instance
1561 * @return $directoryInstance A FrameworkDirectory instance
1563 protected final function getDirectoryInstance () {
1564 return $this->directoryInstance;
1568 * Setter for listener instance
1570 * @param $listenerInstance A Listenable instance
1573 protected final function setListenerInstance (Listenable $listenerInstance) {
1574 $this->listenerInstance = $listenerInstance;
1578 * Getter for listener instance
1580 * @return $listenerInstance A Listenable instance
1582 protected final function getListenerInstance () {
1583 return $this->listenerInstance;
1587 * Getter for communicator instance
1589 * @return $communicatorInstance An instance of a Communicator class
1591 public final function getCommunicatorInstance () {
1592 return $this->communicatorInstance;
1596 * Setter for communicator instance
1598 * @param $communicatorInstance An instance of a Communicator class
1601 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1602 $this->communicatorInstance = $communicatorInstance;
1606 * Setter for state instance
1608 * @param $stateInstance A Stateable instance
1611 public final function setStateInstance (Stateable $stateInstance) {
1612 $this->stateInstance = $stateInstance;
1616 * Getter for state instance
1618 * @return $stateInstance A Stateable instance
1620 public final function getStateInstance () {
1621 return $this->stateInstance;
1625 * Setter for output instance
1627 * @param $outputInstance The debug output instance
1630 public final function setOutputInstance (OutputStreamer $outputInstance) {
1631 $this->outputInstance = $outputInstance;
1635 * Getter for output instance
1637 * @return $outputInstance The debug output instance
1639 public final function getOutputInstance () {
1640 return $this->outputInstance;
1644 * Setter for command name
1646 * @param $commandName Last validated command name
1649 protected final function setCommandName ($commandName) {
1650 $this->commandName = $commandName;
1654 * Getter for command name
1656 * @return $commandName Last validated command name
1658 protected final function getCommandName () {
1659 return $this->commandName;
1663 * Setter for controller name
1665 * @param $controllerName Last validated controller name
1668 protected final function setControllerName ($controllerName) {
1669 $this->controllerName = $controllerName;
1673 * Getter for controller name
1675 * @return $controllerName Last validated controller name
1677 protected final function getControllerName () {
1678 return $this->controllerName;
1682 * Getter for protocol name
1684 * @return $protocolName Name of used protocol
1686 public final function getProtocolName () {
1687 return $this->protocolName;
1691 * Setter for protocol name
1693 * @param $protocolName Name of used protocol
1696 protected final function setProtocolName ($protocolName) {
1697 $this->protocolName = $protocolName;
1701 * Checks whether an object equals this object. You should overwrite this
1702 * method to implement own equality checks
1704 * @param $objectInstance An instance of a FrameworkInterface object
1705 * @return $equals Whether both objects equals
1707 public function equals (FrameworkInterface $objectInstance) {
1710 $this->__toString() == $objectInstance->__toString()
1712 $this->hashCode() == $objectInstance->hashCode()
1715 // Return the result
1720 * Generates a generic hash code of this class. You should really overwrite
1721 * this method with your own hash code generator code. But keep KISS in mind.
1723 * @return $hashCode A generic hash code respresenting this whole class
1725 public function hashCode () {
1727 return crc32($this->__toString());
1731 * Formats computer generated price values into human-understandable formats
1732 * with thousand and decimal separators.
1734 * @param $value The in computer format value for a price
1735 * @param $currency The currency symbol (use HTML-valid characters!)
1736 * @param $decNum Number of decimals after commata
1737 * @return $price The for the current language formated price string
1738 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1739 * thousands separator
1742 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1743 // Are all required attriutes set?
1744 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1745 // Throw an exception
1746 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1750 $value = (float) $value;
1752 // Reformat the US number
1753 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1755 // Return as string...
1760 * Appends a trailing slash to a string
1762 * @param $str A string (maybe) without trailing slash
1763 * @return $str A string with an auto-appended trailing slash
1765 public final function addMissingTrailingSlash ($str) {
1766 // Is there a trailing slash?
1767 if (substr($str, -1, 1) != '/') {
1771 // Return string with trailing slash
1776 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1777 * application helper instance (ApplicationHelper by default).
1779 * @param $applicationInstance An application helper instance or
1780 * null if we shall use the default
1781 * @return $templateInstance The template engine instance
1782 * @throws NullPointerException If the discovered application
1783 * instance is still null
1785 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1786 // Is the application instance set?
1787 if (is_null($applicationInstance)) {
1788 // Get the current instance
1789 $applicationInstance = $this->getApplicationInstance();
1792 if (is_null($applicationInstance)) {
1793 // Thrown an exception
1794 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1798 // Initialize the template engine
1799 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1801 // Return the prepared instance
1802 return $templateInstance;
1806 * Debugs this instance by putting out it's full content
1808 * @param $message Optional message to show in debug output
1811 public final function debugInstance ($message = '') {
1812 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1813 restore_error_handler();
1818 // Is a message set?
1819 if (!empty($message)) {
1820 // Construct message
1821 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1824 // Generate the output
1825 $content .= sprintf('<pre>%s</pre>',
1828 print_r($this, TRUE)
1834 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>',
1835 $this->__toString(),
1837 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1842 * Replaces control characters with printable output
1844 * @param $str String with control characters
1845 * @return $str Replaced string
1847 protected function replaceControlCharacters ($str) {
1850 chr(13), '[r]', str_replace(
1851 chr(10), '[n]', str_replace(
1861 * Output a partial stub message for the caller method
1863 * @param $message An optional message to display
1866 protected function partialStub ($message = '') {
1867 // Get the backtrace
1868 $backtrace = debug_backtrace();
1870 // Generate the class::method string
1871 $methodName = 'UnknownClass->unknownMethod';
1872 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1873 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1876 // Construct the full message
1877 $stubMessage = sprintf('[%s:] Partial stub!',
1881 // Is the extra message given?
1882 if (!empty($message)) {
1883 // Then add it as well
1884 $stubMessage .= ' Message: ' . $message;
1887 // Debug instance is there?
1888 if (!is_null($this->getDebugInstance())) {
1889 // Output stub message
1890 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1893 trigger_error($stubMessage);
1899 * Outputs a debug backtrace and stops further script execution
1901 * @param $message An optional message to output
1902 * @param $doExit Whether exit the program (TRUE is default)
1905 public function debugBackTrace ($message = '', $doExit = TRUE) {
1906 // Sorry, there is no other way getting this nice backtrace
1907 if (!empty($message)) {
1909 printf('Message: %s<br />' . PHP_EOL, $message);
1913 debug_print_backtrace();
1917 if ($doExit === TRUE) {
1923 * Creates an instance of a debugger instance
1925 * @param $className Name of the class (currently unsupported)
1926 * @param $lineNumber Line number where the call was made
1927 * @return $debugInstance An instance of a debugger class
1928 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1930 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1931 // Is the instance set?
1932 if (!Registry::getRegistry()->instanceExists('debug')) {
1933 // Init debug instance
1934 $debugInstance = NULL;
1938 // Get a debugger instance
1939 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1940 } catch (NullPointerException $e) {
1941 // Didn't work, no instance there
1942 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1945 // Empty string should be ignored and used for testing the middleware
1946 DebugMiddleware::getSelfInstance()->output('');
1948 // Set it in its own class. This will set it in the registry
1949 $debugInstance->setDebugInstance($debugInstance);
1951 // Get instance from registry
1952 $debugInstance = Registry::getRegistry()->getDebugInstance();
1956 return $debugInstance;
1960 * Simple output of a message with line-break
1962 * @param $message Message to output
1965 public function outputLine ($message) {
1967 print($message . PHP_EOL);
1971 * Outputs a debug message whether to debug instance (should be set!) or
1972 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1973 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1975 * @param $message Message we shall send out...
1976 * @param $doPrint Whether print or die here (default: print)
1977 * @paran $stripTags Whether to strip tags (default: FALSE)
1980 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1981 // Set debug instance to NULL
1982 $debugInstance = NULL;
1986 // Get debug instance
1987 $debugInstance = $this->getDebugInstance();
1988 } catch (NullPointerException $e) {
1989 // The debug instance is not set (yet)
1992 // Is the debug instance there?
1993 if (is_object($debugInstance)) {
1994 // Use debug output handler
1995 $debugInstance->output($message, $stripTags);
1997 if ($doPrint === FALSE) {
1998 // Die here if not printed
2002 // Are debug times enabled?
2003 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
2005 $message = $this->getPrintableExecutionTime() . $message;
2009 if ($doPrint === TRUE) {
2011 $this->outputLine($message);
2020 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2022 * @param $str The string, what ever it is needs to be converted
2023 * @return $className Generated class name
2025 public static final function convertToClassName ($str) {
2029 // Convert all dashes in underscores
2030 $str = self::convertDashesToUnderscores($str);
2032 // Now use that underscores to get classname parts for hungarian style
2033 foreach (explode('_', $str) as $strPart) {
2034 // Make the class name part lower case and first upper case
2035 $className .= ucfirst(strtolower($strPart));
2038 // Return class name
2043 * Converts dashes to underscores, e.g. useable for configuration entries
2045 * @param $str The string with maybe dashes inside
2046 * @return $str The converted string with no dashed, but underscores
2048 public static final function convertDashesToUnderscores ($str) {
2050 $str = str_replace('-', '_', $str);
2052 // Return converted string
2057 * Marks up the code by adding e.g. line numbers
2059 * @param $phpCode Unmarked PHP code
2060 * @return $markedCode Marked PHP code
2062 public function markupCode ($phpCode) {
2067 $errorArray = error_get_last();
2069 // Init the code with error message
2070 if (is_array($errorArray)) {
2072 $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>',
2073 basename($errorArray['file']),
2074 $errorArray['line'],
2075 $errorArray['message'],
2080 // Add line number to the code
2081 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2083 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2085 htmlentities($code, ENT_QUOTES)
2094 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2095 * beatiful for web-based front-ends. If null is given a message id
2096 * null_timestamp will be resolved and returned.
2098 * @param $timestamp Timestamp to prepare (filter) for display
2099 * @return $readable A readable timestamp
2101 public function doFilterFormatTimestamp ($timestamp) {
2102 // Default value to return
2105 // Is the timestamp null?
2106 if (is_null($timestamp)) {
2107 // Get a message string
2108 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2110 switch ($this->getLanguageInstance()->getLanguageCode()) {
2111 case 'de': // German format is a bit different to default
2112 // Split the GMT stamp up
2113 $dateTime = explode(' ', $timestamp );
2114 $dateArray = explode('-', $dateTime[0]);
2115 $timeArray = explode(':', $dateTime[1]);
2117 // Construct the timestamp
2118 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2128 default: // Default is pass-through
2129 $readable = $timestamp;
2139 * Filter a given number into a localized number
2141 * @param $value The raw value from e.g. database
2142 * @return $localized Localized value
2144 public function doFilterFormatNumber ($value) {
2145 // Generate it from config and localize dependencies
2146 switch ($this->getLanguageInstance()->getLanguageCode()) {
2147 case 'de': // German format is a bit different to default
2148 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2151 default: // US, etc.
2152 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2161 * "Getter" for databse entry
2163 * @return $entry An array with database entries
2164 * @throws NullPointerException If the database result is not found
2165 * @throws InvalidDatabaseResultException If the database result is invalid
2167 protected final function getDatabaseEntry () {
2168 // Is there an instance?
2169 if (!$this->getResultInstance() instanceof SearchableResult) {
2170 // Throw an exception here
2171 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2175 $this->getResultInstance()->rewind();
2177 // Do we have an entry?
2178 if ($this->getResultInstance()->valid() === FALSE) {
2179 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2180 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2184 $this->getResultInstance()->next();
2187 $entry = $this->getResultInstance()->current();
2194 * Getter for field name
2196 * @param $fieldName Field name which we shall get
2197 * @return $fieldValue Field value from the user
2198 * @throws NullPointerException If the result instance is null
2200 public final function getField ($fieldName) {
2201 // Default field value
2204 // Get result instance
2205 $resultInstance = $this->getResultInstance();
2207 // Is this instance null?
2208 if (is_null($resultInstance)) {
2209 // Then the user instance is no longer valid (expired cookies?)
2210 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2213 // Get current array
2214 $fieldArray = $resultInstance->current();
2215 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2217 // Convert dashes to underscore
2218 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2220 // Does the field exist?
2221 if ($this->isFieldSet($fieldName)) {
2223 $fieldValue = $fieldArray[$fieldName2];
2224 } elseif (defined('DEVELOPER')) {
2225 // Missing field entry, may require debugging
2226 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2228 // Missing field entry, may require debugging
2229 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2237 * Checks if given field is set
2239 * @param $fieldName Field name to check
2240 * @return $isSet Whether the given field name is set
2241 * @throws NullPointerException If the result instance is null
2243 public function isFieldSet ($fieldName) {
2244 // Get result instance
2245 $resultInstance = $this->getResultInstance();
2247 // Is this instance null?
2248 if (is_null($resultInstance)) {
2249 // Then the user instance is no longer valid (expired cookies?)
2250 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2253 // Get current array
2254 $fieldArray = $resultInstance->current();
2255 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2257 // Convert dashes to underscore
2258 $fieldName = self::convertDashesToUnderscores($fieldName);
2261 $isSet = isset($fieldArray[$fieldName]);
2268 * Flushs all pending updates to the database layer
2272 public function flushPendingUpdates () {
2273 // Get result instance
2274 $resultInstance = $this->getResultInstance();
2276 // Do we have data to update?
2277 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2278 // Get wrapper class name config entry
2279 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2281 // Create object instance
2282 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2284 // Yes, then send the whole result to the database layer
2285 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2290 * Outputs a deprecation warning to the developer.
2292 * @param $message The message we shall output to the developer
2294 * @todo Write a logging mechanism for productive mode
2296 public function deprecationWarning ($message) {
2297 // Is developer mode active?
2298 if (defined('DEVELOPER')) {
2299 // Debug instance is there?
2300 if (!is_null($this->getDebugInstance())) {
2301 // Output stub message
2302 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2305 trigger_error($message . "<br />\n");
2309 // @TODO Finish this part!
2310 $this->partialStub('Developer mode inactive. Message:' . $message);
2315 * Checks whether the given PHP extension is loaded
2317 * @param $phpExtension The PHP extension we shall check
2318 * @return $isLoaded Whether the PHP extension is loaded
2320 public final function isPhpExtensionLoaded ($phpExtension) {
2322 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2329 * "Getter" as a time() replacement but with milliseconds. You should use this
2330 * method instead of the encapsulated getimeofday() function.
2332 * @return $milliTime Timestamp with milliseconds
2334 public function getMilliTime () {
2335 // Get the time of day as float
2336 $milliTime = gettimeofday(TRUE);
2343 * Idles (sleeps) for given milliseconds
2345 * @return $hasSlept Whether it goes fine
2347 public function idle ($milliSeconds) {
2348 // Sleep is fine by default
2351 // Idle so long with found function
2352 if (function_exists('time_sleep_until')) {
2353 // Get current time and add idle time
2354 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2356 // New PHP 5.1.0 function found, ignore errors
2357 $hasSlept = @time_sleep_until($sleepUntil);
2360 * My Sun station doesn't have that function even with latest PHP
2363 usleep($milliSeconds * 1000);
2370 * Converts a hexadecimal string, even with negative sign as first string to
2371 * a decimal number using BC functions.
2373 * This work is based on comment #86673 on php.net documentation page at:
2374 * <http://de.php.net/manual/en/function.dechex.php#86673>
2376 * @param $hex Hexadecimal string
2377 * @return $dec Decimal number
2379 protected function hex2dec ($hex) {
2380 // Convert to all lower-case
2381 $hex = strtolower($hex);
2383 // Detect sign (negative/positive numbers)
2385 if (substr($hex, 0, 1) == '-') {
2387 $hex = substr($hex, 1);
2390 // Decode the hexadecimal string into a decimal number
2392 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2393 $factor = self::$hexdec[substr($hex, $i, 1)];
2394 $dec = bcadd($dec, bcmul($factor, $e));
2397 // Return the decimal number
2398 return $sign . $dec;
2402 * Converts even very large decimal numbers, also signed, to a hexadecimal
2405 * This work is based on comment #97756 on php.net documentation page at:
2406 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2408 * @param $dec Decimal number, even with negative sign
2409 * @param $maxLength Optional maximum length of the string
2410 * @return $hex Hexadecimal string
2412 protected function dec2hex ($dec, $maxLength = 0) {
2413 // maxLength can be zero or devideable by 2
2414 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2416 // Detect sign (negative/positive numbers)
2423 // Encode the decimal number into a hexadecimal string
2426 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2428 } while ($dec >= 1);
2431 * Leading zeros are required for hex-decimal "numbers". In some
2432 * situations more leading zeros are wanted, so check for both
2435 if ($maxLength > 0) {
2436 // Prepend more zeros
2437 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2438 } elseif ((strlen($hex) % 2) != 0) {
2439 // Only make string's length dividable by 2
2443 // Return the hexadecimal string
2444 return $sign . $hex;
2448 * Converts a ASCII string (0 to 255) into a decimal number.
2450 * @param $asc The ASCII string to be converted
2451 * @return $dec Decimal number
2453 protected function asc2dec ($asc) {
2454 // Convert it into a hexadecimal number
2455 $hex = bin2hex($asc);
2457 // And back into a decimal number
2458 $dec = $this->hex2dec($hex);
2465 * Converts a decimal number into an ASCII string.
2467 * @param $dec Decimal number
2468 * @return $asc An ASCII string
2470 protected function dec2asc ($dec) {
2471 // First convert the number into a hexadecimal string
2472 $hex = $this->dec2hex($dec);
2474 // Then convert it into the ASCII string
2475 $asc = $this->hex2asc($hex);
2482 * Converts a hexadecimal number into an ASCII string. Negative numbers
2485 * @param $hex Hexadecimal string
2486 * @return $asc An ASCII string
2488 protected function hex2asc ($hex) {
2489 // Check for length, it must be devideable by 2
2490 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2491 assert((strlen($hex) % 2) == 0);
2495 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2496 // Get the decimal number of the chunk
2497 $part = hexdec(substr($hex, $idx, 2));
2499 // Add it to the final string
2503 // Return the final string
2508 * Checks whether the given encoded data was encoded with Base64
2510 * @param $encodedData Encoded data we shall check
2511 * @return $isBase64 Whether the encoded data is Base64
2513 protected function isBase64Encoded ($encodedData) {
2515 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2522 * "Getter" to get response/request type from analysis of the system.
2524 * @return $responseType Analyzed response type
2526 protected static function getResponseTypeFromSystem () {
2527 // Default is console
2528 $responseType = 'console';
2530 // Is 'HTTP_HOST' set?
2531 if (isset($_SERVER['HTTP_HOST'])) {
2533 * Then it is a HTML response/request as RSS and so on may be
2534 * transfered over HTTP as well.
2536 $responseType = 'html';
2540 return $responseType;
2544 * Gets a cache key from Criteria instance
2546 * @param $criteriaInstance An instance of a Criteria class
2547 * @param $onlyKeys Only use these keys for a cache key
2548 * @return $cacheKey A cache key suitable for lookup/storage purposes
2550 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2552 $cacheKey = sprintf('%s@%s',
2553 $this->__toString(),
2554 $criteriaInstance->getCacheKey($onlyKeys)
2558 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2563 * Getter for startup time in miliseconds
2565 * @return $startupTime Startup time in miliseconds
2567 protected function getStartupTime () {
2568 return self::$startupTime;
2572 * "Getter" for a printable currently execution time in nice braces
2574 * @return $executionTime Current execution time in nice braces
2576 protected function getPrintableExecutionTime () {
2577 // Caculate the execution time
2578 $executionTime = microtime(TRUE) - $this->getStartupTime();
2580 // Pack it in nice braces
2581 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2584 return $executionTime;
2588 * Hashes a given string with a simple but stronger hash function (no salt)
2589 * and hex-encode it.
2591 * @param $str The string to be hashed
2592 * @return $hash The hash from string $str
2594 public static final function hash ($str) {
2595 // Hash given string with (better secure) hasher
2596 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2603 * "Getter" for length of hash() output. This will be "cached" to speed up
2606 * @return $length Length of hash() output
2608 public static final function getHashLength () {
2610 if (is_null(self::$hashLength)) {
2611 // No, then hash a string and save its length.
2612 self::$hashLength = strlen(self::hash('abc123'));
2616 return self::$hashLength;
2620 * Checks whether the given number is really a number (only chars 0-9).
2622 * @param $num A string consisting only chars between 0 and 9
2623 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2624 * @param $assertMismatch Whether to assert mismatches
2625 * @return $ret The (hopefully) secured numbered value
2627 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2628 // Filter all numbers out
2629 $ret = preg_replace('/[^0123456789]/', '', $num);
2632 if ($castValue === TRUE) {
2633 // Cast to biggest numeric type
2634 $ret = (double) $ret;
2637 // Assert only if requested
2638 if ($assertMismatch === TRUE) {
2639 // Has the whole value changed?
2640 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2648 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2650 * @param $num A string consisting only chars between 0 and 9
2651 * @param $assertMismatch Whether to assert mismatches
2652 * @return $ret The (hopefully) secured hext-numbered value
2654 public function hexval ($num, $assertMismatch = FALSE) {
2655 // Filter all numbers out
2656 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2658 // Assert only if requested
2659 if ($assertMismatch === TRUE) {
2660 // Has the whole value changed?
2661 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2669 * Checks whether start/end marker are set
2671 * @param $data Data to be checked
2672 * @return $isset Whether start/end marker are set
2674 public final function ifStartEndMarkersSet ($data) {
2676 $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));
2678 // ... and return it
2683 * Determines if an element is set in the generic array
2685 * @param $keyGroup Main group for the key
2686 * @param $subGroup Sub group for the key
2687 * @param $key Key to check
2688 * @param $element Element to check
2689 * @return $isset Whether the given key is set
2691 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2693 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2696 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2702 * Determines if a key is set in the generic array
2704 * @param $keyGroup Main group for the key
2705 * @param $subGroup Sub group for the key
2706 * @param $key Key to check
2707 * @return $isset Whether the given key is set
2709 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2711 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2714 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2722 * Determines if a group is set in the generic array
2724 * @param $keyGroup Main group
2725 * @param $subGroup Sub group
2726 * @return $isset Whether the given group is set
2728 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2730 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2733 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2740 * Getter for sub key group
2742 * @param $keyGroup Main key group
2743 * @param $subGroup Sub key group
2744 * @return $array An array with all array elements
2746 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2748 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2749 // No, then abort here
2750 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2755 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2758 return $this->genericArray[$keyGroup][$subGroup];
2762 * Unsets a given key in generic array
2764 * @param $keyGroup Main group for the key
2765 * @param $subGroup Sub group for the key
2766 * @param $key Key to unset
2769 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2771 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2774 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2778 * Unsets a given element in generic array
2780 * @param $keyGroup Main group for the key
2781 * @param $subGroup Sub group for the key
2782 * @param $key Key to unset
2783 * @param $element Element to unset
2786 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2788 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2791 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2795 * Append a string to a given generic array key
2797 * @param $keyGroup Main group for the key
2798 * @param $subGroup Sub group for the key
2799 * @param $key Key to unset
2800 * @param $value Value to add/append
2803 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2805 //* 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);
2807 // Is it already there?
2808 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2810 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2813 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2818 * Append a string to a given generic array element
2820 * @param $keyGroup Main group for the key
2821 * @param $subGroup Sub group for the key
2822 * @param $key Key to unset
2823 * @param $element Element to check
2824 * @param $value Value to add/append
2827 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2829 //* 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);
2831 // Is it already there?
2832 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2834 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2837 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2842 * Sets a string in a given generic array element
2844 * @param $keyGroup Main group for the key
2845 * @param $subGroup Sub group for the key
2846 * @param $key Key to unset
2847 * @param $element Element to check
2848 * @param $value Value to add/append
2851 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2853 //* 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);
2856 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2860 * Initializes given generic array group
2862 * @param $keyGroup Main group for the key
2863 * @param $subGroup Sub group for the key
2864 * @param $key Key to use
2865 * @param $forceInit Optionally force initialization
2868 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2870 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2872 // Is it already set?
2873 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2874 // Already initialized
2875 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2880 $this->genericArray[$keyGroup][$subGroup] = array();
2884 * Initializes given generic array key
2886 * @param $keyGroup Main group for the key
2887 * @param $subGroup Sub group for the key
2888 * @param $key Key to use
2889 * @param $forceInit Optionally force initialization
2892 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2894 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2896 // Is it already set?
2897 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2898 // Already initialized
2899 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2904 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2908 * Initializes given generic array element
2910 * @param $keyGroup Main group for the key
2911 * @param $subGroup Sub group for the key
2912 * @param $key Key to use
2913 * @param $element Element to use
2914 * @param $forceInit Optionally force initialization
2917 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2919 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2921 // Is it already set?
2922 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2923 // Already initialized
2924 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2929 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2933 * Pushes an element to a generic key
2935 * @param $keyGroup Main group for the key
2936 * @param $subGroup Sub group for the key
2937 * @param $key Key to use
2938 * @param $value Value to add/append
2939 * @return $count Number of array elements
2941 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2943 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2946 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2948 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2952 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2955 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2956 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2961 * Pushes an element to a generic array element
2963 * @param $keyGroup Main group for the key
2964 * @param $subGroup Sub group for the key
2965 * @param $key Key to use
2966 * @param $element Element to check
2967 * @param $value Value to add/append
2968 * @return $count Number of array elements
2970 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2972 //* 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));
2975 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2977 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2981 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2984 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2985 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2990 * Pops an element from a generic group
2992 * @param $keyGroup Main group for the key
2993 * @param $subGroup Sub group for the key
2994 * @param $key Key to unset
2995 * @return $value Last "popped" value
2997 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2999 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3002 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3004 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3009 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3012 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3013 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3018 * Shifts an element from a generic group
3020 * @param $keyGroup Main group for the key
3021 * @param $subGroup Sub group for the key
3022 * @param $key Key to unset
3023 * @return $value Last "popped" value
3025 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3027 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3030 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3032 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3037 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3040 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3041 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3046 * Count generic array group
3048 * @param $keyGroup Main group for the key
3049 * @return $count Count of given group
3051 protected final function countGenericArray ($keyGroup) {
3053 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3056 if (!isset($this->genericArray[$keyGroup])) {
3058 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3063 $count = count($this->genericArray[$keyGroup]);
3066 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3073 * Count generic array sub group
3075 * @param $keyGroup Main group for the key
3076 * @param $subGroup Sub group for the key
3077 * @return $count Count of given group
3079 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3081 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3084 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3086 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3091 $count = count($this->genericArray[$keyGroup][$subGroup]);
3094 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3101 * Count generic array elements
3103 * @param $keyGroup Main group for the key
3104 * @param $subGroup Sub group for the key
3105 * @para $key Key to count
3106 * @return $count Count of given key
3108 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3110 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3113 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3115 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3117 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3119 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3124 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3127 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3134 * Getter for whole generic group array
3136 * @param $keyGroup Key group to get
3137 * @return $array Whole generic array group
3139 protected final function getGenericArray ($keyGroup) {
3141 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3144 if (!isset($this->genericArray[$keyGroup])) {
3146 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3151 return $this->genericArray[$keyGroup];
3155 * Setter for generic array key
3157 * @param $keyGroup Key group to get
3158 * @param $subGroup Sub group for the key
3159 * @param $key Key to unset
3160 * @param $value Mixed value from generic array element
3163 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3165 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3168 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3172 * Getter for generic array key
3174 * @param $keyGroup Key group to get
3175 * @param $subGroup Sub group for the key
3176 * @param $key Key to unset
3177 * @return $value Mixed value from generic array element
3179 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3181 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3184 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3186 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3191 return $this->genericArray[$keyGroup][$subGroup][$key];
3195 * Sets a value in given generic array key/element
3197 * @param $keyGroup Main group for the key
3198 * @param $subGroup Sub group for the key
3199 * @param $key Key to set
3200 * @param $element Element to set
3201 * @param $value Value to set
3204 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3206 //* 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));
3209 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3213 * Getter for generic array element
3215 * @param $keyGroup Key group to get
3216 * @param $subGroup Sub group for the key
3217 * @param $key Key to look for
3218 * @param $element Element to look for
3219 * @return $value Mixed value from generic array element
3221 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3223 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3226 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3228 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3233 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3237 * Checks if a given sub group is valid (array)
3239 * @param $keyGroup Key group to get
3240 * @param $subGroup Sub group for the key
3241 * @return $isValid Whether given sub group is valid
3243 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3245 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3248 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3255 * Checks if a given key is valid (array)
3257 * @param $keyGroup Key group to get
3258 * @param $subGroup Sub group for the key
3259 * @param $key Key to check
3260 * @return $isValid Whether given sub group is valid
3262 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3264 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3267 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3274 * Initializes the web output instance
3278 protected function initWebOutputInstance () {
3279 // Get application instance
3280 $applicationInstance = Registry::getRegistry()->getInstance('app');
3282 // Is this a response instance?
3283 if ($this instanceof Responseable) {
3284 // Then set it in application instance
3285 $applicationInstance->setResponseInstance($this);
3288 // Init web output instance
3289 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3292 $this->setWebOutputInstance($outputInstance);
3296 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3298 * @param $boolean Boolean value
3299 * @return $translated Translated boolean value
3301 public static final function translateBooleanToYesNo ($boolean) {
3302 // Make sure it is really boolean
3303 assert(is_bool($boolean));
3306 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3308 // ... and return it
3313 * Encodes raw data (almost any type) by "serializing" it and then pack it
3314 * into a "binary format".
3316 * @param $rawData Raw data (almost any type)
3317 * @return $encoded Encoded data
3319 protected function encodeData ($rawData) {
3320 // Make sure no objects or resources pass through
3321 assert(!is_object($rawData));
3322 assert(!is_resource($rawData));
3324 // First "serialize" it (json_encode() is faster than serialize())
3325 $encoded = $this->packString(json_encode($rawData));
3332 * Pack a string into a "binary format". Please execuse me that this is
3333 * widely undocumented. :-(
3335 * @param $str Unpacked string
3336 * @return $packed Packed string
3337 * @todo Improve documentation
3339 protected function packString ($str) {
3341 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3343 // First compress the string (gzcompress is okay)
3344 $str = gzcompress($str);
3349 // And start the "encoding" loop
3350 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3352 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3353 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3355 if (($idx + $i) <= strlen($str)) {
3356 $ord = ord(substr($str, ($idx + $i), 1));
3358 $add = $ord * pow(256, $factor);
3362 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3366 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3367 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3369 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3370 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3376 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3381 * Checks whether the given file/path is in open_basedir(). This does not
3382 * gurantee that the file is actually readable and/or writeable. If you need
3383 * such gurantee then please use isReadableFile() instead.
3385 * @param $filePathName Name of the file/path to be checked
3386 * @return $isReachable Whether it is within open_basedir()
3388 protected static function isReachableFilePath ($filePathName) {
3389 // Is not reachable by default
3390 $isReachable = FALSE;
3392 // Get open_basedir parameter
3393 $openBaseDir = ini_get('open_basedir');
3396 if (!empty($openBaseDir)) {
3397 // Check all entries
3398 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3399 // Check on existence
3400 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3402 $isReachable = TRUE;
3406 // If open_basedir is not set, all is allowed
3407 $isReachable = TRUE;
3411 return $isReachable;
3415 * Checks whether the give file is within open_basedir() (done by
3416 * isReachableFilePath()), is actually a file and is readable.
3418 * @param $fileName Name of the file to be checked
3419 * @return $isReadable Whether the file is readable (and therefor exists)
3421 public static function isReadableFile ($fileName) {
3422 // Default is not readable
3423 $isReadable = FALSE;
3425 // Is within parameters, so check if it is a file and readable
3426 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3433 * Creates a full-qualified file name (FQFN) for given file name by adding
3434 * a configured temporary file path to it.
3436 * @param $fileName Name for temporary file
3437 * @return $fqfn Full-qualified file name
3438 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3439 * @throws FileIoException If the file cannot be written
3441 protected static function createTempPathForFile ($fileName) {
3443 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3445 // Is the path writeable?
3446 if (!is_writable($basePath)) {
3447 // Path is write-protected
3448 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3452 $fqfn = $basePath . '/' . $fileName;
3455 if (!self::isReachableFilePath($fqfn)) {
3457 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3465 * "Getter" for a printable state name
3467 * @return $stateName Name of the node's state in a printable format
3469 public final function getPrintableState () {
3470 // Default is 'null'
3471 $stateName = 'null';
3473 // Get the state instance
3474 $stateInstance = $this->getStateInstance();
3476 // Is it an instance of Stateable?
3477 if ($stateInstance instanceof Stateable) {
3478 // Then use that state name
3479 $stateName = $stateInstance->getStateName();
3487 * Handles socket error for given socket resource and peer data. This method
3488 * validates $socketResource if it is a valid resource (see is_resource())
3489 * but assumes valid data in array $recipientData, except that
3490 * count($recipientData) is always 2.
3492 * @param $method Value of __METHOD__ from calling method
3493 * @param $line Value of __LINE__ from calling method
3494 * @param $socketResource A valid socket resource
3495 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3497 * @throws InvalidSocketException If $socketResource is no socket resource
3498 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3499 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3501 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3502 // This method handles only socket resources
3503 if (!is_resource($socketResource)) {
3504 // No resource, abort here
3505 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3508 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3509 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3510 assert(isset($socketData[0]));
3511 assert(isset($socketData[1]));
3513 // Get error code for first validation (0 is not an error)
3514 $errorCode = socket_last_error($socketResource);
3516 // If the error code is zero, someone called this method without an error
3517 if ($errorCode == 0) {
3518 // No error detected (or previously cleared outside this method)
3519 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3522 // Get handler (method) name
3523 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3525 // Call-back the error handler method
3526 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3528 // Finally clear the error because it has been handled
3529 socket_clear_error($socketResource);