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\Listener\Listenable;
22 use CoreFramework\Lists\Listable;
23 use CoreFramework\Loader\ClassLoader;
24 use CoreFramework\Manager\ManageableApplication;
25 use CoreFramework\Middleware\Compressor\CompressorChannel;
26 use CoreFramework\Middleware\Debug\DebugMiddleware;
27 use CoreFramework\Parser\Parseable;
28 use CoreFramework\Registry\Register;
29 use CoreFramework\Registry\Registry;
30 use CoreFramework\Request\Requestable;
31 use CoreFramework\Resolver\Resolver;
32 use CoreFramework\Result\Database\CachedDatabaseResult;
33 use CoreFramework\Result\Search\SearchableResult;
34 use CoreFramework\Response\Responseable;
35 use CoreFramework\Stream\Output\OutputStreamer;
36 use CoreFramework\Template\CompileableTemplate;
37 use CoreFramework\User\ManageableAccount;
38 use CoreFramework\Visitor\Visitor;
39 use CoreFramework\Wrapper\Database\DatabaseWrapper;
46 * The simulator system class is the super class of all other classes. This
47 * class handles saving of games etc.
49 * @author Roland Haeder <webmaster@shipsimu.org>
51 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
52 * @license GNU GPL 3.0 or any newer version
53 * @link http://www.shipsimu.org
55 * This program is free software: you can redistribute it and/or modify
56 * it under the terms of the GNU General Public License as published by
57 * the Free Software Foundation, either version 3 of the License, or
58 * (at your option) any later version.
60 * This program is distributed in the hope that it will be useful,
61 * but WITHOUT ANY WARRANTY; without even the implied warranty of
62 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
63 * GNU General Public License for more details.
65 * You should have received a copy of the GNU General Public License
66 * along with this program. If not, see <http://www.gnu.org/licenses/>.
68 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
70 * Length of output from hash()
72 private static $hashLength = NULL;
77 private $realClass = 'BaseFrameworkSystem';
80 * Instance of a Requestable class
82 private $requestInstance = NULL;
85 * Instance of a Responseable class
87 private $responseInstance = NULL;
90 * Search criteria instance
92 private $searchInstance = NULL;
95 * Update criteria instance
97 private $updateInstance = NULL;
100 * The file I/O instance for the template loader
102 private $fileIoInstance = NULL;
107 private $resolverInstance = NULL;
110 * Template engine instance
112 private $templateInstance = NULL;
115 * Database result instance
117 private $resultInstance = NULL;
120 * Instance for user class
122 private $userInstance = NULL;
125 * A controller instance
127 private $controllerInstance = NULL;
132 private $rngInstance = NULL;
135 * Instance of a crypto helper
137 private $cryptoInstance = NULL;
140 * Instance of an Iterator class
142 private $iteratorInstance = NULL;
145 * Instance of the list
147 private $listInstance = NULL;
152 private $menuInstance = NULL;
155 * Instance of the image
157 private $imageInstance = NULL;
160 * Instance of the stacker
162 private $stackInstance = NULL;
165 * A Compressor instance
167 private $compressorInstance = NULL;
170 * A Parseable instance
172 private $parserInstance = NULL;
175 * A HandleableProtocol instance
177 private $protocolInstance = NULL;
180 * A database wrapper instance
182 private $databaseInstance = NULL;
185 * A helper instance for the form
187 private $helperInstance = NULL;
190 * An instance of a Source class
192 private $sourceInstance = NULL;
195 * An instance of a UrlSource class
197 private $urlSourceInstance = NULL;
200 * An instance of a InputStream class
202 private $inputStreamInstance = NULL;
205 * An instance of a OutputStream class
207 private $outputStreamInstance = NULL;
210 * Networkable handler instance
212 private $handlerInstance = NULL;
215 * Visitor handler instance
217 private $visitorInstance = NULL;
222 private $dhtInstance = NULL;
225 * An instance of a database wrapper class
227 private $wrapperInstance = NULL;
230 * An instance of a file I/O pointer class (not handler)
232 private $pointerInstance = NULL;
235 * An instance of an Indexable class
237 private $indexInstance = NULL;
240 * An instance of a Block class
242 private $blockInstance = NULL;
247 private $minableInstance = NULL;
250 * A FrameworkDirectory instance
252 private $directoryInstance = NULL;
257 private $listenerInstance = NULL;
260 * An instance of a communicator
262 private $communicatorInstance = NULL;
265 * The concrete output instance
267 private $outputInstance = NULL;
272 private $stateInstance = NULL;
275 * Thousands separator
277 private $thousands = '.'; // German
282 private $decimals = ','; // German
287 private $socketResource = FALSE;
290 * Regular expression to use for validation
292 private $regularExpression = '';
297 private $packageData = array();
302 private $genericArray = array();
307 private $commandName = '';
312 private $controllerName = '';
315 * Name of used protocol
317 private $protocolName = 'invalid';
320 * Array with bitmasks and such for pack/unpack methods to support both
321 * 32-bit and 64-bit systems
323 private $packingData = array(
326 'left' => 0xffff0000,
327 'right' => 0x0000ffff,
333 'left' => 0xffffffff00000000,
334 'right' => 0x00000000ffffffff,
341 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
343 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
345 private $archArrayElement = FALSE;
347 /***********************
348 * Exception codes.... *
349 ***********************/
351 // @todo Try to clean these constants up
352 const EXCEPTION_IS_NULL_POINTER = 0x001;
353 const EXCEPTION_IS_NO_OBJECT = 0x002;
354 const EXCEPTION_IS_NO_ARRAY = 0x003;
355 const EXCEPTION_MISSING_METHOD = 0x004;
356 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
357 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
358 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
359 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
360 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
361 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
362 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
363 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
364 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
365 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
366 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
367 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
368 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
369 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
370 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
371 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
372 const EXCEPTION_PATH_NOT_FOUND = 0x015;
373 const EXCEPTION_INVALID_PATH_NAME = 0x016;
374 const EXCEPTION_READ_PROTECED_PATH = 0x017;
375 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
376 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
377 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
378 const EXCEPTION_INVALID_RESOURCE = 0x01b;
379 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
380 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
381 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
382 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
383 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
384 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
385 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
386 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
387 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
388 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
389 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
390 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
391 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
392 const EXCEPTION_INVALID_STRING = 0x029;
393 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
394 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
395 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
396 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
397 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
398 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
399 const EXCEPTION_MISSING_ELEMENT = 0x030;
400 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
401 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
402 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
403 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
404 const EXCEPTION_FATAL_ERROR = 0x035;
405 const EXCEPTION_FILE_NOT_FOUND = 0x036;
406 const EXCEPTION_ASSERTION_FAILED = 0x037;
407 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
408 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
409 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
410 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
411 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
412 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
415 * Hexadecimal->Decimal translation array
417 private static $hexdec = array(
437 * Decimal->hexadecimal translation array
439 private static $dechex = array(
459 * Startup time in miliseconds
461 private static $startupTime = 0;
464 * Protected super constructor
466 * @param $className Name of the class
469 protected function __construct ($className) {
471 $this->setRealClass($className);
473 // Set configuration instance if no registry ...
474 if (!$this instanceof Register) {
475 // ... because registries doesn't need to be configured
476 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
479 // Is the startup time set? (0 cannot be TRUE anymore)
480 if (self::$startupTime == 0) {
482 self::$startupTime = microtime(TRUE);
486 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
490 * Destructor for all classes. You should not call this method on your own.
494 public function __destruct () {
495 // Flush any updated entries to the database
496 $this->flushPendingUpdates();
498 // Is this object already destroyed?
499 if ($this->__toString() != 'DestructedObject') {
500 // Destroy all informations about this class but keep some text about it alive
501 $this->setRealClass('DestructedObject');
502 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
503 // Already destructed object
504 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
509 // Do not call this twice
510 trigger_error(__METHOD__ . ': Called twice.');
516 * The __call() method where all non-implemented methods end up
518 * @param $methodName Name of the missing method
519 * @args $args Arguments passed to the method
522 public final function __call ($methodName, $args) {
523 return self::__callStatic($methodName, $args);
527 * The __callStatic() method where all non-implemented static methods end up
529 * @param $methodName Name of the missing method
530 * @args $args Arguments passed to the method
533 public static final function __callStatic ($methodName, $args) {
535 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
537 // Init argument string
540 // Is it NULL, empty or an array?
541 if (is_null($args)) {
543 $argsString = 'NULL';
544 } elseif (is_array($args)) {
548 // Some arguments are there
549 foreach ($args as $arg) {
550 // Add data about the argument
551 $argsString .= gettype($arg) . ':';
554 // Found a NULL argument
555 $argsString .= 'NULL';
556 } elseif (is_string($arg)) {
557 // Add length for strings
558 $argsString .= strlen($arg);
559 } elseif ((is_int($arg)) || (is_float($arg))) {
562 } elseif (is_array($arg)) {
563 // .. or size if array
564 $argsString .= count($arg);
565 } elseif (is_object($arg)) {
567 $reflection = new ReflectionClass($arg);
569 // Is an other object, maybe no __toString() available
570 $argsString .= $reflection->getName();
571 } elseif ($arg === TRUE) {
572 // ... is boolean 'TRUE'
573 $argsString .= 'TRUE';
574 } elseif ($arg === FALSE) {
575 // ... is boolean 'FALSE'
576 $argsString .= 'FALSE';
579 // Comma for next one
584 if (substr($argsString, -2, 1) == ',') {
585 $argsString = substr($argsString, 0, -2);
591 // Invalid arguments!
592 $argsString = '!INVALID:' . gettype($args) . '!';
595 // Output stub message
596 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
597 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
607 * Getter for $realClass
609 * @return $realClass The name of the real class (not BaseFrameworkSystem)
611 public function __toString () {
612 return $this->realClass;
616 * Magic method to catch setting of missing but set class fields/attributes
618 * @param $name Name of the field/attribute
619 * @param $value Value to store
622 public final function __set ($name, $value) {
623 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
626 print_r($value, TRUE)
631 * Magic method to catch getting of missing fields/attributes
633 * @param $name Name of the field/attribute
636 public final function __get ($name) {
637 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
643 * Magic method to catch unsetting of missing fields/attributes
645 * @param $name Name of the field/attribute
648 public final function __unset ($name) {
649 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
655 * Magic method to catch object serialization
657 * @return $unsupported Unsupported method
658 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
660 public final function __sleep () {
661 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
665 * Magic method to catch object deserialization
667 * @return $unsupported Unsupported method
668 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
670 public final function __wakeup () {
671 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
675 * Magic method to catch calls when an object instance is called
677 * @return $unsupported Unsupported method
678 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
680 public final function __invoke () {
681 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
685 * Setter for the real class name
687 * @param $realClass Class name (string)
690 public final function setRealClass ($realClass) {
692 $this->realClass = (string) $realClass;
696 * Setter for database result instance
698 * @param $resultInstance An instance of a database result class
700 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
702 protected final function setResultInstance (SearchableResult $resultInstance) {
703 $this->resultInstance = $resultInstance;
707 * Getter for database result instance
709 * @return $resultInstance An instance of a database result class
711 public final function getResultInstance () {
712 return $this->resultInstance;
716 * Setter for template engine instances
718 * @param $templateInstance An instance of a template engine class
721 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
722 $this->templateInstance = $templateInstance;
726 * Getter for template engine instances
728 * @return $templateInstance An instance of a template engine class
730 protected final function getTemplateInstance () {
731 return $this->templateInstance;
735 * Setter for search instance
737 * @param $searchInstance Searchable criteria instance
740 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
741 $this->searchInstance = $searchInstance;
745 * Getter for search instance
747 * @return $searchInstance Searchable criteria instance
749 public final function getSearchInstance () {
750 return $this->searchInstance;
754 * Setter for update instance
756 * @param $updateInstance An instance of a LocalUpdateCriteria clase
759 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
760 $this->updateInstance = $updateInstance;
764 * Getter for update instance
766 * @return $updateInstance Updateable criteria instance
768 public final function getUpdateInstance () {
769 return $this->updateInstance;
773 * Setter for resolver instance
775 * @param $resolverInstance Instance of a command resolver class
778 public final function setResolverInstance (Resolver $resolverInstance) {
779 $this->resolverInstance = $resolverInstance;
783 * Getter for resolver instance
785 * @return $resolverInstance Instance of a command resolver class
787 public final function getResolverInstance () {
788 return $this->resolverInstance;
792 * Setter for language instance
794 * @param $configInstance The configuration instance which shall
795 * be FrameworkConfiguration
798 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
799 Registry::getRegistry()->addInstance('config', $configInstance);
803 * Getter for configuration instance
805 * @return $configInstance Configuration instance
807 public final function getConfigInstance () {
808 $configInstance = Registry::getRegistry()->getInstance('config');
809 return $configInstance;
813 * Setter for debug instance
815 * @param $debugInstance The instance for debug output class
818 public final function setDebugInstance (DebugMiddleware $debugInstance) {
819 Registry::getRegistry()->addInstance('debug', $debugInstance);
823 * Getter for debug instance
825 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
827 public final function getDebugInstance () {
828 // Get debug instance
829 $debugInstance = Registry::getRegistry()->getInstance('debug');
832 return $debugInstance;
836 * Setter for web output instance
838 * @param $webInstance The instance for web output class
841 public final function setWebOutputInstance (OutputStreamer $webInstance) {
842 Registry::getRegistry()->addInstance('web_output', $webInstance);
846 * Getter for web output instance
848 * @return $webOutputInstance - Instance to class WebOutput
850 public final function getWebOutputInstance () {
851 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
852 return $webOutputInstance;
856 * Setter for database instance
858 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
861 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
862 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
866 * Getter for database layer
868 * @return $databaseInstance The database layer instance
870 public final function getDatabaseInstance () {
872 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
875 return $databaseInstance;
879 * Setter for compressor channel
881 * @param $compressorInstance An instance of CompressorChannel
884 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
885 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
889 * Getter for compressor channel
891 * @return $compressorInstance The compressor channel
893 public final function getCompressorChannel () {
894 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
895 return $compressorInstance;
899 * Protected getter for a manageable application helper class
901 * @return $applicationInstance An instance of a manageable application helper class
903 protected final function getApplicationInstance () {
904 $applicationInstance = Registry::getRegistry()->getInstance('application');
905 return $applicationInstance;
909 * Setter for a manageable application helper class
911 * @param $applicationInstance An instance of a manageable application helper class
914 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
915 Registry::getRegistry()->addInstance('application', $applicationInstance);
919 * Setter for request instance
921 * @param $requestInstance An instance of a Requestable class
924 public final function setRequestInstance (Requestable $requestInstance) {
925 $this->requestInstance = $requestInstance;
929 * Getter for request instance
931 * @return $requestInstance An instance of a Requestable class
933 public final function getRequestInstance () {
934 return $this->requestInstance;
938 * Setter for response instance
940 * @param $responseInstance An instance of a Responseable class
943 public final function setResponseInstance (Responseable $responseInstance) {
944 $this->responseInstance = $responseInstance;
948 * Getter for response instance
950 * @return $responseInstance An instance of a Responseable class
952 public final function getResponseInstance () {
953 return $this->responseInstance;
957 * Private getter for language instance
959 * @return $langInstance An instance to the language sub-system
961 protected final function getLanguageInstance () {
962 $langInstance = Registry::getRegistry()->getInstance('language');
963 return $langInstance;
967 * Setter for language instance
969 * @param $langInstance An instance to the language sub-system
971 * @see LanguageSystem
973 public final function setLanguageInstance (ManageableLanguage $langInstance) {
974 Registry::getRegistry()->addInstance('language', $langInstance);
978 * Private getter for file IO instance
980 * @return $fileIoInstance An instance to the file I/O sub-system
982 protected final function getFileIoInstance () {
983 return $this->fileIoInstance;
987 * Setter for file I/O instance
989 * @param $fileIoInstance An instance to the file I/O sub-system
992 public final function setFileIoInstance (IoHandler $fileIoInstance) {
993 $this->fileIoInstance = $fileIoInstance;
997 * Protected setter for user instance
999 * @param $userInstance An instance of a user class
1002 protected final function setUserInstance (ManageableAccount $userInstance) {
1003 $this->userInstance = $userInstance;
1007 * Getter for user instance
1009 * @return $userInstance An instance of a user class
1011 public final function getUserInstance () {
1012 return $this->userInstance;
1016 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1018 * @param $controllerInstance An instance of the controller
1021 public final function setControllerInstance (Controller $controllerInstance) {
1022 $this->controllerInstance = $controllerInstance;
1026 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1028 * @return $controllerInstance An instance of the controller
1030 public final function getControllerInstance () {
1031 return $this->controllerInstance;
1035 * Setter for RNG instance
1037 * @param $rngInstance An instance of a random number generator (RNG)
1040 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1041 $this->rngInstance = $rngInstance;
1045 * Getter for RNG instance
1047 * @return $rngInstance An instance of a random number generator (RNG)
1049 public final function getRngInstance () {
1050 return $this->rngInstance;
1054 * Setter for Cryptable instance
1056 * @param $cryptoInstance An instance of a Cryptable class
1059 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1060 $this->cryptoInstance = $cryptoInstance;
1064 * Getter for Cryptable instance
1066 * @return $cryptoInstance An instance of a Cryptable class
1068 public final function getCryptoInstance () {
1069 return $this->cryptoInstance;
1073 * Setter for the list instance
1075 * @param $listInstance A list of Listable
1078 protected final function setListInstance (Listable $listInstance) {
1079 $this->listInstance = $listInstance;
1083 * Getter for the list instance
1085 * @return $listInstance A list of Listable
1087 protected final function getListInstance () {
1088 return $this->listInstance;
1092 * Setter for the menu instance
1094 * @param $menuInstance A RenderableMenu instance
1097 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1098 $this->menuInstance = $menuInstance;
1102 * Getter for the menu instance
1104 * @return $menuInstance A RenderableMenu instance
1106 protected final function getMenuInstance () {
1107 return $this->menuInstance;
1111 * Setter for image instance
1113 * @param $imageInstance An instance of an image
1116 public final function setImageInstance (BaseImage $imageInstance) {
1117 $this->imageInstance = $imageInstance;
1121 * Getter for image instance
1123 * @return $imageInstance An instance of an image
1125 public final function getImageInstance () {
1126 return $this->imageInstance;
1130 * Setter for stacker instance
1132 * @param $stackInstance An instance of an stacker
1135 public final function setStackInstance (Stackable $stackInstance) {
1136 $this->stackInstance = $stackInstance;
1140 * Getter for stacker instance
1142 * @return $stackInstance An instance of an stacker
1144 public final function getStackInstance () {
1145 return $this->stackInstance;
1149 * Setter for compressor instance
1151 * @param $compressorInstance An instance of an compressor
1154 public final function setCompressorInstance (Compressor $compressorInstance) {
1155 $this->compressorInstance = $compressorInstance;
1159 * Getter for compressor instance
1161 * @return $compressorInstance An instance of an compressor
1163 public final function getCompressorInstance () {
1164 return $this->compressorInstance;
1168 * Setter for Parseable instance
1170 * @param $parserInstance An instance of an Parseable
1173 public final function setParserInstance (Parseable $parserInstance) {
1174 $this->parserInstance = $parserInstance;
1178 * Getter for Parseable instance
1180 * @return $parserInstance An instance of an Parseable
1182 public final function getParserInstance () {
1183 return $this->parserInstance;
1187 * Setter for HandleableProtocol instance
1189 * @param $protocolInstance An instance of an HandleableProtocol
1192 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1193 $this->protocolInstance = $protocolInstance;
1197 * Getter for HandleableProtocol instance
1199 * @return $protocolInstance An instance of an HandleableProtocol
1201 public final function getProtocolInstance () {
1202 return $this->protocolInstance;
1206 * Setter for DatabaseWrapper instance
1208 * @param $wrapperInstance An instance of an DatabaseWrapper
1211 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1212 $this->wrapperInstance = $wrapperInstance;
1216 * Getter for DatabaseWrapper instance
1218 * @return $wrapperInstance An instance of an DatabaseWrapper
1220 public final function getWrapperInstance () {
1221 return $this->wrapperInstance;
1225 * Setter for socket resource
1227 * @param $socketResource A valid socket resource
1230 public final function setSocketResource ($socketResource) {
1231 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1232 $this->socketResource = $socketResource;
1236 * Getter for socket resource
1238 * @return $socketResource A valid socket resource
1240 public final function getSocketResource () {
1241 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1242 return $this->socketResource;
1246 * Setter for regular expression
1248 * @param $regularExpression A valid regular expression
1251 public final function setRegularExpression ($regularExpression) {
1252 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1253 $this->regularExpression = $regularExpression;
1257 * Getter for regular expression
1259 * @return $regularExpression A valid regular expression
1261 public final function getRegularExpression () {
1262 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1263 return $this->regularExpression;
1267 * Setter for helper instance
1269 * @param $helperInstance An instance of a helper class
1272 protected final function setHelperInstance (Helper $helperInstance) {
1273 $this->helperInstance = $helperInstance;
1277 * Getter for helper instance
1279 * @return $helperInstance An instance of a helper class
1281 public final function getHelperInstance () {
1282 return $this->helperInstance;
1286 * Setter for a Source instance
1288 * @param $sourceInstance An instance of a Source class
1291 protected final function setSourceInstance (Source $sourceInstance) {
1292 $this->sourceInstance = $sourceInstance;
1296 * Getter for a Source instance
1298 * @return $sourceInstance An instance of a Source class
1300 protected final function getSourceInstance () {
1301 return $this->sourceInstance;
1305 * Setter for a UrlSource instance
1307 * @param $sourceInstance An instance of a UrlSource class
1310 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1311 $this->urlSourceInstance = $urlSourceInstance;
1315 * Getter for a UrlSource instance
1317 * @return $urlSourceInstance An instance of a UrlSource class
1319 protected final function getUrlSourceInstance () {
1320 return $this->urlSourceInstance;
1324 * Getter for a InputStream instance
1326 * @param $inputStreamInstance The InputStream instance
1328 protected final function getInputStreamInstance () {
1329 return $this->inputStreamInstance;
1333 * Setter for a InputStream instance
1335 * @param $inputStreamInstance The InputStream instance
1338 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1339 $this->inputStreamInstance = $inputStreamInstance;
1343 * Getter for a OutputStream instance
1345 * @param $outputStreamInstance The OutputStream instance
1347 protected final function getOutputStreamInstance () {
1348 return $this->outputStreamInstance;
1352 * Setter for a OutputStream instance
1354 * @param $outputStreamInstance The OutputStream instance
1357 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1358 $this->outputStreamInstance = $outputStreamInstance;
1362 * Setter for handler instance
1364 * @param $handlerInstance An instance of a Handleable class
1367 protected final function setHandlerInstance (Handleable $handlerInstance) {
1368 $this->handlerInstance = $handlerInstance;
1372 * Getter for handler instance
1374 * @return $handlerInstance A Networkable instance
1376 protected final function getHandlerInstance () {
1377 return $this->handlerInstance;
1381 * Setter for visitor instance
1383 * @param $visitorInstance A Visitor instance
1386 protected final function setVisitorInstance (Visitor $visitorInstance) {
1387 $this->visitorInstance = $visitorInstance;
1391 * Getter for visitor instance
1393 * @return $visitorInstance A Visitor instance
1395 protected final function getVisitorInstance () {
1396 return $this->visitorInstance;
1400 * Setter for DHT instance
1402 * @param $dhtInstance A Distributable instance
1405 protected final function setDhtInstance (Distributable $dhtInstance) {
1406 $this->dhtInstance = $dhtInstance;
1410 * Getter for DHT instance
1412 * @return $dhtInstance A Distributable instance
1414 protected final function getDhtInstance () {
1415 return $this->dhtInstance;
1419 * Setter for raw package Data
1421 * @param $packageData Raw package Data
1424 public final function setPackageData (array $packageData) {
1425 $this->packageData = $packageData;
1429 * Getter for raw package Data
1431 * @return $packageData Raw package Data
1433 public function getPackageData () {
1434 return $this->packageData;
1439 * Setter for Iterator instance
1441 * @param $iteratorInstance An instance of an Iterator
1444 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1445 $this->iteratorInstance = $iteratorInstance;
1449 * Getter for Iterator instance
1451 * @return $iteratorInstance An instance of an Iterator
1453 public final function getIteratorInstance () {
1454 return $this->iteratorInstance;
1458 * Setter for FilePointer instance
1460 * @param $pointerInstance An instance of an FilePointer class
1463 protected final function setPointerInstance (FilePointer $pointerInstance) {
1464 $this->pointerInstance = $pointerInstance;
1468 * Getter for FilePointer instance
1470 * @return $pointerInstance An instance of an FilePointer class
1472 public final function getPointerInstance () {
1473 return $this->pointerInstance;
1477 * Unsets pointer instance which triggers a call of __destruct() if the
1478 * instance is still there. This is surely not fatal on already "closed"
1479 * file pointer instances.
1481 * I don't want to mess around with above setter by giving it a default
1482 * value NULL as setter should always explicitly only set (existing) object
1483 * instances and NULL is NULL.
1487 protected final function unsetPointerInstance () {
1488 // Simply it to NULL
1489 $this->pointerInstance = NULL;
1493 * Setter for Indexable instance
1495 * @param $indexInstance An instance of an Indexable class
1498 protected final function setIndexInstance (Indexable $indexInstance) {
1499 $this->indexInstance = $indexInstance;
1503 * Getter for Indexable instance
1505 * @return $indexInstance An instance of an Indexable class
1507 public final function getIndexInstance () {
1508 return $this->indexInstance;
1512 * Setter for Block instance
1514 * @param $blockInstance An instance of an Block class
1517 protected final function setBlockInstance (Block $blockInstance) {
1518 $this->blockInstance = $blockInstance;
1522 * Getter for Block instance
1524 * @return $blockInstance An instance of an Block class
1526 public final function getBlockInstance () {
1527 return $this->blockInstance;
1531 * Setter for Minable instance
1533 * @param $minableInstance A Minable instance
1536 protected final function setMinableInstance (Minable $minableInstance) {
1537 $this->minableInstance = $minableInstance;
1541 * Getter for minable instance
1543 * @return $minableInstance A Minable instance
1545 protected final function getMinableInstance () {
1546 return $this->minableInstance;
1550 * Setter for FrameworkDirectory instance
1552 * @param $directoryInstance A FrameworkDirectory instance
1555 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1556 $this->directoryInstance = $directoryInstance;
1560 * Getter for FrameworkDirectory instance
1562 * @return $directoryInstance A FrameworkDirectory instance
1564 protected final function getDirectoryInstance () {
1565 return $this->directoryInstance;
1569 * Setter for listener instance
1571 * @param $listenerInstance A Listenable instance
1574 protected final function setListenerInstance (Listenable $listenerInstance) {
1575 $this->listenerInstance = $listenerInstance;
1579 * Getter for listener instance
1581 * @return $listenerInstance A Listenable instance
1583 protected final function getListenerInstance () {
1584 return $this->listenerInstance;
1588 * Getter for communicator instance
1590 * @return $communicatorInstance An instance of a Communicator class
1592 public final function getCommunicatorInstance () {
1593 return $this->communicatorInstance;
1597 * Setter for communicator instance
1599 * @param $communicatorInstance An instance of a Communicator class
1602 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1603 $this->communicatorInstance = $communicatorInstance;
1607 * Setter for state instance
1609 * @param $stateInstance A Stateable instance
1612 public final function setStateInstance (Stateable $stateInstance) {
1613 $this->stateInstance = $stateInstance;
1617 * Getter for state instance
1619 * @return $stateInstance A Stateable instance
1621 public final function getStateInstance () {
1622 return $this->stateInstance;
1626 * Setter for output instance
1628 * @param $outputInstance The debug output instance
1631 public final function setOutputInstance (OutputStreamer $outputInstance) {
1632 $this->outputInstance = $outputInstance;
1636 * Getter for output instance
1638 * @return $outputInstance The debug output instance
1640 public final function getOutputInstance () {
1641 return $this->outputInstance;
1645 * Setter for command name
1647 * @param $commandName Last validated command name
1650 protected final function setCommandName ($commandName) {
1651 $this->commandName = $commandName;
1655 * Getter for command name
1657 * @return $commandName Last validated command name
1659 protected final function getCommandName () {
1660 return $this->commandName;
1664 * Setter for controller name
1666 * @param $controllerName Last validated controller name
1669 protected final function setControllerName ($controllerName) {
1670 $this->controllerName = $controllerName;
1674 * Getter for controller name
1676 * @return $controllerName Last validated controller name
1678 protected final function getControllerName () {
1679 return $this->controllerName;
1683 * Getter for protocol name
1685 * @return $protocolName Name of used protocol
1687 public final function getProtocolName () {
1688 return $this->protocolName;
1692 * Setter for protocol name
1694 * @param $protocolName Name of used protocol
1697 protected final function setProtocolName ($protocolName) {
1698 $this->protocolName = $protocolName;
1702 * Checks whether an object equals this object. You should overwrite this
1703 * method to implement own equality checks
1705 * @param $objectInstance An instance of a FrameworkInterface object
1706 * @return $equals Whether both objects equals
1708 public function equals (FrameworkInterface $objectInstance) {
1711 $this->__toString() == $objectInstance->__toString()
1713 $this->hashCode() == $objectInstance->hashCode()
1716 // Return the result
1721 * Generates a generic hash code of this class. You should really overwrite
1722 * this method with your own hash code generator code. But keep KISS in mind.
1724 * @return $hashCode A generic hash code respresenting this whole class
1726 public function hashCode () {
1728 return crc32($this->__toString());
1732 * Formats computer generated price values into human-understandable formats
1733 * with thousand and decimal separators.
1735 * @param $value The in computer format value for a price
1736 * @param $currency The currency symbol (use HTML-valid characters!)
1737 * @param $decNum Number of decimals after commata
1738 * @return $price The for the current language formated price string
1739 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1740 * thousands separator
1743 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1744 // Are all required attriutes set?
1745 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1746 // Throw an exception
1747 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1751 $value = (float) $value;
1753 // Reformat the US number
1754 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1756 // Return as string...
1761 * Appends a trailing slash to a string
1763 * @param $str A string (maybe) without trailing slash
1764 * @return $str A string with an auto-appended trailing slash
1766 public final function addMissingTrailingSlash ($str) {
1767 // Is there a trailing slash?
1768 if (substr($str, -1, 1) != '/') {
1772 // Return string with trailing slash
1777 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1778 * application helper instance (ApplicationHelper by default).
1780 * @param $applicationInstance An application helper instance or
1781 * null if we shall use the default
1782 * @return $templateInstance The template engine instance
1783 * @throws NullPointerException If the discovered application
1784 * instance is still null
1786 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1787 // Is the application instance set?
1788 if (is_null($applicationInstance)) {
1789 // Get the current instance
1790 $applicationInstance = $this->getApplicationInstance();
1793 if (is_null($applicationInstance)) {
1794 // Thrown an exception
1795 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1799 // Initialize the template engine
1800 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1802 // Return the prepared instance
1803 return $templateInstance;
1807 * Debugs this instance by putting out it's full content
1809 * @param $message Optional message to show in debug output
1812 public final function debugInstance ($message = '') {
1813 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1814 restore_error_handler();
1819 // Is a message set?
1820 if (!empty($message)) {
1821 // Construct message
1822 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1825 // Generate the output
1826 $content .= sprintf('<pre>%s</pre>',
1829 print_r($this, TRUE)
1835 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>',
1836 $this->__toString(),
1838 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1843 * Replaces control characters with printable output
1845 * @param $str String with control characters
1846 * @return $str Replaced string
1848 protected function replaceControlCharacters ($str) {
1851 chr(13), '[r]', str_replace(
1852 chr(10), '[n]', str_replace(
1862 * Output a partial stub message for the caller method
1864 * @param $message An optional message to display
1867 protected function partialStub ($message = '') {
1868 // Get the backtrace
1869 $backtrace = debug_backtrace();
1871 // Generate the class::method string
1872 $methodName = 'UnknownClass->unknownMethod';
1873 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1874 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1877 // Construct the full message
1878 $stubMessage = sprintf('[%s:] Partial stub!',
1882 // Is the extra message given?
1883 if (!empty($message)) {
1884 // Then add it as well
1885 $stubMessage .= ' Message: ' . $message;
1888 // Debug instance is there?
1889 if (!is_null($this->getDebugInstance())) {
1890 // Output stub message
1891 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1894 trigger_error($stubMessage);
1900 * Outputs a debug backtrace and stops further script execution
1902 * @param $message An optional message to output
1903 * @param $doExit Whether exit the program (TRUE is default)
1906 public function debugBackTrace ($message = '', $doExit = TRUE) {
1907 // Sorry, there is no other way getting this nice backtrace
1908 if (!empty($message)) {
1910 printf('Message: %s<br />' . PHP_EOL, $message);
1914 debug_print_backtrace();
1918 if ($doExit === TRUE) {
1924 * Creates an instance of a debugger instance
1926 * @param $className Name of the class (currently unsupported)
1927 * @param $lineNumber Line number where the call was made
1928 * @return $debugInstance An instance of a debugger class
1929 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1931 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1932 // Is the instance set?
1933 if (!Registry::getRegistry()->instanceExists('debug')) {
1934 // Init debug instance
1935 $debugInstance = NULL;
1939 // Get a debugger instance
1940 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1941 } catch (NullPointerException $e) {
1942 // Didn't work, no instance there
1943 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1946 // Empty string should be ignored and used for testing the middleware
1947 DebugMiddleware::getSelfInstance()->output('');
1949 // Set it in its own class. This will set it in the registry
1950 $debugInstance->setDebugInstance($debugInstance);
1952 // Get instance from registry
1953 $debugInstance = Registry::getRegistry()->getDebugInstance();
1957 return $debugInstance;
1961 * Simple output of a message with line-break
1963 * @param $message Message to output
1966 public function outputLine ($message) {
1968 print($message . PHP_EOL);
1972 * Outputs a debug message whether to debug instance (should be set!) or
1973 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1974 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1976 * @param $message Message we shall send out...
1977 * @param $doPrint Whether print or die here (default: print)
1978 * @paran $stripTags Whether to strip tags (default: FALSE)
1981 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1982 // Set debug instance to NULL
1983 $debugInstance = NULL;
1987 // Get debug instance
1988 $debugInstance = $this->getDebugInstance();
1989 } catch (NullPointerException $e) {
1990 // The debug instance is not set (yet)
1993 // Is the debug instance there?
1994 if (is_object($debugInstance)) {
1995 // Use debug output handler
1996 $debugInstance->output($message, $stripTags);
1998 if ($doPrint === FALSE) {
1999 // Die here if not printed
2003 // Are debug times enabled?
2004 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
2006 $message = $this->getPrintableExecutionTime() . $message;
2010 if ($doPrint === TRUE) {
2012 $this->outputLine($message);
2021 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2023 * @param $str The string, what ever it is needs to be converted
2024 * @return $className Generated class name
2026 public static final function convertToClassName ($str) {
2030 // Convert all dashes in underscores
2031 $str = self::convertDashesToUnderscores($str);
2033 // Now use that underscores to get classname parts for hungarian style
2034 foreach (explode('_', $str) as $strPart) {
2035 // Make the class name part lower case and first upper case
2036 $className .= ucfirst(strtolower($strPart));
2039 // Return class name
2044 * Converts dashes to underscores, e.g. useable for configuration entries
2046 * @param $str The string with maybe dashes inside
2047 * @return $str The converted string with no dashed, but underscores
2049 public static final function convertDashesToUnderscores ($str) {
2051 $str = str_replace('-', '_', $str);
2053 // Return converted string
2058 * Marks up the code by adding e.g. line numbers
2060 * @param $phpCode Unmarked PHP code
2061 * @return $markedCode Marked PHP code
2063 public function markupCode ($phpCode) {
2068 $errorArray = error_get_last();
2070 // Init the code with error message
2071 if (is_array($errorArray)) {
2073 $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>',
2074 basename($errorArray['file']),
2075 $errorArray['line'],
2076 $errorArray['message'],
2081 // Add line number to the code
2082 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2084 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2086 htmlentities($code, ENT_QUOTES)
2095 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2096 * beatiful for web-based front-ends. If null is given a message id
2097 * null_timestamp will be resolved and returned.
2099 * @param $timestamp Timestamp to prepare (filter) for display
2100 * @return $readable A readable timestamp
2102 public function doFilterFormatTimestamp ($timestamp) {
2103 // Default value to return
2106 // Is the timestamp null?
2107 if (is_null($timestamp)) {
2108 // Get a message string
2109 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2111 switch ($this->getLanguageInstance()->getLanguageCode()) {
2112 case 'de': // German format is a bit different to default
2113 // Split the GMT stamp up
2114 $dateTime = explode(' ', $timestamp );
2115 $dateArray = explode('-', $dateTime[0]);
2116 $timeArray = explode(':', $dateTime[1]);
2118 // Construct the timestamp
2119 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2129 default: // Default is pass-through
2130 $readable = $timestamp;
2140 * Filter a given number into a localized number
2142 * @param $value The raw value from e.g. database
2143 * @return $localized Localized value
2145 public function doFilterFormatNumber ($value) {
2146 // Generate it from config and localize dependencies
2147 switch ($this->getLanguageInstance()->getLanguageCode()) {
2148 case 'de': // German format is a bit different to default
2149 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2152 default: // US, etc.
2153 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2162 * "Getter" for databse entry
2164 * @return $entry An array with database entries
2165 * @throws NullPointerException If the database result is not found
2166 * @throws InvalidDatabaseResultException If the database result is invalid
2168 protected final function getDatabaseEntry () {
2169 // Is there an instance?
2170 if (!$this->getResultInstance() instanceof SearchableResult) {
2171 // Throw an exception here
2172 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2176 $this->getResultInstance()->rewind();
2178 // Do we have an entry?
2179 if ($this->getResultInstance()->valid() === FALSE) {
2180 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2181 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2185 $this->getResultInstance()->next();
2188 $entry = $this->getResultInstance()->current();
2195 * Getter for field name
2197 * @param $fieldName Field name which we shall get
2198 * @return $fieldValue Field value from the user
2199 * @throws NullPointerException If the result instance is null
2201 public final function getField ($fieldName) {
2202 // Default field value
2205 // Get result instance
2206 $resultInstance = $this->getResultInstance();
2208 // Is this instance null?
2209 if (is_null($resultInstance)) {
2210 // Then the user instance is no longer valid (expired cookies?)
2211 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2214 // Get current array
2215 $fieldArray = $resultInstance->current();
2216 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2218 // Convert dashes to underscore
2219 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2221 // Does the field exist?
2222 if ($this->isFieldSet($fieldName)) {
2224 $fieldValue = $fieldArray[$fieldName2];
2225 } elseif (defined('DEVELOPER')) {
2226 // Missing field entry, may require debugging
2227 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2229 // Missing field entry, may require debugging
2230 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2238 * Checks if given field is set
2240 * @param $fieldName Field name to check
2241 * @return $isSet Whether the given field name is set
2242 * @throws NullPointerException If the result instance is null
2244 public function isFieldSet ($fieldName) {
2245 // Get result instance
2246 $resultInstance = $this->getResultInstance();
2248 // Is this instance null?
2249 if (is_null($resultInstance)) {
2250 // Then the user instance is no longer valid (expired cookies?)
2251 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2254 // Get current array
2255 $fieldArray = $resultInstance->current();
2256 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2258 // Convert dashes to underscore
2259 $fieldName = self::convertDashesToUnderscores($fieldName);
2262 $isSet = isset($fieldArray[$fieldName]);
2269 * Flushs all pending updates to the database layer
2273 public function flushPendingUpdates () {
2274 // Get result instance
2275 $resultInstance = $this->getResultInstance();
2277 // Do we have data to update?
2278 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2279 // Get wrapper class name config entry
2280 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2282 // Create object instance
2283 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2285 // Yes, then send the whole result to the database layer
2286 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2291 * Outputs a deprecation warning to the developer.
2293 * @param $message The message we shall output to the developer
2295 * @todo Write a logging mechanism for productive mode
2297 public function deprecationWarning ($message) {
2298 // Is developer mode active?
2299 if (defined('DEVELOPER')) {
2300 // Debug instance is there?
2301 if (!is_null($this->getDebugInstance())) {
2302 // Output stub message
2303 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2306 trigger_error($message . "<br />\n");
2310 // @TODO Finish this part!
2311 $this->partialStub('Developer mode inactive. Message:' . $message);
2316 * Checks whether the given PHP extension is loaded
2318 * @param $phpExtension The PHP extension we shall check
2319 * @return $isLoaded Whether the PHP extension is loaded
2321 public final function isPhpExtensionLoaded ($phpExtension) {
2323 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2330 * "Getter" as a time() replacement but with milliseconds. You should use this
2331 * method instead of the encapsulated getimeofday() function.
2333 * @return $milliTime Timestamp with milliseconds
2335 public function getMilliTime () {
2336 // Get the time of day as float
2337 $milliTime = gettimeofday(TRUE);
2344 * Idles (sleeps) for given milliseconds
2346 * @return $hasSlept Whether it goes fine
2348 public function idle ($milliSeconds) {
2349 // Sleep is fine by default
2352 // Idle so long with found function
2353 if (function_exists('time_sleep_until')) {
2354 // Get current time and add idle time
2355 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2357 // New PHP 5.1.0 function found, ignore errors
2358 $hasSlept = @time_sleep_until($sleepUntil);
2361 * My Sun station doesn't have that function even with latest PHP
2364 usleep($milliSeconds * 1000);
2371 * Converts a hexadecimal string, even with negative sign as first string to
2372 * a decimal number using BC functions.
2374 * This work is based on comment #86673 on php.net documentation page at:
2375 * <http://de.php.net/manual/en/function.dechex.php#86673>
2377 * @param $hex Hexadecimal string
2378 * @return $dec Decimal number
2380 protected function hex2dec ($hex) {
2381 // Convert to all lower-case
2382 $hex = strtolower($hex);
2384 // Detect sign (negative/positive numbers)
2386 if (substr($hex, 0, 1) == '-') {
2388 $hex = substr($hex, 1);
2391 // Decode the hexadecimal string into a decimal number
2393 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2394 $factor = self::$hexdec[substr($hex, $i, 1)];
2395 $dec = bcadd($dec, bcmul($factor, $e));
2398 // Return the decimal number
2399 return $sign . $dec;
2403 * Converts even very large decimal numbers, also signed, to a hexadecimal
2406 * This work is based on comment #97756 on php.net documentation page at:
2407 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2409 * @param $dec Decimal number, even with negative sign
2410 * @param $maxLength Optional maximum length of the string
2411 * @return $hex Hexadecimal string
2413 protected function dec2hex ($dec, $maxLength = 0) {
2414 // maxLength can be zero or devideable by 2
2415 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2417 // Detect sign (negative/positive numbers)
2424 // Encode the decimal number into a hexadecimal string
2427 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2429 } while ($dec >= 1);
2432 * Leading zeros are required for hex-decimal "numbers". In some
2433 * situations more leading zeros are wanted, so check for both
2436 if ($maxLength > 0) {
2437 // Prepend more zeros
2438 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2439 } elseif ((strlen($hex) % 2) != 0) {
2440 // Only make string's length dividable by 2
2444 // Return the hexadecimal string
2445 return $sign . $hex;
2449 * Converts a ASCII string (0 to 255) into a decimal number.
2451 * @param $asc The ASCII string to be converted
2452 * @return $dec Decimal number
2454 protected function asc2dec ($asc) {
2455 // Convert it into a hexadecimal number
2456 $hex = bin2hex($asc);
2458 // And back into a decimal number
2459 $dec = $this->hex2dec($hex);
2466 * Converts a decimal number into an ASCII string.
2468 * @param $dec Decimal number
2469 * @return $asc An ASCII string
2471 protected function dec2asc ($dec) {
2472 // First convert the number into a hexadecimal string
2473 $hex = $this->dec2hex($dec);
2475 // Then convert it into the ASCII string
2476 $asc = $this->hex2asc($hex);
2483 * Converts a hexadecimal number into an ASCII string. Negative numbers
2486 * @param $hex Hexadecimal string
2487 * @return $asc An ASCII string
2489 protected function hex2asc ($hex) {
2490 // Check for length, it must be devideable by 2
2491 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2492 assert((strlen($hex) % 2) == 0);
2496 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2497 // Get the decimal number of the chunk
2498 $part = hexdec(substr($hex, $idx, 2));
2500 // Add it to the final string
2504 // Return the final string
2509 * Checks whether the given encoded data was encoded with Base64
2511 * @param $encodedData Encoded data we shall check
2512 * @return $isBase64 Whether the encoded data is Base64
2514 protected function isBase64Encoded ($encodedData) {
2516 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2523 * "Getter" to get response/request type from analysis of the system.
2525 * @return $responseType Analyzed response type
2527 protected static function getResponseTypeFromSystem () {
2528 // Default is console
2529 $responseType = 'console';
2531 // Is 'HTTP_HOST' set?
2532 if (isset($_SERVER['HTTP_HOST'])) {
2534 * Then it is a HTML response/request as RSS and so on may be
2535 * transfered over HTTP as well.
2537 $responseType = 'html';
2541 return $responseType;
2545 * Gets a cache key from Criteria instance
2547 * @param $criteriaInstance An instance of a Criteria class
2548 * @param $onlyKeys Only use these keys for a cache key
2549 * @return $cacheKey A cache key suitable for lookup/storage purposes
2551 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2553 $cacheKey = sprintf('%s@%s',
2554 $this->__toString(),
2555 $criteriaInstance->getCacheKey($onlyKeys)
2559 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2564 * Getter for startup time in miliseconds
2566 * @return $startupTime Startup time in miliseconds
2568 protected function getStartupTime () {
2569 return self::$startupTime;
2573 * "Getter" for a printable currently execution time in nice braces
2575 * @return $executionTime Current execution time in nice braces
2577 protected function getPrintableExecutionTime () {
2578 // Caculate the execution time
2579 $executionTime = microtime(TRUE) - $this->getStartupTime();
2581 // Pack it in nice braces
2582 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2585 return $executionTime;
2589 * Hashes a given string with a simple but stronger hash function (no salt)
2590 * and hex-encode it.
2592 * @param $str The string to be hashed
2593 * @return $hash The hash from string $str
2595 public static final function hash ($str) {
2596 // Hash given string with (better secure) hasher
2597 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2604 * "Getter" for length of hash() output. This will be "cached" to speed up
2607 * @return $length Length of hash() output
2609 public static final function getHashLength () {
2611 if (is_null(self::$hashLength)) {
2612 // No, then hash a string and save its length.
2613 self::$hashLength = strlen(self::hash('abc123'));
2617 return self::$hashLength;
2621 * Checks whether the given number is really a number (only chars 0-9).
2623 * @param $num A string consisting only chars between 0 and 9
2624 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2625 * @param $assertMismatch Whether to assert mismatches
2626 * @return $ret The (hopefully) secured numbered value
2628 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2629 // Filter all numbers out
2630 $ret = preg_replace('/[^0123456789]/', '', $num);
2633 if ($castValue === TRUE) {
2634 // Cast to biggest numeric type
2635 $ret = (double) $ret;
2638 // Assert only if requested
2639 if ($assertMismatch === TRUE) {
2640 // Has the whole value changed?
2641 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2649 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2651 * @param $num A string consisting only chars between 0 and 9
2652 * @param $assertMismatch Whether to assert mismatches
2653 * @return $ret The (hopefully) secured hext-numbered value
2655 public function hexval ($num, $assertMismatch = FALSE) {
2656 // Filter all numbers out
2657 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2659 // Assert only if requested
2660 if ($assertMismatch === TRUE) {
2661 // Has the whole value changed?
2662 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2670 * Checks whether start/end marker are set
2672 * @param $data Data to be checked
2673 * @return $isset Whether start/end marker are set
2675 public final function ifStartEndMarkersSet ($data) {
2677 $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));
2679 // ... and return it
2684 * Determines if an element is set in the generic array
2686 * @param $keyGroup Main group for the key
2687 * @param $subGroup Sub group for the key
2688 * @param $key Key to check
2689 * @param $element Element to check
2690 * @return $isset Whether the given key is set
2692 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2694 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2697 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2703 * Determines if a key is set in the generic array
2705 * @param $keyGroup Main group for the key
2706 * @param $subGroup Sub group for the key
2707 * @param $key Key to check
2708 * @return $isset Whether the given key is set
2710 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2712 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2715 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2723 * Determines if a group is set in the generic array
2725 * @param $keyGroup Main group
2726 * @param $subGroup Sub group
2727 * @return $isset Whether the given group is set
2729 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2731 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2734 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2741 * Getter for sub key group
2743 * @param $keyGroup Main key group
2744 * @param $subGroup Sub key group
2745 * @return $array An array with all array elements
2747 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2749 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2750 // No, then abort here
2751 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2756 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2759 return $this->genericArray[$keyGroup][$subGroup];
2763 * Unsets a given key in generic array
2765 * @param $keyGroup Main group for the key
2766 * @param $subGroup Sub group for the key
2767 * @param $key Key to unset
2770 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2772 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2775 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2779 * Unsets a given element in generic array
2781 * @param $keyGroup Main group for the key
2782 * @param $subGroup Sub group for the key
2783 * @param $key Key to unset
2784 * @param $element Element to unset
2787 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2789 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2792 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2796 * Append a string to a given generic array key
2798 * @param $keyGroup Main group for the key
2799 * @param $subGroup Sub group for the key
2800 * @param $key Key to unset
2801 * @param $value Value to add/append
2804 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2806 //* 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);
2808 // Is it already there?
2809 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2811 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2814 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2819 * Append a string to a given generic array element
2821 * @param $keyGroup Main group for the key
2822 * @param $subGroup Sub group for the key
2823 * @param $key Key to unset
2824 * @param $element Element to check
2825 * @param $value Value to add/append
2828 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2830 //* 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);
2832 // Is it already there?
2833 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2835 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2838 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2843 * Sets a string in a given generic array element
2845 * @param $keyGroup Main group for the key
2846 * @param $subGroup Sub group for the key
2847 * @param $key Key to unset
2848 * @param $element Element to check
2849 * @param $value Value to add/append
2852 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2854 //* 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);
2857 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2861 * Initializes given generic array group
2863 * @param $keyGroup Main group for the key
2864 * @param $subGroup Sub group for the key
2865 * @param $key Key to use
2866 * @param $forceInit Optionally force initialization
2869 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2871 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2873 // Is it already set?
2874 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2875 // Already initialized
2876 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2881 $this->genericArray[$keyGroup][$subGroup] = array();
2885 * Initializes given generic array key
2887 * @param $keyGroup Main group for the key
2888 * @param $subGroup Sub group for the key
2889 * @param $key Key to use
2890 * @param $forceInit Optionally force initialization
2893 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2895 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2897 // Is it already set?
2898 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2899 // Already initialized
2900 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2905 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2909 * Initializes given generic array element
2911 * @param $keyGroup Main group for the key
2912 * @param $subGroup Sub group for the key
2913 * @param $key Key to use
2914 * @param $element Element to use
2915 * @param $forceInit Optionally force initialization
2918 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2920 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2922 // Is it already set?
2923 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2924 // Already initialized
2925 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2930 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2934 * Pushes an element to a generic key
2936 * @param $keyGroup Main group for the key
2937 * @param $subGroup Sub group for the key
2938 * @param $key Key to use
2939 * @param $value Value to add/append
2940 * @return $count Number of array elements
2942 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2944 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2947 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2949 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2953 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2956 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2957 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2962 * Pushes an element to a generic array element
2964 * @param $keyGroup Main group for the key
2965 * @param $subGroup Sub group for the key
2966 * @param $key Key to use
2967 * @param $element Element to check
2968 * @param $value Value to add/append
2969 * @return $count Number of array elements
2971 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2973 //* 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));
2976 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2978 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2982 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2985 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2986 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2991 * Pops an element from a generic group
2993 * @param $keyGroup Main group for the key
2994 * @param $subGroup Sub group for the key
2995 * @param $key Key to unset
2996 * @return $value Last "popped" value
2998 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
3000 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3003 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3005 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3010 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3013 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3014 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3019 * Shifts an element from a generic group
3021 * @param $keyGroup Main group for the key
3022 * @param $subGroup Sub group for the key
3023 * @param $key Key to unset
3024 * @return $value Last "popped" value
3026 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3028 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3031 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3033 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3038 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3041 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3042 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3047 * Count generic array group
3049 * @param $keyGroup Main group for the key
3050 * @return $count Count of given group
3052 protected final function countGenericArray ($keyGroup) {
3054 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3057 if (!isset($this->genericArray[$keyGroup])) {
3059 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3064 $count = count($this->genericArray[$keyGroup]);
3067 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3074 * Count generic array sub group
3076 * @param $keyGroup Main group for the key
3077 * @param $subGroup Sub group for the key
3078 * @return $count Count of given group
3080 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3082 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3085 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3087 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3092 $count = count($this->genericArray[$keyGroup][$subGroup]);
3095 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3102 * Count generic array elements
3104 * @param $keyGroup Main group for the key
3105 * @param $subGroup Sub group for the key
3106 * @para $key Key to count
3107 * @return $count Count of given key
3109 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3111 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3114 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3116 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3118 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3120 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3125 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3128 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3135 * Getter for whole generic group array
3137 * @param $keyGroup Key group to get
3138 * @return $array Whole generic array group
3140 protected final function getGenericArray ($keyGroup) {
3142 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3145 if (!isset($this->genericArray[$keyGroup])) {
3147 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3152 return $this->genericArray[$keyGroup];
3156 * Setter for generic array key
3158 * @param $keyGroup Key group to get
3159 * @param $subGroup Sub group for the key
3160 * @param $key Key to unset
3161 * @param $value Mixed value from generic array element
3164 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3166 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3169 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3173 * Getter for generic array key
3175 * @param $keyGroup Key group to get
3176 * @param $subGroup Sub group for the key
3177 * @param $key Key to unset
3178 * @return $value Mixed value from generic array element
3180 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3182 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3185 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3187 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3192 return $this->genericArray[$keyGroup][$subGroup][$key];
3196 * Sets a value in given generic array key/element
3198 * @param $keyGroup Main group for the key
3199 * @param $subGroup Sub group for the key
3200 * @param $key Key to set
3201 * @param $element Element to set
3202 * @param $value Value to set
3205 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3207 //* 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));
3210 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3214 * Getter for generic array element
3216 * @param $keyGroup Key group to get
3217 * @param $subGroup Sub group for the key
3218 * @param $key Key to look for
3219 * @param $element Element to look for
3220 * @return $value Mixed value from generic array element
3222 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3224 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3227 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3229 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3234 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3238 * Checks if a given sub group is valid (array)
3240 * @param $keyGroup Key group to get
3241 * @param $subGroup Sub group for the key
3242 * @return $isValid Whether given sub group is valid
3244 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3246 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3249 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3256 * Checks if a given key is valid (array)
3258 * @param $keyGroup Key group to get
3259 * @param $subGroup Sub group for the key
3260 * @param $key Key to check
3261 * @return $isValid Whether given sub group is valid
3263 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3265 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3268 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3275 * Initializes the web output instance
3279 protected function initWebOutputInstance () {
3280 // Get application instance
3281 $applicationInstance = Registry::getRegistry()->getInstance('app');
3283 // Is this a response instance?
3284 if ($this instanceof Responseable) {
3285 // Then set it in application instance
3286 $applicationInstance->setResponseInstance($this);
3289 // Init web output instance
3290 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3293 $this->setWebOutputInstance($outputInstance);
3297 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3299 * @param $boolean Boolean value
3300 * @return $translated Translated boolean value
3302 public static final function translateBooleanToYesNo ($boolean) {
3303 // Make sure it is really boolean
3304 assert(is_bool($boolean));
3307 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3309 // ... and return it
3314 * Encodes raw data (almost any type) by "serializing" it and then pack it
3315 * into a "binary format".
3317 * @param $rawData Raw data (almost any type)
3318 * @return $encoded Encoded data
3320 protected function encodeData ($rawData) {
3321 // Make sure no objects or resources pass through
3322 assert(!is_object($rawData));
3323 assert(!is_resource($rawData));
3325 // First "serialize" it (json_encode() is faster than serialize())
3326 $encoded = $this->packString(json_encode($rawData));
3333 * Pack a string into a "binary format". Please execuse me that this is
3334 * widely undocumented. :-(
3336 * @param $str Unpacked string
3337 * @return $packed Packed string
3338 * @todo Improve documentation
3340 protected function packString ($str) {
3342 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3344 // First compress the string (gzcompress is okay)
3345 $str = gzcompress($str);
3350 // And start the "encoding" loop
3351 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3353 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3354 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3356 if (($idx + $i) <= strlen($str)) {
3357 $ord = ord(substr($str, ($idx + $i), 1));
3359 $add = $ord * pow(256, $factor);
3363 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3367 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3368 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3370 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3371 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3377 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3382 * Checks whether the given file/path is in open_basedir(). This does not
3383 * gurantee that the file is actually readable and/or writeable. If you need
3384 * such gurantee then please use isReadableFile() instead.
3386 * @param $filePathName Name of the file/path to be checked
3387 * @return $isReachable Whether it is within open_basedir()
3389 protected static function isReachableFilePath ($filePathName) {
3390 // Is not reachable by default
3391 $isReachable = FALSE;
3393 // Get open_basedir parameter
3394 $openBaseDir = ini_get('open_basedir');
3397 if (!empty($openBaseDir)) {
3398 // Check all entries
3399 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3400 // Check on existence
3401 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3403 $isReachable = TRUE;
3407 // If open_basedir is not set, all is allowed
3408 $isReachable = TRUE;
3412 return $isReachable;
3416 * Checks whether the give file is within open_basedir() (done by
3417 * isReachableFilePath()), is actually a file and is readable.
3419 * @param $fileName Name of the file to be checked
3420 * @return $isReadable Whether the file is readable (and therefor exists)
3422 public static function isReadableFile ($fileName) {
3423 // Default is not readable
3424 $isReadable = FALSE;
3426 // Is within parameters, so check if it is a file and readable
3427 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3434 * Creates a full-qualified file name (FQFN) for given file name by adding
3435 * a configured temporary file path to it.
3437 * @param $fileName Name for temporary file
3438 * @return $fqfn Full-qualified file name
3439 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3440 * @throws FileIoException If the file cannot be written
3442 protected static function createTempPathForFile ($fileName) {
3444 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3446 // Is the path writeable?
3447 if (!is_writable($basePath)) {
3448 // Path is write-protected
3449 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3453 $fqfn = $basePath . '/' . $fileName;
3456 if (!self::isReachableFilePath($fqfn)) {
3458 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3466 * "Getter" for a printable state name
3468 * @return $stateName Name of the node's state in a printable format
3470 public final function getPrintableState () {
3471 // Default is 'null'
3472 $stateName = 'null';
3474 // Get the state instance
3475 $stateInstance = $this->getStateInstance();
3477 // Is it an instance of Stateable?
3478 if ($stateInstance instanceof Stateable) {
3479 // Then use that state name
3480 $stateName = $stateInstance->getStateName();
3488 * Handles socket error for given socket resource and peer data. This method
3489 * validates $socketResource if it is a valid resource (see is_resource())
3490 * but assumes valid data in array $recipientData, except that
3491 * count($recipientData) is always 2.
3493 * @param $method Value of __METHOD__ from calling method
3494 * @param $line Value of __LINE__ from calling method
3495 * @param $socketResource A valid socket resource
3496 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3498 * @throws InvalidSocketException If $socketResource is no socket resource
3499 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3500 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3502 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3503 // This method handles only socket resources
3504 if (!is_resource($socketResource)) {
3505 // No resource, abort here
3506 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3509 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3510 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3511 assert(isset($socketData[0]));
3512 assert(isset($socketData[1]));
3514 // Get error code for first validation (0 is not an error)
3515 $errorCode = socket_last_error($socketResource);
3517 // If the error code is zero, someone called this method without an error
3518 if ($errorCode == 0) {
3519 // No error detected (or previously cleared outside this method)
3520 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3523 // Get handler (method) name
3524 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3526 // Call-back the error handler method
3527 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3529 // Finally clear the error because it has been handled
3530 socket_clear_error($socketResource);