3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Generic\FrameworkInterface;
9 use CoreFramework\Generic\NullPointerException;
10 use CoreFramework\Loader\ClassLoader;
11 use CoreFramework\Manager\ManageableApplication;
12 use CoreFramework\Middleware\Debug\DebugMiddleware;
13 use CoreFramework\Registry\Register;
14 use CoreFramework\Registry\Generic\Registry;
15 use CoreFramework\Stream\Output\OutputStreamer;
16 use CoreFramework\Template\CompileableTemplate;
22 * The simulator system class is the super class of all other classes. This
23 * class handles saving of games etc.
25 * @author Roland Haeder <webmaster@shipsimu.org>
27 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
28 * @license GNU GPL 3.0 or any newer version
29 * @link http://www.shipsimu.org
31 * This program is free software: you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation, either version 3 of the License, or
34 * (at your option) any later version.
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
41 * You should have received a copy of the GNU General Public License
42 * along with this program. If not, see <http://www.gnu.org/licenses/>.
44 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
46 * Length of output from hash()
48 private static $hashLength = NULL;
53 private $realClass = 'BaseFrameworkSystem';
56 * Instance of a request class
58 private $requestInstance = NULL;
61 * Instance of a response class
63 private $responseInstance = NULL;
66 * Search criteria instance
68 private $searchInstance = NULL;
71 * Update criteria instance
73 private $updateInstance = NULL;
76 * The file I/O instance for the template loader
78 private $fileIoInstance = NULL;
83 private $resolverInstance = NULL;
86 * Template engine instance
88 private $templateInstance = NULL;
91 * Database result instance
93 private $resultInstance = NULL;
96 * Instance for user class
98 private $userInstance = NULL;
101 * A controller instance
103 private $controllerInstance = NULL;
108 private $rngInstance = NULL;
111 * Instance of a crypto helper
113 private $cryptoInstance = NULL;
116 * Instance of an Iterator class
118 private $iteratorInstance = NULL;
121 * Instance of the list
123 private $listInstance = NULL;
128 private $menuInstance = NULL;
131 * Instance of the image
133 private $imageInstance = NULL;
136 * Instance of the stacker
138 private $stackInstance = NULL;
141 * A Compressor instance
143 private $compressorInstance = NULL;
146 * A Parseable instance
148 private $parserInstance = NULL;
151 * A HandleableProtocol instance
153 private $protocolInstance = NULL;
156 * A database wrapper instance
158 private $databaseInstance = NULL;
161 * A helper instance for the form
163 private $helperInstance = NULL;
166 * An instance of a Source class
168 private $sourceInstance = NULL;
171 * An instance of a UrlSource class
173 private $urlSourceInstance = NULL;
176 * An instance of a InputStream class
178 private $inputStreamInstance = NULL;
181 * An instance of a OutputStream class
183 private $outputStreamInstance = NULL;
186 * Networkable handler instance
188 private $handlerInstance = NULL;
191 * Visitor handler instance
193 private $visitorInstance = NULL;
198 private $dhtInstance = NULL;
201 * An instance of a database wrapper class
203 private $wrapperInstance = NULL;
206 * An instance of a file I/O pointer class (not handler)
208 private $pointerInstance = NULL;
211 * An instance of an Indexable class
213 private $indexInstance = NULL;
216 * An instance of a Block class
218 private $blockInstance = NULL;
223 private $minableInstance = NULL;
226 * A FrameworkDirectory instance
228 private $directoryInstance = NULL;
233 private $listenerInstance = NULL;
236 * An instance of a communicator
238 private $communicatorInstance = NULL;
241 * The concrete output instance
243 private $outputInstance = NULL;
248 private $stateInstance = NULL;
251 * Thousands separator
253 private $thousands = '.'; // German
258 private $decimals = ','; // German
263 private $socketResource = FALSE;
266 * Regular expression to use for validation
268 private $regularExpression = '';
273 private $packageData = array();
278 private $genericArray = array();
283 private $commandName = '';
288 private $controllerName = '';
291 * Name of used protocol
293 private $protocolName = 'invalid';
296 * Array with bitmasks and such for pack/unpack methods to support both
297 * 32-bit and 64-bit systems
299 private $packingData = array(
302 'left' => 0xffff0000,
303 'right' => 0x0000ffff,
309 'left' => 0xffffffff00000000,
310 'right' => 0x00000000ffffffff,
317 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
319 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
321 private $archArrayElement = FALSE;
323 /***********************
324 * Exception codes.... *
325 ***********************/
327 // @todo Try to clean these constants up
328 const EXCEPTION_IS_NULL_POINTER = 0x001;
329 const EXCEPTION_IS_NO_OBJECT = 0x002;
330 const EXCEPTION_IS_NO_ARRAY = 0x003;
331 const EXCEPTION_MISSING_METHOD = 0x004;
332 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
333 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
334 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
335 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
336 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
337 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
338 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
339 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
340 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
341 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
342 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
343 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
344 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
345 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
346 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
347 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
348 const EXCEPTION_PATH_NOT_FOUND = 0x015;
349 const EXCEPTION_INVALID_PATH_NAME = 0x016;
350 const EXCEPTION_READ_PROTECED_PATH = 0x017;
351 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
352 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
353 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
354 const EXCEPTION_INVALID_RESOURCE = 0x01b;
355 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
356 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
357 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
358 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
359 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
360 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
361 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
362 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
363 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
364 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
365 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
366 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
367 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
368 const EXCEPTION_INVALID_STRING = 0x029;
369 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
370 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
371 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
372 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
373 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
374 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
375 const EXCEPTION_MISSING_ELEMENT = 0x030;
376 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
377 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
378 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
379 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
380 const EXCEPTION_FATAL_ERROR = 0x035;
381 const EXCEPTION_FILE_NOT_FOUND = 0x036;
382 const EXCEPTION_ASSERTION_FAILED = 0x037;
383 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
384 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
385 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
386 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
387 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
388 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
391 * Hexadecimal->Decimal translation array
393 private static $hexdec = array(
413 * Decimal->hexadecimal translation array
415 private static $dechex = array(
435 * Startup time in miliseconds
437 private static $startupTime = 0;
440 * Protected super constructor
442 * @param $className Name of the class
445 protected function __construct ($className) {
447 $this->setRealClass($className);
449 // Set configuration instance if no registry ...
450 if (!$this instanceof Register) {
451 // ... because registries doesn't need to be configured
452 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
455 // Is the startup time set? (0 cannot be TRUE anymore)
456 if (self::$startupTime == 0) {
458 self::$startupTime = microtime(TRUE);
462 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
466 * Destructor for all classes. You should not call this method on your own.
470 public function __destruct () {
471 // Flush any updated entries to the database
472 $this->flushPendingUpdates();
474 // Is this object already destroyed?
475 if ($this->__toString() != 'DestructedObject') {
476 // Destroy all informations about this class but keep some text about it alive
477 $this->setRealClass('DestructedObject');
478 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
479 // Already destructed object
480 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
485 // Do not call this twice
486 trigger_error(__METHOD__ . ': Called twice.');
492 * The __call() method where all non-implemented methods end up
494 * @param $methodName Name of the missing method
495 * @args $args Arguments passed to the method
498 public final function __call ($methodName, $args) {
499 return self::__callStatic($methodName, $args);
503 * The __callStatic() method where all non-implemented static methods end up
505 * @param $methodName Name of the missing method
506 * @args $args Arguments passed to the method
509 public static final function __callStatic ($methodName, $args) {
510 // Init argument string
513 // Is it NULL, empty or an array?
514 if (is_null($args)) {
516 $argsString = 'NULL';
517 } elseif (is_array($args)) {
521 // Some arguments are there
522 foreach ($args as $arg) {
523 // Add data about the argument
524 $argsString .= gettype($arg) . ':';
527 // Found a NULL argument
528 $argsString .= 'NULL';
529 } elseif (is_string($arg)) {
530 // Add length for strings
531 $argsString .= strlen($arg);
532 } elseif ((is_int($arg)) || (is_float($arg))) {
535 } elseif (is_array($arg)) {
536 // .. or size if array
537 $argsString .= count($arg);
538 } elseif (is_object($arg)) {
540 $reflection = new ReflectionClass($arg);
542 // Is an other object, maybe no __toString() available
543 $argsString .= $reflection->getName();
544 } elseif ($arg === TRUE) {
545 // ... is boolean 'TRUE'
546 $argsString .= 'TRUE';
547 } elseif ($arg === FALSE) {
548 // ... is boolean 'FALSE'
549 $argsString .= 'FALSE';
552 // Comma for next one
557 if (substr($argsString, -2, 1) == ',') {
558 $argsString = substr($argsString, 0, -2);
564 // Invalid arguments!
565 $argsString = '!INVALID:' . gettype($args) . '!';
568 // Output stub message
569 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
570 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
580 * Getter for $realClass
582 * @return $realClass The name of the real class (not BaseFrameworkSystem)
584 public function __toString () {
585 return $this->realClass;
589 * Magic method to catch setting of missing but set class fields/attributes
591 * @param $name Name of the field/attribute
592 * @param $value Value to store
595 public final function __set ($name, $value) {
596 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
599 print_r($value, TRUE)
604 * Magic method to catch getting of missing fields/attributes
606 * @param $name Name of the field/attribute
609 public final function __get ($name) {
610 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
616 * Magic method to catch unsetting of missing fields/attributes
618 * @param $name Name of the field/attribute
621 public final function __unset ($name) {
622 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
628 * Magic method to catch object serialization
630 * @return $unsupported Unsupported method
631 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
633 public final function __sleep () {
634 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
638 * Magic method to catch object deserialization
640 * @return $unsupported Unsupported method
641 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
643 public final function __wakeup () {
644 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
648 * Magic method to catch calls when an object instance is called
650 * @return $unsupported Unsupported method
651 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
653 public final function __invoke () {
654 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
658 * Setter for the real class name
660 * @param $realClass Class name (string)
663 public final function setRealClass ($realClass) {
665 $this->realClass = (string) $realClass;
669 * Setter for database result instance
671 * @param $resultInstance An instance of a database result class
673 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
675 protected final function setResultInstance (SearchableResult $resultInstance) {
676 $this->resultInstance = $resultInstance;
680 * Getter for database result instance
682 * @return $resultInstance An instance of a database result class
684 public final function getResultInstance () {
685 return $this->resultInstance;
689 * Setter for template engine instances
691 * @param $templateInstance An instance of a template engine class
694 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
695 $this->templateInstance = $templateInstance;
699 * Getter for template engine instances
701 * @return $templateInstance An instance of a template engine class
703 protected final function getTemplateInstance () {
704 return $this->templateInstance;
708 * Setter for search instance
710 * @param $searchInstance Searchable criteria instance
713 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
714 $this->searchInstance = $searchInstance;
718 * Getter for search instance
720 * @return $searchInstance Searchable criteria instance
722 public final function getSearchInstance () {
723 return $this->searchInstance;
727 * Setter for update instance
729 * @param $updateInstance Searchable criteria instance
732 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
733 $this->updateInstance = $updateInstance;
737 * Getter for update instance
739 * @return $updateInstance Updateable criteria instance
741 public final function getUpdateInstance () {
742 return $this->updateInstance;
746 * Setter for resolver instance
748 * @param $resolverInstance Instance of a command resolver class
751 public final function setResolverInstance (Resolver $resolverInstance) {
752 $this->resolverInstance = $resolverInstance;
756 * Getter for resolver instance
758 * @return $resolverInstance Instance of a command resolver class
760 public final function getResolverInstance () {
761 return $this->resolverInstance;
765 * Setter for language instance
767 * @param $configInstance The configuration instance which shall
768 * be FrameworkConfiguration
771 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
772 Registry::getRegistry()->addInstance('config', $configInstance);
776 * Getter for configuration instance
778 * @return $configInstance Configuration instance
780 public final function getConfigInstance () {
781 $configInstance = Registry::getRegistry()->getInstance('config');
782 return $configInstance;
786 * Setter for debug instance
788 * @param $debugInstance The instance for debug output class
791 public final function setDebugInstance (DebugMiddleware $debugInstance) {
792 Registry::getRegistry()->addInstance('debug', $debugInstance);
796 * Getter for debug instance
798 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
800 public final function getDebugInstance () {
801 // Get debug instance
802 $debugInstance = Registry::getRegistry()->getInstance('debug');
805 return $debugInstance;
809 * Setter for web output instance
811 * @param $webInstance The instance for web output class
814 public final function setWebOutputInstance (OutputStreamer $webInstance) {
815 Registry::getRegistry()->addInstance('web_output', $webInstance);
819 * Getter for web output instance
821 * @return $webOutputInstance - Instance to class WebOutput
823 public final function getWebOutputInstance () {
824 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
825 return $webOutputInstance;
829 * Setter for database instance
831 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
834 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
835 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
839 * Getter for database layer
841 * @return $databaseInstance The database layer instance
843 public final function getDatabaseInstance () {
845 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
848 return $databaseInstance;
852 * Setter for compressor channel
854 * @param $compressorInstance An instance of CompressorChannel
857 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
858 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
862 * Getter for compressor channel
864 * @return $compressorInstance The compressor channel
866 public final function getCompressorChannel () {
867 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
868 return $compressorInstance;
872 * Protected getter for a manageable application helper class
874 * @return $applicationInstance An instance of a manageable application helper class
876 protected final function getApplicationInstance () {
877 $applicationInstance = Registry::getRegistry()->getInstance('application');
878 return $applicationInstance;
882 * Setter for a manageable application helper class
884 * @param $applicationInstance An instance of a manageable application helper class
887 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
888 Registry::getRegistry()->addInstance('application', $applicationInstance);
892 * Setter for request instance
894 * @param $requestInstance An instance of a Requestable class
897 public final function setRequestInstance (Requestable $requestInstance) {
898 $this->requestInstance = $requestInstance;
902 * Getter for request instance
904 * @return $requestInstance An instance of a Requestable class
906 public final function getRequestInstance () {
907 return $this->requestInstance;
911 * Setter for response instance
913 * @param $responseInstance An instance of a Responseable class
916 public final function setResponseInstance (Responseable $responseInstance) {
917 $this->responseInstance = $responseInstance;
921 * Getter for response instance
923 * @return $responseInstance An instance of a Responseable class
925 public final function getResponseInstance () {
926 return $this->responseInstance;
930 * Private getter for language instance
932 * @return $langInstance An instance to the language sub-system
934 protected final function getLanguageInstance () {
935 $langInstance = Registry::getRegistry()->getInstance('language');
936 return $langInstance;
940 * Setter for language instance
942 * @param $langInstance An instance to the language sub-system
944 * @see LanguageSystem
946 public final function setLanguageInstance (ManageableLanguage $langInstance) {
947 Registry::getRegistry()->addInstance('language', $langInstance);
951 * Private getter for file IO instance
953 * @return $fileIoInstance An instance to the file I/O sub-system
955 protected final function getFileIoInstance () {
956 return $this->fileIoInstance;
960 * Setter for file I/O instance
962 * @param $fileIoInstance An instance to the file I/O sub-system
965 public final function setFileIoInstance (IoHandler $fileIoInstance) {
966 $this->fileIoInstance = $fileIoInstance;
970 * Protected setter for user instance
972 * @param $userInstance An instance of a user class
975 protected final function setUserInstance (ManageableAccount $userInstance) {
976 $this->userInstance = $userInstance;
980 * Getter for user instance
982 * @return $userInstance An instance of a user class
984 public final function getUserInstance () {
985 return $this->userInstance;
989 * Setter for controller instance (this surely breaks a bit the MVC patterm)
991 * @param $controllerInstance An instance of the controller
994 public final function setControllerInstance (Controller $controllerInstance) {
995 $this->controllerInstance = $controllerInstance;
999 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1001 * @return $controllerInstance An instance of the controller
1003 public final function getControllerInstance () {
1004 return $this->controllerInstance;
1008 * Setter for RNG instance
1010 * @param $rngInstance An instance of a random number generator (RNG)
1013 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1014 $this->rngInstance = $rngInstance;
1018 * Getter for RNG instance
1020 * @return $rngInstance An instance of a random number generator (RNG)
1022 public final function getRngInstance () {
1023 return $this->rngInstance;
1027 * Setter for Cryptable instance
1029 * @param $cryptoInstance An instance of a Cryptable class
1032 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1033 $this->cryptoInstance = $cryptoInstance;
1037 * Getter for Cryptable instance
1039 * @return $cryptoInstance An instance of a Cryptable class
1041 public final function getCryptoInstance () {
1042 return $this->cryptoInstance;
1046 * Setter for the list instance
1048 * @param $listInstance A list of Listable
1051 protected final function setListInstance (Listable $listInstance) {
1052 $this->listInstance = $listInstance;
1056 * Getter for the list instance
1058 * @return $listInstance A list of Listable
1060 protected final function getListInstance () {
1061 return $this->listInstance;
1065 * Setter for the menu instance
1067 * @param $menuInstance A RenderableMenu instance
1070 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1071 $this->menuInstance = $menuInstance;
1075 * Getter for the menu instance
1077 * @return $menuInstance A RenderableMenu instance
1079 protected final function getMenuInstance () {
1080 return $this->menuInstance;
1084 * Setter for image instance
1086 * @param $imageInstance An instance of an image
1089 public final function setImageInstance (BaseImage $imageInstance) {
1090 $this->imageInstance = $imageInstance;
1094 * Getter for image instance
1096 * @return $imageInstance An instance of an image
1098 public final function getImageInstance () {
1099 return $this->imageInstance;
1103 * Setter for stacker instance
1105 * @param $stackInstance An instance of an stacker
1108 public final function setStackInstance (Stackable $stackInstance) {
1109 $this->stackInstance = $stackInstance;
1113 * Getter for stacker instance
1115 * @return $stackInstance An instance of an stacker
1117 public final function getStackInstance () {
1118 return $this->stackInstance;
1122 * Setter for compressor instance
1124 * @param $compressorInstance An instance of an compressor
1127 public final function setCompressorInstance (Compressor $compressorInstance) {
1128 $this->compressorInstance = $compressorInstance;
1132 * Getter for compressor instance
1134 * @return $compressorInstance An instance of an compressor
1136 public final function getCompressorInstance () {
1137 return $this->compressorInstance;
1141 * Setter for Parseable instance
1143 * @param $parserInstance An instance of an Parseable
1146 public final function setParserInstance (Parseable $parserInstance) {
1147 $this->parserInstance = $parserInstance;
1151 * Getter for Parseable instance
1153 * @return $parserInstance An instance of an Parseable
1155 public final function getParserInstance () {
1156 return $this->parserInstance;
1160 * Setter for HandleableProtocol instance
1162 * @param $protocolInstance An instance of an HandleableProtocol
1165 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1166 $this->protocolInstance = $protocolInstance;
1170 * Getter for HandleableProtocol instance
1172 * @return $protocolInstance An instance of an HandleableProtocol
1174 public final function getProtocolInstance () {
1175 return $this->protocolInstance;
1179 * Setter for DatabaseWrapper instance
1181 * @param $wrapperInstance An instance of an DatabaseWrapper
1184 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1185 $this->wrapperInstance = $wrapperInstance;
1189 * Getter for DatabaseWrapper instance
1191 * @return $wrapperInstance An instance of an DatabaseWrapper
1193 public final function getWrapperInstance () {
1194 return $this->wrapperInstance;
1198 * Setter for socket resource
1200 * @param $socketResource A valid socket resource
1203 public final function setSocketResource ($socketResource) {
1204 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1205 $this->socketResource = $socketResource;
1209 * Getter for socket resource
1211 * @return $socketResource A valid socket resource
1213 public final function getSocketResource () {
1214 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1215 return $this->socketResource;
1219 * Setter for regular expression
1221 * @param $regularExpression A valid regular expression
1224 public final function setRegularExpression ($regularExpression) {
1225 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1226 $this->regularExpression = $regularExpression;
1230 * Getter for regular expression
1232 * @return $regularExpression A valid regular expression
1234 public final function getRegularExpression () {
1235 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1236 return $this->regularExpression;
1240 * Setter for helper instance
1242 * @param $helperInstance An instance of a helper class
1245 protected final function setHelperInstance (Helper $helperInstance) {
1246 $this->helperInstance = $helperInstance;
1250 * Getter for helper instance
1252 * @return $helperInstance An instance of a helper class
1254 public final function getHelperInstance () {
1255 return $this->helperInstance;
1259 * Setter for a Source instance
1261 * @param $sourceInstance An instance of a Source class
1264 protected final function setSourceInstance (Source $sourceInstance) {
1265 $this->sourceInstance = $sourceInstance;
1269 * Getter for a Source instance
1271 * @return $sourceInstance An instance of a Source class
1273 protected final function getSourceInstance () {
1274 return $this->sourceInstance;
1278 * Setter for a UrlSource instance
1280 * @param $sourceInstance An instance of a UrlSource class
1283 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1284 $this->urlSourceInstance = $urlSourceInstance;
1288 * Getter for a UrlSource instance
1290 * @return $urlSourceInstance An instance of a UrlSource class
1292 protected final function getUrlSourceInstance () {
1293 return $this->urlSourceInstance;
1297 * Getter for a InputStream instance
1299 * @param $inputStreamInstance The InputStream instance
1301 protected final function getInputStreamInstance () {
1302 return $this->inputStreamInstance;
1306 * Setter for a InputStream instance
1308 * @param $inputStreamInstance The InputStream instance
1311 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1312 $this->inputStreamInstance = $inputStreamInstance;
1316 * Getter for a OutputStream instance
1318 * @param $outputStreamInstance The OutputStream instance
1320 protected final function getOutputStreamInstance () {
1321 return $this->outputStreamInstance;
1325 * Setter for a OutputStream instance
1327 * @param $outputStreamInstance The OutputStream instance
1330 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1331 $this->outputStreamInstance = $outputStreamInstance;
1335 * Setter for handler instance
1337 * @param $handlerInstance An instance of a Handleable class
1340 protected final function setHandlerInstance (Handleable $handlerInstance) {
1341 $this->handlerInstance = $handlerInstance;
1345 * Getter for handler instance
1347 * @return $handlerInstance A Networkable instance
1349 protected final function getHandlerInstance () {
1350 return $this->handlerInstance;
1354 * Setter for visitor instance
1356 * @param $visitorInstance A Visitor instance
1359 protected final function setVisitorInstance (Visitor $visitorInstance) {
1360 $this->visitorInstance = $visitorInstance;
1364 * Getter for visitor instance
1366 * @return $visitorInstance A Visitor instance
1368 protected final function getVisitorInstance () {
1369 return $this->visitorInstance;
1373 * Setter for DHT instance
1375 * @param $dhtInstance A Distributable instance
1378 protected final function setDhtInstance (Distributable $dhtInstance) {
1379 $this->dhtInstance = $dhtInstance;
1383 * Getter for DHT instance
1385 * @return $dhtInstance A Distributable instance
1387 protected final function getDhtInstance () {
1388 return $this->dhtInstance;
1392 * Setter for raw package Data
1394 * @param $packageData Raw package Data
1397 public final function setPackageData (array $packageData) {
1398 $this->packageData = $packageData;
1402 * Getter for raw package Data
1404 * @return $packageData Raw package Data
1406 public function getPackageData () {
1407 return $this->packageData;
1412 * Setter for Iterator instance
1414 * @param $iteratorInstance An instance of an Iterator
1417 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1418 $this->iteratorInstance = $iteratorInstance;
1422 * Getter for Iterator instance
1424 * @return $iteratorInstance An instance of an Iterator
1426 public final function getIteratorInstance () {
1427 return $this->iteratorInstance;
1431 * Setter for FilePointer instance
1433 * @param $pointerInstance An instance of an FilePointer class
1436 protected final function setPointerInstance (FilePointer $pointerInstance) {
1437 $this->pointerInstance = $pointerInstance;
1441 * Getter for FilePointer instance
1443 * @return $pointerInstance An instance of an FilePointer class
1445 public final function getPointerInstance () {
1446 return $this->pointerInstance;
1450 * Unsets pointer instance which triggers a call of __destruct() if the
1451 * instance is still there. This is surely not fatal on already "closed"
1452 * file pointer instances.
1454 * I don't want to mess around with above setter by giving it a default
1455 * value NULL as setter should always explicitly only set (existing) object
1456 * instances and NULL is NULL.
1460 protected final function unsetPointerInstance () {
1461 // Simply it to NULL
1462 $this->pointerInstance = NULL;
1466 * Setter for Indexable instance
1468 * @param $indexInstance An instance of an Indexable class
1471 protected final function setIndexInstance (Indexable $indexInstance) {
1472 $this->indexInstance = $indexInstance;
1476 * Getter for Indexable instance
1478 * @return $indexInstance An instance of an Indexable class
1480 public final function getIndexInstance () {
1481 return $this->indexInstance;
1485 * Setter for Block instance
1487 * @param $blockInstance An instance of an Block class
1490 protected final function setBlockInstance (Block $blockInstance) {
1491 $this->blockInstance = $blockInstance;
1495 * Getter for Block instance
1497 * @return $blockInstance An instance of an Block class
1499 public final function getBlockInstance () {
1500 return $this->blockInstance;
1504 * Setter for Minable instance
1506 * @param $minableInstance A Minable instance
1509 protected final function setMinableInstance (Minable $minableInstance) {
1510 $this->minableInstance = $minableInstance;
1514 * Getter for minable instance
1516 * @return $minableInstance A Minable instance
1518 protected final function getMinableInstance () {
1519 return $this->minableInstance;
1523 * Setter for FrameworkDirectory instance
1525 * @param $directoryInstance A FrameworkDirectoryPointer instance
1528 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1529 $this->directoryInstance = $directoryInstance;
1533 * Getter for FrameworkDirectory instance
1535 * @return $directoryInstance A FrameworkDirectory instance
1537 protected final function getDirectoryInstance () {
1538 return $this->directoryInstance;
1542 * Setter for listener instance
1544 * @param $listenerInstance A Listenable instance
1547 protected final function setListenerInstance (Listenable $listenerInstance) {
1548 $this->listenerInstance = $listenerInstance;
1552 * Getter for listener instance
1554 * @return $listenerInstance A Listenable instance
1556 protected final function getListenerInstance () {
1557 return $this->listenerInstance;
1561 * Getter for communicator instance
1563 * @return $communicatorInstance An instance of a Communicator class
1565 public final function getCommunicatorInstance () {
1566 return $this->communicatorInstance;
1570 * Setter for communicator instance
1572 * @param $communicatorInstance An instance of a Communicator class
1575 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1576 $this->communicatorInstance = $communicatorInstance;
1580 * Setter for state instance
1582 * @param $stateInstance A Stateable instance
1585 public final function setStateInstance (Stateable $stateInstance) {
1586 $this->stateInstance = $stateInstance;
1590 * Getter for state instance
1592 * @return $stateInstance A Stateable instance
1594 public final function getStateInstance () {
1595 return $this->stateInstance;
1599 * Setter for output instance
1601 * @param $outputInstance The debug output instance
1604 public final function setOutputInstance (OutputStreamer $outputInstance) {
1605 $this->outputInstance = $outputInstance;
1609 * Getter for output instance
1611 * @return $outputInstance The debug output instance
1613 public final function getOutputInstance () {
1614 return $this->outputInstance;
1618 * Setter for command name
1620 * @param $commandName Last validated command name
1623 protected final function setCommandName ($commandName) {
1624 $this->commandName = $commandName;
1628 * Getter for command name
1630 * @return $commandName Last validated command name
1632 protected final function getCommandName () {
1633 return $this->commandName;
1637 * Setter for controller name
1639 * @param $controllerName Last validated controller name
1642 protected final function setControllerName ($controllerName) {
1643 $this->controllerName = $controllerName;
1647 * Getter for controller name
1649 * @return $controllerName Last validated controller name
1651 protected final function getControllerName () {
1652 return $this->controllerName;
1656 * Getter for protocol name
1658 * @return $protocolName Name of used protocol
1660 public final function getProtocolName () {
1661 return $this->protocolName;
1665 * Setter for protocol name
1667 * @param $protocolName Name of used protocol
1670 protected final function setProtocolName ($protocolName) {
1671 $this->protocolName = $protocolName;
1675 * Checks whether an object equals this object. You should overwrite this
1676 * method to implement own equality checks
1678 * @param $objectInstance An instance of a FrameworkInterface object
1679 * @return $equals Whether both objects equals
1681 public function equals (FrameworkInterface $objectInstance) {
1684 $this->__toString() == $objectInstance->__toString()
1686 $this->hashCode() == $objectInstance->hashCode()
1689 // Return the result
1694 * Generates a generic hash code of this class. You should really overwrite
1695 * this method with your own hash code generator code. But keep KISS in mind.
1697 * @return $hashCode A generic hash code respresenting this whole class
1699 public function hashCode () {
1701 return crc32($this->__toString());
1705 * Formats computer generated price values into human-understandable formats
1706 * with thousand and decimal separators.
1708 * @param $value The in computer format value for a price
1709 * @param $currency The currency symbol (use HTML-valid characters!)
1710 * @param $decNum Number of decimals after commata
1711 * @return $price The for the current language formated price string
1712 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1713 * thousands separator
1716 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1717 // Are all required attriutes set?
1718 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1719 // Throw an exception
1720 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1724 $value = (float) $value;
1726 // Reformat the US number
1727 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1729 // Return as string...
1734 * Appends a trailing slash to a string
1736 * @param $str A string (maybe) without trailing slash
1737 * @return $str A string with an auto-appended trailing slash
1739 public final function addMissingTrailingSlash ($str) {
1740 // Is there a trailing slash?
1741 if (substr($str, -1, 1) != '/') {
1745 // Return string with trailing slash
1750 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1751 * application helper instance (ApplicationHelper by default).
1753 * @param $applicationInstance An application helper instance or
1754 * null if we shall use the default
1755 * @return $templateInstance The template engine instance
1756 * @throws NullPointerException If the discovered application
1757 * instance is still null
1759 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1760 // Is the application instance set?
1761 if (is_null($applicationInstance)) {
1762 // Get the current instance
1763 $applicationInstance = $this->getApplicationInstance();
1766 if (is_null($applicationInstance)) {
1767 // Thrown an exception
1768 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1772 // Initialize the template engine
1773 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1775 // Return the prepared instance
1776 return $templateInstance;
1780 * Debugs this instance by putting out it's full content
1782 * @param $message Optional message to show in debug output
1785 public final function debugInstance ($message = '') {
1786 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1787 restore_error_handler();
1792 // Is a message set?
1793 if (!empty($message)) {
1794 // Construct message
1795 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1798 // Generate the output
1799 $content .= sprintf('<pre>%s</pre>',
1802 print_r($this, TRUE)
1808 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>',
1809 $this->__toString(),
1811 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1816 * Replaces control characters with printable output
1818 * @param $str String with control characters
1819 * @return $str Replaced string
1821 protected function replaceControlCharacters ($str) {
1824 chr(13), '[r]', str_replace(
1825 chr(10), '[n]', str_replace(
1835 * Output a partial stub message for the caller method
1837 * @param $message An optional message to display
1840 protected function partialStub ($message = '') {
1841 // Get the backtrace
1842 $backtrace = debug_backtrace();
1844 // Generate the class::method string
1845 $methodName = 'UnknownClass->unknownMethod';
1846 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1847 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1850 // Construct the full message
1851 $stubMessage = sprintf('[%s:] Partial stub!',
1855 // Is the extra message given?
1856 if (!empty($message)) {
1857 // Then add it as well
1858 $stubMessage .= ' Message: ' . $message;
1861 // Debug instance is there?
1862 if (!is_null($this->getDebugInstance())) {
1863 // Output stub message
1864 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1867 trigger_error($stubMessage);
1873 * Outputs a debug backtrace and stops further script execution
1875 * @param $message An optional message to output
1876 * @param $doExit Whether exit the program (TRUE is default)
1879 public function debugBackTrace ($message = '', $doExit = TRUE) {
1880 // Sorry, there is no other way getting this nice backtrace
1881 if (!empty($message)) {
1883 printf('Message: %s<br />' . PHP_EOL, $message);
1887 debug_print_backtrace();
1891 if ($doExit === TRUE) {
1897 * Creates an instance of a debugger instance
1899 * @param $className Name of the class (currently unsupported)
1900 * @param $lineNumber Line number where the call was made
1901 * @return $debugInstance An instance of a debugger class
1902 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1904 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1905 // Is the instance set?
1906 if (!Registry::getRegistry()->instanceExists('debug')) {
1907 // Init debug instance
1908 $debugInstance = NULL;
1912 // Get a debugger instance
1913 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1914 } catch (NullPointerException $e) {
1915 // Didn't work, no instance there
1916 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1919 // Empty string should be ignored and used for testing the middleware
1920 DebugMiddleware::getSelfInstance()->output('');
1922 // Set it in its own class. This will set it in the registry
1923 $debugInstance->setDebugInstance($debugInstance);
1925 // Get instance from registry
1926 $debugInstance = Registry::getRegistry()->getDebugInstance();
1930 return $debugInstance;
1934 * Simple output of a message with line-break
1936 * @param $message Message to output
1939 public function outputLine ($message) {
1941 print($message . PHP_EOL);
1945 * Outputs a debug message whether to debug instance (should be set!) or
1946 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1947 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1949 * @param $message Message we shall send out...
1950 * @param $doPrint Whether print or die here (default: print)
1951 * @paran $stripTags Whether to strip tags (default: FALSE)
1954 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1955 // Set debug instance to NULL
1956 $debugInstance = NULL;
1960 // Get debug instance
1961 $debugInstance = $this->getDebugInstance();
1962 } catch (NullPointerException $e) {
1963 // The debug instance is not set (yet)
1966 // Is the debug instance there?
1967 if (is_object($debugInstance)) {
1968 // Use debug output handler
1969 $debugInstance->output($message, $stripTags);
1971 if ($doPrint === FALSE) {
1972 // Die here if not printed
1976 // Are debug times enabled?
1977 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1979 $message = $this->getPrintableExecutionTime() . $message;
1983 if ($doPrint === TRUE) {
1985 $this->outputLine($message);
1994 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1996 * @param $str The string, what ever it is needs to be converted
1997 * @return $className Generated class name
1999 public static final function convertToClassName ($str) {
2003 // Convert all dashes in underscores
2004 $str = self::convertDashesToUnderscores($str);
2006 // Now use that underscores to get classname parts for hungarian style
2007 foreach (explode('_', $str) as $strPart) {
2008 // Make the class name part lower case and first upper case
2009 $className .= ucfirst(strtolower($strPart));
2012 // Return class name
2017 * Converts dashes to underscores, e.g. useable for configuration entries
2019 * @param $str The string with maybe dashes inside
2020 * @return $str The converted string with no dashed, but underscores
2022 public static final function convertDashesToUnderscores ($str) {
2024 $str = str_replace('-', '_', $str);
2026 // Return converted string
2031 * Marks up the code by adding e.g. line numbers
2033 * @param $phpCode Unmarked PHP code
2034 * @return $markedCode Marked PHP code
2036 public function markupCode ($phpCode) {
2041 $errorArray = error_get_last();
2043 // Init the code with error message
2044 if (is_array($errorArray)) {
2046 $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>',
2047 basename($errorArray['file']),
2048 $errorArray['line'],
2049 $errorArray['message'],
2054 // Add line number to the code
2055 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2057 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2059 htmlentities($code, ENT_QUOTES)
2068 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2069 * beatiful for web-based front-ends. If null is given a message id
2070 * null_timestamp will be resolved and returned.
2072 * @param $timestamp Timestamp to prepare (filter) for display
2073 * @return $readable A readable timestamp
2075 public function doFilterFormatTimestamp ($timestamp) {
2076 // Default value to return
2079 // Is the timestamp null?
2080 if (is_null($timestamp)) {
2081 // Get a message string
2082 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2084 switch ($this->getLanguageInstance()->getLanguageCode()) {
2085 case 'de': // German format is a bit different to default
2086 // Split the GMT stamp up
2087 $dateTime = explode(' ', $timestamp );
2088 $dateArray = explode('-', $dateTime[0]);
2089 $timeArray = explode(':', $dateTime[1]);
2091 // Construct the timestamp
2092 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2102 default: // Default is pass-through
2103 $readable = $timestamp;
2113 * Filter a given number into a localized number
2115 * @param $value The raw value from e.g. database
2116 * @return $localized Localized value
2118 public function doFilterFormatNumber ($value) {
2119 // Generate it from config and localize dependencies
2120 switch ($this->getLanguageInstance()->getLanguageCode()) {
2121 case 'de': // German format is a bit different to default
2122 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2125 default: // US, etc.
2126 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2135 * "Getter" for databse entry
2137 * @return $entry An array with database entries
2138 * @throws NullPointerException If the database result is not found
2139 * @throws InvalidDatabaseResultException If the database result is invalid
2141 protected final function getDatabaseEntry () {
2142 // Is there an instance?
2143 if (!$this->getResultInstance() instanceof SearchableResult) {
2144 // Throw an exception here
2145 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2149 $this->getResultInstance()->rewind();
2151 // Do we have an entry?
2152 if ($this->getResultInstance()->valid() === FALSE) {
2153 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2154 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2158 $this->getResultInstance()->next();
2161 $entry = $this->getResultInstance()->current();
2168 * Getter for field name
2170 * @param $fieldName Field name which we shall get
2171 * @return $fieldValue Field value from the user
2172 * @throws NullPointerException If the result instance is null
2174 public final function getField ($fieldName) {
2175 // Default field value
2178 // Get result instance
2179 $resultInstance = $this->getResultInstance();
2181 // Is this instance null?
2182 if (is_null($resultInstance)) {
2183 // Then the user instance is no longer valid (expired cookies?)
2184 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2187 // Get current array
2188 $fieldArray = $resultInstance->current();
2189 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2191 // Convert dashes to underscore
2192 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2194 // Does the field exist?
2195 if ($this->isFieldSet($fieldName)) {
2197 $fieldValue = $fieldArray[$fieldName2];
2198 } elseif (defined('DEVELOPER')) {
2199 // Missing field entry, may require debugging
2200 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2202 // Missing field entry, may require debugging
2203 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2211 * Checks if given field is set
2213 * @param $fieldName Field name to check
2214 * @return $isSet Whether the given field name is set
2215 * @throws NullPointerException If the result instance is null
2217 public function isFieldSet ($fieldName) {
2218 // Get result instance
2219 $resultInstance = $this->getResultInstance();
2221 // Is this instance null?
2222 if (is_null($resultInstance)) {
2223 // Then the user instance is no longer valid (expired cookies?)
2224 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2227 // Get current array
2228 $fieldArray = $resultInstance->current();
2229 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2231 // Convert dashes to underscore
2232 $fieldName = self::convertDashesToUnderscores($fieldName);
2235 $isSet = isset($fieldArray[$fieldName]);
2242 * Flushs all pending updates to the database layer
2246 public function flushPendingUpdates () {
2247 // Get result instance
2248 $resultInstance = $this->getResultInstance();
2250 // Do we have data to update?
2251 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2252 // Get wrapper class name config entry
2253 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2255 // Create object instance
2256 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2258 // Yes, then send the whole result to the database layer
2259 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2264 * Outputs a deprecation warning to the developer.
2266 * @param $message The message we shall output to the developer
2268 * @todo Write a logging mechanism for productive mode
2270 public function deprecationWarning ($message) {
2271 // Is developer mode active?
2272 if (defined('DEVELOPER')) {
2273 // Debug instance is there?
2274 if (!is_null($this->getDebugInstance())) {
2275 // Output stub message
2276 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2279 trigger_error($message . "<br />\n");
2283 // @TODO Finish this part!
2284 $this->partialStub('Developer mode inactive. Message:' . $message);
2289 * Checks whether the given PHP extension is loaded
2291 * @param $phpExtension The PHP extension we shall check
2292 * @return $isLoaded Whether the PHP extension is loaded
2294 public final function isPhpExtensionLoaded ($phpExtension) {
2296 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2303 * "Getter" as a time() replacement but with milliseconds. You should use this
2304 * method instead of the encapsulated getimeofday() function.
2306 * @return $milliTime Timestamp with milliseconds
2308 public function getMilliTime () {
2309 // Get the time of day as float
2310 $milliTime = gettimeofday(TRUE);
2317 * Idles (sleeps) for given milliseconds
2319 * @return $hasSlept Whether it goes fine
2321 public function idle ($milliSeconds) {
2322 // Sleep is fine by default
2325 // Idle so long with found function
2326 if (function_exists('time_sleep_until')) {
2327 // Get current time and add idle time
2328 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2330 // New PHP 5.1.0 function found, ignore errors
2331 $hasSlept = @time_sleep_until($sleepUntil);
2334 * My Sun station doesn't have that function even with latest PHP
2337 usleep($milliSeconds * 1000);
2344 * Converts a hexadecimal string, even with negative sign as first string to
2345 * a decimal number using BC functions.
2347 * This work is based on comment #86673 on php.net documentation page at:
2348 * <http://de.php.net/manual/en/function.dechex.php#86673>
2350 * @param $hex Hexadecimal string
2351 * @return $dec Decimal number
2353 protected function hex2dec ($hex) {
2354 // Convert to all lower-case
2355 $hex = strtolower($hex);
2357 // Detect sign (negative/positive numbers)
2359 if (substr($hex, 0, 1) == '-') {
2361 $hex = substr($hex, 1);
2364 // Decode the hexadecimal string into a decimal number
2366 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2367 $factor = self::$hexdec[substr($hex, $i, 1)];
2368 $dec = bcadd($dec, bcmul($factor, $e));
2371 // Return the decimal number
2372 return $sign . $dec;
2376 * Converts even very large decimal numbers, also signed, to a hexadecimal
2379 * This work is based on comment #97756 on php.net documentation page at:
2380 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2382 * @param $dec Decimal number, even with negative sign
2383 * @param $maxLength Optional maximum length of the string
2384 * @return $hex Hexadecimal string
2386 protected function dec2hex ($dec, $maxLength = 0) {
2387 // maxLength can be zero or devideable by 2
2388 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2390 // Detect sign (negative/positive numbers)
2397 // Encode the decimal number into a hexadecimal string
2400 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2402 } while ($dec >= 1);
2405 * Leading zeros are required for hex-decimal "numbers". In some
2406 * situations more leading zeros are wanted, so check for both
2409 if ($maxLength > 0) {
2410 // Prepend more zeros
2411 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2412 } elseif ((strlen($hex) % 2) != 0) {
2413 // Only make string's length dividable by 2
2417 // Return the hexadecimal string
2418 return $sign . $hex;
2422 * Converts a ASCII string (0 to 255) into a decimal number.
2424 * @param $asc The ASCII string to be converted
2425 * @return $dec Decimal number
2427 protected function asc2dec ($asc) {
2428 // Convert it into a hexadecimal number
2429 $hex = bin2hex($asc);
2431 // And back into a decimal number
2432 $dec = $this->hex2dec($hex);
2439 * Converts a decimal number into an ASCII string.
2441 * @param $dec Decimal number
2442 * @return $asc An ASCII string
2444 protected function dec2asc ($dec) {
2445 // First convert the number into a hexadecimal string
2446 $hex = $this->dec2hex($dec);
2448 // Then convert it into the ASCII string
2449 $asc = $this->hex2asc($hex);
2456 * Converts a hexadecimal number into an ASCII string. Negative numbers
2459 * @param $hex Hexadecimal string
2460 * @return $asc An ASCII string
2462 protected function hex2asc ($hex) {
2463 // Check for length, it must be devideable by 2
2464 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2465 assert((strlen($hex) % 2) == 0);
2469 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2470 // Get the decimal number of the chunk
2471 $part = hexdec(substr($hex, $idx, 2));
2473 // Add it to the final string
2477 // Return the final string
2482 * Checks whether the given encoded data was encoded with Base64
2484 * @param $encodedData Encoded data we shall check
2485 * @return $isBase64 Whether the encoded data is Base64
2487 protected function isBase64Encoded ($encodedData) {
2489 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2496 * "Getter" to get response/request type from analysis of the system.
2498 * @return $responseType Analyzed response type
2500 protected static function getResponseTypeFromSystem () {
2501 // Default is console
2502 $responseType = 'console';
2504 // Is 'HTTP_HOST' set?
2505 if (isset($_SERVER['HTTP_HOST'])) {
2507 * Then it is a HTML response/request as RSS and so on may be
2508 * transfered over HTTP as well.
2510 $responseType = 'html';
2514 return $responseType;
2518 * Gets a cache key from Criteria instance
2520 * @param $criteriaInstance An instance of a Criteria class
2521 * @param $onlyKeys Only use these keys for a cache key
2522 * @return $cacheKey A cache key suitable for lookup/storage purposes
2524 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2526 $cacheKey = sprintf('%s@%s',
2527 $this->__toString(),
2528 $criteriaInstance->getCacheKey($onlyKeys)
2532 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2537 * Getter for startup time in miliseconds
2539 * @return $startupTime Startup time in miliseconds
2541 protected function getStartupTime () {
2542 return self::$startupTime;
2546 * "Getter" for a printable currently execution time in nice braces
2548 * @return $executionTime Current execution time in nice braces
2550 protected function getPrintableExecutionTime () {
2551 // Caculate the execution time
2552 $executionTime = microtime(TRUE) - $this->getStartupTime();
2554 // Pack it in nice braces
2555 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2558 return $executionTime;
2562 * Hashes a given string with a simple but stronger hash function (no salt)
2563 * and hex-encode it.
2565 * @param $str The string to be hashed
2566 * @return $hash The hash from string $str
2568 public static final function hash ($str) {
2569 // Hash given string with (better secure) hasher
2570 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2577 * "Getter" for length of hash() output. This will be "cached" to speed up
2580 * @return $length Length of hash() output
2582 public static final function getHashLength () {
2584 if (is_null(self::$hashLength)) {
2585 // No, then hash a string and save its length.
2586 self::$hashLength = strlen(self::hash('abc123'));
2590 return self::$hashLength;
2594 * Checks whether the given number is really a number (only chars 0-9).
2596 * @param $num A string consisting only chars between 0 and 9
2597 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2598 * @param $assertMismatch Whether to assert mismatches
2599 * @return $ret The (hopefully) secured numbered value
2601 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2602 // Filter all numbers out
2603 $ret = preg_replace('/[^0123456789]/', '', $num);
2606 if ($castValue === TRUE) {
2607 // Cast to biggest numeric type
2608 $ret = (double) $ret;
2611 // Assert only if requested
2612 if ($assertMismatch === TRUE) {
2613 // Has the whole value changed?
2614 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2622 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2624 * @param $num A string consisting only chars between 0 and 9
2625 * @param $assertMismatch Whether to assert mismatches
2626 * @return $ret The (hopefully) secured hext-numbered value
2628 public function hexval ($num, $assertMismatch = FALSE) {
2629 // Filter all numbers out
2630 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2632 // Assert only if requested
2633 if ($assertMismatch === TRUE) {
2634 // Has the whole value changed?
2635 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2643 * Checks whether start/end marker are set
2645 * @param $data Data to be checked
2646 * @return $isset Whether start/end marker are set
2648 public final function ifStartEndMarkersSet ($data) {
2650 $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));
2652 // ... and return it
2657 * Determines if an element is set in the generic array
2659 * @param $keyGroup Main group for the key
2660 * @param $subGroup Sub group for the key
2661 * @param $key Key to check
2662 * @param $element Element to check
2663 * @return $isset Whether the given key is set
2665 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2667 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2670 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2676 * Determines if a key 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 * @return $isset Whether the given key is set
2683 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2685 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2688 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2696 * Determines if a group is set in the generic array
2698 * @param $keyGroup Main group
2699 * @param $subGroup Sub group
2700 * @return $isset Whether the given group is set
2702 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2704 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2707 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2714 * Getter for sub key group
2716 * @param $keyGroup Main key group
2717 * @param $subGroup Sub key group
2718 * @return $array An array with all array elements
2720 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2722 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2723 // No, then abort here
2724 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2729 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2732 return $this->genericArray[$keyGroup][$subGroup];
2736 * Unsets a given key in generic array
2738 * @param $keyGroup Main group for the key
2739 * @param $subGroup Sub group for the key
2740 * @param $key Key to unset
2743 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2745 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2748 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2752 * Unsets a given element in generic array
2754 * @param $keyGroup Main group for the key
2755 * @param $subGroup Sub group for the key
2756 * @param $key Key to unset
2757 * @param $element Element to unset
2760 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2762 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2765 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2769 * Append a string to a given generic array key
2771 * @param $keyGroup Main group for the key
2772 * @param $subGroup Sub group for the key
2773 * @param $key Key to unset
2774 * @param $value Value to add/append
2777 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2779 //* 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);
2781 // Is it already there?
2782 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2784 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2787 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2792 * Append a string to a given generic array element
2794 * @param $keyGroup Main group for the key
2795 * @param $subGroup Sub group for the key
2796 * @param $key Key to unset
2797 * @param $element Element to check
2798 * @param $value Value to add/append
2801 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2803 //* 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);
2805 // Is it already there?
2806 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2808 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2811 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2816 * Sets a string in a given generic array element
2818 * @param $keyGroup Main group for the key
2819 * @param $subGroup Sub group for the key
2820 * @param $key Key to unset
2821 * @param $element Element to check
2822 * @param $value Value to add/append
2825 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2827 //* 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);
2830 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2834 * Initializes given generic array group
2836 * @param $keyGroup Main group for the key
2837 * @param $subGroup Sub group for the key
2838 * @param $key Key to use
2839 * @param $forceInit Optionally force initialization
2842 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2844 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2846 // Is it already set?
2847 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2848 // Already initialized
2849 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2854 $this->genericArray[$keyGroup][$subGroup] = array();
2858 * Initializes given generic array key
2860 * @param $keyGroup Main group for the key
2861 * @param $subGroup Sub group for the key
2862 * @param $key Key to use
2863 * @param $forceInit Optionally force initialization
2866 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2868 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2870 // Is it already set?
2871 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2872 // Already initialized
2873 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2878 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2882 * Initializes given generic array element
2884 * @param $keyGroup Main group for the key
2885 * @param $subGroup Sub group for the key
2886 * @param $key Key to use
2887 * @param $element Element to use
2888 * @param $forceInit Optionally force initialization
2891 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2893 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2895 // Is it already set?
2896 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2897 // Already initialized
2898 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2903 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2907 * Pushes an element to a generic key
2909 * @param $keyGroup Main group for the key
2910 * @param $subGroup Sub group for the key
2911 * @param $key Key to use
2912 * @param $value Value to add/append
2913 * @return $count Number of array elements
2915 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2917 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2920 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2922 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2926 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2929 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2930 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2935 * Pushes an element to a generic array element
2937 * @param $keyGroup Main group for the key
2938 * @param $subGroup Sub group for the key
2939 * @param $key Key to use
2940 * @param $element Element to check
2941 * @param $value Value to add/append
2942 * @return $count Number of array elements
2944 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2946 //* 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));
2949 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2951 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2955 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2958 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2959 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2964 * Pops an element from a generic group
2966 * @param $keyGroup Main group for the key
2967 * @param $subGroup Sub group for the key
2968 * @param $key Key to unset
2969 * @return $value Last "popped" value
2971 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2973 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2976 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2978 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2983 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2986 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2987 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2992 * Shifts an element from a generic group
2994 * @param $keyGroup Main group for the key
2995 * @param $subGroup Sub group for the key
2996 * @param $key Key to unset
2997 * @return $value Last "popped" value
2999 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3001 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3004 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3006 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3011 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3014 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3015 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3020 * Count generic array group
3022 * @param $keyGroup Main group for the key
3023 * @return $count Count of given group
3025 protected final function countGenericArray ($keyGroup) {
3027 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3030 if (!isset($this->genericArray[$keyGroup])) {
3032 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3037 $count = count($this->genericArray[$keyGroup]);
3040 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3047 * Count generic array sub group
3049 * @param $keyGroup Main group for the key
3050 * @param $subGroup Sub group for the key
3051 * @return $count Count of given group
3053 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3055 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3058 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3060 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3065 $count = count($this->genericArray[$keyGroup][$subGroup]);
3068 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3075 * Count generic array elements
3077 * @param $keyGroup Main group for the key
3078 * @param $subGroup Sub group for the key
3079 * @para $key Key to count
3080 * @return $count Count of given key
3082 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3084 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3087 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3089 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3091 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3093 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3098 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3101 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3108 * Getter for whole generic group array
3110 * @param $keyGroup Key group to get
3111 * @return $array Whole generic array group
3113 protected final function getGenericArray ($keyGroup) {
3115 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3118 if (!isset($this->genericArray[$keyGroup])) {
3120 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3125 return $this->genericArray[$keyGroup];
3129 * Setter for generic array key
3131 * @param $keyGroup Key group to get
3132 * @param $subGroup Sub group for the key
3133 * @param $key Key to unset
3134 * @param $value Mixed value from generic array element
3137 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3139 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3142 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3146 * Getter for generic array key
3148 * @param $keyGroup Key group to get
3149 * @param $subGroup Sub group for the key
3150 * @param $key Key to unset
3151 * @return $value Mixed value from generic array element
3153 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3155 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3158 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3160 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3165 return $this->genericArray[$keyGroup][$subGroup][$key];
3169 * Sets a value in given generic array key/element
3171 * @param $keyGroup Main group for the key
3172 * @param $subGroup Sub group for the key
3173 * @param $key Key to set
3174 * @param $element Element to set
3175 * @param $value Value to set
3178 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3180 //* 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));
3183 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3187 * Getter for generic array element
3189 * @param $keyGroup Key group to get
3190 * @param $subGroup Sub group for the key
3191 * @param $key Key to look for
3192 * @param $element Element to look for
3193 * @return $value Mixed value from generic array element
3195 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3197 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3200 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3202 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3207 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3211 * Checks if a given sub group is valid (array)
3213 * @param $keyGroup Key group to get
3214 * @param $subGroup Sub group for the key
3215 * @return $isValid Whether given sub group is valid
3217 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3219 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3222 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3229 * Checks if a given key is valid (array)
3231 * @param $keyGroup Key group to get
3232 * @param $subGroup Sub group for the key
3233 * @param $key Key to check
3234 * @return $isValid Whether given sub group is valid
3236 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3238 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3241 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3248 * Initializes the web output instance
3252 protected function initWebOutputInstance () {
3253 // Get application instance
3254 $applicationInstance = Registry::getRegistry()->getInstance('app');
3256 // Is this a response instance?
3257 if ($this instanceof Responseable) {
3258 // Then set it in application instance
3259 $applicationInstance->setResponseInstance($this);
3262 // Init web output instance
3263 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3266 $this->setWebOutputInstance($outputInstance);
3270 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3272 * @param $boolean Boolean value
3273 * @return $translated Translated boolean value
3275 public static final function translateBooleanToYesNo ($boolean) {
3276 // Make sure it is really boolean
3277 assert(is_bool($boolean));
3280 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3282 // ... and return it
3287 * Encodes raw data (almost any type) by "serializing" it and then pack it
3288 * into a "binary format".
3290 * @param $rawData Raw data (almost any type)
3291 * @return $encoded Encoded data
3293 protected function encodeData ($rawData) {
3294 // Make sure no objects or resources pass through
3295 assert(!is_object($rawData));
3296 assert(!is_resource($rawData));
3298 // First "serialize" it (json_encode() is faster than serialize())
3299 $encoded = $this->packString(json_encode($rawData));
3306 * Pack a string into a "binary format". Please execuse me that this is
3307 * widely undocumented. :-(
3309 * @param $str Unpacked string
3310 * @return $packed Packed string
3311 * @todo Improve documentation
3313 protected function packString ($str) {
3315 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3317 // First compress the string (gzcompress is okay)
3318 $str = gzcompress($str);
3323 // And start the "encoding" loop
3324 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3326 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3327 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3329 if (($idx + $i) <= strlen($str)) {
3330 $ord = ord(substr($str, ($idx + $i), 1));
3332 $add = $ord * pow(256, $factor);
3336 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3340 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3341 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3343 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3344 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3350 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3355 * Checks whether the given file/path is in open_basedir(). This does not
3356 * gurantee that the file is actually readable and/or writeable. If you need
3357 * such gurantee then please use isReadableFile() instead.
3359 * @param $filePathName Name of the file/path to be checked
3360 * @return $isReachable Whether it is within open_basedir()
3362 protected static function isReachableFilePath ($filePathName) {
3363 // Is not reachable by default
3364 $isReachable = FALSE;
3366 // Get open_basedir parameter
3367 $openBaseDir = ini_get('open_basedir');
3370 if (!empty($openBaseDir)) {
3371 // Check all entries
3372 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3373 // Check on existence
3374 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3376 $isReachable = TRUE;
3380 // If open_basedir is not set, all is allowed
3381 $isReachable = TRUE;
3385 return $isReachable;
3389 * Checks whether the give file is within open_basedir() (done by
3390 * isReachableFilePath()), is actually a file and is readable.
3392 * @param $fileName Name of the file to be checked
3393 * @return $isReadable Whether the file is readable (and therefor exists)
3395 public static function isReadableFile ($fileName) {
3396 // Default is not readable
3397 $isReadable = FALSE;
3399 // Is within parameters, so check if it is a file and readable
3400 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3407 * Creates a full-qualified file name (FQFN) for given file name by adding
3408 * a configured temporary file path to it.
3410 * @param $fileName Name for temporary file
3411 * @return $fqfn Full-qualified file name
3412 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3413 * @throws FileIoException If the file cannot be written
3415 protected static function createTempPathForFile ($fileName) {
3417 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3419 // Is the path writeable?
3420 if (!is_writable($basePath)) {
3421 // Path is write-protected
3422 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3426 $fqfn = $basePath . '/' . $fileName;
3429 if (!self::isReachableFilePath($fqfn)) {
3431 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3439 * "Getter" for a printable state name
3441 * @return $stateName Name of the node's state in a printable format
3443 public final function getPrintableState () {
3444 // Default is 'null'
3445 $stateName = 'null';
3447 // Get the state instance
3448 $stateInstance = $this->getStateInstance();
3450 // Is it an instance of Stateable?
3451 if ($stateInstance instanceof Stateable) {
3452 // Then use that state name
3453 $stateName = $stateInstance->getStateName();
3461 * Handles socket error for given socket resource and peer data. This method
3462 * validates $socketResource if it is a valid resource (see is_resource())
3463 * but assumes valid data in array $recipientData, except that
3464 * count($recipientData) is always 2.
3466 * @param $method Value of __METHOD__ from calling method
3467 * @param $line Value of __LINE__ from calling method
3468 * @param $socketResource A valid socket resource
3469 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3471 * @throws InvalidSocketException If $socketResource is no socket resource
3472 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3473 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3475 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3476 // This method handles only socket resources
3477 if (!is_resource($socketResource)) {
3478 // No resource, abort here
3479 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3482 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3483 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3484 assert(isset($socketData[0]));
3485 assert(isset($socketData[1]));
3487 // Get error code for first validation (0 is not an error)
3488 $errorCode = socket_last_error($socketResource);
3490 // If the error code is zero, someone called this method without an error
3491 if ($errorCode == 0) {
3492 // No error detected (or previously cleared outside this method)
3493 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3496 // Get handler (method) name
3497 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3499 // Call-back the error handler method
3500 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3502 // Finally clear the error because it has been handled
3503 socket_clear_error($socketResource);