3 * The simulator system class is the super class of all other classes. This
4 * class handles saving of games etc.
6 * @author Roland Haeder <webmaster@shipsimu.org>
8 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.shipsimu.org
12 * This program is free software: you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation, either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
29 private $realClass = 'BaseFrameworkSystem';
32 * Instance of a request class
34 private $requestInstance = NULL;
37 * Instance of a response class
39 private $responseInstance = NULL;
42 * Search criteria instance
44 private $searchInstance = NULL;
47 * Update criteria instance
49 private $updateInstance = NULL;
52 * The file I/O instance for the template loader
54 private $fileIoInstance = NULL;
59 private $resolverInstance = NULL;
62 * Template engine instance
64 private $templateInstance = NULL;
67 * Database result instance
69 private $resultInstance = NULL;
72 * Instance for user class
74 private $userInstance = NULL;
77 * A controller instance
79 private $controllerInstance = NULL;
84 private $rngInstance = NULL;
87 * Instance of a crypto helper
89 private $cryptoInstance = NULL;
92 * Instance of an Iterator class
94 private $iteratorInstance = NULL;
97 * Instance of the list
99 private $listInstance = NULL;
104 private $menuInstance = NULL;
107 * Instance of the image
109 private $imageInstance = NULL;
112 * Instance of the stacker
114 private $stackerInstance = NULL;
117 * A Compressor instance
119 private $compressorInstance = NULL;
122 * A Parseable instance
124 private $parserInstance = NULL;
127 * A ProtocolHandler instance
129 private $protocolInstance = NULL;
132 * A database wrapper instance
134 private $databaseInstance = NULL;
137 * A helper instance for the form
139 private $helperInstance = NULL;
142 * An instance of a Sourceable class
144 private $sourceInstance = NULL;
147 * An instance of a InputStream class
149 private $inputStreamInstance = NULL;
152 * An instance of a OutputStream class
154 private $outputStreamInstance = NULL;
157 * Networkable handler instance
159 private $handlerInstance = NULL;
162 * Visitor handler instance
164 private $visitorInstance = NULL;
169 private $dhtInstance = NULL;
172 * An instance of a database wrapper class
174 private $wrapperInstance = NULL;
177 * An instance of a file I/O pointer class (not handler)
179 private $pointerInstance = NULL;
182 * An instance of an Indexable class
184 private $indexInstance = NULL;
187 * An instance of a Block class
189 private $blockInstance = NULL;
192 * Thousands separator
194 private $thousands = '.'; // German
199 private $decimals = ','; // German
204 private $socketResource = FALSE;
209 private $packageData = array();
214 private $genericArray = array();
216 /***********************
217 * Exception codes.... *
218 ***********************/
220 // @todo Try to clean these constants up
221 const EXCEPTION_IS_NULL_POINTER = 0x001;
222 const EXCEPTION_IS_NO_OBJECT = 0x002;
223 const EXCEPTION_IS_NO_ARRAY = 0x003;
224 const EXCEPTION_MISSING_METHOD = 0x004;
225 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
226 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
227 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
228 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
229 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
230 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
231 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
232 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
233 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
234 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
235 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
236 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
237 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
238 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
239 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
240 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
241 const EXCEPTION_PATH_NOT_FOUND = 0x015;
242 const EXCEPTION_INVALID_PATH_NAME = 0x016;
243 const EXCEPTION_READ_PROTECED_PATH = 0x017;
244 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
245 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
246 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
247 const EXCEPTION_INVALID_RESOURCE = 0x01b;
248 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
249 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
250 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
251 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
252 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
253 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
254 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
255 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
256 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
257 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
258 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
259 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
260 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
261 const EXCEPTION_INVALID_STRING = 0x029;
262 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
263 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
264 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
265 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
266 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
267 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
268 const EXCEPTION_MISSING_ELEMENT = 0x030;
269 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
270 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
271 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
272 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
273 const EXCEPTION_FATAL_ERROR = 0x035;
274 const EXCEPTION_FILE_NOT_FOUND = 0x036;
275 const EXCEPTION_ASSERTION_FAILED = 0x037;
276 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
277 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
278 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03a;
281 * Hexadecimal->Decimal translation array
283 private static $hexdec = array(
303 * Decimal->hexadecimal translation array
305 private static $dechex = array(
325 * Startup time in miliseconds
327 private static $startupTime = 0;
330 * Protected super constructor
332 * @param $className Name of the class
335 protected function __construct ($className) {
337 $this->setRealClass($className);
339 // Set configuration instance if no registry ...
340 if (!$this instanceof Register) {
341 // ... because registries doesn't need to be configured
342 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
345 // Is the startup time set? (0 cannot be TRUE anymore)
346 if (self::$startupTime == 0) {
348 self::$startupTime = microtime(TRUE);
353 * Destructor for all classes
357 public function __destruct () {
358 // Flush any updated entries to the database
359 $this->flushPendingUpdates();
361 // Is this object already destroyed?
362 if ($this->__toString() != 'DestructedObject') {
363 // Destroy all informations about this class but keep some text about it alive
364 $this->setRealClass('DestructedObject');
365 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
366 // Already destructed object
367 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
372 // Do not call this twice
373 trigger_error(__METHOD__ . ': Called twice.');
379 * The __call() method where all non-implemented methods end up
381 * @param $methodName Name of the missing method
382 * @args $args Arguments passed to the method
385 public final function __call ($methodName, $args) {
386 return self::__callStatic($methodName, $args);
390 * The __callStatic() method where all non-implemented static methods end up
392 * @param $methodName Name of the missing method
393 * @args $args Arguments passed to the method
396 public static final function __callStatic ($methodName, $args) {
397 // Init argument string
400 // Is it empty or an array?
403 $argsString = 'NULL';
404 } elseif (is_array($args)) {
405 // Some arguments are there
406 foreach ($args as $arg) {
407 // Add the value itself if not array. This prevents 'array to string conversion' message
408 if (is_array($arg)) {
409 $argsString .= 'Array';
414 // Add data about the argument
415 $argsString .= ' (' . gettype($arg);
417 if (is_string($arg)) {
418 // Add length for strings
419 $argsString .= ', ' . strlen($arg);
420 } elseif (is_array($arg)) {
421 // .. or size if array
422 $argsString .= ', ' . count($arg);
423 } elseif ($arg === TRUE) {
424 // ... is boolean 'TRUE'
425 $argsString .= ', TRUE';
426 } elseif ($arg === FALSE) {
427 // ... is boolean 'FALSE'
428 $argsString .= ', FALSE';
432 $argsString .= '), ';
436 if (substr($argsString, -2, 1) == ',') {
437 $argsString = substr($argsString, 0, -2);
440 // Invalid arguments!
441 $argsString = '!INVALID:' . gettype($args) . '!';
444 // Output stub message
445 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
446 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
456 * Getter for $realClass
458 * @return $realClass The name of the real class (not BaseFrameworkSystem)
460 public function __toString () {
461 return $this->realClass;
465 * Magic function to catch setting of missing but set class fields/attributes
467 * @param $name Name of the field/attribute
468 * @param $value Value to store
471 public final function __set ($name, $value) {
472 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
475 print_r($value, TRUE)
480 * Magic function to catch getting of missing fields/attributes
482 * @param $name Name of the field/attribute
485 public final function __get ($name) {
486 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
492 * Magic function to catch unsetting of missing fields/attributes
494 * @param $name Name of the field/attribute
497 public final function __unset ($name) {
498 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
504 * Setter for the real class name
506 * @param $realClass Class name (string)
509 public final function setRealClass ($realClass) {
511 $this->realClass = (string) $realClass;
515 * Setter for database result instance
517 * @param $resultInstance An instance of a database result class
519 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
521 protected final function setResultInstance (SearchableResult $resultInstance) {
522 $this->resultInstance = $resultInstance;
526 * Getter for database result instance
528 * @return $resultInstance An instance of a database result class
530 public final function getResultInstance () {
531 return $this->resultInstance;
535 * Setter for template engine instances
537 * @param $templateInstance An instance of a template engine class
540 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
541 $this->templateInstance = $templateInstance;
545 * Getter for template engine instances
547 * @return $templateInstance An instance of a template engine class
549 protected final function getTemplateInstance () {
550 return $this->templateInstance;
554 * Setter for search instance
556 * @param $searchInstance Searchable criteria instance
559 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
560 $this->searchInstance = $searchInstance;
564 * Getter for search instance
566 * @return $searchInstance Searchable criteria instance
568 public final function getSearchInstance () {
569 return $this->searchInstance;
573 * Setter for update instance
575 * @param $updateInstance Searchable criteria instance
578 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
579 $this->updateInstance = $updateInstance;
583 * Getter for update instance
585 * @return $updateInstance Updateable criteria instance
587 public final function getUpdateInstance () {
588 return $this->updateInstance;
592 * Setter for resolver instance
594 * @param $resolverInstance Instance of a command resolver class
597 public final function setResolverInstance (Resolver $resolverInstance) {
598 $this->resolverInstance = $resolverInstance;
602 * Getter for resolver instance
604 * @return $resolverInstance Instance of a command resolver class
606 public final function getResolverInstance () {
607 return $this->resolverInstance;
611 * Setter for language instance
613 * @param $configInstance The configuration instance which shall
614 * be FrameworkConfiguration
617 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
618 Registry::getRegistry()->addInstance('config', $configInstance);
622 * Getter for configuration instance
624 * @return $configInstance Configuration instance
626 public final function getConfigInstance () {
627 $configInstance = Registry::getRegistry()->getInstance('config');
628 return $configInstance;
632 * Setter for debug instance
634 * @param $debugInstance The instance for debug output class
637 public final function setDebugInstance (DebugMiddleware $debugInstance) {
638 Registry::getRegistry()->addInstance('debug', $debugInstance);
642 * Getter for debug instance
644 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
646 public final function getDebugInstance () {
647 // Get debug instance
648 $debugInstance = Registry::getRegistry()->getInstance('debug');
651 return $debugInstance;
655 * Setter for web output instance
657 * @param $webInstance The instance for web output class
660 public final function setWebOutputInstance (OutputStreamer $webInstance) {
661 Registry::getRegistry()->addInstance('web_output', $webInstance);
665 * Getter for web output instance
667 * @return $webOutputInstance - Instance to class WebOutput
669 public final function getWebOutputInstance () {
670 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
671 return $webOutputInstance;
675 * Setter for database instance
677 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
680 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
681 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
685 * Getter for database layer
687 * @return $databaseInstance The database layer instance
689 public final function getDatabaseInstance () {
691 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
694 return $databaseInstance;
698 * Setter for compressor channel
700 * @param $compressorInstance An instance of CompressorChannel
703 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
704 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
708 * Getter for compressor channel
710 * @return $compressorInstance The compressor channel
712 public final function getCompressorChannel () {
713 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
714 return $compressorInstance;
718 * Protected getter for a manageable application helper class
720 * @return $applicationInstance An instance of a manageable application helper class
722 protected final function getApplicationInstance () {
723 $applicationInstance = Registry::getRegistry()->getInstance('application');
724 return $applicationInstance;
728 * Setter for a manageable application helper class
730 * @param $applicationInstance An instance of a manageable application helper class
733 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
734 Registry::getRegistry()->addInstance('application', $applicationInstance);
738 * Setter for request instance
740 * @param $requestInstance An instance of a Requestable class
743 public final function setRequestInstance (Requestable $requestInstance) {
744 $this->requestInstance = $requestInstance;
748 * Getter for request instance
750 * @return $requestInstance An instance of a Requestable class
752 public final function getRequestInstance () {
753 return $this->requestInstance;
757 * Setter for response instance
759 * @param $responseInstance An instance of a Responseable class
762 public final function setResponseInstance (Responseable $responseInstance) {
763 $this->responseInstance = $responseInstance;
767 * Getter for response instance
769 * @return $responseInstance An instance of a Responseable class
771 public final function getResponseInstance () {
772 return $this->responseInstance;
776 * Private getter for language instance
778 * @return $langInstance An instance to the language sub-system
780 protected final function getLanguageInstance () {
781 $langInstance = Registry::getRegistry()->getInstance('language');
782 return $langInstance;
786 * Setter for language instance
788 * @param $langInstance An instance to the language sub-system
790 * @see LanguageSystem
792 public final function setLanguageInstance (ManageableLanguage $langInstance) {
793 Registry::getRegistry()->addInstance('language', $langInstance);
797 * Private getter for file IO instance
799 * @return $fileIoInstance An instance to the file I/O sub-system
801 protected final function getFileIoInstance () {
802 return $this->fileIoInstance;
806 * Setter for file I/O instance
808 * @param $fileIoInstance An instance to the file I/O sub-system
811 public final function setFileIoInstance (IoHandler $fileIoInstance) {
812 $this->fileIoInstance = $fileIoInstance;
816 * Protected setter for user instance
818 * @param $userInstance An instance of a user class
821 protected final function setUserInstance (ManageableAccount $userInstance) {
822 $this->userInstance = $userInstance;
826 * Getter for user instance
828 * @return $userInstance An instance of a user class
830 public final function getUserInstance () {
831 return $this->userInstance;
835 * Setter for controller instance (this surely breaks a bit the MVC patterm)
837 * @param $controllerInstance An instance of the controller
840 public final function setControllerInstance (Controller $controllerInstance) {
841 $this->controllerInstance = $controllerInstance;
845 * Getter for controller instance (this surely breaks a bit the MVC patterm)
847 * @return $controllerInstance An instance of the controller
849 public final function getControllerInstance () {
850 return $this->controllerInstance;
854 * Setter for RNG instance
856 * @param $rngInstance An instance of a random number generator (RNG)
859 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
860 $this->rngInstance = $rngInstance;
864 * Getter for RNG instance
866 * @return $rngInstance An instance of a random number generator (RNG)
868 public final function getRngInstance () {
869 return $this->rngInstance;
873 * Setter for Cryptable instance
875 * @param $cryptoInstance An instance of a Cryptable class
878 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
879 $this->cryptoInstance = $cryptoInstance;
883 * Getter for Cryptable instance
885 * @return $cryptoInstance An instance of a Cryptable class
887 public final function getCryptoInstance () {
888 return $this->cryptoInstance;
892 * Setter for the list instance
894 * @param $listInstance A list of Listable
897 protected final function setListInstance (Listable $listInstance) {
898 $this->listInstance = $listInstance;
902 * Getter for the list instance
904 * @return $listInstance A list of Listable
906 protected final function getListInstance () {
907 return $this->listInstance;
911 * Setter for the menu instance
913 * @param $menuInstance A RenderableMenu instance
916 protected final function setMenuInstance (RenderableMenu $menuInstance) {
917 $this->menuInstance = $menuInstance;
921 * Getter for the menu instance
923 * @return $menuInstance A RenderableMenu instance
925 protected final function getMenuInstance () {
926 return $this->menuInstance;
930 * Setter for image instance
932 * @param $imageInstance An instance of an image
935 public final function setImageInstance (BaseImage $imageInstance) {
936 $this->imageInstance = $imageInstance;
940 * Getter for image instance
942 * @return $imageInstance An instance of an image
944 public final function getImageInstance () {
945 return $this->imageInstance;
949 * Setter for stacker instance
951 * @param $stackerInstance An instance of an stacker
954 public final function setStackerInstance (Stackable $stackerInstance) {
955 $this->stackerInstance = $stackerInstance;
959 * Getter for stacker instance
961 * @return $stackerInstance An instance of an stacker
963 public final function getStackerInstance () {
964 return $this->stackerInstance;
968 * Setter for compressor instance
970 * @param $compressorInstance An instance of an compressor
973 public final function setCompressorInstance (Compressor $compressorInstance) {
974 $this->compressorInstance = $compressorInstance;
978 * Getter for compressor instance
980 * @return $compressorInstance An instance of an compressor
982 public final function getCompressorInstance () {
983 return $this->compressorInstance;
987 * Setter for Parseable instance
989 * @param $parserInstance An instance of an Parseable
992 public final function setParserInstance (Parseable $parserInstance) {
993 $this->parserInstance = $parserInstance;
997 * Getter for Parseable instance
999 * @return $parserInstance An instance of an Parseable
1001 public final function getParserInstance () {
1002 return $this->parserInstance;
1006 * Setter for ProtocolHandler instance
1008 * @param $protocolInstance An instance of an ProtocolHandler
1011 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
1012 $this->protocolInstance = $protocolInstance;
1016 * Getter for ProtocolHandler instance
1018 * @return $protocolInstance An instance of an ProtocolHandler
1020 public final function getProtocolInstance () {
1021 return $this->protocolInstance;
1025 * Setter for DatabaseWrapper instance
1027 * @param $wrapperInstance An instance of an DatabaseWrapper
1030 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1031 $this->wrapperInstance = $wrapperInstance;
1035 * Getter for DatabaseWrapper instance
1037 * @return $wrapperInstance An instance of an DatabaseWrapper
1039 public final function getWrapperInstance () {
1040 return $this->wrapperInstance;
1044 * Setter for socket resource
1046 * @param $socketResource A valid socket resource
1049 public final function setSocketResource ($socketResource) {
1050 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1051 $this->socketResource = $socketResource;
1055 * Getter for socket resource
1057 * @return $socketResource A valid socket resource
1059 public final function getSocketResource () {
1060 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1061 return $this->socketResource;
1065 * Setter for helper instance
1067 * @param $helperInstance An instance of a helper class
1070 protected final function setHelperInstance (Helper $helperInstance) {
1071 $this->helperInstance = $helperInstance;
1075 * Getter for helper instance
1077 * @return $helperInstance An instance of a helper class
1079 public final function getHelperInstance () {
1080 return $this->helperInstance;
1084 * Setter for a Sourceable instance
1086 * @param $sourceInstance The Sourceable instance
1089 protected final function setSourceInstance (Sourceable $sourceInstance) {
1090 $this->sourceInstance = $sourceInstance;
1094 * Getter for a Sourceable instance
1096 * @return $sourceInstance The Sourceable instance
1098 protected final function getSourceInstance () {
1099 return $this->sourceInstance;
1103 * Getter for a InputStream instance
1105 * @param $inputStreamInstance The InputStream instance
1107 protected final function getInputStreamInstance () {
1108 return $this->inputStreamInstance;
1112 * Setter for a InputStream instance
1114 * @param $inputStreamInstance The InputStream instance
1117 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1118 $this->inputStreamInstance = $inputStreamInstance;
1122 * Getter for a OutputStream instance
1124 * @param $outputStreamInstance The OutputStream instance
1126 protected final function getOutputStreamInstance () {
1127 return $this->outputStreamInstance;
1131 * Setter for a OutputStream instance
1133 * @param $outputStreamInstance The OutputStream instance
1136 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1137 $this->outputStreamInstance = $outputStreamInstance;
1141 * Setter for handler instance
1143 * @param $handlerInstance An instance of a Handleable class
1146 protected final function setHandlerInstance (Handleable $handlerInstance) {
1147 $this->handlerInstance = $handlerInstance;
1151 * Getter for handler instance
1153 * @return $handlerInstance A Networkable instance
1155 protected final function getHandlerInstance () {
1156 return $this->handlerInstance;
1160 * Setter for visitor instance
1162 * @param $visitorInstance A Visitor instance
1165 protected final function setVisitorInstance (Visitor $visitorInstance) {
1166 $this->visitorInstance = $visitorInstance;
1170 * Getter for visitor instance
1172 * @return $visitorInstance A Visitor instance
1174 protected final function getVisitorInstance () {
1175 return $this->visitorInstance;
1179 * Setter for DHT instance
1181 * @param $dhtInstance A Distributable instance
1184 protected final function setDhtInstance (Distributable $dhtInstance) {
1185 $this->dhtInstance = $dhtInstance;
1189 * Getter for DHT instance
1191 * @return $dhtInstance A Distributable instance
1193 protected final function getDhtInstance () {
1194 return $this->dhtInstance;
1198 * Setter for raw package Data
1200 * @param $packageData Raw package Data
1203 public final function setPackageData (array $packageData) {
1204 $this->packageData = $packageData;
1208 * Getter for raw package Data
1210 * @return $packageData Raw package Data
1212 public function getPackageData () {
1213 return $this->packageData;
1218 * Setter for Iterator instance
1220 * @param $iteratorInstance An instance of an Iterator
1223 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1224 $this->iteratorInstance = $iteratorInstance;
1228 * Getter for Iterator instance
1230 * @return $iteratorInstance An instance of an Iterator
1232 public final function getIteratorInstance () {
1233 return $this->iteratorInstance;
1237 * Setter for InputOutputPointer instance
1239 * @param $pointerInstance An instance of an InputOutputPointer class
1242 protected final function setPointerInstance (InputOutputPointer $pointerInstance) {
1243 $this->pointerInstance = $pointerInstance;
1247 * Getter for InputOutputPointer instance
1249 * @return $pointerInstance An instance of an InputOutputPointer class
1251 public final function getPointerInstance () {
1252 return $this->pointerInstance;
1256 * Setter for Indexable instance
1258 * @param $indexInstance An instance of an Indexable class
1261 protected final function setIndexInstance (Indexable $indexInstance) {
1262 $this->indexInstance = $indexInstance;
1266 * Getter for Indexable instance
1268 * @return $indexInstance An instance of an Indexable class
1270 public final function getIndexInstance () {
1271 return $this->indexInstance;
1275 * Setter for Block instance
1277 * @param $blockInstance An instance of an Block class
1280 protected final function setBlockInstance (Block $blockInstance) {
1281 $this->blockInstance = $blockInstance;
1285 * Getter for Block instance
1287 * @return $blockInstance An instance of an Block class
1289 public final function getBlockInstance () {
1290 return $this->blockInstance;
1294 * Checks whether an object equals this object. You should overwrite this
1295 * method to implement own equality checks
1297 * @param $objectInstance An instance of a FrameworkInterface object
1298 * @return $equals Whether both objects equals
1300 public function equals (FrameworkInterface $objectInstance) {
1303 $this->__toString() == $objectInstance->__toString()
1305 $this->hashCode() == $objectInstance->hashCode()
1308 // Return the result
1313 * Generates a generic hash code of this class. You should really overwrite
1314 * this method with your own hash code generator code. But keep KISS in mind.
1316 * @return $hashCode A generic hash code respresenting this whole class
1318 public function hashCode () {
1320 return crc32($this->__toString());
1324 * Formats computer generated price values into human-understandable formats
1325 * with thousand and decimal separators.
1327 * @param $value The in computer format value for a price
1328 * @param $currency The currency symbol (use HTML-valid characters!)
1329 * @param $decNum Number of decimals after commata
1330 * @return $price The for the current language formated price string
1331 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1332 * thousands separator
1335 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1336 // Are all required attriutes set?
1337 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1338 // Throw an exception
1339 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1343 $value = (float) $value;
1345 // Reformat the US number
1346 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1348 // Return as string...
1353 * Appends a trailing slash to a string
1355 * @param $str A string (maybe) without trailing slash
1356 * @return $str A string with an auto-appended trailing slash
1358 public final function addMissingTrailingSlash ($str) {
1359 // Is there a trailing slash?
1360 if (substr($str, -1, 1) != '/') {
1364 // Return string with trailing slash
1369 * Prepare the template engine (WebTemplateEngine by default) for a given
1370 * application helper instance (ApplicationHelper by default).
1372 * @param $applicationInstance An application helper instance or
1373 * null if we shall use the default
1374 * @return $templateInstance The template engine instance
1375 * @throws NullPointerException If the discovered application
1376 * instance is still null
1378 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1379 // Is the application instance set?
1380 if (is_null($applicationInstance)) {
1381 // Get the current instance
1382 $applicationInstance = $this->getApplicationInstance();
1385 if (is_null($applicationInstance)) {
1386 // Thrown an exception
1387 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1391 // Initialize the template engine
1392 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1394 // Return the prepared instance
1395 return $templateInstance;
1399 * Debugs this instance by putting out it's full content
1401 * @param $message Optional message to show in debug output
1404 public final function debugInstance ($message = '') {
1405 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1406 restore_error_handler();
1411 // Is a message set?
1412 if (!empty($message)) {
1413 // Construct message
1414 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1417 // Generate the output
1418 $content .= sprintf('<pre>%s</pre>',
1421 print_r($this, TRUE)
1427 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>',
1428 $this->__toString(),
1430 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1435 * Replaces control characters with printable output
1437 * @param $str String with control characters
1438 * @return $str Replaced string
1440 protected function replaceControlCharacters ($str) {
1443 chr(13), '[r]', str_replace(
1444 chr(10), '[n]', str_replace(
1454 * Output a partial stub message for the caller method
1456 * @param $message An optional message to display
1459 protected function partialStub ($message = '') {
1460 // Get the backtrace
1461 $backtrace = debug_backtrace();
1463 // Generate the class::method string
1464 $methodName = 'UnknownClass->unknownMethod';
1465 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1466 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1469 // Construct the full message
1470 $stubMessage = sprintf('[%s:] Partial stub!',
1474 // Is the extra message given?
1475 if (!empty($message)) {
1476 // Then add it as well
1477 $stubMessage .= ' Message: ' . $message;
1480 // Debug instance is there?
1481 if (!is_null($this->getDebugInstance())) {
1482 // Output stub message
1483 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1486 trigger_error($stubMessage);
1492 * Outputs a debug backtrace and stops further script execution
1494 * @param $message An optional message to output
1495 * @param $doExit Whether exit the program (TRUE is default)
1498 public function debugBackTrace ($message = '', $doExit = TRUE) {
1499 // Sorry, there is no other way getting this nice backtrace
1500 if (!empty($message)) {
1502 printf('Message: %s<br />' . chr(10), $message);
1506 debug_print_backtrace();
1510 if ($doExit === TRUE) {
1516 * Creates an instance of a debugger instance
1518 * @param $className Name of the class (currently unsupported)
1519 * @return $debugInstance An instance of a debugger class
1521 public final static function createDebugInstance ($className) {
1522 // Is the instance set?
1523 if (!Registry::getRegistry()->instanceExists('debug')) {
1524 // Init debug instance
1525 $debugInstance = NULL;
1529 // Get a debugger instance
1530 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_class'));
1531 } catch (NullPointerException $e) {
1532 // Didn't work, no instance there
1533 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1536 // Empty string should be ignored and used for testing the middleware
1537 DebugMiddleware::getSelfInstance()->output('');
1539 // Set it in its own class. This will set it in the registry
1540 $debugInstance->setDebugInstance($debugInstance);
1542 // Get instance from registry
1543 $debugInstance = Registry::getRegistry()->getDebugInstance();
1547 return $debugInstance;
1551 * Simple output of a message with line-break
1553 * @param $message Message to output
1556 public function outputLine ($message) {
1558 print($message . PHP_EOL);
1562 * Outputs a debug message whether to debug instance (should be set!) or
1563 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1564 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1566 * @param $message Message we shall send out...
1567 * @param $doPrint Whether print or die here (default: print)
1568 * @paran $stripTags Whether to strip tags (default: FALSE)
1571 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1572 // Set debug instance to NULL
1573 $debugInstance = NULL;
1577 // Get debug instance
1578 $debugInstance = $this->getDebugInstance();
1579 } catch (NullPointerException $e) {
1580 // The debug instance is not set (yet)
1583 // Is the debug instance there?
1584 if (is_object($debugInstance)) {
1585 // Use debug output handler
1586 $debugInstance->output($message, $stripTags);
1588 if ($doPrint === FALSE) {
1589 // Die here if not printed
1593 // Are debug times enabled?
1594 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1596 $message = $this->getPrintableExecutionTime() . $message;
1600 if ($doPrint === TRUE) {
1602 $this->outputLine($message);
1611 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1613 * @param $str The string, what ever it is needs to be converted
1614 * @return $className Generated class name
1616 public function convertToClassName ($str) {
1620 // Convert all dashes in underscores
1621 $str = $this->convertDashesToUnderscores($str);
1623 // Now use that underscores to get classname parts for hungarian style
1624 foreach (explode('_', $str) as $strPart) {
1625 // Make the class name part lower case and first upper case
1626 $className .= ucfirst(strtolower($strPart));
1629 // Return class name
1634 * Converts dashes to underscores, e.g. useable for configuration entries
1636 * @param $str The string with maybe dashes inside
1637 * @return $str The converted string with no dashed, but underscores
1639 public final function convertDashesToUnderscores ($str) {
1641 $str = str_replace('-', '_', $str);
1643 // Return converted string
1648 * Marks up the code by adding e.g. line numbers
1650 * @param $phpCode Unmarked PHP code
1651 * @return $markedCode Marked PHP code
1653 public function markupCode ($phpCode) {
1658 $errorArray = error_get_last();
1660 // Init the code with error message
1661 if (is_array($errorArray)) {
1663 $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>',
1664 basename($errorArray['file']),
1665 $errorArray['line'],
1666 $errorArray['message'],
1671 // Add line number to the code
1672 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1674 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1676 htmlentities($code, ENT_QUOTES)
1685 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1686 * beatiful for web-based front-ends. If null is given a message id
1687 * null_timestamp will be resolved and returned.
1689 * @param $timestamp Timestamp to prepare (filter) for display
1690 * @return $readable A readable timestamp
1692 public function doFilterFormatTimestamp ($timestamp) {
1693 // Default value to return
1696 // Is the timestamp null?
1697 if (is_null($timestamp)) {
1698 // Get a message string
1699 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1701 switch ($this->getLanguageInstance()->getLanguageCode()) {
1702 case 'de': // German format is a bit different to default
1703 // Split the GMT stamp up
1704 $dateTime = explode(' ', $timestamp );
1705 $dateArray = explode('-', $dateTime[0]);
1706 $timeArray = explode(':', $dateTime[1]);
1708 // Construct the timestamp
1709 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1719 default: // Default is pass-through
1720 $readable = $timestamp;
1730 * Filter a given number into a localized number
1732 * @param $value The raw value from e.g. database
1733 * @return $localized Localized value
1735 public function doFilterFormatNumber ($value) {
1736 // Generate it from config and localize dependencies
1737 switch ($this->getLanguageInstance()->getLanguageCode()) {
1738 case 'de': // German format is a bit different to default
1739 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1742 default: // US, etc.
1743 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1752 * "Getter" for databse entry
1754 * @return $entry An array with database entries
1755 * @throws NullPointerException If the database result is not found
1756 * @throws InvalidDatabaseResultException If the database result is invalid
1758 protected final function getDatabaseEntry () {
1759 // Is there an instance?
1760 if (is_null($this->getResultInstance())) {
1761 // Throw an exception here
1762 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1766 $this->getResultInstance()->rewind();
1768 // Do we have an entry?
1769 if ($this->getResultInstance()->valid() === FALSE) {
1770 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1774 $this->getResultInstance()->next();
1777 $entry = $this->getResultInstance()->current();
1784 * Getter for field name
1786 * @param $fieldName Field name which we shall get
1787 * @return $fieldValue Field value from the user
1788 * @throws NullPointerException If the result instance is null
1790 public final function getField ($fieldName) {
1791 // Default field value
1794 // Get result instance
1795 $resultInstance = $this->getResultInstance();
1797 // Is this instance null?
1798 if (is_null($resultInstance)) {
1799 // Then the user instance is no longer valid (expired cookies?)
1800 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1803 // Get current array
1804 $fieldArray = $resultInstance->current();
1805 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
1807 // Convert dashes to underscore
1808 $fieldName = $this->convertDashesToUnderscores($fieldName);
1810 // Does the field exist?
1811 if (isset($fieldArray[$fieldName])) {
1813 $fieldValue = $fieldArray[$fieldName];
1815 // Missing field entry, may require debugging
1816 self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1824 * Flushs all pending updates to the database layer
1828 public function flushPendingUpdates () {
1829 // Get result instance
1830 $resultInstance = $this->getResultInstance();
1832 // Do we have data to update?
1833 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1834 // Get wrapper class name config entry
1835 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1837 // Create object instance
1838 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1840 // Yes, then send the whole result to the database layer
1841 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1846 * Outputs a deprecation warning to the developer.
1848 * @param $message The message we shall output to the developer
1850 * @todo Write a logging mechanism for productive mode
1852 public function deprecationWarning ($message) {
1853 // Is developer mode active?
1854 if (defined('DEVELOPER')) {
1855 // Debug instance is there?
1856 if (!is_null($this->getDebugInstance())) {
1857 // Output stub message
1858 self::createDebugInstance(__CLASS__)->debugOutput($message);
1861 trigger_error($message . "<br />\n");
1865 // @TODO Finish this part!
1866 $this->partialStub('Developer mode inactive. Message:' . $message);
1871 * Checks whether the given PHP extension is loaded
1873 * @param $phpExtension The PHP extension we shall check
1874 * @return $isLoaded Whether the PHP extension is loaded
1876 public final function isPhpExtensionLoaded ($phpExtension) {
1878 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1885 * "Getter" as a time() replacement but with milliseconds. You should use this
1886 * method instead of the encapsulated getimeofday() function.
1888 * @return $milliTime Timestamp with milliseconds
1890 public function getMilliTime () {
1891 // Get the time of day as float
1892 $milliTime = gettimeofday(TRUE);
1899 * Idles (sleeps) for given milliseconds
1901 * @return $hasSlept Whether it goes fine
1903 public function idle ($milliSeconds) {
1904 // Sleep is fine by default
1907 // Idle so long with found function
1908 if (function_exists('time_sleep_until')) {
1909 // Get current time and add idle time
1910 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1912 // New PHP 5.1.0 function found, ignore errors
1913 $hasSlept = @time_sleep_until($sleepUntil);
1916 * My Sun station doesn't have that function even with latest PHP
1919 usleep($milliSeconds * 1000);
1926 * Converts a hexadecimal string, even with negative sign as first string to
1927 * a decimal number using BC functions.
1929 * This work is based on comment #86673 on php.net documentation page at:
1930 * <http://de.php.net/manual/en/function.dechex.php#86673>
1932 * @param $hex Hexadecimal string
1933 * @return $dec Decimal number
1935 protected function hex2dec ($hex) {
1936 // Convert to all lower-case
1937 $hex = strtolower($hex);
1939 // Detect sign (negative/positive numbers)
1941 if (substr($hex, 0, 1) == '-') {
1943 $hex = substr($hex, 1);
1946 // Decode the hexadecimal string into a decimal number
1948 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1949 $factor = self::$hexdec[substr($hex, $i, 1)];
1950 $dec = bcadd($dec, bcmul($factor, $e));
1953 // Return the decimal number
1954 return $sign . $dec;
1958 * Converts even very large decimal numbers, also signed, to a hexadecimal
1961 * This work is based on comment #97756 on php.net documentation page at:
1962 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1964 * @param $dec Decimal number, even with negative sign
1965 * @param $maxLength Optional maximum length of the string
1966 * @return $hex Hexadecimal string
1968 protected function dec2hex ($dec, $maxLength = 0) {
1969 // maxLength can be zero or devideable by 2
1970 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1972 // Detect sign (negative/positive numbers)
1979 // Encode the decimal number into a hexadecimal string
1982 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
1984 } while ($dec >= 1);
1987 * Leading zeros are required for hex-decimal "numbers". In some
1988 * situations more leading zeros are wanted, so check for both
1991 if ($maxLength > 0) {
1992 // Prepend more zeros
1993 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
1994 } elseif ((strlen($hex) % 2) != 0) {
1995 // Only make string's length dividable by 2
1999 // Return the hexadecimal string
2000 return $sign . $hex;
2004 * Converts a ASCII string (0 to 255) into a decimal number.
2006 * @param $asc The ASCII string to be converted
2007 * @return $dec Decimal number
2009 protected function asc2dec ($asc) {
2010 // Convert it into a hexadecimal number
2011 $hex = bin2hex($asc);
2013 // And back into a decimal number
2014 $dec = $this->hex2dec($hex);
2021 * Converts a decimal number into an ASCII string.
2023 * @param $dec Decimal number
2024 * @return $asc An ASCII string
2026 protected function dec2asc ($dec) {
2027 // First convert the number into a hexadecimal string
2028 $hex = $this->dec2hex($dec);
2030 // Then convert it into the ASCII string
2031 $asc = $this->hex2asc($hex);
2038 * Converts a hexadecimal number into an ASCII string. Negative numbers
2041 * @param $hex Hexadecimal string
2042 * @return $asc An ASCII string
2044 protected function hex2asc ($hex) {
2045 // Check for length, it must be devideable by 2
2046 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2047 assert((strlen($hex) % 2) == 0);
2051 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2052 // Get the decimal number of the chunk
2053 $part = hexdec(substr($hex, $idx, 2));
2055 // Add it to the final string
2059 // Return the final string
2064 * Checks whether the given encoded data was encoded with Base64
2066 * @param $encodedData Encoded data we shall check
2067 * @return $isBase64 Whether the encoded data is Base64
2069 protected function isBase64Encoded ($encodedData) {
2071 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2078 * "Getter" to get response/request type from analysis of the system.
2080 * @return $responseType Analyzed response type
2082 protected function getResponseTypeFromSystem () {
2083 // Default is console
2084 $responseType = 'console';
2086 // Is 'HTTP_HOST' set?
2087 if (isset($_SERVER['HTTP_HOST'])) {
2088 // Then it is a HTTP response/request
2089 $responseType = 'http';
2093 return $responseType;
2097 * Gets a cache key from Criteria instance
2099 * @param $criteriaInstance An instance of a Criteria class
2100 * @param $onlyKeys Only use these keys for a cache key
2101 * @return $cacheKey A cache key suitable for lookup/storage purposes
2103 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2105 $cacheKey = sprintf('%s@%s',
2106 $this->__toString(),
2107 $criteriaInstance->getCacheKey($onlyKeys)
2111 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2116 * Getter for startup time in miliseconds
2118 * @return $startupTime Startup time in miliseconds
2120 protected function getStartupTime () {
2121 return self::$startupTime;
2125 * "Getter" for a printable currently execution time in nice braces
2127 * @return $executionTime Current execution time in nice braces
2129 protected function getPrintableExecutionTime () {
2130 // Caculate the execution time
2131 $executionTime = microtime(TRUE) - $this->getStartupTime();
2133 // Pack it in nice braces
2134 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2137 return $executionTime;
2141 * Hashes a given string with a simple but stronger hash function (no salt)
2142 * and hex-encode it.
2144 * @param $str The string to be hashed
2145 * @return $hash The hash from string $str
2147 public static final function hash ($str) {
2148 // Hash given string with (better secure) hasher
2149 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2156 * "Getter" for length of hash() output. This will be "cached" to speed up
2159 * @return $length Length of hash() output
2161 public static final function getHashLength () {
2163 if (is_null(self::$hashLength)) {
2164 // No, then hash a string and save its length.
2165 self::$hashLength = strlen(self::hash('abc123'));
2169 return self::$hashLength;
2173 * Checks whether the given number is really a number (only chars 0-9).
2175 * @param $num A string consisting only chars between 0 and 9
2176 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2177 * @param $assertMismatch Whether to assert mismatches
2178 * @return $ret The (hopefully) secured numbered value
2180 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2181 // Filter all numbers out
2182 $ret = preg_replace('/[^0123456789]/', '', $num);
2185 if ($castValue === TRUE) {
2186 // Cast to biggest numeric type
2187 $ret = (double) $ret;
2190 // Assert only if requested
2191 if ($assertMismatch === TRUE) {
2192 // Has the whole value changed?
2193 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2201 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2203 * @param $num A string consisting only chars between 0 and 9
2204 * @param $assertMismatch Whether to assert mismatches
2205 * @return $ret The (hopefully) secured hext-numbered value
2207 public function hexval ($num, $assertMismatch = FALSE) {
2208 // Filter all numbers out
2209 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2211 // Assert only if requested
2212 if ($assertMismatch === TRUE) {
2213 // Has the whole value changed?
2214 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2222 * Checks whether start/end marker are set
2224 * @param $data Data to be checked
2225 * @return $isset Whether start/end marker are set
2227 public final function ifStartEndMarkersSet ($data) {
2229 $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));
2231 // ... and return it
2236 * Determines if an element is set in the generic array
2238 * @param $keyGroup Main group for the key
2239 * @param $subGroup Sub group for the key
2240 * @param $key Key to check
2241 * @param $element Element to check
2242 * @return $isset Whether the given key is set
2244 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2246 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2249 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2255 * Determines if a key is set in the generic array
2257 * @param $keyGroup Main group for the key
2258 * @param $subGroup Sub group for the key
2259 * @param $key Key to check
2260 * @return $isset Whether the given key is set
2262 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2264 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2267 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2275 * Determines if a group is set in the generic array
2277 * @param $keyGroup Main group
2278 * @param $subGroup Sub group
2279 * @return $isset Whether the given group is set
2281 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2283 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2286 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2293 * Getter for sub key group
2295 * @param $keyGroup Main key group
2296 * @param $subGroup Sub key group
2297 * @return $array An array with all array elements
2299 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2301 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2302 // No, then abort here
2303 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2308 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2311 return $this->genericArray[$keyGroup][$subGroup];
2315 * Unsets a given key in generic array
2317 * @param $keyGroup Main group for the key
2318 * @param $subGroup Sub group for the key
2319 * @param $key Key to unset
2322 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2324 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2327 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2331 * Unsets a given element in generic array
2333 * @param $keyGroup Main group for the key
2334 * @param $subGroup Sub group for the key
2335 * @param $key Key to unset
2336 * @param $element Element to unset
2339 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2341 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2344 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2348 * Append a string to a given generic array key
2350 * @param $keyGroup Main group for the key
2351 * @param $subGroup Sub group for the key
2352 * @param $key Key to unset
2353 * @param $value Value to add/append
2356 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2358 //* 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);
2360 // Is it already there?
2361 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2363 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2366 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2371 * Append a string to a given generic array element
2373 * @param $keyGroup Main group for the key
2374 * @param $subGroup Sub group for the key
2375 * @param $key Key to unset
2376 * @param $element Element to check
2377 * @param $value Value to add/append
2380 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2382 //* 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);
2384 // Is it already there?
2385 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2387 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2390 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2395 * Initializes given generic array group
2397 * @param $keyGroup Main group for the key
2398 * @param $subGroup Sub group for the key
2399 * @param $key Key to use
2400 * @param $forceInit Optionally force initialization
2403 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2405 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2407 // Is it already set?
2408 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2409 // Already initialized
2410 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2415 $this->genericArray[$keyGroup][$subGroup] = array();
2419 * Initializes given generic array key
2421 * @param $keyGroup Main group for the key
2422 * @param $subGroup Sub group for the key
2423 * @param $key Key to use
2424 * @param $forceInit Optionally force initialization
2427 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2429 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2431 // Is it already set?
2432 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2433 // Already initialized
2434 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2439 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2443 * Initializes given generic array element
2445 * @param $keyGroup Main group for the key
2446 * @param $subGroup Sub group for the key
2447 * @param $key Key to use
2448 * @param $element Element to use
2449 * @param $forceInit Optionally force initialization
2452 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2454 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2456 // Is it already set?
2457 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2458 // Already initialized
2459 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2464 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2468 * Pushes an element to a generic key
2470 * @param $keyGroup Main group for the key
2471 * @param $subGroup Sub group for the key
2472 * @param $key Key to use
2473 * @param $value Value to add/append
2474 * @return $count Number of array elements
2476 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2478 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2481 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2483 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2487 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2490 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2491 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2496 * Pushes an element to a generic array element
2498 * @param $keyGroup Main group for the key
2499 * @param $subGroup Sub group for the key
2500 * @param $key Key to use
2501 * @param $element Element to check
2502 * @param $value Value to add/append
2503 * @return $count Number of array elements
2505 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2507 //* 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));
2510 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2512 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2516 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2519 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2520 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2525 * Pops an element from a generic group
2527 * @param $keyGroup Main group for the key
2528 * @param $subGroup Sub group for the key
2529 * @param $key Key to unset
2530 * @return $value Last "popped" value
2532 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2534 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2537 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2539 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2544 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2547 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2548 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2553 * Shifts an element from a generic group
2555 * @param $keyGroup Main group for the key
2556 * @param $subGroup Sub group for the key
2557 * @param $key Key to unset
2558 * @return $value Last "popped" value
2560 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2562 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2565 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2567 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2572 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2575 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2576 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2581 * Count generic array group
2583 * @param $keyGroup Main group for the key
2584 * @return $count Count of given group
2586 protected final function countGenericArray ($keyGroup) {
2588 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2591 if (!isset($this->genericArray[$keyGroup])) {
2593 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2598 $count = count($this->genericArray[$keyGroup]);
2601 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2608 * Count generic array sub group
2610 * @param $keyGroup Main group for the key
2611 * @param $subGroup Sub group for the key
2612 * @return $count Count of given group
2614 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2616 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2619 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2621 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2626 $count = count($this->genericArray[$keyGroup][$subGroup]);
2629 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2636 * Count generic array elements
2638 * @param $keyGroup Main group for the key
2639 * @param $subGroup Sub group for the key
2640 * @para $key Key to count
2641 * @return $count Count of given key
2643 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2645 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2648 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2650 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2652 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2654 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2659 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2662 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2669 * Getter for whole generic group array
2671 * @param $keyGroup Key group to get
2672 * @return $array Whole generic array group
2674 protected final function getGenericArray ($keyGroup) {
2676 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2679 if (!isset($this->genericArray[$keyGroup])) {
2681 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2686 return $this->genericArray[$keyGroup];
2690 * Setter for generic array key
2692 * @param $keyGroup Key group to get
2693 * @param $subGroup Sub group for the key
2694 * @param $key Key to unset
2695 * @param $value Mixed value from generic array element
2698 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2700 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2703 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2707 * Getter for generic array key
2709 * @param $keyGroup Key group to get
2710 * @param $subGroup Sub group for the key
2711 * @param $key Key to unset
2712 * @return $value Mixed value from generic array element
2714 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2716 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2719 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2721 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2726 return $this->genericArray[$keyGroup][$subGroup][$key];
2730 * Sets a value in given generic array key/element
2732 * @param $keyGroup Main group for the key
2733 * @param $subGroup Sub group for the key
2734 * @param $key Key to set
2735 * @param $element Element to set
2736 * @param $value Value to set
2739 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2741 //* 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));
2744 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2748 * Getter for generic array element
2750 * @param $keyGroup Key group to get
2751 * @param $subGroup Sub group for the key
2752 * @param $key Key to look for
2753 * @param $element Element to look for
2754 * @return $value Mixed value from generic array element
2756 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2758 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2761 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2763 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2768 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2772 * Checks if a given sub group is valid (array)
2774 * @param $keyGroup Key group to get
2775 * @param $subGroup Sub group for the key
2776 * @return $isValid Whether given sub group is valid
2778 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2780 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2783 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2790 * Checks if a given key is valid (array)
2792 * @param $keyGroup Key group to get
2793 * @param $subGroup Sub group for the key
2794 * @param $key Key to check
2795 * @return $isValid Whether given sub group is valid
2797 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2799 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2802 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2809 * Translates boolean TRUE to 'Y' and FALSE to 'N'
2811 * @param $boolean Boolean value
2812 * @return $translated Translated boolean value
2814 public static final function translateBooleanToYesNo ($boolean) {
2815 // Make sure it is really boolean
2816 assert(is_bool($boolean));
2819 $translated = ($boolean === TRUE) ? 'Y' : 'N';
2821 // ... and return it