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;
79 private $realClass = "FrameworkSystem";
82 * A human-readable description for this simulator part
84 private $objectDescription = "Namenlose Framework-Einheit";
87 * The unique ID string for identifying all type of classes
89 private $uniqueID = "";
94 private $thousands = "."; // German
99 private $decimals = ","; // German
101 /***********************
102 * Exception codes.... *
103 ***********************/
105 const EXCEPTION_IS_NULL_POINTER = 0x001;
106 const EXCEPTION_IS_NO_OBJECT = 0x002;
107 const EXCEPTION_IS_NO_ARRAY = 0x003;
108 const EXCEPTION_MISSING_METHOD = 0x004;
109 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
110 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
111 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
112 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
113 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
114 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
115 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
116 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
117 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
118 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
119 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
120 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
121 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
122 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
123 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
124 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
125 const EXCEPTION_PATH_NOT_FOUND = 0x015;
126 const EXCEPTION_INVALID_PATH_NAME = 0x016;
127 const EXCEPTION_READ_PROTECED_PATH = 0x017;
128 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
129 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
130 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
131 const EXCEPTION_INVALID_DIRECTORY_POINTER = 0x01b;
132 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
133 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
134 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
135 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
136 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
137 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
138 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
139 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
140 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
141 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
142 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
143 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
144 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
145 const EXCEPTION_INVALID_STRING = 0x029;
146 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
147 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
148 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
149 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
150 const EXCEPTION_MISSING_LANGUAGE_HANDLER = 0x02e;
151 const EXCEPTION_MISSING_FILE_IO_HANDLER = 0x02f;
152 const EXCEPTION_MISSING_ELEMENT = 0x030;
153 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
154 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
155 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
156 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
157 const EXCEPTION_FATAL_ERROR = 0x035;
158 const EXCEPTION_FILE_NOT_FOUND = 0x036;
159 const EXCEPTION_ASSERTION_FAILED = 0x037;
160 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
161 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
164 * In the super constructor these system classes shall be ignored or else
165 * we would get an endless calling loop.
167 *---------------------------------------------------------------------*
168 * ATTENTION: IF YOU REMOVE ONE OF THEM YOU WILL RUN YOUR SERVER IN AN *
170 *---------------------------------------------------------------------*
172 private $systemClasses = array(
173 "DebugMiddleware", // Debug middleware output sub-system
174 "Registry", // Object registry
175 "ObjectFactory", // Object factory
176 "DebugWebOutput", // Debug web output sub-system
177 "WebOutput", // Web output sub-system
178 "CompressorChannel", // Compressor sub-system
179 "DebugConsoleOutput", // Debug console output sub-system
180 "DebugErrorLogOutput", // Debug error_log() output sub-system
181 "FrameworkDirectoryPointer", // Directory handler sub-system
182 "NullCompressor", // Null compressor
183 "Bzip2Compressor", // BZIP2 compressor
184 "GzipCompressor", // GZIP compressor
191 * Private super constructor
193 * @param $className Name of the class
196 protected function __construct ($className) {
198 $this->setRealClass($className);
200 // Initialize the class if the registry is there
201 if ((class_exists('Registry')) && (Registry::isInitialized() === false)) {
202 $this->initInstance();
207 * Destructor reached...
210 * @todo This is old code. Do we still need this old lost code?
212 public function __destruct() {
213 // Is this object already destroyed?
214 if ($this->__toString() != 'DestructedObject') {
215 // Destroy all informations about this class but keep some text about it alive
216 $this->setObjectDescription(sprintf("Removed object <em>%s</em>", $this->__toString()));
217 $this->setRealClass('DestructedObject');
218 $this->resetUniqueID();
219 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
220 // Already destructed object
221 $this->getDebugInstance()->output(sprintf("[%s:] The object <strong>%s</strong> is already destroyed.",
222 __CLASS__, $this->__toString()
228 * The call method where all non-implemented methods end up
232 public final function __call ($methodName, $args) {
233 // Implode all given arguments
237 $argsString = "NULL";
238 } elseif (is_array($args)) {
239 // Some arguments are there
240 foreach ($args as $arg) {
244 if ($arg) $argsString .= "true(bool)"; else $argsString .= "false(bool)";
245 } elseif (is_int($arg)) {
247 $argsString .= $arg."(int)";
248 } elseif (is_float($arg)) {
250 $argsString .= $arg."(float)";
251 } elseif ($arg instanceof BaseFrameworkSystem) {
252 // Own object instance
253 $argsString .= $arg->__toString()."(Object)";
254 } elseif (is_object($arg)) {
256 $argsString .= "unknown object(!)";
257 } elseif (is_array($arg)) {
259 $argsString .= "Array(array)";
260 } elseif (is_string($arg)) {
262 $argsString .= "\"".$arg."\"(string)";
263 } elseif (is_null($arg)) {
265 $argsString .= "(null)";
266 } elseif (is_resource($arg)) {
268 $argsString .= "(resource)";
270 // Unknown type (please report!)
271 $argsString .= $arg."(<em>unknown!</em>)";
279 if (substr($argsString, -2, 1) === ",") {
280 $argsString = substr($argsString, 0, -2);
283 // Invalid arguments!
284 $argsString = sprintf("!INVALID:%s!", $args);
287 // Output stub message
288 $this->getDebugInstance()->output(sprintf("[%s->%s] Stub! Args: %s",
299 * Private initializer for this class
303 private final function initInstance () {
304 // Is this a system class?
305 if (!in_array($this->__toString(), $this->systemClasses)) {
306 // Add application helper to our class
307 $this->systemclasses[] = $this->getConfigInstance()->readConfig('app_helper_class');
309 // Set debug instance
310 $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig('debug_class')));
312 // Get output instance and set it
313 $outputInstance = ObjectFactory::createObjectByConfiguredName('web_engine', array($this->getConfigInstance()->readConfig('web_content_type')));
314 $this->setWebOutputInstance($outputInstance);
316 // Set the compressor channel
317 $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
319 $this->getConfigInstance()->readConfig('compressor_base_path')
322 // Initialization done! :D
323 Registry::isInitialized('OK');
324 } elseif ($this->__toString() == 'DebugMiddleware') {
325 // Set configuration instance
326 $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
331 * Setter for database result instance
333 * @param $resultInstance An instance of a database result class
335 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
337 protected final function setResultInstance (SearchableResult $resultInstance) {
338 $this->resultInstance = $resultInstance;
342 * Getter for database result instance
344 * @return $resultInstance An instance of a database result class
346 public final function getResultInstance () {
347 return $this->resultInstance;
351 * Setter for template engine instances
353 * @param $templateInstance An instance of a template engine class
356 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
357 $this->templateInstance = $templateInstance;
361 * Getter for template engine instances
363 * @return $templateInstance An instance of a template engine class
365 protected final function getTemplateInstance () {
366 return $this->templateInstance;
370 * Setter for search instance
372 * @param $searchInstance Searchable criteria instance
375 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
376 $this->searchInstance = $searchInstance;
380 * Getter for search instance
382 * @return $searchInstance Searchable criteria instance
384 public final function getSearchInstance () {
385 return $this->searchInstance;
389 * Setter for resolver instance
391 * @param $resolverInstance Instance of a command resolver class
394 public final function setResolverInstance (Resolver $resolverInstance) {
395 $this->resolverInstance = $resolverInstance;
399 * Getter for resolver instance
401 * @return $resolverInstance Instance of a command resolver class
403 public final function getResolverInstance () {
404 return $this->resolverInstance;
408 * Setter for language instance
410 * @param $configInstance The configuration instance which shall
411 * be FrameworkConfiguration
414 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
415 Registry::getRegistry()->addInstance('config', $configInstance);
419 * Getter for configuration instance
421 * @return $cfgInstance Configuration instance
423 public final function getConfigInstance () {
424 $cfgInstance = Registry::getRegistry()->getInstance('config');
429 * Setter for debug instance
431 * @param $debugInstance The instance for debug output class
434 public final function setDebugInstance (DebugMiddleware $debugInstance) {
435 self::$debugInstance = $debugInstance;
439 * Getter for debug instance
441 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
443 public final function getDebugInstance () {
444 return self::$debugInstance;
448 * Setter for web output instance
450 * @param $webInstance The instance for web output class
453 public final function setWebOutputInstance (OutputStreamer $webInstance) {
454 Registry::getRegistry()->addInstance('web_output', $webInstance);
458 * Getter for web output instance
460 * @return $webOutput - Instance to class WebOutput
462 public final function getWebOutputInstance () {
463 return Registry::getRegistry()->getInstance('web_output');
467 * Setter for database instance
469 * @param $dbInstance The instance for the database connection
470 * (forced DatabaseConnection)
473 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
474 Registry::getRegistry()->addInstance('dbInstance', $dbInstance);
478 * Getter for database layer
480 * @return $dbInstance The database layer instance
482 public final function getDatabaseInstance () {
483 if ((class_exists('Registry')) && (Registry::isInitialized() === true)) {
484 return Registry::getRegistry()->getInstance('dbInstance');
491 * Setter for compressor channel
493 * @param $compressorChannel An instance of CompressorChannel
496 public final function setCompressorChannel (CompressorChannel $compressorChannel) {
497 Registry::getRegistry()->addInstance('compressor', $compressorChannel);
501 * Getter for compressor channel
503 * @return $compressor The compressor channel
505 public final function getCompressorChannel () {
506 return Registry::getRegistry()->getInstance('compressor');
510 * Protected getter for a manageable application helper class
512 * @return $applicationInstance An instance of a manageable application helper class
514 protected final function getApplicationInstance () {
515 return self::$applicationInstance;
519 * Setter for a manageable application helper class
521 * @param $applicationInstance An instance of a manageable application helper class
524 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
525 self::$applicationInstance = $applicationInstance;
529 * Setter for request instance
531 * @param $requestInstance An instance of a Requestable class
534 public final function setRequestInstance (Requestable $requestInstance) {
535 $this->requestInstance = $requestInstance;
539 * Getter for request instance
541 * @return $requestInstance An instance of a Requestable class
543 public final function getRequestInstance () {
544 return $this->requestInstance;
548 * Setter for response instance
550 * @param $responseInstance An instance of a Responseable class
553 public final function setResponseInstance (Responseable $responseInstance) {
554 $this->responseInstance = $responseInstance;
558 * Getter for response instance
560 * @return $responseInstance An instance of a Responseable class
562 public final function getResponseInstance () {
563 return $this->responseInstance;
567 * Getter for $realClass
569 * @return $realClass The name of the real class (not BaseFrameworkSystem)
571 public final function __toString () {
572 return $this->realClass;
576 * Setter for the real class name
578 * @param $realClass Class name (string)
581 public final function setRealClass ($realClass) {
583 $realClass = (string) $realClass;
586 $this->realClass = $realClass;
590 * Generate unique ID from a lot entropy
594 public final function generateUniqueId () {
595 // Is the id set for this class?
596 if (empty($this->uniqueID)) {
598 // Correct missing class name
600 if ($this->__toString() == "") {
601 $this->setRealClass(__CLASS__);
605 // Cache datbase instance
606 $db = $this->getDatabaseInstance();
611 // Generate a unique ID number
612 $tempID = $this->generateIdNumber();
615 // Try to figure out if the ID number is not yet used
617 // Is this a registry?
618 if ($this->__toString() == "Registry") {
619 // Registry, then abort here
621 } elseif (is_object($db)) {
622 $isUsed = $db->isUniqueIdUsed($tempID, true);
624 } catch (FrameworkException $e) {
625 // Catches all and ignores all ;-)
649 $this->setUniqueID($tempID);
651 // Revert maybe corrected class name
653 $this->setRealClass("");
656 // Remove system classes if we are in a system class
657 if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
658 // This may save some RAM...
659 $this->removeSystemArray();
665 * Generates a new ID number for classes based from the class' real name,
666 * the description and some random data
668 * @return $tempID The new (temporary) ID number
670 private final function generateIdNumber () {
671 return sprintf("%s@%s",
673 md5(sprintf("%s:%s:%s:%s:%s:%s",
675 $this->getObjectDescription(),
677 getenv('REMOTE_ADDR'),
678 getenv('SERVER_ADDR'),
685 * Setter for unique ID
687 * @param $uniqueID The newly generated unique ID number
690 private final function setUniqueID ($uniqueID) {
692 $uniqueID = (string) $uniqueID;
695 $this->uniqueID = $uniqueID;
699 * Getter for unique ID
701 * @return $uniqueID The unique ID of this class
703 public final function getUniqueID () {
704 return $this->uniqueID;
708 * Resets or recreates the unique ID number
712 public final function resetUniqueID() {
713 // Sweet and simple... ;-)
714 $newUniqueID = $this->generateIdNumber();
715 $this->setUniqueID($newUniqueID);
719 * Getter for simulator description
721 * @return $objectDescription The description of this simulation part
723 public final function getObjectDescription () {
724 if (isset($this->objectDescription)) {
725 return $this->objectDescription;
732 * Setter for simulation part description
734 * @param $objectDescription The description as string for this simulation part
737 public final function setObjectDescription ($objectDescription) {
738 $this->objectDescription = (String) $objectDescription;
742 * Validate if given object is the same as current
744 * @param $object An object instance for comparison with this class
745 * @return boolean The result of comparing both's unique ID
747 public final function equals (FrameworkInterface $object) {
748 return ($this->getUniqueID() == $object->getUniqueID());
752 * Compare if both simulation part description and class name matches
755 * @param $itemInstance An object instance to an other class
756 * @return boolean The result of comparing class name simulation part description
758 public function itemMatches ($itemInstance) {
761 $this->__toString() == $itemInstance->__toString()
763 $this->getObjectDescription() == $itemInstance->getObjectDescription()
769 * Compare class name of this and given class name
771 * @param $className The class name as string from the other class
772 * @return boolean The result of comparing both class names
774 public final function isClass ($className) {
775 return ($this->__toString() == $className);
779 * Stub method (only real cabins shall override it)
781 * @return boolean false = is no cabin, true = is a cabin
783 public function isCabin () {
788 * Stub method for tradeable objects
790 * @return boolean false = is not tradeable by the Merchant class,
791 * true = is a tradeable object
793 public function isTradeable () {
798 * Formats computer generated price values into human-understandable formats
799 * with thousand and decimal seperators.
801 * @param $value The in computer format value for a price
802 * @param $currency The currency symbol (use HTML-valid characters!)
803 * @param $decNum Number of decimals after commata
804 * @return $price The for the current language formated price string
805 * @throws MissingDecimalsThousandsSeperatorException If decimals or
806 * thousands seperator
809 public function formatCurrency ($value, $currency = "€", $decNum = 2) {
810 // Are all required attriutes set?
811 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
812 // Throw an exception
813 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
817 $value = (float) $value;
819 // Reformat the US number
820 $price = sprintf("%s %s",
821 number_format($value, $decNum, $this->decimals, $this->thousands),
825 // Return as string...
830 * Removes number formating characters
834 public final function removeNumberFormaters () {
835 unset($this->thousands);
836 unset($this->decimals);
840 * Private getter for language instance
842 * @return $langInstance An instance to the language sub-system
844 protected final function getLanguageInstance () {
845 return self::$langInstance;
849 * Setter for language instance
851 * @param $langInstance An instance to the language sub-system
853 * @see LanguageSystem
855 public final function setLanguageInstance (ManageableLanguage $langInstance) {
856 self::$langInstance = $langInstance;
860 * Remove the $systemClasses array from memory
864 public final function removeSystemArray () {
865 unset($this->systemClasses);
869 * Create a file name and path name from the object's unique ID number.
870 * The left part of the ID shall always be a valid class name and the
871 * right part an ID number.
873 * @return $pfn The file name with a prepended path name
874 * @throws NoArrayCreatedException If explode() fails to create an array
875 * @throws InvalidArrayCountException If the array contains less or
876 * more than two elements
878 public final function getPathFileNameFromObject () {
879 // Get the main object's unique ID. We use this as a path/filename combination
880 $pathFile = $this->getUniqueID();
882 // Split it up in path and file name
883 $pathFile = explode("@", $pathFile);
885 // Are there two elements? Index 0 is the path, 1 the file name + global extension
886 if (!is_array($pathFile)) {
888 throw new NoArrayCreatedException(array($this, 'pathFile'), self::EXCEPTION_ARRAY_EXPECTED);
889 } elseif (count($pathFile) != 2) {
890 // Invalid ID returned!
891 throw new InvalidArrayCountException(array($this, 'pathFile', count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
894 // Auto-append missing trailing slash
895 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
897 // Create the file name and return it
898 $pfn = ($pathFile[0] . $pathFile[1]);
903 * Appends a trailing slash to a string
905 * @param $str A string (maybe) without trailing slash
906 * @return $str A string with an auto-appended trailing slash
908 public final function addMissingTrailingSlash ($str) {
909 // Is there a trailing slash?
910 if (substr($str, -1, 1) != "/") $str .= "/";
915 * Private getter for file IO instance
917 * @return $fileIoInstance An instance to the file I/O sub-system
919 protected final function getFileIoInstance () {
920 return $this->fileIoInstance;
924 * Setter for file I/O instance
926 * @param $fileIoInstance An instance to the file I/O sub-system
929 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
930 $this->fileIoInstance = $fileIoInstance;
934 * Prepare the template engine (WebTemplateEngine by default) for a given
935 * application helper instance (ApplicationHelper by default).
937 * @param $appInstance An application helper instance or
938 * null if we shall use the default
939 * @return $templateInstance The template engine instance
940 * @throws NullPointerException If the template engine could not
942 * @throws UnsupportedTemplateEngineException If $templateInstance is an
943 * unsupported template engine
944 * @throws MissingLanguageHandlerException If the language sub-system
945 * is not yet initialized
946 * @throws NullPointerException If the discovered application
947 * instance is still null
949 protected function prepareTemplateInstance (BaseFrameworkSystem $appInstance=null) {
950 // Is the application instance set?
951 if (is_null($appInstance)) {
952 // Get the current instance
953 $appInstance = $this->getApplicationInstance();
956 if (is_null($appInstance)) {
957 // Thrown an exception
958 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
962 // Generate FQFN for all application templates
963 $fqfn = sprintf("%s%s/%s/%s",
965 $this->getConfigInstance()->readConfig('application_path'),
966 strtolower($appInstance->getAppShortName()),
967 $this->getConfigInstance()->readConfig('tpl_base_path')
970 // Are both instances set?
971 if ($appInstance->getLanguageInstance() === null) {
972 // Invalid language instance
973 throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
974 } elseif ($appInstance->getFileIoInstance() === null) {
975 // Invalid language instance
976 throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
979 // Initialize the template engine
980 $templateInstance = ObjectFactory::createObjectByConfiguredName('template_class', array($fqfn, $appInstance->getLanguageInstance(), $appInstance->getFileIoInstance()));
982 // Return the prepared instance
983 return $templateInstance;
987 * Debugs this instance by putting out it's full content
991 public final function debugInstance () {
992 // Generate the output
993 $content = sprintf("<pre>%s</pre>",
994 trim(print_r($this, true))
998 ApplicationEntryPoint::app_die(sprintf("<strong>%s debug output:</strong><div id=\"debug_content\">%s</div>Loaded includes: <div id=\"debug_include_list\">%s</div>",
1001 ClassLoader::getInstance()->getPrintableIncludeList()
1006 * Output a partial stub message for the caller method
1008 * @param $message An optional message to display
1011 protected function partialStub ($message = "") {
1012 // Get the backtrace
1013 $backtrace = debug_backtrace();
1015 // Generate the class::method string
1016 $methodName = "UnknownClass->unknownMethod";
1017 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1018 $methodName = $backtrace[1]['class']."->".$backtrace[1]['function'];
1021 // Construct the full message
1022 $stubMessage = sprintf("[%s:] Partial stub!",
1026 // Is the extra message given?
1027 if (!empty($message)) {
1028 // Then add it as well
1029 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
1032 // Debug instance is there?
1033 if (!is_null($this->getDebugInstance())) {
1034 // Output stub message
1035 $this->getDebugInstance()->output($stubMessage);
1038 trigger_error($stubMessage."<br />\n");
1043 * Outputs a debug backtrace and stops further script execution
1047 public function debugBackTrace () {
1048 // Sorry, there is no other way getting this nice backtrace
1050 debug_print_backtrace();
1056 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
1058 * @param $message Message we shall send out...
1059 * @param $doPrint Wether we shall print or die here which last is the default
1062 public function debugOutput ($message, $doPrint = false) {
1063 // Get debug instance
1064 $debugInstance = $this->getDebugInstance();
1066 // Is the debug instance there?
1067 if (is_object($debugInstance)) {
1068 // Use debug output handler
1069 $debugInstance->output($message);
1070 if (!$doPrint) die(); // Die here if not printed
1073 // DO NOT REWRITE THIS TO app_die() !!!
1083 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1085 * @param $str The string, what ever it is needs to be converted
1086 * @return $className Generated class name
1088 public function convertToClassName ($str) {
1092 // Convert all dashes in underscores
1093 $str = str_replace("-", "_", $str);
1095 // Now use that underscores to get classname parts for hungarian style
1096 foreach (explode("_", $str) as $strPart) {
1097 // Make the class name part lower case and first upper case
1098 $className .= ucfirst(strtolower($strPart));
1101 // Return class name
1106 * Marks up the code by adding e.g. line numbers
1108 * @param $phpCode Unmarked PHP code
1109 * @return $markedCode Marked PHP code
1111 public function markupCode ($phpCode) {
1113 $errorArray = error_get_last();
1115 // Init the code with error message
1117 if (is_array($errorArray)) {
1119 $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>",
1120 basename($errorArray['file']),
1121 $errorArray['line'],
1122 $errorArray['message'],
1127 // Add line number to the code
1128 foreach (explode("\n", $phpCode) as $lineNo=>$code) {
1130 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
1132 htmlentities($code, ENT_QUOTES)
1141 * Filter a given timestamp to make it look more beatifull for web-based
1142 * front-ends. If null is given a message id null_timestamp will be
1143 * resolved and returned.
1145 * @param $timestamp Timestamp to prepare (filter) for display
1146 * @return $readable A readable timestamp
1148 public function doFilterFormatTimestamp ($timestamp) {
1149 // Default value to return
1152 // Is the timestamp null?
1153 if (is_null($timestamp)) {
1154 // Get a message string
1155 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1157 $this->partialStub("Do further analysis on timestamp {$timestamp}.");
1165 * "Getter" for databse entry
1167 * @return $entry An array with database entries
1168 * @throws NullPointerException If the database result is not found
1169 * @throws InvalidDatabaseResultException If the database result is invalid
1171 protected final function getDatabaseEntry () {
1172 // Is there an instance?
1173 if (is_null($this->getResultInstance())) {
1174 // Throw an exception here
1175 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1179 $this->getResultInstance()->rewind();
1181 // Do we have an entry?
1182 if (!$this->getResultInstance()->valid()) {
1183 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1187 $this->getResultInstance()->next();
1190 $entry = $this->getResultInstance()->current();
1197 * Getter for field name
1199 * @param $fieldName Field name which we shall get
1200 * @return $fieldValue Field value from the user
1201 * @throws NullPointerException If the result instance is null
1203 public final function getField ($fieldName) {
1204 // Default field value
1207 // Get result instance
1208 $resultInstance = $this->getResultInstance();
1210 // Is this instance null?
1211 if (is_null($resultInstance)) {
1212 // Then the user instance is no longer valid (expired cookies?)
1213 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1216 // Get current array
1217 $fieldArray = $resultInstance->current();
1219 // Does the field exist?
1220 if (isset($fieldArray[$fieldName])) {
1222 $fieldValue = $fieldArray[$fieldName];
1230 * Updates a given field with new value
1232 * @param $fieldName Field to update
1233 * @param $fieldValue New value to store
1235 * @throws DatabaseUpdateSupportException If this class does not support database updates
1237 public function updateDatabaseField ($fieldName, $fieldValue) {
1238 // Is updating database fields allowed by interface?
1239 if (!$this instanceof Updateable) {
1240 // Update not supported!
1241 throw new DatabaseUpdateSupportException($this, self::EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED);
1244 // Get a critieria instance
1245 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
1247 // Add search criteria
1248 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
1249 $searchInstance->setLimit(1);
1251 // Now get another criteria
1252 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
1254 // And add our both entries
1255 $updateInstance->addCriteria($fieldName, $fieldValue);
1257 // Add the search criteria for searching for the right entry
1258 $updateInstance->setSearchInstance($searchInstance);
1260 // Remember the update in database result
1261 $this->getResultInstance()->add2UpdateQueue($updateInstance);