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 {
27 * Length of output from hash()
29 private static $hashLength = NULL;
34 private $realClass = 'BaseFrameworkSystem';
37 * Instance of a request class
39 private $requestInstance = NULL;
42 * Instance of a response class
44 private $responseInstance = NULL;
47 * Search criteria instance
49 private $searchInstance = NULL;
52 * Update criteria instance
54 private $updateInstance = NULL;
57 * The file I/O instance for the template loader
59 private $fileIoInstance = NULL;
64 private $resolverInstance = NULL;
67 * Template engine instance
69 private $templateInstance = NULL;
72 * Database result instance
74 private $resultInstance = NULL;
77 * Instance for user class
79 private $userInstance = NULL;
82 * A controller instance
84 private $controllerInstance = NULL;
89 private $rngInstance = NULL;
92 * Instance of a crypto helper
94 private $cryptoInstance = NULL;
97 * Instance of an Iterator class
99 private $iteratorInstance = NULL;
102 * Instance of the list
104 private $listInstance = NULL;
109 private $menuInstance = NULL;
112 * Instance of the image
114 private $imageInstance = NULL;
117 * Instance of the stacker
119 private $stackInstance = NULL;
122 * A Compressor instance
124 private $compressorInstance = NULL;
127 * A Parseable instance
129 private $parserInstance = NULL;
132 * A ProtocolHandler instance
134 private $protocolInstance = NULL;
137 * A database wrapper instance
139 private $databaseInstance = NULL;
142 * A helper instance for the form
144 private $helperInstance = NULL;
147 * An instance of a Sourceable class
149 private $sourceInstance = NULL;
152 * An instance of a InputStream class
154 private $inputStreamInstance = NULL;
157 * An instance of a OutputStream class
159 private $outputStreamInstance = NULL;
162 * Networkable handler instance
164 private $handlerInstance = NULL;
167 * Visitor handler instance
169 private $visitorInstance = NULL;
174 private $dhtInstance = NULL;
177 * An instance of a database wrapper class
179 private $wrapperInstance = NULL;
182 * An instance of a file I/O pointer class (not handler)
184 private $pointerInstance = NULL;
187 * An instance of an Indexable class
189 private $indexInstance = NULL;
192 * An instance of a Block class
194 private $blockInstance = NULL;
197 * Thousands separator
199 private $thousands = '.'; // German
204 private $decimals = ','; // German
209 private $socketResource = FALSE;
214 private $packageData = array();
219 private $genericArray = array();
221 /***********************
222 * Exception codes.... *
223 ***********************/
225 // @todo Try to clean these constants up
226 const EXCEPTION_IS_NULL_POINTER = 0x001;
227 const EXCEPTION_IS_NO_OBJECT = 0x002;
228 const EXCEPTION_IS_NO_ARRAY = 0x003;
229 const EXCEPTION_MISSING_METHOD = 0x004;
230 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
231 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
232 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
233 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
234 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
235 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
236 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
237 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
238 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
239 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
240 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
241 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
242 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
243 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
244 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
245 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
246 const EXCEPTION_PATH_NOT_FOUND = 0x015;
247 const EXCEPTION_INVALID_PATH_NAME = 0x016;
248 const EXCEPTION_READ_PROTECED_PATH = 0x017;
249 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
250 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
251 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
252 const EXCEPTION_INVALID_RESOURCE = 0x01b;
253 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
254 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
255 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
256 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
257 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
258 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
259 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
260 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
261 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
262 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
263 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
264 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
265 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
266 const EXCEPTION_INVALID_STRING = 0x029;
267 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
268 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
269 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
270 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
271 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
272 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
273 const EXCEPTION_MISSING_ELEMENT = 0x030;
274 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
275 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
276 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
277 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
278 const EXCEPTION_FATAL_ERROR = 0x035;
279 const EXCEPTION_FILE_NOT_FOUND = 0x036;
280 const EXCEPTION_ASSERTION_FAILED = 0x037;
281 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
282 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
283 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03a;
286 * Hexadecimal->Decimal translation array
288 private static $hexdec = array(
308 * Decimal->hexadecimal translation array
310 private static $dechex = array(
330 * Startup time in miliseconds
332 private static $startupTime = 0;
335 * Protected super constructor
337 * @param $className Name of the class
340 protected function __construct ($className) {
342 $this->setRealClass($className);
344 // Set configuration instance if no registry ...
345 if (!$this instanceof Register) {
346 // ... because registries doesn't need to be configured
347 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
350 // Is the startup time set? (0 cannot be TRUE anymore)
351 if (self::$startupTime == 0) {
353 self::$startupTime = microtime(TRUE);
358 * Destructor for all classes
362 public function __destruct () {
363 // Flush any updated entries to the database
364 $this->flushPendingUpdates();
366 // Is this object already destroyed?
367 if ($this->__toString() != 'DestructedObject') {
368 // Destroy all informations about this class but keep some text about it alive
369 $this->setRealClass('DestructedObject');
370 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
371 // Already destructed object
372 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
377 // Do not call this twice
378 trigger_error(__METHOD__ . ': Called twice.');
384 * The __call() method where all non-implemented methods end up
386 * @param $methodName Name of the missing method
387 * @args $args Arguments passed to the method
390 public final function __call ($methodName, $args) {
391 return self::__callStatic($methodName, $args);
395 * The __callStatic() method where all non-implemented static methods end up
397 * @param $methodName Name of the missing method
398 * @args $args Arguments passed to the method
401 public static final function __callStatic ($methodName, $args) {
402 // Init argument string
405 // Is it empty or an array?
408 $argsString = 'NULL';
409 } elseif (is_array($args)) {
410 // Some arguments are there
411 foreach ($args as $arg) {
412 // Add the value itself if not array. This prevents 'array to string conversion' message
413 if (is_array($arg)) {
414 $argsString .= 'Array';
419 // Add data about the argument
420 $argsString .= ' (' . gettype($arg);
422 if (is_string($arg)) {
423 // Add length for strings
424 $argsString .= ', ' . strlen($arg);
425 } elseif (is_array($arg)) {
426 // .. or size if array
427 $argsString .= ', ' . count($arg);
428 } elseif ($arg === TRUE) {
429 // ... is boolean 'TRUE'
430 $argsString .= ', TRUE';
431 } elseif ($arg === FALSE) {
432 // ... is boolean 'FALSE'
433 $argsString .= ', FALSE';
437 $argsString .= '), ';
441 if (substr($argsString, -2, 1) == ',') {
442 $argsString = substr($argsString, 0, -2);
445 // Invalid arguments!
446 $argsString = '!INVALID:' . gettype($args) . '!';
449 // Output stub message
450 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
451 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
461 * Getter for $realClass
463 * @return $realClass The name of the real class (not BaseFrameworkSystem)
465 public function __toString () {
466 return $this->realClass;
470 * Magic function to catch setting of missing but set class fields/attributes
472 * @param $name Name of the field/attribute
473 * @param $value Value to store
476 public final function __set ($name, $value) {
477 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
480 print_r($value, TRUE)
485 * Magic function to catch getting of missing fields/attributes
487 * @param $name Name of the field/attribute
490 public final function __get ($name) {
491 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
497 * Magic function to catch unsetting of missing fields/attributes
499 * @param $name Name of the field/attribute
502 public final function __unset ($name) {
503 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
509 * Setter for the real class name
511 * @param $realClass Class name (string)
514 public final function setRealClass ($realClass) {
516 $this->realClass = (string) $realClass;
520 * Setter for database result instance
522 * @param $resultInstance An instance of a database result class
524 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
526 protected final function setResultInstance (SearchableResult $resultInstance) {
527 $this->resultInstance = $resultInstance;
531 * Getter for database result instance
533 * @return $resultInstance An instance of a database result class
535 public final function getResultInstance () {
536 return $this->resultInstance;
540 * Setter for template engine instances
542 * @param $templateInstance An instance of a template engine class
545 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
546 $this->templateInstance = $templateInstance;
550 * Getter for template engine instances
552 * @return $templateInstance An instance of a template engine class
554 protected final function getTemplateInstance () {
555 return $this->templateInstance;
559 * Setter for search instance
561 * @param $searchInstance Searchable criteria instance
564 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
565 $this->searchInstance = $searchInstance;
569 * Getter for search instance
571 * @return $searchInstance Searchable criteria instance
573 public final function getSearchInstance () {
574 return $this->searchInstance;
578 * Setter for update instance
580 * @param $updateInstance Searchable criteria instance
583 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
584 $this->updateInstance = $updateInstance;
588 * Getter for update instance
590 * @return $updateInstance Updateable criteria instance
592 public final function getUpdateInstance () {
593 return $this->updateInstance;
597 * Setter for resolver instance
599 * @param $resolverInstance Instance of a command resolver class
602 public final function setResolverInstance (Resolver $resolverInstance) {
603 $this->resolverInstance = $resolverInstance;
607 * Getter for resolver instance
609 * @return $resolverInstance Instance of a command resolver class
611 public final function getResolverInstance () {
612 return $this->resolverInstance;
616 * Setter for language instance
618 * @param $configInstance The configuration instance which shall
619 * be FrameworkConfiguration
622 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
623 Registry::getRegistry()->addInstance('config', $configInstance);
627 * Getter for configuration instance
629 * @return $configInstance Configuration instance
631 public final function getConfigInstance () {
632 $configInstance = Registry::getRegistry()->getInstance('config');
633 return $configInstance;
637 * Setter for debug instance
639 * @param $debugInstance The instance for debug output class
642 public final function setDebugInstance (DebugMiddleware $debugInstance) {
643 Registry::getRegistry()->addInstance('debug', $debugInstance);
647 * Getter for debug instance
649 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
651 public final function getDebugInstance () {
652 // Get debug instance
653 $debugInstance = Registry::getRegistry()->getInstance('debug');
656 return $debugInstance;
660 * Setter for web output instance
662 * @param $webInstance The instance for web output class
665 public final function setWebOutputInstance (OutputStreamer $webInstance) {
666 Registry::getRegistry()->addInstance('web_output', $webInstance);
670 * Getter for web output instance
672 * @return $webOutputInstance - Instance to class WebOutput
674 public final function getWebOutputInstance () {
675 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
676 return $webOutputInstance;
680 * Setter for database instance
682 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
685 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
686 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
690 * Getter for database layer
692 * @return $databaseInstance The database layer instance
694 public final function getDatabaseInstance () {
696 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
699 return $databaseInstance;
703 * Setter for compressor channel
705 * @param $compressorInstance An instance of CompressorChannel
708 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
709 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
713 * Getter for compressor channel
715 * @return $compressorInstance The compressor channel
717 public final function getCompressorChannel () {
718 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
719 return $compressorInstance;
723 * Protected getter for a manageable application helper class
725 * @return $applicationInstance An instance of a manageable application helper class
727 protected final function getApplicationInstance () {
728 $applicationInstance = Registry::getRegistry()->getInstance('application');
729 return $applicationInstance;
733 * Setter for a manageable application helper class
735 * @param $applicationInstance An instance of a manageable application helper class
738 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
739 Registry::getRegistry()->addInstance('application', $applicationInstance);
743 * Setter for request instance
745 * @param $requestInstance An instance of a Requestable class
748 public final function setRequestInstance (Requestable $requestInstance) {
749 $this->requestInstance = $requestInstance;
753 * Getter for request instance
755 * @return $requestInstance An instance of a Requestable class
757 public final function getRequestInstance () {
758 return $this->requestInstance;
762 * Setter for response instance
764 * @param $responseInstance An instance of a Responseable class
767 public final function setResponseInstance (Responseable $responseInstance) {
768 $this->responseInstance = $responseInstance;
772 * Getter for response instance
774 * @return $responseInstance An instance of a Responseable class
776 public final function getResponseInstance () {
777 return $this->responseInstance;
781 * Private getter for language instance
783 * @return $langInstance An instance to the language sub-system
785 protected final function getLanguageInstance () {
786 $langInstance = Registry::getRegistry()->getInstance('language');
787 return $langInstance;
791 * Setter for language instance
793 * @param $langInstance An instance to the language sub-system
795 * @see LanguageSystem
797 public final function setLanguageInstance (ManageableLanguage $langInstance) {
798 Registry::getRegistry()->addInstance('language', $langInstance);
802 * Private getter for file IO instance
804 * @return $fileIoInstance An instance to the file I/O sub-system
806 protected final function getFileIoInstance () {
807 return $this->fileIoInstance;
811 * Setter for file I/O instance
813 * @param $fileIoInstance An instance to the file I/O sub-system
816 public final function setFileIoInstance (IoHandler $fileIoInstance) {
817 $this->fileIoInstance = $fileIoInstance;
821 * Protected setter for user instance
823 * @param $userInstance An instance of a user class
826 protected final function setUserInstance (ManageableAccount $userInstance) {
827 $this->userInstance = $userInstance;
831 * Getter for user instance
833 * @return $userInstance An instance of a user class
835 public final function getUserInstance () {
836 return $this->userInstance;
840 * Setter for controller instance (this surely breaks a bit the MVC patterm)
842 * @param $controllerInstance An instance of the controller
845 public final function setControllerInstance (Controller $controllerInstance) {
846 $this->controllerInstance = $controllerInstance;
850 * Getter for controller instance (this surely breaks a bit the MVC patterm)
852 * @return $controllerInstance An instance of the controller
854 public final function getControllerInstance () {
855 return $this->controllerInstance;
859 * Setter for RNG instance
861 * @param $rngInstance An instance of a random number generator (RNG)
864 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
865 $this->rngInstance = $rngInstance;
869 * Getter for RNG instance
871 * @return $rngInstance An instance of a random number generator (RNG)
873 public final function getRngInstance () {
874 return $this->rngInstance;
878 * Setter for Cryptable instance
880 * @param $cryptoInstance An instance of a Cryptable class
883 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
884 $this->cryptoInstance = $cryptoInstance;
888 * Getter for Cryptable instance
890 * @return $cryptoInstance An instance of a Cryptable class
892 public final function getCryptoInstance () {
893 return $this->cryptoInstance;
897 * Setter for the list instance
899 * @param $listInstance A list of Listable
902 protected final function setListInstance (Listable $listInstance) {
903 $this->listInstance = $listInstance;
907 * Getter for the list instance
909 * @return $listInstance A list of Listable
911 protected final function getListInstance () {
912 return $this->listInstance;
916 * Setter for the menu instance
918 * @param $menuInstance A RenderableMenu instance
921 protected final function setMenuInstance (RenderableMenu $menuInstance) {
922 $this->menuInstance = $menuInstance;
926 * Getter for the menu instance
928 * @return $menuInstance A RenderableMenu instance
930 protected final function getMenuInstance () {
931 return $this->menuInstance;
935 * Setter for image instance
937 * @param $imageInstance An instance of an image
940 public final function setImageInstance (BaseImage $imageInstance) {
941 $this->imageInstance = $imageInstance;
945 * Getter for image instance
947 * @return $imageInstance An instance of an image
949 public final function getImageInstance () {
950 return $this->imageInstance;
954 * Setter for stacker instance
956 * @param $stackInstance An instance of an stacker
959 public final function setStackInstance (Stackable $stackInstance) {
960 $this->stackInstance = $stackInstance;
964 * Getter for stacker instance
966 * @return $stackInstance An instance of an stacker
968 public final function getStackInstance () {
969 return $this->stackInstance;
973 * Setter for compressor instance
975 * @param $compressorInstance An instance of an compressor
978 public final function setCompressorInstance (Compressor $compressorInstance) {
979 $this->compressorInstance = $compressorInstance;
983 * Getter for compressor instance
985 * @return $compressorInstance An instance of an compressor
987 public final function getCompressorInstance () {
988 return $this->compressorInstance;
992 * Setter for Parseable instance
994 * @param $parserInstance An instance of an Parseable
997 public final function setParserInstance (Parseable $parserInstance) {
998 $this->parserInstance = $parserInstance;
1002 * Getter for Parseable instance
1004 * @return $parserInstance An instance of an Parseable
1006 public final function getParserInstance () {
1007 return $this->parserInstance;
1011 * Setter for ProtocolHandler instance
1013 * @param $protocolInstance An instance of an ProtocolHandler
1016 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
1017 $this->protocolInstance = $protocolInstance;
1021 * Getter for ProtocolHandler instance
1023 * @return $protocolInstance An instance of an ProtocolHandler
1025 public final function getProtocolInstance () {
1026 return $this->protocolInstance;
1030 * Setter for DatabaseWrapper instance
1032 * @param $wrapperInstance An instance of an DatabaseWrapper
1035 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1036 $this->wrapperInstance = $wrapperInstance;
1040 * Getter for DatabaseWrapper instance
1042 * @return $wrapperInstance An instance of an DatabaseWrapper
1044 public final function getWrapperInstance () {
1045 return $this->wrapperInstance;
1049 * Setter for socket resource
1051 * @param $socketResource A valid socket resource
1054 public final function setSocketResource ($socketResource) {
1055 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1056 $this->socketResource = $socketResource;
1060 * Getter for socket resource
1062 * @return $socketResource A valid socket resource
1064 public final function getSocketResource () {
1065 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1066 return $this->socketResource;
1070 * Setter for helper instance
1072 * @param $helperInstance An instance of a helper class
1075 protected final function setHelperInstance (Helper $helperInstance) {
1076 $this->helperInstance = $helperInstance;
1080 * Getter for helper instance
1082 * @return $helperInstance An instance of a helper class
1084 public final function getHelperInstance () {
1085 return $this->helperInstance;
1089 * Setter for a Sourceable instance
1091 * @param $sourceInstance The Sourceable instance
1094 protected final function setSourceInstance (Sourceable $sourceInstance) {
1095 $this->sourceInstance = $sourceInstance;
1099 * Getter for a Sourceable instance
1101 * @return $sourceInstance The Sourceable instance
1103 protected final function getSourceInstance () {
1104 return $this->sourceInstance;
1108 * Getter for a InputStream instance
1110 * @param $inputStreamInstance The InputStream instance
1112 protected final function getInputStreamInstance () {
1113 return $this->inputStreamInstance;
1117 * Setter for a InputStream instance
1119 * @param $inputStreamInstance The InputStream instance
1122 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1123 $this->inputStreamInstance = $inputStreamInstance;
1127 * Getter for a OutputStream instance
1129 * @param $outputStreamInstance The OutputStream instance
1131 protected final function getOutputStreamInstance () {
1132 return $this->outputStreamInstance;
1136 * Setter for a OutputStream instance
1138 * @param $outputStreamInstance The OutputStream instance
1141 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1142 $this->outputStreamInstance = $outputStreamInstance;
1146 * Setter for handler instance
1148 * @param $handlerInstance An instance of a Handleable class
1151 protected final function setHandlerInstance (Handleable $handlerInstance) {
1152 $this->handlerInstance = $handlerInstance;
1156 * Getter for handler instance
1158 * @return $handlerInstance A Networkable instance
1160 protected final function getHandlerInstance () {
1161 return $this->handlerInstance;
1165 * Setter for visitor instance
1167 * @param $visitorInstance A Visitor instance
1170 protected final function setVisitorInstance (Visitor $visitorInstance) {
1171 $this->visitorInstance = $visitorInstance;
1175 * Getter for visitor instance
1177 * @return $visitorInstance A Visitor instance
1179 protected final function getVisitorInstance () {
1180 return $this->visitorInstance;
1184 * Setter for DHT instance
1186 * @param $dhtInstance A Distributable instance
1189 protected final function setDhtInstance (Distributable $dhtInstance) {
1190 $this->dhtInstance = $dhtInstance;
1194 * Getter for DHT instance
1196 * @return $dhtInstance A Distributable instance
1198 protected final function getDhtInstance () {
1199 return $this->dhtInstance;
1203 * Setter for raw package Data
1205 * @param $packageData Raw package Data
1208 public final function setPackageData (array $packageData) {
1209 $this->packageData = $packageData;
1213 * Getter for raw package Data
1215 * @return $packageData Raw package Data
1217 public function getPackageData () {
1218 return $this->packageData;
1223 * Setter for Iterator instance
1225 * @param $iteratorInstance An instance of an Iterator
1228 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1229 $this->iteratorInstance = $iteratorInstance;
1233 * Getter for Iterator instance
1235 * @return $iteratorInstance An instance of an Iterator
1237 public final function getIteratorInstance () {
1238 return $this->iteratorInstance;
1242 * Setter for InputOutputPointer instance
1244 * @param $pointerInstance An instance of an InputOutputPointer class
1247 protected final function setPointerInstance (InputOutputPointer $pointerInstance) {
1248 $this->pointerInstance = $pointerInstance;
1252 * Getter for InputOutputPointer instance
1254 * @return $pointerInstance An instance of an InputOutputPointer class
1256 public final function getPointerInstance () {
1257 return $this->pointerInstance;
1261 * Setter for Indexable instance
1263 * @param $indexInstance An instance of an Indexable class
1266 protected final function setIndexInstance (Indexable $indexInstance) {
1267 $this->indexInstance = $indexInstance;
1271 * Getter for Indexable instance
1273 * @return $indexInstance An instance of an Indexable class
1275 public final function getIndexInstance () {
1276 return $this->indexInstance;
1280 * Setter for Block instance
1282 * @param $blockInstance An instance of an Block class
1285 protected final function setBlockInstance (Block $blockInstance) {
1286 $this->blockInstance = $blockInstance;
1290 * Getter for Block instance
1292 * @return $blockInstance An instance of an Block class
1294 public final function getBlockInstance () {
1295 return $this->blockInstance;
1299 * Checks whether an object equals this object. You should overwrite this
1300 * method to implement own equality checks
1302 * @param $objectInstance An instance of a FrameworkInterface object
1303 * @return $equals Whether both objects equals
1305 public function equals (FrameworkInterface $objectInstance) {
1308 $this->__toString() == $objectInstance->__toString()
1310 $this->hashCode() == $objectInstance->hashCode()
1313 // Return the result
1318 * Generates a generic hash code of this class. You should really overwrite
1319 * this method with your own hash code generator code. But keep KISS in mind.
1321 * @return $hashCode A generic hash code respresenting this whole class
1323 public function hashCode () {
1325 return crc32($this->__toString());
1329 * Formats computer generated price values into human-understandable formats
1330 * with thousand and decimal separators.
1332 * @param $value The in computer format value for a price
1333 * @param $currency The currency symbol (use HTML-valid characters!)
1334 * @param $decNum Number of decimals after commata
1335 * @return $price The for the current language formated price string
1336 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1337 * thousands separator
1340 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1341 // Are all required attriutes set?
1342 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1343 // Throw an exception
1344 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1348 $value = (float) $value;
1350 // Reformat the US number
1351 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1353 // Return as string...
1358 * Appends a trailing slash to a string
1360 * @param $str A string (maybe) without trailing slash
1361 * @return $str A string with an auto-appended trailing slash
1363 public final function addMissingTrailingSlash ($str) {
1364 // Is there a trailing slash?
1365 if (substr($str, -1, 1) != '/') {
1369 // Return string with trailing slash
1374 * Prepare the template engine (WebTemplateEngine by default) for a given
1375 * application helper instance (ApplicationHelper by default).
1377 * @param $applicationInstance An application helper instance or
1378 * null if we shall use the default
1379 * @return $templateInstance The template engine instance
1380 * @throws NullPointerException If the discovered application
1381 * instance is still null
1383 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1384 // Is the application instance set?
1385 if (is_null($applicationInstance)) {
1386 // Get the current instance
1387 $applicationInstance = $this->getApplicationInstance();
1390 if (is_null($applicationInstance)) {
1391 // Thrown an exception
1392 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1396 // Initialize the template engine
1397 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1399 // Return the prepared instance
1400 return $templateInstance;
1404 * Debugs this instance by putting out it's full content
1406 * @param $message Optional message to show in debug output
1409 public final function debugInstance ($message = '') {
1410 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1411 restore_error_handler();
1416 // Is a message set?
1417 if (!empty($message)) {
1418 // Construct message
1419 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1422 // Generate the output
1423 $content .= sprintf('<pre>%s</pre>',
1426 print_r($this, TRUE)
1432 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>',
1433 $this->__toString(),
1435 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1440 * Replaces control characters with printable output
1442 * @param $str String with control characters
1443 * @return $str Replaced string
1445 protected function replaceControlCharacters ($str) {
1448 chr(13), '[r]', str_replace(
1449 chr(10), '[n]', str_replace(
1459 * Output a partial stub message for the caller method
1461 * @param $message An optional message to display
1464 protected function partialStub ($message = '') {
1465 // Get the backtrace
1466 $backtrace = debug_backtrace();
1468 // Generate the class::method string
1469 $methodName = 'UnknownClass->unknownMethod';
1470 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1471 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1474 // Construct the full message
1475 $stubMessage = sprintf('[%s:] Partial stub!',
1479 // Is the extra message given?
1480 if (!empty($message)) {
1481 // Then add it as well
1482 $stubMessage .= ' Message: ' . $message;
1485 // Debug instance is there?
1486 if (!is_null($this->getDebugInstance())) {
1487 // Output stub message
1488 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1491 trigger_error($stubMessage);
1497 * Outputs a debug backtrace and stops further script execution
1499 * @param $message An optional message to output
1500 * @param $doExit Whether exit the program (TRUE is default)
1503 public function debugBackTrace ($message = '', $doExit = TRUE) {
1504 // Sorry, there is no other way getting this nice backtrace
1505 if (!empty($message)) {
1507 printf('Message: %s<br />' . chr(10), $message);
1511 debug_print_backtrace();
1515 if ($doExit === TRUE) {
1521 * Creates an instance of a debugger instance
1523 * @param $className Name of the class (currently unsupported)
1524 * @return $debugInstance An instance of a debugger class
1526 public final static function createDebugInstance ($className) {
1527 // Is the instance set?
1528 if (!Registry::getRegistry()->instanceExists('debug')) {
1529 // Init debug instance
1530 $debugInstance = NULL;
1534 // Get a debugger instance
1535 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_class'));
1536 } catch (NullPointerException $e) {
1537 // Didn't work, no instance there
1538 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1541 // Empty string should be ignored and used for testing the middleware
1542 DebugMiddleware::getSelfInstance()->output('');
1544 // Set it in its own class. This will set it in the registry
1545 $debugInstance->setDebugInstance($debugInstance);
1547 // Get instance from registry
1548 $debugInstance = Registry::getRegistry()->getDebugInstance();
1552 return $debugInstance;
1556 * Simple output of a message with line-break
1558 * @param $message Message to output
1561 public function outputLine ($message) {
1563 print($message . PHP_EOL);
1567 * Outputs a debug message whether to debug instance (should be set!) or
1568 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1569 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1571 * @param $message Message we shall send out...
1572 * @param $doPrint Whether print or die here (default: print)
1573 * @paran $stripTags Whether to strip tags (default: FALSE)
1576 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1577 // Set debug instance to NULL
1578 $debugInstance = NULL;
1582 // Get debug instance
1583 $debugInstance = $this->getDebugInstance();
1584 } catch (NullPointerException $e) {
1585 // The debug instance is not set (yet)
1588 // Is the debug instance there?
1589 if (is_object($debugInstance)) {
1590 // Use debug output handler
1591 $debugInstance->output($message, $stripTags);
1593 if ($doPrint === FALSE) {
1594 // Die here if not printed
1598 // Are debug times enabled?
1599 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1601 $message = $this->getPrintableExecutionTime() . $message;
1605 if ($doPrint === TRUE) {
1607 $this->outputLine($message);
1616 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1618 * @param $str The string, what ever it is needs to be converted
1619 * @return $className Generated class name
1621 public function convertToClassName ($str) {
1625 // Convert all dashes in underscores
1626 $str = $this->convertDashesToUnderscores($str);
1628 // Now use that underscores to get classname parts for hungarian style
1629 foreach (explode('_', $str) as $strPart) {
1630 // Make the class name part lower case and first upper case
1631 $className .= ucfirst(strtolower($strPart));
1634 // Return class name
1639 * Converts dashes to underscores, e.g. useable for configuration entries
1641 * @param $str The string with maybe dashes inside
1642 * @return $str The converted string with no dashed, but underscores
1644 public final function convertDashesToUnderscores ($str) {
1646 $str = str_replace('-', '_', $str);
1648 // Return converted string
1653 * Marks up the code by adding e.g. line numbers
1655 * @param $phpCode Unmarked PHP code
1656 * @return $markedCode Marked PHP code
1658 public function markupCode ($phpCode) {
1663 $errorArray = error_get_last();
1665 // Init the code with error message
1666 if (is_array($errorArray)) {
1668 $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>',
1669 basename($errorArray['file']),
1670 $errorArray['line'],
1671 $errorArray['message'],
1676 // Add line number to the code
1677 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1679 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1681 htmlentities($code, ENT_QUOTES)
1690 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1691 * beatiful for web-based front-ends. If null is given a message id
1692 * null_timestamp will be resolved and returned.
1694 * @param $timestamp Timestamp to prepare (filter) for display
1695 * @return $readable A readable timestamp
1697 public function doFilterFormatTimestamp ($timestamp) {
1698 // Default value to return
1701 // Is the timestamp null?
1702 if (is_null($timestamp)) {
1703 // Get a message string
1704 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1706 switch ($this->getLanguageInstance()->getLanguageCode()) {
1707 case 'de': // German format is a bit different to default
1708 // Split the GMT stamp up
1709 $dateTime = explode(' ', $timestamp );
1710 $dateArray = explode('-', $dateTime[0]);
1711 $timeArray = explode(':', $dateTime[1]);
1713 // Construct the timestamp
1714 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1724 default: // Default is pass-through
1725 $readable = $timestamp;
1735 * Filter a given number into a localized number
1737 * @param $value The raw value from e.g. database
1738 * @return $localized Localized value
1740 public function doFilterFormatNumber ($value) {
1741 // Generate it from config and localize dependencies
1742 switch ($this->getLanguageInstance()->getLanguageCode()) {
1743 case 'de': // German format is a bit different to default
1744 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1747 default: // US, etc.
1748 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1757 * "Getter" for databse entry
1759 * @return $entry An array with database entries
1760 * @throws NullPointerException If the database result is not found
1761 * @throws InvalidDatabaseResultException If the database result is invalid
1763 protected final function getDatabaseEntry () {
1764 // Is there an instance?
1765 if (is_null($this->getResultInstance())) {
1766 // Throw an exception here
1767 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1771 $this->getResultInstance()->rewind();
1773 // Do we have an entry?
1774 if ($this->getResultInstance()->valid() === FALSE) {
1775 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1779 $this->getResultInstance()->next();
1782 $entry = $this->getResultInstance()->current();
1789 * Getter for field name
1791 * @param $fieldName Field name which we shall get
1792 * @return $fieldValue Field value from the user
1793 * @throws NullPointerException If the result instance is null
1795 public final function getField ($fieldName) {
1796 // Default field value
1799 // Get result instance
1800 $resultInstance = $this->getResultInstance();
1802 // Is this instance null?
1803 if (is_null($resultInstance)) {
1804 // Then the user instance is no longer valid (expired cookies?)
1805 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1808 // Get current array
1809 $fieldArray = $resultInstance->current();
1810 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
1812 // Convert dashes to underscore
1813 $fieldName = $this->convertDashesToUnderscores($fieldName);
1815 // Does the field exist?
1816 if (isset($fieldArray[$fieldName])) {
1818 $fieldValue = $fieldArray[$fieldName];
1820 // Missing field entry, may require debugging
1821 self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1829 * Flushs all pending updates to the database layer
1833 public function flushPendingUpdates () {
1834 // Get result instance
1835 $resultInstance = $this->getResultInstance();
1837 // Do we have data to update?
1838 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1839 // Get wrapper class name config entry
1840 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1842 // Create object instance
1843 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1845 // Yes, then send the whole result to the database layer
1846 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1851 * Outputs a deprecation warning to the developer.
1853 * @param $message The message we shall output to the developer
1855 * @todo Write a logging mechanism for productive mode
1857 public function deprecationWarning ($message) {
1858 // Is developer mode active?
1859 if (defined('DEVELOPER')) {
1860 // Debug instance is there?
1861 if (!is_null($this->getDebugInstance())) {
1862 // Output stub message
1863 self::createDebugInstance(__CLASS__)->debugOutput($message);
1866 trigger_error($message . "<br />\n");
1870 // @TODO Finish this part!
1871 $this->partialStub('Developer mode inactive. Message:' . $message);
1876 * Checks whether the given PHP extension is loaded
1878 * @param $phpExtension The PHP extension we shall check
1879 * @return $isLoaded Whether the PHP extension is loaded
1881 public final function isPhpExtensionLoaded ($phpExtension) {
1883 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1890 * "Getter" as a time() replacement but with milliseconds. You should use this
1891 * method instead of the encapsulated getimeofday() function.
1893 * @return $milliTime Timestamp with milliseconds
1895 public function getMilliTime () {
1896 // Get the time of day as float
1897 $milliTime = gettimeofday(TRUE);
1904 * Idles (sleeps) for given milliseconds
1906 * @return $hasSlept Whether it goes fine
1908 public function idle ($milliSeconds) {
1909 // Sleep is fine by default
1912 // Idle so long with found function
1913 if (function_exists('time_sleep_until')) {
1914 // Get current time and add idle time
1915 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1917 // New PHP 5.1.0 function found, ignore errors
1918 $hasSlept = @time_sleep_until($sleepUntil);
1921 * My Sun station doesn't have that function even with latest PHP
1924 usleep($milliSeconds * 1000);
1931 * Converts a hexadecimal string, even with negative sign as first string to
1932 * a decimal number using BC functions.
1934 * This work is based on comment #86673 on php.net documentation page at:
1935 * <http://de.php.net/manual/en/function.dechex.php#86673>
1937 * @param $hex Hexadecimal string
1938 * @return $dec Decimal number
1940 protected function hex2dec ($hex) {
1941 // Convert to all lower-case
1942 $hex = strtolower($hex);
1944 // Detect sign (negative/positive numbers)
1946 if (substr($hex, 0, 1) == '-') {
1948 $hex = substr($hex, 1);
1951 // Decode the hexadecimal string into a decimal number
1953 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1954 $factor = self::$hexdec[substr($hex, $i, 1)];
1955 $dec = bcadd($dec, bcmul($factor, $e));
1958 // Return the decimal number
1959 return $sign . $dec;
1963 * Converts even very large decimal numbers, also signed, to a hexadecimal
1966 * This work is based on comment #97756 on php.net documentation page at:
1967 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1969 * @param $dec Decimal number, even with negative sign
1970 * @param $maxLength Optional maximum length of the string
1971 * @return $hex Hexadecimal string
1973 protected function dec2hex ($dec, $maxLength = 0) {
1974 // maxLength can be zero or devideable by 2
1975 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1977 // Detect sign (negative/positive numbers)
1984 // Encode the decimal number into a hexadecimal string
1987 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
1989 } while ($dec >= 1);
1992 * Leading zeros are required for hex-decimal "numbers". In some
1993 * situations more leading zeros are wanted, so check for both
1996 if ($maxLength > 0) {
1997 // Prepend more zeros
1998 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
1999 } elseif ((strlen($hex) % 2) != 0) {
2000 // Only make string's length dividable by 2
2004 // Return the hexadecimal string
2005 return $sign . $hex;
2009 * Converts a ASCII string (0 to 255) into a decimal number.
2011 * @param $asc The ASCII string to be converted
2012 * @return $dec Decimal number
2014 protected function asc2dec ($asc) {
2015 // Convert it into a hexadecimal number
2016 $hex = bin2hex($asc);
2018 // And back into a decimal number
2019 $dec = $this->hex2dec($hex);
2026 * Converts a decimal number into an ASCII string.
2028 * @param $dec Decimal number
2029 * @return $asc An ASCII string
2031 protected function dec2asc ($dec) {
2032 // First convert the number into a hexadecimal string
2033 $hex = $this->dec2hex($dec);
2035 // Then convert it into the ASCII string
2036 $asc = $this->hex2asc($hex);
2043 * Converts a hexadecimal number into an ASCII string. Negative numbers
2046 * @param $hex Hexadecimal string
2047 * @return $asc An ASCII string
2049 protected function hex2asc ($hex) {
2050 // Check for length, it must be devideable by 2
2051 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2052 assert((strlen($hex) % 2) == 0);
2056 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2057 // Get the decimal number of the chunk
2058 $part = hexdec(substr($hex, $idx, 2));
2060 // Add it to the final string
2064 // Return the final string
2069 * Checks whether the given encoded data was encoded with Base64
2071 * @param $encodedData Encoded data we shall check
2072 * @return $isBase64 Whether the encoded data is Base64
2074 protected function isBase64Encoded ($encodedData) {
2076 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2083 * "Getter" to get response/request type from analysis of the system.
2085 * @return $responseType Analyzed response type
2087 protected function getResponseTypeFromSystem () {
2088 // Default is console
2089 $responseType = 'console';
2091 // Is 'HTTP_HOST' set?
2092 if (isset($_SERVER['HTTP_HOST'])) {
2093 // Then it is a HTTP response/request
2094 $responseType = 'http';
2098 return $responseType;
2102 * Gets a cache key from Criteria instance
2104 * @param $criteriaInstance An instance of a Criteria class
2105 * @param $onlyKeys Only use these keys for a cache key
2106 * @return $cacheKey A cache key suitable for lookup/storage purposes
2108 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2110 $cacheKey = sprintf('%s@%s',
2111 $this->__toString(),
2112 $criteriaInstance->getCacheKey($onlyKeys)
2116 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2121 * Getter for startup time in miliseconds
2123 * @return $startupTime Startup time in miliseconds
2125 protected function getStartupTime () {
2126 return self::$startupTime;
2130 * "Getter" for a printable currently execution time in nice braces
2132 * @return $executionTime Current execution time in nice braces
2134 protected function getPrintableExecutionTime () {
2135 // Caculate the execution time
2136 $executionTime = microtime(TRUE) - $this->getStartupTime();
2138 // Pack it in nice braces
2139 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2142 return $executionTime;
2146 * Hashes a given string with a simple but stronger hash function (no salt)
2147 * and hex-encode it.
2149 * @param $str The string to be hashed
2150 * @return $hash The hash from string $str
2152 public static final function hash ($str) {
2153 // Hash given string with (better secure) hasher
2154 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2161 * "Getter" for length of hash() output. This will be "cached" to speed up
2164 * @return $length Length of hash() output
2166 public static final function getHashLength () {
2168 if (is_null(self::$hashLength)) {
2169 // No, then hash a string and save its length.
2170 self::$hashLength = strlen(self::hash('abc123'));
2174 return self::$hashLength;
2178 * Checks whether the given number is really a number (only chars 0-9).
2180 * @param $num A string consisting only chars between 0 and 9
2181 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2182 * @param $assertMismatch Whether to assert mismatches
2183 * @return $ret The (hopefully) secured numbered value
2185 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2186 // Filter all numbers out
2187 $ret = preg_replace('/[^0123456789]/', '', $num);
2190 if ($castValue === TRUE) {
2191 // Cast to biggest numeric type
2192 $ret = (double) $ret;
2195 // Assert only if requested
2196 if ($assertMismatch === TRUE) {
2197 // Has the whole value changed?
2198 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2206 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2208 * @param $num A string consisting only chars between 0 and 9
2209 * @param $assertMismatch Whether to assert mismatches
2210 * @return $ret The (hopefully) secured hext-numbered value
2212 public function hexval ($num, $assertMismatch = FALSE) {
2213 // Filter all numbers out
2214 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2216 // Assert only if requested
2217 if ($assertMismatch === TRUE) {
2218 // Has the whole value changed?
2219 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2227 * Checks whether start/end marker are set
2229 * @param $data Data to be checked
2230 * @return $isset Whether start/end marker are set
2232 public final function ifStartEndMarkersSet ($data) {
2234 $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));
2236 // ... and return it
2241 * Determines if an element is set in the generic array
2243 * @param $keyGroup Main group for the key
2244 * @param $subGroup Sub group for the key
2245 * @param $key Key to check
2246 * @param $element Element to check
2247 * @return $isset Whether the given key is set
2249 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2251 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2254 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2260 * Determines if a key is set in the generic array
2262 * @param $keyGroup Main group for the key
2263 * @param $subGroup Sub group for the key
2264 * @param $key Key to check
2265 * @return $isset Whether the given key is set
2267 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2269 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2272 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2280 * Determines if a group is set in the generic array
2282 * @param $keyGroup Main group
2283 * @param $subGroup Sub group
2284 * @return $isset Whether the given group is set
2286 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2288 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2291 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2298 * Getter for sub key group
2300 * @param $keyGroup Main key group
2301 * @param $subGroup Sub key group
2302 * @return $array An array with all array elements
2304 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2306 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2307 // No, then abort here
2308 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2313 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2316 return $this->genericArray[$keyGroup][$subGroup];
2320 * Unsets a given key in generic array
2322 * @param $keyGroup Main group for the key
2323 * @param $subGroup Sub group for the key
2324 * @param $key Key to unset
2327 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2329 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2332 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2336 * Unsets a given element in generic array
2338 * @param $keyGroup Main group for the key
2339 * @param $subGroup Sub group for the key
2340 * @param $key Key to unset
2341 * @param $element Element to unset
2344 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2346 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2349 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2353 * Append a string to a given generic array key
2355 * @param $keyGroup Main group for the key
2356 * @param $subGroup Sub group for the key
2357 * @param $key Key to unset
2358 * @param $value Value to add/append
2361 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2363 //* 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);
2365 // Is it already there?
2366 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2368 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2371 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2376 * Append a string to a given generic array element
2378 * @param $keyGroup Main group for the key
2379 * @param $subGroup Sub group for the key
2380 * @param $key Key to unset
2381 * @param $element Element to check
2382 * @param $value Value to add/append
2385 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2387 //* 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);
2389 // Is it already there?
2390 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2392 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2395 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2400 * Initializes given generic array group
2402 * @param $keyGroup Main group for the key
2403 * @param $subGroup Sub group for the key
2404 * @param $key Key to use
2405 * @param $forceInit Optionally force initialization
2408 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2410 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2412 // Is it already set?
2413 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2414 // Already initialized
2415 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2420 $this->genericArray[$keyGroup][$subGroup] = array();
2424 * Initializes given generic array key
2426 * @param $keyGroup Main group for the key
2427 * @param $subGroup Sub group for the key
2428 * @param $key Key to use
2429 * @param $forceInit Optionally force initialization
2432 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2434 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2436 // Is it already set?
2437 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2438 // Already initialized
2439 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2444 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2448 * Initializes given generic array element
2450 * @param $keyGroup Main group for the key
2451 * @param $subGroup Sub group for the key
2452 * @param $key Key to use
2453 * @param $element Element to use
2454 * @param $forceInit Optionally force initialization
2457 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2459 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2461 // Is it already set?
2462 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2463 // Already initialized
2464 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2469 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2473 * Pushes an element to a generic key
2475 * @param $keyGroup Main group for the key
2476 * @param $subGroup Sub group for the key
2477 * @param $key Key to use
2478 * @param $value Value to add/append
2479 * @return $count Number of array elements
2481 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2483 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2486 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2488 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2492 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2495 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2496 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2501 * Pushes an element to a generic array element
2503 * @param $keyGroup Main group for the key
2504 * @param $subGroup Sub group for the key
2505 * @param $key Key to use
2506 * @param $element Element to check
2507 * @param $value Value to add/append
2508 * @return $count Number of array elements
2510 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2512 //* 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));
2515 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2517 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2521 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2524 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2525 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2530 * Pops an element from a generic group
2532 * @param $keyGroup Main group for the key
2533 * @param $subGroup Sub group for the key
2534 * @param $key Key to unset
2535 * @return $value Last "popped" value
2537 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2539 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2542 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2544 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2549 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2552 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2553 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2558 * Shifts an element from a generic group
2560 * @param $keyGroup Main group for the key
2561 * @param $subGroup Sub group for the key
2562 * @param $key Key to unset
2563 * @return $value Last "popped" value
2565 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2567 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2570 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2572 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2577 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2580 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2581 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2586 * Count generic array group
2588 * @param $keyGroup Main group for the key
2589 * @return $count Count of given group
2591 protected final function countGenericArray ($keyGroup) {
2593 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2596 if (!isset($this->genericArray[$keyGroup])) {
2598 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2603 $count = count($this->genericArray[$keyGroup]);
2606 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2613 * Count generic array sub group
2615 * @param $keyGroup Main group for the key
2616 * @param $subGroup Sub group for the key
2617 * @return $count Count of given group
2619 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2621 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2624 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2626 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2631 $count = count($this->genericArray[$keyGroup][$subGroup]);
2634 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2641 * Count generic array elements
2643 * @param $keyGroup Main group for the key
2644 * @param $subGroup Sub group for the key
2645 * @para $key Key to count
2646 * @return $count Count of given key
2648 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2650 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2653 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2655 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2657 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2659 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2664 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2667 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2674 * Getter for whole generic group array
2676 * @param $keyGroup Key group to get
2677 * @return $array Whole generic array group
2679 protected final function getGenericArray ($keyGroup) {
2681 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2684 if (!isset($this->genericArray[$keyGroup])) {
2686 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2691 return $this->genericArray[$keyGroup];
2695 * Setter for generic array key
2697 * @param $keyGroup Key group to get
2698 * @param $subGroup Sub group for the key
2699 * @param $key Key to unset
2700 * @param $value Mixed value from generic array element
2703 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2705 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2708 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2712 * Getter for generic array key
2714 * @param $keyGroup Key group to get
2715 * @param $subGroup Sub group for the key
2716 * @param $key Key to unset
2717 * @return $value Mixed value from generic array element
2719 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2721 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2724 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2726 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2731 return $this->genericArray[$keyGroup][$subGroup][$key];
2735 * Sets a value in given generic array key/element
2737 * @param $keyGroup Main group for the key
2738 * @param $subGroup Sub group for the key
2739 * @param $key Key to set
2740 * @param $element Element to set
2741 * @param $value Value to set
2744 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2746 //* 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));
2749 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2753 * Getter for generic array element
2755 * @param $keyGroup Key group to get
2756 * @param $subGroup Sub group for the key
2757 * @param $key Key to look for
2758 * @param $element Element to look for
2759 * @return $value Mixed value from generic array element
2761 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2763 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2766 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2768 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2773 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2777 * Checks if a given sub group is valid (array)
2779 * @param $keyGroup Key group to get
2780 * @param $subGroup Sub group for the key
2781 * @return $isValid Whether given sub group is valid
2783 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2785 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2788 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2795 * Checks if a given key is valid (array)
2797 * @param $keyGroup Key group to get
2798 * @param $subGroup Sub group for the key
2799 * @param $key Key to check
2800 * @return $isValid Whether given sub group is valid
2802 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2804 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2807 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2814 * Translates boolean TRUE to 'Y' and FALSE to 'N'
2816 * @param $boolean Boolean value
2817 * @return $translated Translated boolean value
2819 public static final function translateBooleanToYesNo ($boolean) {
2820 // Make sure it is really boolean
2821 assert(is_bool($boolean));
2824 $translated = ($boolean === TRUE) ? 'Y' : 'N';
2826 // ... and return it