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@ship-simu.org>
8 * @copyright Copyright (c) 2007, 2008 Roland Haeder, this is free software
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.ship-simu.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 * Instance to an application helper class
29 private static $applicationInstance = null;
32 * The language instance for the template loader
34 private static $langInstance = null;
39 private static $debugInstance = null;
42 * Instance of a request class
44 private $requestInstance = null;
47 * Instance of a response class
49 private $responseInstance = null;
52 * Search criteria instance
54 private $searchInstance = 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;
84 private $realClass = "FrameworkSystem";
87 * A human-readable description for this simulator part
89 private $objectDescription = "Namenlose Framework-Einheit";
92 * The unique ID string for identifying all type of classes
94 private $uniqueID = "";
99 private $thousands = "."; // German
104 private $decimals = ","; // German
106 /***********************
107 * Exception codes.... *
108 ***********************/
110 const EXCEPTION_IS_NULL_POINTER = 0x001;
111 const EXCEPTION_IS_NO_OBJECT = 0x002;
112 const EXCEPTION_IS_NO_ARRAY = 0x003;
113 const EXCEPTION_MISSING_METHOD = 0x004;
114 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
115 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
116 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
117 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
118 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
119 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
120 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
121 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
122 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
123 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
124 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
125 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
126 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
127 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
128 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
129 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
130 const EXCEPTION_PATH_NOT_FOUND = 0x015;
131 const EXCEPTION_INVALID_PATH_NAME = 0x016;
132 const EXCEPTION_READ_PROTECED_PATH = 0x017;
133 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
134 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
135 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
136 const EXCEPTION_INVALID_DIRECTORY_POINTER = 0x01b;
137 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
138 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
139 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
140 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
141 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
142 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
143 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
144 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
145 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
146 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
147 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
148 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
149 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
150 const EXCEPTION_INVALID_STRING = 0x029;
151 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
152 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
153 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
154 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
155 const EXCEPTION_MISSING_LANGUAGE_HANDLER = 0x02e;
156 const EXCEPTION_MISSING_FILE_IO_HANDLER = 0x02f;
157 const EXCEPTION_MISSING_ELEMENT = 0x030;
158 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
159 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
160 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
161 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
162 const EXCEPTION_FATAL_ERROR = 0x035;
163 const EXCEPTION_FILE_NOT_FOUND = 0x036;
164 const EXCEPTION_ASSERTION_FAILED = 0x037;
165 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
166 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
169 * In the super constructor these system classes shall be ignored or else
170 * we would get an endless calling loop.
172 *---------------------------------------------------------------------*
173 * ATTENTION: IF YOU REMOVE ONE OF THEM YOU WILL RUN YOUR SERVER IN AN *
175 *---------------------------------------------------------------------*
177 private $systemClasses = array(
178 "DebugMiddleware", // Debug middleware output sub-system
179 "Registry", // Object registry
180 "ObjectFactory", // Object factory
181 "DebugWebOutput", // Debug web output sub-system
182 "WebOutput", // Web output sub-system
183 "CompressorChannel", // Compressor sub-system
184 "DebugConsoleOutput", // Debug console output sub-system
185 "DebugErrorLogOutput", // Debug error_log() output sub-system
186 "FrameworkDirectoryPointer", // Directory handler sub-system
187 "NullCompressor", // Null compressor
188 "Bzip2Compressor", // BZIP2 compressor
189 "GzipCompressor", // GZIP compressor
196 * Private super constructor
198 * @param $className Name of the class
201 protected function __construct ($className) {
203 $this->setRealClass($className);
205 // Initialize the class if the registry is there
206 if ((class_exists('Registry')) && (Registry::isInitialized() === false)) {
207 $this->initInstance();
212 * Destructor reached...
215 * @todo This is old code. Do we still need this old lost code?
217 public function __destruct() {
218 // Is this object already destroyed?
219 if ($this->__toString() != 'DestructedObject') {
220 // Destroy all informations about this class but keep some text about it alive
221 $this->setObjectDescription(sprintf("Removed object <em>%s</em>", $this->__toString()));
222 $this->setRealClass('DestructedObject');
223 $this->resetUniqueID();
224 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
225 // Already destructed object
226 $this->debugOutput(sprintf("[%s:] The object <strong>%s</strong> is already destroyed.",
227 __CLASS__, $this->__toString()
233 * The call method where all non-implemented methods end up
237 public final function __call ($methodName, $args) {
238 // Implode all given arguments
242 $argsString = "NULL";
243 } elseif (is_array($args)) {
244 // Some arguments are there
245 foreach ($args as $arg) {
247 $argsString .= $arg." (".gettype($arg)."), ";
251 if (substr($argsString, -2, 1) === ",") {
252 $argsString = substr($argsString, 0, -2);
255 // Invalid arguments!
256 $argsString = sprintf("!INVALID:%s!", $args);
259 // Output stub message
260 $this->debugOutput(sprintf("[%s->%s] Stub! Args: %s",
271 * Private initializer for this class
275 private final function initInstance () {
276 // Is this a system class?
277 if (!in_array($this->__toString(), $this->systemClasses)) {
278 // Add application helper to our class
279 $this->systemclasses[] = $this->getConfigInstance()->readConfig('app_helper_class');
281 // Set debug instance
282 $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig('debug_class')));
284 // Get output instance and set it
285 $outputInstance = ObjectFactory::createObjectByConfiguredName('web_engine', array($this->getConfigInstance()->readConfig('web_content_type')));
286 $this->setWebOutputInstance($outputInstance);
288 // Set the compressor channel
289 $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
291 $this->getConfigInstance()->readConfig('compressor_base_path')
294 // Initialization done! :D
295 Registry::isInitialized('OK');
296 } elseif ($this->__toString() == 'DebugMiddleware') {
297 // Set configuration instance
298 $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
303 * Setter for database result instance
305 * @param $resultInstance An instance of a database result class
307 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
309 protected final function setResultInstance (SearchableResult $resultInstance) {
310 $this->resultInstance = $resultInstance;
314 * Getter for database result instance
316 * @return $resultInstance An instance of a database result class
318 public final function getResultInstance () {
319 return $this->resultInstance;
323 * Setter for template engine instances
325 * @param $templateInstance An instance of a template engine class
328 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
329 $this->templateInstance = $templateInstance;
333 * Getter for template engine instances
335 * @return $templateInstance An instance of a template engine class
337 protected final function getTemplateInstance () {
338 return $this->templateInstance;
342 * Setter for search instance
344 * @param $searchInstance Searchable criteria instance
347 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
348 $this->searchInstance = $searchInstance;
352 * Getter for search instance
354 * @return $searchInstance Searchable criteria instance
356 public final function getSearchInstance () {
357 return $this->searchInstance;
361 * Setter for resolver instance
363 * @param $resolverInstance Instance of a command resolver class
366 public final function setResolverInstance (Resolver $resolverInstance) {
367 $this->resolverInstance = $resolverInstance;
371 * Getter for resolver instance
373 * @return $resolverInstance Instance of a command resolver class
375 public final function getResolverInstance () {
376 return $this->resolverInstance;
380 * Setter for language instance
382 * @param $configInstance The configuration instance which shall
383 * be FrameworkConfiguration
386 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
387 Registry::getRegistry()->addInstance('config', $configInstance);
391 * Getter for configuration instance
393 * @return $cfgInstance Configuration instance
395 public final function getConfigInstance () {
396 $cfgInstance = Registry::getRegistry()->getInstance('config');
401 * Setter for debug instance
403 * @param $debugInstance The instance for debug output class
406 public final function setDebugInstance (DebugMiddleware $debugInstance) {
407 self::$debugInstance = $debugInstance;
411 * Getter for debug instance
413 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
415 public final function getDebugInstance () {
416 return self::$debugInstance;
420 * Setter for web output instance
422 * @param $webInstance The instance for web output class
425 public final function setWebOutputInstance (OutputStreamer $webInstance) {
426 Registry::getRegistry()->addInstance('web_output', $webInstance);
430 * Getter for web output instance
432 * @return $webOutput - Instance to class WebOutput
434 public final function getWebOutputInstance () {
435 return Registry::getRegistry()->getInstance('web_output');
439 * Setter for database instance
441 * @param $dbInstance The instance for the database connection
442 * (forced DatabaseConnection)
445 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
446 Registry::getRegistry()->addInstance('dbInstance', $dbInstance);
450 * Getter for database layer
452 * @return $dbInstance The database layer instance
454 public final function getDatabaseInstance () {
455 // Default is invalid db instance
458 // Is the registry there and initialized?
459 if ((class_exists('Registry')) && (Registry::isInitialized() === true)) {
460 $dbInstance = Registry::getRegistry()->getInstance('dbInstance');
468 * Setter for compressor channel
470 * @param $compressorChannel An instance of CompressorChannel
473 public final function setCompressorChannel (CompressorChannel $compressorChannel) {
474 Registry::getRegistry()->addInstance('compressor', $compressorChannel);
478 * Getter for compressor channel
480 * @return $compressor The compressor channel
482 public final function getCompressorChannel () {
483 return Registry::getRegistry()->getInstance('compressor');
487 * Protected getter for a manageable application helper class
489 * @return $applicationInstance An instance of a manageable application helper class
491 protected final function getApplicationInstance () {
492 return self::$applicationInstance;
496 * Setter for a manageable application helper class
498 * @param $applicationInstance An instance of a manageable application helper class
501 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
502 self::$applicationInstance = $applicationInstance;
506 * Setter for request instance
508 * @param $requestInstance An instance of a Requestable class
511 public final function setRequestInstance (Requestable $requestInstance) {
512 $this->requestInstance = $requestInstance;
516 * Getter for request instance
518 * @return $requestInstance An instance of a Requestable class
520 public final function getRequestInstance () {
521 return $this->requestInstance;
525 * Setter for response instance
527 * @param $responseInstance An instance of a Responseable class
530 public final function setResponseInstance (Responseable $responseInstance) {
531 $this->responseInstance = $responseInstance;
535 * Getter for response instance
537 * @return $responseInstance An instance of a Responseable class
539 public final function getResponseInstance () {
540 return $this->responseInstance;
544 * Getter for $realClass
546 * @return $realClass The name of the real class (not BaseFrameworkSystem)
548 public final function __toString () {
549 return $this->realClass;
553 * Setter for the real class name
555 * @param $realClass Class name (string)
558 public final function setRealClass ($realClass) {
560 $realClass = (string) $realClass;
563 $this->realClass = $realClass;
567 * Generate unique ID from a lot entropy
571 public final function generateUniqueId () {
572 // Is the id set for this class?
573 if (empty($this->uniqueID)) {
575 // Correct missing class name
577 if ($this->__toString() == "") {
578 $this->setRealClass(__CLASS__);
582 // Cache datbase instance
583 $db = $this->getDatabaseInstance();
588 // Generate a unique ID number
589 $tempID = $this->generateIdNumber();
592 // Try to figure out if the ID number is not yet used
594 // Is this a registry?
595 if ($this->__toString() == "Registry") {
596 // Registry, then abort here
598 } elseif (is_object($db)) {
599 $isUsed = $db->isUniqueIdUsed($tempID, true);
601 } catch (FrameworkException $e) {
602 // Catches all and ignores all ;-)
626 $this->setUniqueID($tempID);
628 // Revert maybe corrected class name
630 $this->setRealClass("");
633 // Remove system classes if we are in a system class
634 if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
635 // This may save some RAM...
636 $this->removeSystemArray();
642 * Generates a new ID number for classes based from the class' real name,
643 * the description and some random data
645 * @return $tempID The new (temporary) ID number
647 private final function generateIdNumber () {
648 return sprintf("%s@%s",
650 md5(sprintf("%s:%s:%s:%s:%s:%s",
652 $this->getObjectDescription(),
654 getenv('REMOTE_ADDR'),
655 getenv('SERVER_ADDR'),
662 * Setter for unique ID
664 * @param $uniqueID The newly generated unique ID number
667 private final function setUniqueID ($uniqueID) {
669 $uniqueID = (string) $uniqueID;
672 $this->uniqueID = $uniqueID;
676 * Getter for unique ID
678 * @return $uniqueID The unique ID of this class
680 public final function getUniqueID () {
681 return $this->uniqueID;
685 * Resets or recreates the unique ID number
689 public final function resetUniqueID() {
690 // Sweet and simple... ;-)
691 $newUniqueID = $this->generateIdNumber();
692 $this->setUniqueID($newUniqueID);
696 * Getter for simulator description
698 * @return $objectDescription The description of this simulation part
700 public final function getObjectDescription () {
701 return $this->objectDescription;
705 * Setter for simulation part description
707 * @param $objectDescription The description as string for this simulation part
710 public final function setObjectDescription ($objectDescription) {
711 $this->objectDescription = (String) $objectDescription;
715 * Validate if given object is the same as current
717 * @param $object An object instance for comparison with this class
718 * @return boolean The result of comparing both's unique ID
720 public final function equals (FrameworkInterface $object) {
721 return ($this->getUniqueID() == $object->getUniqueID());
725 * Compare if both simulation part description and class name matches
728 * @param $itemInstance An object instance to an other class
729 * @return boolean The result of comparing class name simulation part description
731 public function itemMatches ($itemInstance) {
734 $this->__toString() == $itemInstance->__toString()
736 $this->getObjectDescription() == $itemInstance->getObjectDescription()
742 * Compare class name of this and given class name
744 * @param $className The class name as string from the other class
745 * @return boolean The result of comparing both class names
747 public final function isClass ($className) {
748 return ($this->__toString() == $className);
752 * Stub method (only real cabins shall override it)
754 * @return boolean false = is no cabin, true = is a cabin
756 public function isCabin () {
761 * Stub method for tradeable objects
763 * @return boolean false = is not tradeable by the Merchant class,
764 * true = is a tradeable object
766 public function isTradeable () {
771 * Formats computer generated price values into human-understandable formats
772 * with thousand and decimal seperators.
774 * @param $value The in computer format value for a price
775 * @param $currency The currency symbol (use HTML-valid characters!)
776 * @param $decNum Number of decimals after commata
777 * @return $price The for the current language formated price string
778 * @throws MissingDecimalsThousandsSeperatorException If decimals or
779 * thousands seperator
782 public function formatCurrency ($value, $currency = "€", $decNum = 2) {
783 // Are all required attriutes set?
784 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
785 // Throw an exception
786 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
790 $value = (float) $value;
792 // Reformat the US number
793 $price = sprintf("%s %s",
794 number_format($value, $decNum, $this->decimals, $this->thousands),
798 // Return as string...
803 * Removes number formating characters
807 public final function removeNumberFormaters () {
808 unset($this->thousands);
809 unset($this->decimals);
813 * Private getter for language instance
815 * @return $langInstance An instance to the language sub-system
817 protected final function getLanguageInstance () {
818 return self::$langInstance;
822 * Setter for language instance
824 * @param $langInstance An instance to the language sub-system
826 * @see LanguageSystem
828 public final function setLanguageInstance (ManageableLanguage $langInstance) {
829 self::$langInstance = $langInstance;
833 * Remove the $systemClasses array from memory
837 public final function removeSystemArray () {
838 unset($this->systemClasses);
842 * Create a file name and path name from the object's unique ID number.
843 * The left part of the ID shall always be a valid class name and the
844 * right part an ID number.
846 * @return $pfn The file name with a prepended path name
847 * @throws NoArrayCreatedException If explode() fails to create an array
848 * @throws InvalidArrayCountException If the array contains less or
849 * more than two elements
851 public final function getPathFileNameFromObject () {
852 // Get the main object's unique ID. We use this as a path/filename combination
853 $pathFile = $this->getUniqueID();
855 // Split it up in path and file name
856 $pathFile = explode("@", $pathFile);
858 // Are there two elements? Index 0 is the path, 1 the file name + global extension
859 if (!is_array($pathFile)) {
861 throw new NoArrayCreatedException(array($this, 'pathFile'), self::EXCEPTION_ARRAY_EXPECTED);
862 } elseif (count($pathFile) != 2) {
863 // Invalid ID returned!
864 throw new InvalidArrayCountException(array($this, 'pathFile', count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
867 // Auto-append missing trailing slash
868 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
870 // Create the file name and return it
871 $pfn = ($pathFile[0] . $pathFile[1]);
876 * Appends a trailing slash to a string
878 * @param $str A string (maybe) without trailing slash
879 * @return $str A string with an auto-appended trailing slash
881 public final function addMissingTrailingSlash ($str) {
882 // Is there a trailing slash?
883 if (substr($str, -1, 1) != "/") $str .= "/";
888 * Private getter for file IO instance
890 * @return $fileIoInstance An instance to the file I/O sub-system
892 protected final function getFileIoInstance () {
893 return $this->fileIoInstance;
897 * Setter for file I/O instance
899 * @param $fileIoInstance An instance to the file I/O sub-system
902 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
903 $this->fileIoInstance = $fileIoInstance;
907 * Prepare the template engine (WebTemplateEngine by default) for a given
908 * application helper instance (ApplicationHelper by default).
910 * @param $appInstance An application helper instance or
911 * null if we shall use the default
912 * @return $templateInstance The template engine instance
913 * @throws NullPointerException If the template engine could not
915 * @throws UnsupportedTemplateEngineException If $templateInstance is an
916 * unsupported template engine
917 * @throws MissingLanguageHandlerException If the language sub-system
918 * is not yet initialized
919 * @throws NullPointerException If the discovered application
920 * instance is still null
922 protected function prepareTemplateInstance (BaseFrameworkSystem $appInstance=null) {
923 // Is the application instance set?
924 if (is_null($appInstance)) {
925 // Get the current instance
926 $appInstance = $this->getApplicationInstance();
929 if (is_null($appInstance)) {
930 // Thrown an exception
931 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
935 // Generate FQFN for all application templates
936 $fqfn = sprintf("%s%s/%s/%s",
938 $this->getConfigInstance()->readConfig('application_path'),
939 strtolower($appInstance->getAppShortName()),
940 $this->getConfigInstance()->readConfig('tpl_base_path')
943 // Are both instances set?
944 if ($appInstance->getLanguageInstance() === null) {
945 // Invalid language instance
946 throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
947 } elseif ($appInstance->getFileIoInstance() === null) {
948 // Invalid language instance
949 throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
952 // Initialize the template engine
953 $templateInstance = ObjectFactory::createObjectByConfiguredName('template_class', array($fqfn, $appInstance->getLanguageInstance(), $appInstance->getFileIoInstance()));
955 // Return the prepared instance
956 return $templateInstance;
960 * Debugs this instance by putting out it's full content
964 public final function debugInstance () {
965 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
966 restore_error_handler();
968 // Generate the output
969 $content = sprintf("<pre>%s</pre>",
978 ApplicationEntryPoint::app_die(sprintf("<strong>%s debug output:</strong><div id=\"debug_content\">%s</div>\nLoaded includes: <div id=\"debug_include_list\">%s</div>",
981 ClassLoader::getInstance()->getPrintableIncludeList()
986 * Output a partial stub message for the caller method
988 * @param $message An optional message to display
991 protected function partialStub ($message = "") {
993 $backtrace = debug_backtrace();
995 // Generate the class::method string
996 $methodName = "UnknownClass->unknownMethod";
997 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
998 $methodName = $backtrace[1]['class']."->".$backtrace[1]['function'];
1001 // Construct the full message
1002 $stubMessage = sprintf("[%s:] Partial stub!",
1006 // Is the extra message given?
1007 if (!empty($message)) {
1008 // Then add it as well
1009 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
1012 // Debug instance is there?
1013 if (!is_null($this->getDebugInstance())) {
1014 // Output stub message
1015 $this->debugOutput($stubMessage);
1018 trigger_error($stubMessage."<br />\n");
1023 * Outputs a debug backtrace and stops further script execution
1027 public function debugBackTrace () {
1028 // Sorry, there is no other way getting this nice backtrace
1030 debug_print_backtrace();
1036 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
1038 * @param $message Message we shall send out...
1039 * @param $doPrint Wether we shall print or die here which first is the default
1042 public function debugOutput ($message, $doPrint = true) {
1043 // Get debug instance
1044 $debugInstance = $this->getDebugInstance();
1046 // Is the debug instance there?
1047 if (is_object($debugInstance)) {
1048 // Use debug output handler
1049 $debugInstance->output($message);
1050 if (!$doPrint) die(); // Die here if not printed
1056 // DO NOT REWRITE THIS TO app_die() !!!
1063 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1065 * @param $str The string, what ever it is needs to be converted
1066 * @return $className Generated class name
1068 public function convertToClassName ($str) {
1072 // Convert all dashes in underscores
1073 $str = str_replace("-", "_", $str);
1075 // Now use that underscores to get classname parts for hungarian style
1076 foreach (explode("_", $str) as $strPart) {
1077 // Make the class name part lower case and first upper case
1078 $className .= ucfirst(strtolower($strPart));
1081 // Return class name
1086 * Marks up the code by adding e.g. line numbers
1088 * @param $phpCode Unmarked PHP code
1089 * @return $markedCode Marked PHP code
1091 public function markupCode ($phpCode) {
1093 $errorArray = error_get_last();
1095 // Init the code with error message
1097 if (is_array($errorArray)) {
1099 $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>",
1100 basename($errorArray['file']),
1101 $errorArray['line'],
1102 $errorArray['message'],
1107 // Add line number to the code
1108 foreach (explode("\n", $phpCode) as $lineNo=>$code) {
1110 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
1112 htmlentities($code, ENT_QUOTES)
1121 * Filter a given timestamp to make it look more beatifull for web-based
1122 * front-ends. If null is given a message id null_timestamp will be
1123 * resolved and returned.
1125 * @param $timestamp Timestamp to prepare (filter) for display
1126 * @return $readable A readable timestamp
1128 public function doFilterFormatTimestamp ($timestamp) {
1129 // Default value to return
1132 // Is the timestamp null?
1133 if (is_null($timestamp)) {
1134 // Get a message string
1135 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1137 $this->partialStub("Do further analysis on timestamp {$timestamp}.");
1145 * "Getter" for databse entry
1147 * @return $entry An array with database entries
1148 * @throws NullPointerException If the database result is not found
1149 * @throws InvalidDatabaseResultException If the database result is invalid
1151 protected final function getDatabaseEntry () {
1152 // Is there an instance?
1153 if (is_null($this->getResultInstance())) {
1154 // Throw an exception here
1155 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1159 $this->getResultInstance()->rewind();
1161 // Do we have an entry?
1162 if (!$this->getResultInstance()->valid()) {
1163 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1167 $this->getResultInstance()->next();
1170 $entry = $this->getResultInstance()->current();
1177 * Getter for field name
1179 * @param $fieldName Field name which we shall get
1180 * @return $fieldValue Field value from the user
1181 * @throws NullPointerException If the result instance is null
1183 public final function getField ($fieldName) {
1184 // Default field value
1187 // Get result instance
1188 $resultInstance = $this->getResultInstance();
1190 // Is this instance null?
1191 if (is_null($resultInstance)) {
1192 // Then the user instance is no longer valid (expired cookies?)
1193 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1196 // Get current array
1197 $fieldArray = $resultInstance->current();
1199 // Does the field exist?
1200 if (isset($fieldArray[$fieldName])) {
1202 $fieldValue = $fieldArray[$fieldName];
1210 * Protected setter for user instance
1212 * @param $userInstance An instance of a user class
1215 protected final function setUserInstance (ManageableAccount $userInstance) {
1216 $this->userInstance = $userInstance;
1220 * Getter for user instance
1222 * @return $userInstance An instance of a user class
1224 public final function getUserInstance () {
1225 return $this->userInstance;