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->debugOutput(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->debugOutput(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 // Default is invalid db instance
486 // Is the registry there and initialized?
487 if ((class_exists('Registry')) && (Registry::isInitialized() === true)) {
488 $dbInstance = Registry::getRegistry()->getInstance('dbInstance');
496 * Setter for compressor channel
498 * @param $compressorChannel An instance of CompressorChannel
501 public final function setCompressorChannel (CompressorChannel $compressorChannel) {
502 Registry::getRegistry()->addInstance('compressor', $compressorChannel);
506 * Getter for compressor channel
508 * @return $compressor The compressor channel
510 public final function getCompressorChannel () {
511 return Registry::getRegistry()->getInstance('compressor');
515 * Protected getter for a manageable application helper class
517 * @return $applicationInstance An instance of a manageable application helper class
519 protected final function getApplicationInstance () {
520 return self::$applicationInstance;
524 * Setter for a manageable application helper class
526 * @param $applicationInstance An instance of a manageable application helper class
529 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
530 self::$applicationInstance = $applicationInstance;
534 * Setter for request instance
536 * @param $requestInstance An instance of a Requestable class
539 public final function setRequestInstance (Requestable $requestInstance) {
540 $this->requestInstance = $requestInstance;
544 * Getter for request instance
546 * @return $requestInstance An instance of a Requestable class
548 public final function getRequestInstance () {
549 return $this->requestInstance;
553 * Setter for response instance
555 * @param $responseInstance An instance of a Responseable class
558 public final function setResponseInstance (Responseable $responseInstance) {
559 $this->responseInstance = $responseInstance;
563 * Getter for response instance
565 * @return $responseInstance An instance of a Responseable class
567 public final function getResponseInstance () {
568 return $this->responseInstance;
572 * Getter for $realClass
574 * @return $realClass The name of the real class (not BaseFrameworkSystem)
576 public final function __toString () {
577 return $this->realClass;
581 * Setter for the real class name
583 * @param $realClass Class name (string)
586 public final function setRealClass ($realClass) {
588 $realClass = (string) $realClass;
591 $this->realClass = $realClass;
595 * Generate unique ID from a lot entropy
599 public final function generateUniqueId () {
600 // Is the id set for this class?
601 if (empty($this->uniqueID)) {
603 // Correct missing class name
605 if ($this->__toString() == "") {
606 $this->setRealClass(__CLASS__);
610 // Cache datbase instance
611 $db = $this->getDatabaseInstance();
616 // Generate a unique ID number
617 $tempID = $this->generateIdNumber();
620 // Try to figure out if the ID number is not yet used
622 // Is this a registry?
623 if ($this->__toString() == "Registry") {
624 // Registry, then abort here
626 } elseif (is_object($db)) {
627 $isUsed = $db->isUniqueIdUsed($tempID, true);
629 } catch (FrameworkException $e) {
630 // Catches all and ignores all ;-)
654 $this->setUniqueID($tempID);
656 // Revert maybe corrected class name
658 $this->setRealClass("");
661 // Remove system classes if we are in a system class
662 if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
663 // This may save some RAM...
664 $this->removeSystemArray();
670 * Generates a new ID number for classes based from the class' real name,
671 * the description and some random data
673 * @return $tempID The new (temporary) ID number
675 private final function generateIdNumber () {
676 return sprintf("%s@%s",
678 md5(sprintf("%s:%s:%s:%s:%s:%s",
680 $this->getObjectDescription(),
682 getenv('REMOTE_ADDR'),
683 getenv('SERVER_ADDR'),
690 * Setter for unique ID
692 * @param $uniqueID The newly generated unique ID number
695 private final function setUniqueID ($uniqueID) {
697 $uniqueID = (string) $uniqueID;
700 $this->uniqueID = $uniqueID;
704 * Getter for unique ID
706 * @return $uniqueID The unique ID of this class
708 public final function getUniqueID () {
709 return $this->uniqueID;
713 * Resets or recreates the unique ID number
717 public final function resetUniqueID() {
718 // Sweet and simple... ;-)
719 $newUniqueID = $this->generateIdNumber();
720 $this->setUniqueID($newUniqueID);
724 * Getter for simulator description
726 * @return $objectDescription The description of this simulation part
728 public final function getObjectDescription () {
729 return $this->objectDescription;
733 * Setter for simulation part description
735 * @param $objectDescription The description as string for this simulation part
738 public final function setObjectDescription ($objectDescription) {
739 $this->objectDescription = (String) $objectDescription;
743 * Validate if given object is the same as current
745 * @param $object An object instance for comparison with this class
746 * @return boolean The result of comparing both's unique ID
748 public final function equals (FrameworkInterface $object) {
749 return ($this->getUniqueID() == $object->getUniqueID());
753 * Compare if both simulation part description and class name matches
756 * @param $itemInstance An object instance to an other class
757 * @return boolean The result of comparing class name simulation part description
759 public function itemMatches ($itemInstance) {
762 $this->__toString() == $itemInstance->__toString()
764 $this->getObjectDescription() == $itemInstance->getObjectDescription()
770 * Compare class name of this and given class name
772 * @param $className The class name as string from the other class
773 * @return boolean The result of comparing both class names
775 public final function isClass ($className) {
776 return ($this->__toString() == $className);
780 * Stub method (only real cabins shall override it)
782 * @return boolean false = is no cabin, true = is a cabin
784 public function isCabin () {
789 * Stub method for tradeable objects
791 * @return boolean false = is not tradeable by the Merchant class,
792 * true = is a tradeable object
794 public function isTradeable () {
799 * Formats computer generated price values into human-understandable formats
800 * with thousand and decimal seperators.
802 * @param $value The in computer format value for a price
803 * @param $currency The currency symbol (use HTML-valid characters!)
804 * @param $decNum Number of decimals after commata
805 * @return $price The for the current language formated price string
806 * @throws MissingDecimalsThousandsSeperatorException If decimals or
807 * thousands seperator
810 public function formatCurrency ($value, $currency = "€", $decNum = 2) {
811 // Are all required attriutes set?
812 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
813 // Throw an exception
814 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
818 $value = (float) $value;
820 // Reformat the US number
821 $price = sprintf("%s %s",
822 number_format($value, $decNum, $this->decimals, $this->thousands),
826 // Return as string...
831 * Removes number formating characters
835 public final function removeNumberFormaters () {
836 unset($this->thousands);
837 unset($this->decimals);
841 * Private getter for language instance
843 * @return $langInstance An instance to the language sub-system
845 protected final function getLanguageInstance () {
846 return self::$langInstance;
850 * Setter for language instance
852 * @param $langInstance An instance to the language sub-system
854 * @see LanguageSystem
856 public final function setLanguageInstance (ManageableLanguage $langInstance) {
857 self::$langInstance = $langInstance;
861 * Remove the $systemClasses array from memory
865 public final function removeSystemArray () {
866 unset($this->systemClasses);
870 * Create a file name and path name from the object's unique ID number.
871 * The left part of the ID shall always be a valid class name and the
872 * right part an ID number.
874 * @return $pfn The file name with a prepended path name
875 * @throws NoArrayCreatedException If explode() fails to create an array
876 * @throws InvalidArrayCountException If the array contains less or
877 * more than two elements
879 public final function getPathFileNameFromObject () {
880 // Get the main object's unique ID. We use this as a path/filename combination
881 $pathFile = $this->getUniqueID();
883 // Split it up in path and file name
884 $pathFile = explode("@", $pathFile);
886 // Are there two elements? Index 0 is the path, 1 the file name + global extension
887 if (!is_array($pathFile)) {
889 throw new NoArrayCreatedException(array($this, 'pathFile'), self::EXCEPTION_ARRAY_EXPECTED);
890 } elseif (count($pathFile) != 2) {
891 // Invalid ID returned!
892 throw new InvalidArrayCountException(array($this, 'pathFile', count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
895 // Auto-append missing trailing slash
896 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
898 // Create the file name and return it
899 $pfn = ($pathFile[0] . $pathFile[1]);
904 * Appends a trailing slash to a string
906 * @param $str A string (maybe) without trailing slash
907 * @return $str A string with an auto-appended trailing slash
909 public final function addMissingTrailingSlash ($str) {
910 // Is there a trailing slash?
911 if (substr($str, -1, 1) != "/") $str .= "/";
916 * Private getter for file IO instance
918 * @return $fileIoInstance An instance to the file I/O sub-system
920 protected final function getFileIoInstance () {
921 return $this->fileIoInstance;
925 * Setter for file I/O instance
927 * @param $fileIoInstance An instance to the file I/O sub-system
930 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
931 $this->fileIoInstance = $fileIoInstance;
935 * Prepare the template engine (WebTemplateEngine by default) for a given
936 * application helper instance (ApplicationHelper by default).
938 * @param $appInstance An application helper instance or
939 * null if we shall use the default
940 * @return $templateInstance The template engine instance
941 * @throws NullPointerException If the template engine could not
943 * @throws UnsupportedTemplateEngineException If $templateInstance is an
944 * unsupported template engine
945 * @throws MissingLanguageHandlerException If the language sub-system
946 * is not yet initialized
947 * @throws NullPointerException If the discovered application
948 * instance is still null
950 protected function prepareTemplateInstance (BaseFrameworkSystem $appInstance=null) {
951 // Is the application instance set?
952 if (is_null($appInstance)) {
953 // Get the current instance
954 $appInstance = $this->getApplicationInstance();
957 if (is_null($appInstance)) {
958 // Thrown an exception
959 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
963 // Generate FQFN for all application templates
964 $fqfn = sprintf("%s%s/%s/%s",
966 $this->getConfigInstance()->readConfig('application_path'),
967 strtolower($appInstance->getAppShortName()),
968 $this->getConfigInstance()->readConfig('tpl_base_path')
971 // Are both instances set?
972 if ($appInstance->getLanguageInstance() === null) {
973 // Invalid language instance
974 throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
975 } elseif ($appInstance->getFileIoInstance() === null) {
976 // Invalid language instance
977 throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
980 // Initialize the template engine
981 $templateInstance = ObjectFactory::createObjectByConfiguredName('template_class', array($fqfn, $appInstance->getLanguageInstance(), $appInstance->getFileIoInstance()));
983 // Return the prepared instance
984 return $templateInstance;
988 * Debugs this instance by putting out it's full content
992 public final function debugInstance () {
993 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
994 restore_error_handler();
996 // Generate the output
997 $content = sprintf("<pre>%s</pre>",
1000 print_r($this, true)
1006 ApplicationEntryPoint::app_die(sprintf("<strong>%s debug output:</strong><div id=\"debug_content\">%s</div>\nLoaded includes: <div id=\"debug_include_list\">%s</div>",
1007 $this->__toString(),
1009 ClassLoader::getInstance()->getPrintableIncludeList()
1014 * Output a partial stub message for the caller method
1016 * @param $message An optional message to display
1019 protected function partialStub ($message = "") {
1020 // Get the backtrace
1021 $backtrace = debug_backtrace();
1023 // Generate the class::method string
1024 $methodName = "UnknownClass->unknownMethod";
1025 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1026 $methodName = $backtrace[1]['class']."->".$backtrace[1]['function'];
1029 // Construct the full message
1030 $stubMessage = sprintf("[%s:] Partial stub!",
1034 // Is the extra message given?
1035 if (!empty($message)) {
1036 // Then add it as well
1037 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
1040 // Debug instance is there?
1041 if (!is_null($this->getDebugInstance())) {
1042 // Output stub message
1043 $this->debugOutput($stubMessage);
1046 trigger_error($stubMessage."<br />\n");
1051 * Outputs a debug backtrace and stops further script execution
1055 public function debugBackTrace () {
1056 // Sorry, there is no other way getting this nice backtrace
1058 debug_print_backtrace();
1064 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
1066 * @param $message Message we shall send out...
1067 * @param $doPrint Wether we shall print or die here which first is the default
1070 public function debugOutput ($message, $doPrint = true) {
1071 // Get debug instance
1072 $debugInstance = $this->getDebugInstance();
1074 // Is the debug instance there?
1075 if (is_object($debugInstance)) {
1076 // Use debug output handler
1077 $debugInstance->output($message);
1078 if (!$doPrint) die(); // Die here if not printed
1084 // DO NOT REWRITE THIS TO app_die() !!!
1091 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1093 * @param $str The string, what ever it is needs to be converted
1094 * @return $className Generated class name
1096 public function convertToClassName ($str) {
1100 // Convert all dashes in underscores
1101 $str = str_replace("-", "_", $str);
1103 // Now use that underscores to get classname parts for hungarian style
1104 foreach (explode("_", $str) as $strPart) {
1105 // Make the class name part lower case and first upper case
1106 $className .= ucfirst(strtolower($strPart));
1109 // Return class name
1114 * Marks up the code by adding e.g. line numbers
1116 * @param $phpCode Unmarked PHP code
1117 * @return $markedCode Marked PHP code
1119 public function markupCode ($phpCode) {
1121 $errorArray = error_get_last();
1123 // Init the code with error message
1125 if (is_array($errorArray)) {
1127 $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>",
1128 basename($errorArray['file']),
1129 $errorArray['line'],
1130 $errorArray['message'],
1135 // Add line number to the code
1136 foreach (explode("\n", $phpCode) as $lineNo=>$code) {
1138 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
1140 htmlentities($code, ENT_QUOTES)
1149 * Filter a given timestamp to make it look more beatifull for web-based
1150 * front-ends. If null is given a message id null_timestamp will be
1151 * resolved and returned.
1153 * @param $timestamp Timestamp to prepare (filter) for display
1154 * @return $readable A readable timestamp
1156 public function doFilterFormatTimestamp ($timestamp) {
1157 // Default value to return
1160 // Is the timestamp null?
1161 if (is_null($timestamp)) {
1162 // Get a message string
1163 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1165 $this->partialStub("Do further analysis on timestamp {$timestamp}.");
1173 * "Getter" for databse entry
1175 * @return $entry An array with database entries
1176 * @throws NullPointerException If the database result is not found
1177 * @throws InvalidDatabaseResultException If the database result is invalid
1179 protected final function getDatabaseEntry () {
1180 // Is there an instance?
1181 if (is_null($this->getResultInstance())) {
1182 // Throw an exception here
1183 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1187 $this->getResultInstance()->rewind();
1189 // Do we have an entry?
1190 if (!$this->getResultInstance()->valid()) {
1191 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1195 $this->getResultInstance()->next();
1198 $entry = $this->getResultInstance()->current();
1205 * Getter for field name
1207 * @param $fieldName Field name which we shall get
1208 * @return $fieldValue Field value from the user
1209 * @throws NullPointerException If the result instance is null
1211 public final function getField ($fieldName) {
1212 // Default field value
1215 // Get result instance
1216 $resultInstance = $this->getResultInstance();
1218 // Is this instance null?
1219 if (is_null($resultInstance)) {
1220 // Then the user instance is no longer valid (expired cookies?)
1221 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1224 // Get current array
1225 $fieldArray = $resultInstance->current();
1227 // Does the field exist?
1228 if (isset($fieldArray[$fieldName])) {
1230 $fieldValue = $fieldArray[$fieldName];
1238 * Updates a given field with new value
1240 * @param $fieldName Field to update
1241 * @param $fieldValue New value to store
1243 * @throws DatabaseUpdateSupportException If this class does not support database updates
1245 public function updateDatabaseField ($fieldName, $fieldValue) {
1246 // Is updating database fields allowed by interface?
1247 if (!$this instanceof Updateable) {
1248 // Update not supported!
1249 throw new DatabaseUpdateSupportException($this, self::EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED);
1252 // Get a critieria instance
1253 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
1255 // Add search criteria
1256 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
1257 $searchInstance->setLimit(1);
1259 // Now get another criteria
1260 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
1262 // And add our both entries
1263 $updateInstance->addCriteria($fieldName, $fieldValue);
1265 // Add the search criteria for searching for the right entry
1266 $updateInstance->setSearchInstance($searchInstance);
1268 // Remember the update in database result
1269 $this->getResultInstance()->add2UpdateQueue($updateInstance);