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\FrameworkDirectory;
16 use CoreFramework\Generic\FrameworkInterface;
17 use CoreFramework\Generic\NullPointerException;
18 use CoreFramework\Handler\Stream\IoHandler;
19 use CoreFramework\Loader\ClassLoader;
20 use CoreFramework\Manager\ManageableApplication;
21 use CoreFramework\Middleware\Compressor\CompressorChannel;
22 use CoreFramework\Middleware\Debug\DebugMiddleware;
23 use CoreFramework\Registry\Register;
24 use CoreFramework\Registry\Registry;
25 use CoreFramework\Request\Requestable;
26 use CoreFramework\Resolver\Resolver;
27 use CoreFramework\Result\Database\CachedDatabaseResult;
28 use CoreFramework\Result\Search\SearchableResult;
29 use CoreFramework\Response\Responseable;
30 use CoreFramework\Stream\Output\OutputStreamer;
31 use CoreFramework\Template\CompileableTemplate;
32 use CoreFramework\Wrapper\Database\DatabaseWrapper;
38 * The simulator system class is the super class of all other classes. This
39 * class handles saving of games etc.
41 * @author Roland Haeder <webmaster@shipsimu.org>
43 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
44 * @license GNU GPL 3.0 or any newer version
45 * @link http://www.shipsimu.org
47 * This program is free software: you can redistribute it and/or modify
48 * it under the terms of the GNU General Public License as published by
49 * the Free Software Foundation, either version 3 of the License, or
50 * (at your option) any later version.
52 * This program is distributed in the hope that it will be useful,
53 * but WITHOUT ANY WARRANTY; without even the implied warranty of
54 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
55 * GNU General Public License for more details.
57 * You should have received a copy of the GNU General Public License
58 * along with this program. If not, see <http://www.gnu.org/licenses/>.
60 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
62 * Length of output from hash()
64 private static $hashLength = NULL;
69 private $realClass = 'BaseFrameworkSystem';
72 * Instance of a Requestable class
74 private $requestInstance = NULL;
77 * Instance of a Responseable class
79 private $responseInstance = NULL;
82 * Search criteria instance
84 private $searchInstance = NULL;
87 * Update criteria instance
89 private $updateInstance = NULL;
92 * The file I/O instance for the template loader
94 private $fileIoInstance = NULL;
99 private $resolverInstance = NULL;
102 * Template engine instance
104 private $templateInstance = NULL;
107 * Database result instance
109 private $resultInstance = NULL;
112 * Instance for user class
114 private $userInstance = NULL;
117 * A controller instance
119 private $controllerInstance = NULL;
124 private $rngInstance = NULL;
127 * Instance of a crypto helper
129 private $cryptoInstance = NULL;
132 * Instance of an Iterator class
134 private $iteratorInstance = NULL;
137 * Instance of the list
139 private $listInstance = NULL;
144 private $menuInstance = NULL;
147 * Instance of the image
149 private $imageInstance = NULL;
152 * Instance of the stacker
154 private $stackInstance = NULL;
157 * A Compressor instance
159 private $compressorInstance = NULL;
162 * A Parseable instance
164 private $parserInstance = NULL;
167 * A HandleableProtocol instance
169 private $protocolInstance = NULL;
172 * A database wrapper instance
174 private $databaseInstance = NULL;
177 * A helper instance for the form
179 private $helperInstance = NULL;
182 * An instance of a Source class
184 private $sourceInstance = NULL;
187 * An instance of a UrlSource class
189 private $urlSourceInstance = NULL;
192 * An instance of a InputStream class
194 private $inputStreamInstance = NULL;
197 * An instance of a OutputStream class
199 private $outputStreamInstance = NULL;
202 * Networkable handler instance
204 private $handlerInstance = NULL;
207 * Visitor handler instance
209 private $visitorInstance = NULL;
214 private $dhtInstance = NULL;
217 * An instance of a database wrapper class
219 private $wrapperInstance = NULL;
222 * An instance of a file I/O pointer class (not handler)
224 private $pointerInstance = NULL;
227 * An instance of an Indexable class
229 private $indexInstance = NULL;
232 * An instance of a Block class
234 private $blockInstance = NULL;
239 private $minableInstance = NULL;
242 * A FrameworkDirectory instance
244 private $directoryInstance = NULL;
249 private $listenerInstance = NULL;
252 * An instance of a communicator
254 private $communicatorInstance = NULL;
257 * The concrete output instance
259 private $outputInstance = NULL;
264 private $stateInstance = NULL;
267 * Thousands separator
269 private $thousands = '.'; // German
274 private $decimals = ','; // German
279 private $socketResource = FALSE;
282 * Regular expression to use for validation
284 private $regularExpression = '';
289 private $packageData = array();
294 private $genericArray = array();
299 private $commandName = '';
304 private $controllerName = '';
307 * Name of used protocol
309 private $protocolName = 'invalid';
312 * Array with bitmasks and such for pack/unpack methods to support both
313 * 32-bit and 64-bit systems
315 private $packingData = array(
318 'left' => 0xffff0000,
319 'right' => 0x0000ffff,
325 'left' => 0xffffffff00000000,
326 'right' => 0x00000000ffffffff,
333 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
335 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
337 private $archArrayElement = FALSE;
339 /***********************
340 * Exception codes.... *
341 ***********************/
343 // @todo Try to clean these constants up
344 const EXCEPTION_IS_NULL_POINTER = 0x001;
345 const EXCEPTION_IS_NO_OBJECT = 0x002;
346 const EXCEPTION_IS_NO_ARRAY = 0x003;
347 const EXCEPTION_MISSING_METHOD = 0x004;
348 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
349 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
350 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
351 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
352 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
353 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
354 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
355 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
356 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
357 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
358 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
359 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
360 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
361 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
362 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
363 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
364 const EXCEPTION_PATH_NOT_FOUND = 0x015;
365 const EXCEPTION_INVALID_PATH_NAME = 0x016;
366 const EXCEPTION_READ_PROTECED_PATH = 0x017;
367 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
368 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
369 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
370 const EXCEPTION_INVALID_RESOURCE = 0x01b;
371 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
372 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
373 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
374 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
375 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
376 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
377 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
378 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
379 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
380 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
381 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
382 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
383 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
384 const EXCEPTION_INVALID_STRING = 0x029;
385 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
386 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
387 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
388 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
389 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
390 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
391 const EXCEPTION_MISSING_ELEMENT = 0x030;
392 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
393 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
394 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
395 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
396 const EXCEPTION_FATAL_ERROR = 0x035;
397 const EXCEPTION_FILE_NOT_FOUND = 0x036;
398 const EXCEPTION_ASSERTION_FAILED = 0x037;
399 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
400 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
401 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
402 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
403 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
404 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
407 * Hexadecimal->Decimal translation array
409 private static $hexdec = array(
429 * Decimal->hexadecimal translation array
431 private static $dechex = array(
451 * Startup time in miliseconds
453 private static $startupTime = 0;
456 * Protected super constructor
458 * @param $className Name of the class
461 protected function __construct ($className) {
463 $this->setRealClass($className);
465 // Set configuration instance if no registry ...
466 if (!$this instanceof Register) {
467 // ... because registries doesn't need to be configured
468 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
471 // Is the startup time set? (0 cannot be TRUE anymore)
472 if (self::$startupTime == 0) {
474 self::$startupTime = microtime(TRUE);
478 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
482 * Destructor for all classes. You should not call this method on your own.
486 public function __destruct () {
487 // Flush any updated entries to the database
488 $this->flushPendingUpdates();
490 // Is this object already destroyed?
491 if ($this->__toString() != 'DestructedObject') {
492 // Destroy all informations about this class but keep some text about it alive
493 $this->setRealClass('DestructedObject');
494 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
495 // Already destructed object
496 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
501 // Do not call this twice
502 trigger_error(__METHOD__ . ': Called twice.');
508 * The __call() method where all non-implemented methods end up
510 * @param $methodName Name of the missing method
511 * @args $args Arguments passed to the method
514 public final function __call ($methodName, $args) {
515 return self::__callStatic($methodName, $args);
519 * The __callStatic() method where all non-implemented static methods end up
521 * @param $methodName Name of the missing method
522 * @args $args Arguments passed to the method
525 public static final function __callStatic ($methodName, $args) {
527 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
529 // Init argument string
532 // Is it NULL, empty or an array?
533 if (is_null($args)) {
535 $argsString = 'NULL';
536 } elseif (is_array($args)) {
540 // Some arguments are there
541 foreach ($args as $arg) {
542 // Add data about the argument
543 $argsString .= gettype($arg) . ':';
546 // Found a NULL argument
547 $argsString .= 'NULL';
548 } elseif (is_string($arg)) {
549 // Add length for strings
550 $argsString .= strlen($arg);
551 } elseif ((is_int($arg)) || (is_float($arg))) {
554 } elseif (is_array($arg)) {
555 // .. or size if array
556 $argsString .= count($arg);
557 } elseif (is_object($arg)) {
559 $reflection = new ReflectionClass($arg);
561 // Is an other object, maybe no __toString() available
562 $argsString .= $reflection->getName();
563 } elseif ($arg === TRUE) {
564 // ... is boolean 'TRUE'
565 $argsString .= 'TRUE';
566 } elseif ($arg === FALSE) {
567 // ... is boolean 'FALSE'
568 $argsString .= 'FALSE';
571 // Comma for next one
576 if (substr($argsString, -2, 1) == ',') {
577 $argsString = substr($argsString, 0, -2);
583 // Invalid arguments!
584 $argsString = '!INVALID:' . gettype($args) . '!';
587 // Output stub message
588 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
589 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
599 * Getter for $realClass
601 * @return $realClass The name of the real class (not BaseFrameworkSystem)
603 public function __toString () {
604 return $this->realClass;
608 * Magic method to catch setting of missing but set class fields/attributes
610 * @param $name Name of the field/attribute
611 * @param $value Value to store
614 public final function __set ($name, $value) {
615 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
618 print_r($value, TRUE)
623 * Magic method to catch getting of missing fields/attributes
625 * @param $name Name of the field/attribute
628 public final function __get ($name) {
629 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
635 * Magic method to catch unsetting of missing fields/attributes
637 * @param $name Name of the field/attribute
640 public final function __unset ($name) {
641 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
647 * Magic method to catch object serialization
649 * @return $unsupported Unsupported method
650 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
652 public final function __sleep () {
653 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
657 * Magic method to catch object deserialization
659 * @return $unsupported Unsupported method
660 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
662 public final function __wakeup () {
663 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
667 * Magic method to catch calls when an object instance is called
669 * @return $unsupported Unsupported method
670 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
672 public final function __invoke () {
673 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
677 * Setter for the real class name
679 * @param $realClass Class name (string)
682 public final function setRealClass ($realClass) {
684 $this->realClass = (string) $realClass;
688 * Setter for database result instance
690 * @param $resultInstance An instance of a database result class
692 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
694 protected final function setResultInstance (SearchableResult $resultInstance) {
695 $this->resultInstance = $resultInstance;
699 * Getter for database result instance
701 * @return $resultInstance An instance of a database result class
703 public final function getResultInstance () {
704 return $this->resultInstance;
708 * Setter for template engine instances
710 * @param $templateInstance An instance of a template engine class
713 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
714 $this->templateInstance = $templateInstance;
718 * Getter for template engine instances
720 * @return $templateInstance An instance of a template engine class
722 protected final function getTemplateInstance () {
723 return $this->templateInstance;
727 * Setter for search instance
729 * @param $searchInstance Searchable criteria instance
732 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
733 $this->searchInstance = $searchInstance;
737 * Getter for search instance
739 * @return $searchInstance Searchable criteria instance
741 public final function getSearchInstance () {
742 return $this->searchInstance;
746 * Setter for update instance
748 * @param $updateInstance An instance of a LocalUpdateCriteria clase
751 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
752 $this->updateInstance = $updateInstance;
756 * Getter for update instance
758 * @return $updateInstance Updateable criteria instance
760 public final function getUpdateInstance () {
761 return $this->updateInstance;
765 * Setter for resolver instance
767 * @param $resolverInstance Instance of a command resolver class
770 public final function setResolverInstance (Resolver $resolverInstance) {
771 $this->resolverInstance = $resolverInstance;
775 * Getter for resolver instance
777 * @return $resolverInstance Instance of a command resolver class
779 public final function getResolverInstance () {
780 return $this->resolverInstance;
784 * Setter for language instance
786 * @param $configInstance The configuration instance which shall
787 * be FrameworkConfiguration
790 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
791 Registry::getRegistry()->addInstance('config', $configInstance);
795 * Getter for configuration instance
797 * @return $configInstance Configuration instance
799 public final function getConfigInstance () {
800 $configInstance = Registry::getRegistry()->getInstance('config');
801 return $configInstance;
805 * Setter for debug instance
807 * @param $debugInstance The instance for debug output class
810 public final function setDebugInstance (DebugMiddleware $debugInstance) {
811 Registry::getRegistry()->addInstance('debug', $debugInstance);
815 * Getter for debug instance
817 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
819 public final function getDebugInstance () {
820 // Get debug instance
821 $debugInstance = Registry::getRegistry()->getInstance('debug');
824 return $debugInstance;
828 * Setter for web output instance
830 * @param $webInstance The instance for web output class
833 public final function setWebOutputInstance (OutputStreamer $webInstance) {
834 Registry::getRegistry()->addInstance('web_output', $webInstance);
838 * Getter for web output instance
840 * @return $webOutputInstance - Instance to class WebOutput
842 public final function getWebOutputInstance () {
843 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
844 return $webOutputInstance;
848 * Setter for database instance
850 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
853 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
854 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
858 * Getter for database layer
860 * @return $databaseInstance The database layer instance
862 public final function getDatabaseInstance () {
864 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
867 return $databaseInstance;
871 * Setter for compressor channel
873 * @param $compressorInstance An instance of CompressorChannel
876 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
877 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
881 * Getter for compressor channel
883 * @return $compressorInstance The compressor channel
885 public final function getCompressorChannel () {
886 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
887 return $compressorInstance;
891 * Protected getter for a manageable application helper class
893 * @return $applicationInstance An instance of a manageable application helper class
895 protected final function getApplicationInstance () {
896 $applicationInstance = Registry::getRegistry()->getInstance('application');
897 return $applicationInstance;
901 * Setter for a manageable application helper class
903 * @param $applicationInstance An instance of a manageable application helper class
906 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
907 Registry::getRegistry()->addInstance('application', $applicationInstance);
911 * Setter for request instance
913 * @param $requestInstance An instance of a Requestable class
916 public final function setRequestInstance (Requestable $requestInstance) {
917 $this->requestInstance = $requestInstance;
921 * Getter for request instance
923 * @return $requestInstance An instance of a Requestable class
925 public final function getRequestInstance () {
926 return $this->requestInstance;
930 * Setter for response instance
932 * @param $responseInstance An instance of a Responseable class
935 public final function setResponseInstance (Responseable $responseInstance) {
936 $this->responseInstance = $responseInstance;
940 * Getter for response instance
942 * @return $responseInstance An instance of a Responseable class
944 public final function getResponseInstance () {
945 return $this->responseInstance;
949 * Private getter for language instance
951 * @return $langInstance An instance to the language sub-system
953 protected final function getLanguageInstance () {
954 $langInstance = Registry::getRegistry()->getInstance('language');
955 return $langInstance;
959 * Setter for language instance
961 * @param $langInstance An instance to the language sub-system
963 * @see LanguageSystem
965 public final function setLanguageInstance (ManageableLanguage $langInstance) {
966 Registry::getRegistry()->addInstance('language', $langInstance);
970 * Private getter for file IO instance
972 * @return $fileIoInstance An instance to the file I/O sub-system
974 protected final function getFileIoInstance () {
975 return $this->fileIoInstance;
979 * Setter for file I/O instance
981 * @param $fileIoInstance An instance to the file I/O sub-system
984 public final function setFileIoInstance (IoHandler $fileIoInstance) {
985 $this->fileIoInstance = $fileIoInstance;
989 * Protected setter for user instance
991 * @param $userInstance An instance of a user class
994 protected final function setUserInstance (ManageableAccount $userInstance) {
995 $this->userInstance = $userInstance;
999 * Getter for user instance
1001 * @return $userInstance An instance of a user class
1003 public final function getUserInstance () {
1004 return $this->userInstance;
1008 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1010 * @param $controllerInstance An instance of the controller
1013 public final function setControllerInstance (Controller $controllerInstance) {
1014 $this->controllerInstance = $controllerInstance;
1018 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1020 * @return $controllerInstance An instance of the controller
1022 public final function getControllerInstance () {
1023 return $this->controllerInstance;
1027 * Setter for RNG instance
1029 * @param $rngInstance An instance of a random number generator (RNG)
1032 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1033 $this->rngInstance = $rngInstance;
1037 * Getter for RNG instance
1039 * @return $rngInstance An instance of a random number generator (RNG)
1041 public final function getRngInstance () {
1042 return $this->rngInstance;
1046 * Setter for Cryptable instance
1048 * @param $cryptoInstance An instance of a Cryptable class
1051 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1052 $this->cryptoInstance = $cryptoInstance;
1056 * Getter for Cryptable instance
1058 * @return $cryptoInstance An instance of a Cryptable class
1060 public final function getCryptoInstance () {
1061 return $this->cryptoInstance;
1065 * Setter for the list instance
1067 * @param $listInstance A list of Listable
1070 protected final function setListInstance (Listable $listInstance) {
1071 $this->listInstance = $listInstance;
1075 * Getter for the list instance
1077 * @return $listInstance A list of Listable
1079 protected final function getListInstance () {
1080 return $this->listInstance;
1084 * Setter for the menu instance
1086 * @param $menuInstance A RenderableMenu instance
1089 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1090 $this->menuInstance = $menuInstance;
1094 * Getter for the menu instance
1096 * @return $menuInstance A RenderableMenu instance
1098 protected final function getMenuInstance () {
1099 return $this->menuInstance;
1103 * Setter for image instance
1105 * @param $imageInstance An instance of an image
1108 public final function setImageInstance (BaseImage $imageInstance) {
1109 $this->imageInstance = $imageInstance;
1113 * Getter for image instance
1115 * @return $imageInstance An instance of an image
1117 public final function getImageInstance () {
1118 return $this->imageInstance;
1122 * Setter for stacker instance
1124 * @param $stackInstance An instance of an stacker
1127 public final function setStackInstance (Stackable $stackInstance) {
1128 $this->stackInstance = $stackInstance;
1132 * Getter for stacker instance
1134 * @return $stackInstance An instance of an stacker
1136 public final function getStackInstance () {
1137 return $this->stackInstance;
1141 * Setter for compressor instance
1143 * @param $compressorInstance An instance of an compressor
1146 public final function setCompressorInstance (Compressor $compressorInstance) {
1147 $this->compressorInstance = $compressorInstance;
1151 * Getter for compressor instance
1153 * @return $compressorInstance An instance of an compressor
1155 public final function getCompressorInstance () {
1156 return $this->compressorInstance;
1160 * Setter for Parseable instance
1162 * @param $parserInstance An instance of an Parseable
1165 public final function setParserInstance (Parseable $parserInstance) {
1166 $this->parserInstance = $parserInstance;
1170 * Getter for Parseable instance
1172 * @return $parserInstance An instance of an Parseable
1174 public final function getParserInstance () {
1175 return $this->parserInstance;
1179 * Setter for HandleableProtocol instance
1181 * @param $protocolInstance An instance of an HandleableProtocol
1184 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1185 $this->protocolInstance = $protocolInstance;
1189 * Getter for HandleableProtocol instance
1191 * @return $protocolInstance An instance of an HandleableProtocol
1193 public final function getProtocolInstance () {
1194 return $this->protocolInstance;
1198 * Setter for DatabaseWrapper instance
1200 * @param $wrapperInstance An instance of an DatabaseWrapper
1203 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1204 $this->wrapperInstance = $wrapperInstance;
1208 * Getter for DatabaseWrapper instance
1210 * @return $wrapperInstance An instance of an DatabaseWrapper
1212 public final function getWrapperInstance () {
1213 return $this->wrapperInstance;
1217 * Setter for socket resource
1219 * @param $socketResource A valid socket resource
1222 public final function setSocketResource ($socketResource) {
1223 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1224 $this->socketResource = $socketResource;
1228 * Getter for socket resource
1230 * @return $socketResource A valid socket resource
1232 public final function getSocketResource () {
1233 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1234 return $this->socketResource;
1238 * Setter for regular expression
1240 * @param $regularExpression A valid regular expression
1243 public final function setRegularExpression ($regularExpression) {
1244 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1245 $this->regularExpression = $regularExpression;
1249 * Getter for regular expression
1251 * @return $regularExpression A valid regular expression
1253 public final function getRegularExpression () {
1254 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1255 return $this->regularExpression;
1259 * Setter for helper instance
1261 * @param $helperInstance An instance of a helper class
1264 protected final function setHelperInstance (Helper $helperInstance) {
1265 $this->helperInstance = $helperInstance;
1269 * Getter for helper instance
1271 * @return $helperInstance An instance of a helper class
1273 public final function getHelperInstance () {
1274 return $this->helperInstance;
1278 * Setter for a Source instance
1280 * @param $sourceInstance An instance of a Source class
1283 protected final function setSourceInstance (Source $sourceInstance) {
1284 $this->sourceInstance = $sourceInstance;
1288 * Getter for a Source instance
1290 * @return $sourceInstance An instance of a Source class
1292 protected final function getSourceInstance () {
1293 return $this->sourceInstance;
1297 * Setter for a UrlSource instance
1299 * @param $sourceInstance An instance of a UrlSource class
1302 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1303 $this->urlSourceInstance = $urlSourceInstance;
1307 * Getter for a UrlSource instance
1309 * @return $urlSourceInstance An instance of a UrlSource class
1311 protected final function getUrlSourceInstance () {
1312 return $this->urlSourceInstance;
1316 * Getter for a InputStream instance
1318 * @param $inputStreamInstance The InputStream instance
1320 protected final function getInputStreamInstance () {
1321 return $this->inputStreamInstance;
1325 * Setter for a InputStream instance
1327 * @param $inputStreamInstance The InputStream instance
1330 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1331 $this->inputStreamInstance = $inputStreamInstance;
1335 * Getter for a OutputStream instance
1337 * @param $outputStreamInstance The OutputStream instance
1339 protected final function getOutputStreamInstance () {
1340 return $this->outputStreamInstance;
1344 * Setter for a OutputStream instance
1346 * @param $outputStreamInstance The OutputStream instance
1349 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1350 $this->outputStreamInstance = $outputStreamInstance;
1354 * Setter for handler instance
1356 * @param $handlerInstance An instance of a Handleable class
1359 protected final function setHandlerInstance (Handleable $handlerInstance) {
1360 $this->handlerInstance = $handlerInstance;
1364 * Getter for handler instance
1366 * @return $handlerInstance A Networkable instance
1368 protected final function getHandlerInstance () {
1369 return $this->handlerInstance;
1373 * Setter for visitor instance
1375 * @param $visitorInstance A Visitor instance
1378 protected final function setVisitorInstance (Visitor $visitorInstance) {
1379 $this->visitorInstance = $visitorInstance;
1383 * Getter for visitor instance
1385 * @return $visitorInstance A Visitor instance
1387 protected final function getVisitorInstance () {
1388 return $this->visitorInstance;
1392 * Setter for DHT instance
1394 * @param $dhtInstance A Distributable instance
1397 protected final function setDhtInstance (Distributable $dhtInstance) {
1398 $this->dhtInstance = $dhtInstance;
1402 * Getter for DHT instance
1404 * @return $dhtInstance A Distributable instance
1406 protected final function getDhtInstance () {
1407 return $this->dhtInstance;
1411 * Setter for raw package Data
1413 * @param $packageData Raw package Data
1416 public final function setPackageData (array $packageData) {
1417 $this->packageData = $packageData;
1421 * Getter for raw package Data
1423 * @return $packageData Raw package Data
1425 public function getPackageData () {
1426 return $this->packageData;
1431 * Setter for Iterator instance
1433 * @param $iteratorInstance An instance of an Iterator
1436 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1437 $this->iteratorInstance = $iteratorInstance;
1441 * Getter for Iterator instance
1443 * @return $iteratorInstance An instance of an Iterator
1445 public final function getIteratorInstance () {
1446 return $this->iteratorInstance;
1450 * Setter for FilePointer instance
1452 * @param $pointerInstance An instance of an FilePointer class
1455 protected final function setPointerInstance (FilePointer $pointerInstance) {
1456 $this->pointerInstance = $pointerInstance;
1460 * Getter for FilePointer instance
1462 * @return $pointerInstance An instance of an FilePointer class
1464 public final function getPointerInstance () {
1465 return $this->pointerInstance;
1469 * Unsets pointer instance which triggers a call of __destruct() if the
1470 * instance is still there. This is surely not fatal on already "closed"
1471 * file pointer instances.
1473 * I don't want to mess around with above setter by giving it a default
1474 * value NULL as setter should always explicitly only set (existing) object
1475 * instances and NULL is NULL.
1479 protected final function unsetPointerInstance () {
1480 // Simply it to NULL
1481 $this->pointerInstance = NULL;
1485 * Setter for Indexable instance
1487 * @param $indexInstance An instance of an Indexable class
1490 protected final function setIndexInstance (Indexable $indexInstance) {
1491 $this->indexInstance = $indexInstance;
1495 * Getter for Indexable instance
1497 * @return $indexInstance An instance of an Indexable class
1499 public final function getIndexInstance () {
1500 return $this->indexInstance;
1504 * Setter for Block instance
1506 * @param $blockInstance An instance of an Block class
1509 protected final function setBlockInstance (Block $blockInstance) {
1510 $this->blockInstance = $blockInstance;
1514 * Getter for Block instance
1516 * @return $blockInstance An instance of an Block class
1518 public final function getBlockInstance () {
1519 return $this->blockInstance;
1523 * Setter for Minable instance
1525 * @param $minableInstance A Minable instance
1528 protected final function setMinableInstance (Minable $minableInstance) {
1529 $this->minableInstance = $minableInstance;
1533 * Getter for minable instance
1535 * @return $minableInstance A Minable instance
1537 protected final function getMinableInstance () {
1538 return $this->minableInstance;
1542 * Setter for FrameworkDirectory instance
1544 * @param $directoryInstance A FrameworkDirectory instance
1547 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1548 $this->directoryInstance = $directoryInstance;
1552 * Getter for FrameworkDirectory instance
1554 * @return $directoryInstance A FrameworkDirectory instance
1556 protected final function getDirectoryInstance () {
1557 return $this->directoryInstance;
1561 * Setter for listener instance
1563 * @param $listenerInstance A Listenable instance
1566 protected final function setListenerInstance (Listenable $listenerInstance) {
1567 $this->listenerInstance = $listenerInstance;
1571 * Getter for listener instance
1573 * @return $listenerInstance A Listenable instance
1575 protected final function getListenerInstance () {
1576 return $this->listenerInstance;
1580 * Getter for communicator instance
1582 * @return $communicatorInstance An instance of a Communicator class
1584 public final function getCommunicatorInstance () {
1585 return $this->communicatorInstance;
1589 * Setter for communicator instance
1591 * @param $communicatorInstance An instance of a Communicator class
1594 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1595 $this->communicatorInstance = $communicatorInstance;
1599 * Setter for state instance
1601 * @param $stateInstance A Stateable instance
1604 public final function setStateInstance (Stateable $stateInstance) {
1605 $this->stateInstance = $stateInstance;
1609 * Getter for state instance
1611 * @return $stateInstance A Stateable instance
1613 public final function getStateInstance () {
1614 return $this->stateInstance;
1618 * Setter for output instance
1620 * @param $outputInstance The debug output instance
1623 public final function setOutputInstance (OutputStreamer $outputInstance) {
1624 $this->outputInstance = $outputInstance;
1628 * Getter for output instance
1630 * @return $outputInstance The debug output instance
1632 public final function getOutputInstance () {
1633 return $this->outputInstance;
1637 * Setter for command name
1639 * @param $commandName Last validated command name
1642 protected final function setCommandName ($commandName) {
1643 $this->commandName = $commandName;
1647 * Getter for command name
1649 * @return $commandName Last validated command name
1651 protected final function getCommandName () {
1652 return $this->commandName;
1656 * Setter for controller name
1658 * @param $controllerName Last validated controller name
1661 protected final function setControllerName ($controllerName) {
1662 $this->controllerName = $controllerName;
1666 * Getter for controller name
1668 * @return $controllerName Last validated controller name
1670 protected final function getControllerName () {
1671 return $this->controllerName;
1675 * Getter for protocol name
1677 * @return $protocolName Name of used protocol
1679 public final function getProtocolName () {
1680 return $this->protocolName;
1684 * Setter for protocol name
1686 * @param $protocolName Name of used protocol
1689 protected final function setProtocolName ($protocolName) {
1690 $this->protocolName = $protocolName;
1694 * Checks whether an object equals this object. You should overwrite this
1695 * method to implement own equality checks
1697 * @param $objectInstance An instance of a FrameworkInterface object
1698 * @return $equals Whether both objects equals
1700 public function equals (FrameworkInterface $objectInstance) {
1703 $this->__toString() == $objectInstance->__toString()
1705 $this->hashCode() == $objectInstance->hashCode()
1708 // Return the result
1713 * Generates a generic hash code of this class. You should really overwrite
1714 * this method with your own hash code generator code. But keep KISS in mind.
1716 * @return $hashCode A generic hash code respresenting this whole class
1718 public function hashCode () {
1720 return crc32($this->__toString());
1724 * Formats computer generated price values into human-understandable formats
1725 * with thousand and decimal separators.
1727 * @param $value The in computer format value for a price
1728 * @param $currency The currency symbol (use HTML-valid characters!)
1729 * @param $decNum Number of decimals after commata
1730 * @return $price The for the current language formated price string
1731 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1732 * thousands separator
1735 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1736 // Are all required attriutes set?
1737 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1738 // Throw an exception
1739 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1743 $value = (float) $value;
1745 // Reformat the US number
1746 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1748 // Return as string...
1753 * Appends a trailing slash to a string
1755 * @param $str A string (maybe) without trailing slash
1756 * @return $str A string with an auto-appended trailing slash
1758 public final function addMissingTrailingSlash ($str) {
1759 // Is there a trailing slash?
1760 if (substr($str, -1, 1) != '/') {
1764 // Return string with trailing slash
1769 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1770 * application helper instance (ApplicationHelper by default).
1772 * @param $applicationInstance An application helper instance or
1773 * null if we shall use the default
1774 * @return $templateInstance The template engine instance
1775 * @throws NullPointerException If the discovered application
1776 * instance is still null
1778 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1779 // Is the application instance set?
1780 if (is_null($applicationInstance)) {
1781 // Get the current instance
1782 $applicationInstance = $this->getApplicationInstance();
1785 if (is_null($applicationInstance)) {
1786 // Thrown an exception
1787 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1791 // Initialize the template engine
1792 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1794 // Return the prepared instance
1795 return $templateInstance;
1799 * Debugs this instance by putting out it's full content
1801 * @param $message Optional message to show in debug output
1804 public final function debugInstance ($message = '') {
1805 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1806 restore_error_handler();
1811 // Is a message set?
1812 if (!empty($message)) {
1813 // Construct message
1814 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1817 // Generate the output
1818 $content .= sprintf('<pre>%s</pre>',
1821 print_r($this, TRUE)
1827 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>',
1828 $this->__toString(),
1830 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1835 * Replaces control characters with printable output
1837 * @param $str String with control characters
1838 * @return $str Replaced string
1840 protected function replaceControlCharacters ($str) {
1843 chr(13), '[r]', str_replace(
1844 chr(10), '[n]', str_replace(
1854 * Output a partial stub message for the caller method
1856 * @param $message An optional message to display
1859 protected function partialStub ($message = '') {
1860 // Get the backtrace
1861 $backtrace = debug_backtrace();
1863 // Generate the class::method string
1864 $methodName = 'UnknownClass->unknownMethod';
1865 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1866 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1869 // Construct the full message
1870 $stubMessage = sprintf('[%s:] Partial stub!',
1874 // Is the extra message given?
1875 if (!empty($message)) {
1876 // Then add it as well
1877 $stubMessage .= ' Message: ' . $message;
1880 // Debug instance is there?
1881 if (!is_null($this->getDebugInstance())) {
1882 // Output stub message
1883 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1886 trigger_error($stubMessage);
1892 * Outputs a debug backtrace and stops further script execution
1894 * @param $message An optional message to output
1895 * @param $doExit Whether exit the program (TRUE is default)
1898 public function debugBackTrace ($message = '', $doExit = TRUE) {
1899 // Sorry, there is no other way getting this nice backtrace
1900 if (!empty($message)) {
1902 printf('Message: %s<br />' . PHP_EOL, $message);
1906 debug_print_backtrace();
1910 if ($doExit === TRUE) {
1916 * Creates an instance of a debugger instance
1918 * @param $className Name of the class (currently unsupported)
1919 * @param $lineNumber Line number where the call was made
1920 * @return $debugInstance An instance of a debugger class
1921 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1923 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1924 // Is the instance set?
1925 if (!Registry::getRegistry()->instanceExists('debug')) {
1926 // Init debug instance
1927 $debugInstance = NULL;
1931 // Get a debugger instance
1932 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1933 } catch (NullPointerException $e) {
1934 // Didn't work, no instance there
1935 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1938 // Empty string should be ignored and used for testing the middleware
1939 DebugMiddleware::getSelfInstance()->output('');
1941 // Set it in its own class. This will set it in the registry
1942 $debugInstance->setDebugInstance($debugInstance);
1944 // Get instance from registry
1945 $debugInstance = Registry::getRegistry()->getDebugInstance();
1949 return $debugInstance;
1953 * Simple output of a message with line-break
1955 * @param $message Message to output
1958 public function outputLine ($message) {
1960 print($message . PHP_EOL);
1964 * Outputs a debug message whether to debug instance (should be set!) or
1965 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1966 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1968 * @param $message Message we shall send out...
1969 * @param $doPrint Whether print or die here (default: print)
1970 * @paran $stripTags Whether to strip tags (default: FALSE)
1973 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1974 // Set debug instance to NULL
1975 $debugInstance = NULL;
1979 // Get debug instance
1980 $debugInstance = $this->getDebugInstance();
1981 } catch (NullPointerException $e) {
1982 // The debug instance is not set (yet)
1985 // Is the debug instance there?
1986 if (is_object($debugInstance)) {
1987 // Use debug output handler
1988 $debugInstance->output($message, $stripTags);
1990 if ($doPrint === FALSE) {
1991 // Die here if not printed
1995 // Are debug times enabled?
1996 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1998 $message = $this->getPrintableExecutionTime() . $message;
2002 if ($doPrint === TRUE) {
2004 $this->outputLine($message);
2013 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2015 * @param $str The string, what ever it is needs to be converted
2016 * @return $className Generated class name
2018 public static final function convertToClassName ($str) {
2022 // Convert all dashes in underscores
2023 $str = self::convertDashesToUnderscores($str);
2025 // Now use that underscores to get classname parts for hungarian style
2026 foreach (explode('_', $str) as $strPart) {
2027 // Make the class name part lower case and first upper case
2028 $className .= ucfirst(strtolower($strPart));
2031 // Return class name
2036 * Converts dashes to underscores, e.g. useable for configuration entries
2038 * @param $str The string with maybe dashes inside
2039 * @return $str The converted string with no dashed, but underscores
2041 public static final function convertDashesToUnderscores ($str) {
2043 $str = str_replace('-', '_', $str);
2045 // Return converted string
2050 * Marks up the code by adding e.g. line numbers
2052 * @param $phpCode Unmarked PHP code
2053 * @return $markedCode Marked PHP code
2055 public function markupCode ($phpCode) {
2060 $errorArray = error_get_last();
2062 // Init the code with error message
2063 if (is_array($errorArray)) {
2065 $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>',
2066 basename($errorArray['file']),
2067 $errorArray['line'],
2068 $errorArray['message'],
2073 // Add line number to the code
2074 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2076 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2078 htmlentities($code, ENT_QUOTES)
2087 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2088 * beatiful for web-based front-ends. If null is given a message id
2089 * null_timestamp will be resolved and returned.
2091 * @param $timestamp Timestamp to prepare (filter) for display
2092 * @return $readable A readable timestamp
2094 public function doFilterFormatTimestamp ($timestamp) {
2095 // Default value to return
2098 // Is the timestamp null?
2099 if (is_null($timestamp)) {
2100 // Get a message string
2101 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2103 switch ($this->getLanguageInstance()->getLanguageCode()) {
2104 case 'de': // German format is a bit different to default
2105 // Split the GMT stamp up
2106 $dateTime = explode(' ', $timestamp );
2107 $dateArray = explode('-', $dateTime[0]);
2108 $timeArray = explode(':', $dateTime[1]);
2110 // Construct the timestamp
2111 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2121 default: // Default is pass-through
2122 $readable = $timestamp;
2132 * Filter a given number into a localized number
2134 * @param $value The raw value from e.g. database
2135 * @return $localized Localized value
2137 public function doFilterFormatNumber ($value) {
2138 // Generate it from config and localize dependencies
2139 switch ($this->getLanguageInstance()->getLanguageCode()) {
2140 case 'de': // German format is a bit different to default
2141 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2144 default: // US, etc.
2145 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2154 * "Getter" for databse entry
2156 * @return $entry An array with database entries
2157 * @throws NullPointerException If the database result is not found
2158 * @throws InvalidDatabaseResultException If the database result is invalid
2160 protected final function getDatabaseEntry () {
2161 // Is there an instance?
2162 if (!$this->getResultInstance() instanceof SearchableResult) {
2163 // Throw an exception here
2164 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2168 $this->getResultInstance()->rewind();
2170 // Do we have an entry?
2171 if ($this->getResultInstance()->valid() === FALSE) {
2172 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2173 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2177 $this->getResultInstance()->next();
2180 $entry = $this->getResultInstance()->current();
2187 * Getter for field name
2189 * @param $fieldName Field name which we shall get
2190 * @return $fieldValue Field value from the user
2191 * @throws NullPointerException If the result instance is null
2193 public final function getField ($fieldName) {
2194 // Default field value
2197 // Get result instance
2198 $resultInstance = $this->getResultInstance();
2200 // Is this instance null?
2201 if (is_null($resultInstance)) {
2202 // Then the user instance is no longer valid (expired cookies?)
2203 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2206 // Get current array
2207 $fieldArray = $resultInstance->current();
2208 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2210 // Convert dashes to underscore
2211 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2213 // Does the field exist?
2214 if ($this->isFieldSet($fieldName)) {
2216 $fieldValue = $fieldArray[$fieldName2];
2217 } elseif (defined('DEVELOPER')) {
2218 // Missing field entry, may require debugging
2219 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2221 // Missing field entry, may require debugging
2222 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2230 * Checks if given field is set
2232 * @param $fieldName Field name to check
2233 * @return $isSet Whether the given field name is set
2234 * @throws NullPointerException If the result instance is null
2236 public function isFieldSet ($fieldName) {
2237 // Get result instance
2238 $resultInstance = $this->getResultInstance();
2240 // Is this instance null?
2241 if (is_null($resultInstance)) {
2242 // Then the user instance is no longer valid (expired cookies?)
2243 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2246 // Get current array
2247 $fieldArray = $resultInstance->current();
2248 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2250 // Convert dashes to underscore
2251 $fieldName = self::convertDashesToUnderscores($fieldName);
2254 $isSet = isset($fieldArray[$fieldName]);
2261 * Flushs all pending updates to the database layer
2265 public function flushPendingUpdates () {
2266 // Get result instance
2267 $resultInstance = $this->getResultInstance();
2269 // Do we have data to update?
2270 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2271 // Get wrapper class name config entry
2272 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2274 // Create object instance
2275 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2277 // Yes, then send the whole result to the database layer
2278 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2283 * Outputs a deprecation warning to the developer.
2285 * @param $message The message we shall output to the developer
2287 * @todo Write a logging mechanism for productive mode
2289 public function deprecationWarning ($message) {
2290 // Is developer mode active?
2291 if (defined('DEVELOPER')) {
2292 // Debug instance is there?
2293 if (!is_null($this->getDebugInstance())) {
2294 // Output stub message
2295 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2298 trigger_error($message . "<br />\n");
2302 // @TODO Finish this part!
2303 $this->partialStub('Developer mode inactive. Message:' . $message);
2308 * Checks whether the given PHP extension is loaded
2310 * @param $phpExtension The PHP extension we shall check
2311 * @return $isLoaded Whether the PHP extension is loaded
2313 public final function isPhpExtensionLoaded ($phpExtension) {
2315 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2322 * "Getter" as a time() replacement but with milliseconds. You should use this
2323 * method instead of the encapsulated getimeofday() function.
2325 * @return $milliTime Timestamp with milliseconds
2327 public function getMilliTime () {
2328 // Get the time of day as float
2329 $milliTime = gettimeofday(TRUE);
2336 * Idles (sleeps) for given milliseconds
2338 * @return $hasSlept Whether it goes fine
2340 public function idle ($milliSeconds) {
2341 // Sleep is fine by default
2344 // Idle so long with found function
2345 if (function_exists('time_sleep_until')) {
2346 // Get current time and add idle time
2347 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2349 // New PHP 5.1.0 function found, ignore errors
2350 $hasSlept = @time_sleep_until($sleepUntil);
2353 * My Sun station doesn't have that function even with latest PHP
2356 usleep($milliSeconds * 1000);
2363 * Converts a hexadecimal string, even with negative sign as first string to
2364 * a decimal number using BC functions.
2366 * This work is based on comment #86673 on php.net documentation page at:
2367 * <http://de.php.net/manual/en/function.dechex.php#86673>
2369 * @param $hex Hexadecimal string
2370 * @return $dec Decimal number
2372 protected function hex2dec ($hex) {
2373 // Convert to all lower-case
2374 $hex = strtolower($hex);
2376 // Detect sign (negative/positive numbers)
2378 if (substr($hex, 0, 1) == '-') {
2380 $hex = substr($hex, 1);
2383 // Decode the hexadecimal string into a decimal number
2385 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2386 $factor = self::$hexdec[substr($hex, $i, 1)];
2387 $dec = bcadd($dec, bcmul($factor, $e));
2390 // Return the decimal number
2391 return $sign . $dec;
2395 * Converts even very large decimal numbers, also signed, to a hexadecimal
2398 * This work is based on comment #97756 on php.net documentation page at:
2399 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2401 * @param $dec Decimal number, even with negative sign
2402 * @param $maxLength Optional maximum length of the string
2403 * @return $hex Hexadecimal string
2405 protected function dec2hex ($dec, $maxLength = 0) {
2406 // maxLength can be zero or devideable by 2
2407 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2409 // Detect sign (negative/positive numbers)
2416 // Encode the decimal number into a hexadecimal string
2419 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2421 } while ($dec >= 1);
2424 * Leading zeros are required for hex-decimal "numbers". In some
2425 * situations more leading zeros are wanted, so check for both
2428 if ($maxLength > 0) {
2429 // Prepend more zeros
2430 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2431 } elseif ((strlen($hex) % 2) != 0) {
2432 // Only make string's length dividable by 2
2436 // Return the hexadecimal string
2437 return $sign . $hex;
2441 * Converts a ASCII string (0 to 255) into a decimal number.
2443 * @param $asc The ASCII string to be converted
2444 * @return $dec Decimal number
2446 protected function asc2dec ($asc) {
2447 // Convert it into a hexadecimal number
2448 $hex = bin2hex($asc);
2450 // And back into a decimal number
2451 $dec = $this->hex2dec($hex);
2458 * Converts a decimal number into an ASCII string.
2460 * @param $dec Decimal number
2461 * @return $asc An ASCII string
2463 protected function dec2asc ($dec) {
2464 // First convert the number into a hexadecimal string
2465 $hex = $this->dec2hex($dec);
2467 // Then convert it into the ASCII string
2468 $asc = $this->hex2asc($hex);
2475 * Converts a hexadecimal number into an ASCII string. Negative numbers
2478 * @param $hex Hexadecimal string
2479 * @return $asc An ASCII string
2481 protected function hex2asc ($hex) {
2482 // Check for length, it must be devideable by 2
2483 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2484 assert((strlen($hex) % 2) == 0);
2488 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2489 // Get the decimal number of the chunk
2490 $part = hexdec(substr($hex, $idx, 2));
2492 // Add it to the final string
2496 // Return the final string
2501 * Checks whether the given encoded data was encoded with Base64
2503 * @param $encodedData Encoded data we shall check
2504 * @return $isBase64 Whether the encoded data is Base64
2506 protected function isBase64Encoded ($encodedData) {
2508 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2515 * "Getter" to get response/request type from analysis of the system.
2517 * @return $responseType Analyzed response type
2519 protected static function getResponseTypeFromSystem () {
2520 // Default is console
2521 $responseType = 'console';
2523 // Is 'HTTP_HOST' set?
2524 if (isset($_SERVER['HTTP_HOST'])) {
2526 * Then it is a HTML response/request as RSS and so on may be
2527 * transfered over HTTP as well.
2529 $responseType = 'html';
2533 return $responseType;
2537 * Gets a cache key from Criteria instance
2539 * @param $criteriaInstance An instance of a Criteria class
2540 * @param $onlyKeys Only use these keys for a cache key
2541 * @return $cacheKey A cache key suitable for lookup/storage purposes
2543 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2545 $cacheKey = sprintf('%s@%s',
2546 $this->__toString(),
2547 $criteriaInstance->getCacheKey($onlyKeys)
2551 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2556 * Getter for startup time in miliseconds
2558 * @return $startupTime Startup time in miliseconds
2560 protected function getStartupTime () {
2561 return self::$startupTime;
2565 * "Getter" for a printable currently execution time in nice braces
2567 * @return $executionTime Current execution time in nice braces
2569 protected function getPrintableExecutionTime () {
2570 // Caculate the execution time
2571 $executionTime = microtime(TRUE) - $this->getStartupTime();
2573 // Pack it in nice braces
2574 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2577 return $executionTime;
2581 * Hashes a given string with a simple but stronger hash function (no salt)
2582 * and hex-encode it.
2584 * @param $str The string to be hashed
2585 * @return $hash The hash from string $str
2587 public static final function hash ($str) {
2588 // Hash given string with (better secure) hasher
2589 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2596 * "Getter" for length of hash() output. This will be "cached" to speed up
2599 * @return $length Length of hash() output
2601 public static final function getHashLength () {
2603 if (is_null(self::$hashLength)) {
2604 // No, then hash a string and save its length.
2605 self::$hashLength = strlen(self::hash('abc123'));
2609 return self::$hashLength;
2613 * Checks whether the given number is really a number (only chars 0-9).
2615 * @param $num A string consisting only chars between 0 and 9
2616 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2617 * @param $assertMismatch Whether to assert mismatches
2618 * @return $ret The (hopefully) secured numbered value
2620 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2621 // Filter all numbers out
2622 $ret = preg_replace('/[^0123456789]/', '', $num);
2625 if ($castValue === TRUE) {
2626 // Cast to biggest numeric type
2627 $ret = (double) $ret;
2630 // Assert only if requested
2631 if ($assertMismatch === TRUE) {
2632 // Has the whole value changed?
2633 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2641 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2643 * @param $num A string consisting only chars between 0 and 9
2644 * @param $assertMismatch Whether to assert mismatches
2645 * @return $ret The (hopefully) secured hext-numbered value
2647 public function hexval ($num, $assertMismatch = FALSE) {
2648 // Filter all numbers out
2649 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2651 // Assert only if requested
2652 if ($assertMismatch === TRUE) {
2653 // Has the whole value changed?
2654 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2662 * Checks whether start/end marker are set
2664 * @param $data Data to be checked
2665 * @return $isset Whether start/end marker are set
2667 public final function ifStartEndMarkersSet ($data) {
2669 $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));
2671 // ... and return it
2676 * Determines if an element is set in the generic array
2678 * @param $keyGroup Main group for the key
2679 * @param $subGroup Sub group for the key
2680 * @param $key Key to check
2681 * @param $element Element to check
2682 * @return $isset Whether the given key is set
2684 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2686 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2689 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2695 * Determines if a key is set in the generic array
2697 * @param $keyGroup Main group for the key
2698 * @param $subGroup Sub group for the key
2699 * @param $key Key to check
2700 * @return $isset Whether the given key is set
2702 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2704 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2707 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2715 * Determines if a group is set in the generic array
2717 * @param $keyGroup Main group
2718 * @param $subGroup Sub group
2719 * @return $isset Whether the given group is set
2721 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2723 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2726 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2733 * Getter for sub key group
2735 * @param $keyGroup Main key group
2736 * @param $subGroup Sub key group
2737 * @return $array An array with all array elements
2739 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2741 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2742 // No, then abort here
2743 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2748 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2751 return $this->genericArray[$keyGroup][$subGroup];
2755 * Unsets a given key in generic array
2757 * @param $keyGroup Main group for the key
2758 * @param $subGroup Sub group for the key
2759 * @param $key Key to unset
2762 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2764 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2767 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2771 * Unsets a given element in generic array
2773 * @param $keyGroup Main group for the key
2774 * @param $subGroup Sub group for the key
2775 * @param $key Key to unset
2776 * @param $element Element to unset
2779 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2781 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2784 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2788 * Append a string to a given generic array key
2790 * @param $keyGroup Main group for the key
2791 * @param $subGroup Sub group for the key
2792 * @param $key Key to unset
2793 * @param $value Value to add/append
2796 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2798 //* 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);
2800 // Is it already there?
2801 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2803 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2806 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2811 * Append a string to a given generic array element
2813 * @param $keyGroup Main group for the key
2814 * @param $subGroup Sub group for the key
2815 * @param $key Key to unset
2816 * @param $element Element to check
2817 * @param $value Value to add/append
2820 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2822 //* 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);
2824 // Is it already there?
2825 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2827 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2830 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2835 * Sets a string in a given generic array element
2837 * @param $keyGroup Main group for the key
2838 * @param $subGroup Sub group for the key
2839 * @param $key Key to unset
2840 * @param $element Element to check
2841 * @param $value Value to add/append
2844 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2846 //* 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);
2849 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2853 * Initializes given generic array group
2855 * @param $keyGroup Main group for the key
2856 * @param $subGroup Sub group for the key
2857 * @param $key Key to use
2858 * @param $forceInit Optionally force initialization
2861 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2863 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2865 // Is it already set?
2866 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2867 // Already initialized
2868 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2873 $this->genericArray[$keyGroup][$subGroup] = array();
2877 * Initializes given generic array key
2879 * @param $keyGroup Main group for the key
2880 * @param $subGroup Sub group for the key
2881 * @param $key Key to use
2882 * @param $forceInit Optionally force initialization
2885 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2887 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2889 // Is it already set?
2890 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2891 // Already initialized
2892 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2897 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2901 * Initializes given generic array element
2903 * @param $keyGroup Main group for the key
2904 * @param $subGroup Sub group for the key
2905 * @param $key Key to use
2906 * @param $element Element to use
2907 * @param $forceInit Optionally force initialization
2910 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2912 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2914 // Is it already set?
2915 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2916 // Already initialized
2917 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2922 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2926 * Pushes an element to a generic key
2928 * @param $keyGroup Main group for the key
2929 * @param $subGroup Sub group for the key
2930 * @param $key Key to use
2931 * @param $value Value to add/append
2932 * @return $count Number of array elements
2934 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2936 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2939 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2941 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2945 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2948 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2949 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2954 * Pushes an element to a generic array element
2956 * @param $keyGroup Main group for the key
2957 * @param $subGroup Sub group for the key
2958 * @param $key Key to use
2959 * @param $element Element to check
2960 * @param $value Value to add/append
2961 * @return $count Number of array elements
2963 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2965 //* 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));
2968 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2970 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2974 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2977 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2978 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2983 * Pops an element from a generic group
2985 * @param $keyGroup Main group for the key
2986 * @param $subGroup Sub group for the key
2987 * @param $key Key to unset
2988 * @return $value Last "popped" value
2990 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2992 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2995 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2997 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3002 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3005 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3006 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3011 * Shifts an element from a generic group
3013 * @param $keyGroup Main group for the key
3014 * @param $subGroup Sub group for the key
3015 * @param $key Key to unset
3016 * @return $value Last "popped" value
3018 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3020 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3023 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3025 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3030 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3033 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3034 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3039 * Count generic array group
3041 * @param $keyGroup Main group for the key
3042 * @return $count Count of given group
3044 protected final function countGenericArray ($keyGroup) {
3046 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3049 if (!isset($this->genericArray[$keyGroup])) {
3051 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3056 $count = count($this->genericArray[$keyGroup]);
3059 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3066 * Count generic array sub group
3068 * @param $keyGroup Main group for the key
3069 * @param $subGroup Sub group for the key
3070 * @return $count Count of given group
3072 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3074 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3077 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3079 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3084 $count = count($this->genericArray[$keyGroup][$subGroup]);
3087 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3094 * Count generic array elements
3096 * @param $keyGroup Main group for the key
3097 * @param $subGroup Sub group for the key
3098 * @para $key Key to count
3099 * @return $count Count of given key
3101 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3103 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3106 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3108 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3110 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3112 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3117 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3120 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3127 * Getter for whole generic group array
3129 * @param $keyGroup Key group to get
3130 * @return $array Whole generic array group
3132 protected final function getGenericArray ($keyGroup) {
3134 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3137 if (!isset($this->genericArray[$keyGroup])) {
3139 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3144 return $this->genericArray[$keyGroup];
3148 * Setter for generic array key
3150 * @param $keyGroup Key group to get
3151 * @param $subGroup Sub group for the key
3152 * @param $key Key to unset
3153 * @param $value Mixed value from generic array element
3156 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3158 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3161 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3165 * Getter for generic array key
3167 * @param $keyGroup Key group to get
3168 * @param $subGroup Sub group for the key
3169 * @param $key Key to unset
3170 * @return $value Mixed value from generic array element
3172 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3174 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3177 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3179 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3184 return $this->genericArray[$keyGroup][$subGroup][$key];
3188 * Sets a value in given generic array key/element
3190 * @param $keyGroup Main group for the key
3191 * @param $subGroup Sub group for the key
3192 * @param $key Key to set
3193 * @param $element Element to set
3194 * @param $value Value to set
3197 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3199 //* 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));
3202 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3206 * Getter for generic array element
3208 * @param $keyGroup Key group to get
3209 * @param $subGroup Sub group for the key
3210 * @param $key Key to look for
3211 * @param $element Element to look for
3212 * @return $value Mixed value from generic array element
3214 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3216 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3219 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3221 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3226 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3230 * Checks if a given sub group is valid (array)
3232 * @param $keyGroup Key group to get
3233 * @param $subGroup Sub group for the key
3234 * @return $isValid Whether given sub group is valid
3236 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3238 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3241 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3248 * Checks if a given key is valid (array)
3250 * @param $keyGroup Key group to get
3251 * @param $subGroup Sub group for the key
3252 * @param $key Key to check
3253 * @return $isValid Whether given sub group is valid
3255 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3257 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3260 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3267 * Initializes the web output instance
3271 protected function initWebOutputInstance () {
3272 // Get application instance
3273 $applicationInstance = Registry::getRegistry()->getInstance('app');
3275 // Is this a response instance?
3276 if ($this instanceof Responseable) {
3277 // Then set it in application instance
3278 $applicationInstance->setResponseInstance($this);
3281 // Init web output instance
3282 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3285 $this->setWebOutputInstance($outputInstance);
3289 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3291 * @param $boolean Boolean value
3292 * @return $translated Translated boolean value
3294 public static final function translateBooleanToYesNo ($boolean) {
3295 // Make sure it is really boolean
3296 assert(is_bool($boolean));
3299 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3301 // ... and return it
3306 * Encodes raw data (almost any type) by "serializing" it and then pack it
3307 * into a "binary format".
3309 * @param $rawData Raw data (almost any type)
3310 * @return $encoded Encoded data
3312 protected function encodeData ($rawData) {
3313 // Make sure no objects or resources pass through
3314 assert(!is_object($rawData));
3315 assert(!is_resource($rawData));
3317 // First "serialize" it (json_encode() is faster than serialize())
3318 $encoded = $this->packString(json_encode($rawData));
3325 * Pack a string into a "binary format". Please execuse me that this is
3326 * widely undocumented. :-(
3328 * @param $str Unpacked string
3329 * @return $packed Packed string
3330 * @todo Improve documentation
3332 protected function packString ($str) {
3334 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3336 // First compress the string (gzcompress is okay)
3337 $str = gzcompress($str);
3342 // And start the "encoding" loop
3343 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3345 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3346 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3348 if (($idx + $i) <= strlen($str)) {
3349 $ord = ord(substr($str, ($idx + $i), 1));
3351 $add = $ord * pow(256, $factor);
3355 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3359 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3360 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3362 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3363 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3369 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3374 * Checks whether the given file/path is in open_basedir(). This does not
3375 * gurantee that the file is actually readable and/or writeable. If you need
3376 * such gurantee then please use isReadableFile() instead.
3378 * @param $filePathName Name of the file/path to be checked
3379 * @return $isReachable Whether it is within open_basedir()
3381 protected static function isReachableFilePath ($filePathName) {
3382 // Is not reachable by default
3383 $isReachable = FALSE;
3385 // Get open_basedir parameter
3386 $openBaseDir = ini_get('open_basedir');
3389 if (!empty($openBaseDir)) {
3390 // Check all entries
3391 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3392 // Check on existence
3393 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3395 $isReachable = TRUE;
3399 // If open_basedir is not set, all is allowed
3400 $isReachable = TRUE;
3404 return $isReachable;
3408 * Checks whether the give file is within open_basedir() (done by
3409 * isReachableFilePath()), is actually a file and is readable.
3411 * @param $fileName Name of the file to be checked
3412 * @return $isReadable Whether the file is readable (and therefor exists)
3414 public static function isReadableFile ($fileName) {
3415 // Default is not readable
3416 $isReadable = FALSE;
3418 // Is within parameters, so check if it is a file and readable
3419 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3426 * Creates a full-qualified file name (FQFN) for given file name by adding
3427 * a configured temporary file path to it.
3429 * @param $fileName Name for temporary file
3430 * @return $fqfn Full-qualified file name
3431 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3432 * @throws FileIoException If the file cannot be written
3434 protected static function createTempPathForFile ($fileName) {
3436 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3438 // Is the path writeable?
3439 if (!is_writable($basePath)) {
3440 // Path is write-protected
3441 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3445 $fqfn = $basePath . '/' . $fileName;
3448 if (!self::isReachableFilePath($fqfn)) {
3450 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3458 * "Getter" for a printable state name
3460 * @return $stateName Name of the node's state in a printable format
3462 public final function getPrintableState () {
3463 // Default is 'null'
3464 $stateName = 'null';
3466 // Get the state instance
3467 $stateInstance = $this->getStateInstance();
3469 // Is it an instance of Stateable?
3470 if ($stateInstance instanceof Stateable) {
3471 // Then use that state name
3472 $stateName = $stateInstance->getStateName();
3480 * Handles socket error for given socket resource and peer data. This method
3481 * validates $socketResource if it is a valid resource (see is_resource())
3482 * but assumes valid data in array $recipientData, except that
3483 * count($recipientData) is always 2.
3485 * @param $method Value of __METHOD__ from calling method
3486 * @param $line Value of __LINE__ from calling method
3487 * @param $socketResource A valid socket resource
3488 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3490 * @throws InvalidSocketException If $socketResource is no socket resource
3491 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3492 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3494 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3495 // This method handles only socket resources
3496 if (!is_resource($socketResource)) {
3497 // No resource, abort here
3498 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3501 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3502 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3503 assert(isset($socketData[0]));
3504 assert(isset($socketData[1]));
3506 // Get error code for first validation (0 is not an error)
3507 $errorCode = socket_last_error($socketResource);
3509 // If the error code is zero, someone called this method without an error
3510 if ($errorCode == 0) {
3511 // No error detected (or previously cleared outside this method)
3512 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3515 // Get handler (method) name
3516 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3518 // Call-back the error handler method
3519 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3521 // Finally clear the error because it has been handled
3522 socket_clear_error($socketResource);