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, 2009, 2010 Core Developer Team
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 of a request class
29 private $requestInstance = null;
32 * Instance of a response class
34 private $responseInstance = null;
37 * Search criteria instance
39 private $searchInstance = null;
42 * Update criteria instance
44 private $updateInstance = null;
47 * The file I/O instance for the template loader
49 private $fileIoInstance = null;
54 private $resolverInstance = null;
57 * Template engine instance
59 private $templateInstance = null;
62 * Database result instance
64 private $resultInstance = null;
67 * Instance for user class
69 private $userInstance = null;
72 * A controller instance
74 private $controllerInstance = null;
79 private $rngInstance = null;
82 * Instance of an Iterator class
84 private $iteratorInstance = null;
87 * Instance of the list
89 private $listInstance = null;
94 private $menuInstance = null;
97 * Instance of the image
99 private $imageInstance = null;
102 * Instance of the stacker
104 private $stackerInstance = null;
107 * A Compressor instance
109 private $compressorInstance = null;
112 * A Parseable instance
114 private $parserInstance = null;
117 * A ProtocolHandler instance
119 private $protocolInstance = null;
122 * A database wrapper instance
124 private $databaseInstance = null;
127 * The real class name
129 private $realClass = 'BaseFrameworkSystem';
132 * Thousands seperator
134 private $thousands = '.'; // German
139 private $decimals = ','; // German
144 private $socketResource = false;
149 private $packageData = array();
151 /***********************
152 * Exception codes.... *
153 ***********************/
154 // @todo Try to clean these constants up
155 const EXCEPTION_IS_NULL_POINTER = 0x001;
156 const EXCEPTION_IS_NO_OBJECT = 0x002;
157 const EXCEPTION_IS_NO_ARRAY = 0x003;
158 const EXCEPTION_MISSING_METHOD = 0x004;
159 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
160 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
161 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
162 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
163 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
164 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
165 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
166 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
167 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
168 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
169 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
170 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
171 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
172 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
173 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
174 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
175 const EXCEPTION_PATH_NOT_FOUND = 0x015;
176 const EXCEPTION_INVALID_PATH_NAME = 0x016;
177 const EXCEPTION_READ_PROTECED_PATH = 0x017;
178 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
179 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
180 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
181 const EXCEPTION_INVALID_RESOURCE = 0x01b;
182 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
183 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
184 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
185 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
186 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
187 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
188 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
189 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
190 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
191 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
192 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
193 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
194 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
195 const EXCEPTION_INVALID_STRING = 0x029;
196 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
197 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
198 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
199 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
200 const EXCEPTION_MISSING_LANGUAGE_HANDLER = 0x02e;
201 const EXCEPTION_MISSING_FILE_IO_HANDLER = 0x02f;
202 const EXCEPTION_MISSING_ELEMENT = 0x030;
203 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
204 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
205 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
206 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
207 const EXCEPTION_FATAL_ERROR = 0x035;
208 const EXCEPTION_FILE_NOT_FOUND = 0x036;
209 const EXCEPTION_ASSERTION_FAILED = 0x037;
210 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
211 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
212 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x040;
215 * Protected super constructor
217 * @param $className Name of the class
220 protected function __construct ($className) {
222 $this->setRealClass($className);
224 // Set configuration instance if no registry
225 if (!$this instanceof Register) {
226 // Because registries doesn't need to be configured
227 $this->setConfigInstance(FrameworkConfiguration::getInstance());
232 * Destructor reached...
235 * @todo This is old code. Do we still need this old lost code?
237 public function __destruct() {
238 // Flush any updated entries to the database
239 $this->flushPendingUpdates();
241 // Is this object already destroyed?
242 if ($this->__toString() != 'DestructedObject') {
243 // Destroy all informations about this class but keep some text about it alive
244 $this->setRealClass('DestructedObject');
245 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
246 // Already destructed object
247 $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
255 * The call method where all non-implemented methods end up
259 public final function __call ($methodName, $args) {
260 // Implode all given arguments
264 $argsString = 'NULL';
265 } elseif (is_array($args)) {
266 // Some arguments are there
267 foreach ($args as $arg) {
269 $argsString .= $this->replaceControlCharacters($arg) . ' (' . gettype($arg);
271 // Add length if type is string
272 if (gettype($arg) == 'string') $argsString .= ', '.strlen($arg);
275 $argsString .= '), ';
279 if (substr($argsString, -2, 1) == ',') {
280 $argsString = substr($argsString, 0, -2);
283 // Invalid arguments!
284 $argsString = '!INVALID:' . gettype($args) . '!';
287 // Output stub message
288 $this->debugOutput(sprintf("[%s->%s] Stub! Args: %s",
299 * Setter for database result instance
301 * @param $resultInstance An instance of a database result class
303 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
305 protected final function setResultInstance (SearchableResult $resultInstance) {
306 $this->resultInstance = $resultInstance;
310 * Getter for database result instance
312 * @return $resultInstance An instance of a database result class
314 public final function getResultInstance () {
315 return $this->resultInstance;
319 * Setter for template engine instances
321 * @param $templateInstance An instance of a template engine class
324 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
325 $this->templateInstance = $templateInstance;
329 * Getter for template engine instances
331 * @return $templateInstance An instance of a template engine class
333 protected final function getTemplateInstance () {
334 return $this->templateInstance;
338 * Setter for search instance
340 * @param $searchInstance Searchable criteria instance
343 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
344 $this->searchInstance = $searchInstance;
348 * Getter for search instance
350 * @return $searchInstance Searchable criteria instance
352 public final function getSearchInstance () {
353 return $this->searchInstance;
357 * Setter for update instance
359 * @param $updateInstance Searchable criteria instance
362 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
363 $this->updateInstance = $updateInstance;
367 * Getter for update instance
369 * @return $updateInstance Updateable criteria instance
371 public final function getUpdateInstance () {
372 return $this->updateInstance;
376 * Setter for resolver instance
378 * @param $resolverInstance Instance of a command resolver class
381 public final function setResolverInstance (Resolver $resolverInstance) {
382 $this->resolverInstance = $resolverInstance;
386 * Getter for resolver instance
388 * @return $resolverInstance Instance of a command resolver class
390 public final function getResolverInstance () {
391 return $this->resolverInstance;
395 * Setter for language instance
397 * @param $configInstance The configuration instance which shall
398 * be FrameworkConfiguration
401 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
402 Registry::getRegistry()->addInstance('config', $configInstance);
406 * Getter for configuration instance
408 * @return $configInstance Configuration instance
410 public final function getConfigInstance () {
411 $configInstance = Registry::getRegistry()->getInstance('config');
412 return $configInstance;
416 * Setter for debug instance
418 * @param $debugInstance The instance for debug output class
421 public final function setDebugInstance (DebugMiddleware $debugInstance) {
422 Registry::getRegistry()->addInstance('debug', $debugInstance);
426 * Getter for debug instance
428 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
430 public final function getDebugInstance () {
431 // Get debug instance
432 $debugInstance = Registry::getRegistry()->getInstance('debug');
435 return $debugInstance;
439 * Setter for web output instance
441 * @param $webInstance The instance for web output class
444 public final function setWebOutputInstance (OutputStreamer $webInstance) {
445 Registry::getRegistry()->addInstance('web_output', $webInstance);
449 * Getter for web output instance
451 * @return $webOutputInstance - Instance to class WebOutput
453 public final function getWebOutputInstance () {
454 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
455 return $webOutputInstance;
459 * Setter for database instance
461 * @param $dbInstance The instance for the database connection (forced DatabaseConnection)
464 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
465 Registry::getRegistry()->addInstance('db_instance', $dbInstance);
469 * Getter for database layer
471 * @return $dbInstance The database layer instance
473 public final function getDatabaseInstance () {
475 $dbInstance = Registry::getRegistry()->getInstance('db_instance');
482 * Setter for compressor channel
484 * @param $compressorInstance An instance of CompressorChannel
487 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
488 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
492 * Getter for compressor channel
494 * @return $compressorInstance The compressor channel
496 public final function getCompressorChannel () {
497 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
498 return $compressorInstance;
502 * Protected getter for a manageable application helper class
504 * @return $applicationInstance An instance of a manageable application helper class
506 protected final function getApplicationInstance () {
507 $applicationInstance = Registry::getRegistry()->getInstance('application');
508 return $applicationInstance;
512 * Setter for a manageable application helper class
514 * @param $applicationInstance An instance of a manageable application helper class
517 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
518 Registry::getRegistry()->addInstance('application', $applicationInstance);
522 * Setter for request instance
524 * @param $requestInstance An instance of a Requestable class
527 public final function setRequestInstance (Requestable $requestInstance) {
528 $this->requestInstance = $requestInstance;
532 * Getter for request instance
534 * @return $requestInstance An instance of a Requestable class
536 public final function getRequestInstance () {
537 return $this->requestInstance;
541 * Setter for response instance
543 * @param $responseInstance An instance of a Responseable class
546 public final function setResponseInstance (Responseable $responseInstance) {
547 $this->responseInstance = $responseInstance;
551 * Getter for response instance
553 * @return $responseInstance An instance of a Responseable class
555 public final function getResponseInstance () {
556 return $this->responseInstance;
560 * Getter for $realClass
562 * @return $realClass The name of the real class (not BaseFrameworkSystem)
564 public function __toString () {
565 return $this->realClass;
569 * Setter for the real class name
571 * @param $realClass Class name (string)
574 public final function setRealClass ($realClass) {
576 $realClass = (string) $realClass;
579 $this->realClass = $realClass;
583 * Checks wether an object equals this object. You should overwrite this
584 * method to implement own equality checks
586 * @param $objectInstance An instance of a FrameworkInterface object
587 * @return $equals Wether both objects equals
589 public function equals (FrameworkInterface $objectInstance) {
592 $this->__toString() == $objectInstance->__toString()
594 $this->hashCode() == $objectInstance->hashCode()
602 * Generates a generic hash code of this class. You should really overwrite
603 * this method with your own hash code generator code. But keep KISS in mind.
605 * @return $hashCode A generic hash code respresenting this whole class
607 public function hashCode () {
609 return crc32($this->__toString());
613 * Formats computer generated price values into human-understandable formats
614 * with thousand and decimal seperators.
616 * @param $value The in computer format value for a price
617 * @param $currency The currency symbol (use HTML-valid characters!)
618 * @param $decNum Number of decimals after commata
619 * @return $price The for the current language formated price string
620 * @throws MissingDecimalsThousandsSeperatorException If decimals or
621 * thousands seperator
624 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
625 // Are all required attriutes set?
626 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
627 // Throw an exception
628 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
632 $value = (float) $value;
634 // Reformat the US number
635 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
637 // Return as string...
642 * Private getter for language instance
644 * @return $langInstance An instance to the language sub-system
646 protected final function getLanguageInstance () {
647 $langInstance = Registry::getRegistry()->getInstance('language');
648 return $langInstance;
652 * Setter for language instance
654 * @param $langInstance An instance to the language sub-system
656 * @see LanguageSystem
658 public final function setLanguageInstance (ManageableLanguage $langInstance) {
659 Registry::getRegistry()->addInstance('language', $langInstance);
663 * Appends a trailing slash to a string
665 * @param $str A string (maybe) without trailing slash
666 * @return $str A string with an auto-appended trailing slash
668 public final function addMissingTrailingSlash ($str) {
669 // Is there a trailing slash?
670 if (substr($str, -1, 1) != '/') $str .= '/';
675 * Private getter for file IO instance
677 * @return $fileIoInstance An instance to the file I/O sub-system
679 protected final function getFileIoInstance () {
680 return $this->fileIoInstance;
684 * Setter for file I/O instance
686 * @param $fileIoInstance An instance to the file I/O sub-system
689 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
690 $this->fileIoInstance = $fileIoInstance;
694 * Prepare the template engine (WebTemplateEngine by default) for a given
695 * application helper instance (ApplicationHelper by default).
697 * @param $appInstance An application helper instance or
698 * null if we shall use the default
699 * @return $templateInstance The template engine instance
700 * @throws NullPointerException If the template engine could not
702 * @throws UnsupportedTemplateEngineException If $templateInstance is an
703 * unsupported template engine
704 * @throws MissingLanguageHandlerException If the language sub-system
705 * is not yet initialized
706 * @throws NullPointerException If the discovered application
707 * instance is still null
709 protected function prepareTemplateInstance (FrameworkInterface $appInstance=null) {
710 // Is the application instance set?
711 if (is_null($appInstance)) {
712 // Get the current instance
713 $appInstance = $this->getApplicationInstance();
716 if (is_null($appInstance)) {
717 // Thrown an exception
718 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
722 // Are both instances set?
723 if ($appInstance->getLanguageInstance() === null) {
724 // Invalid language instance
725 throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
726 } elseif ($appInstance->getFileIoInstance() === null) {
727 // Invalid language instance
728 throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
731 // Initialize the template engine
732 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class', array($appInstance));
734 // Return the prepared instance
735 return $templateInstance;
739 * Debugs this instance by putting out it's full content
741 * @param $message Optional message to show in debug output
744 public final function debugInstance ($message = '') {
745 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
746 restore_error_handler();
752 if (!empty($message)) {
754 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
757 // Generate the output
758 $content .= sprintf("<pre>%s</pre>",
767 ApplicationEntryPoint::app_die(sprintf("<div class=\"debug_header\">%s debug output:</div><div class=\"debug_content\">%s</div>\nLoaded includes: <div class=\"debug_include_list\">%s</div>",
770 ClassLoader::getInstance()->getPrintableIncludeList()
775 * Replaces control characters with printable output
777 * @param $str String with control characters
778 * @return $str Replaced string
780 protected function replaceControlCharacters ($str) {
783 "\r", '[r]', str_replace(
784 "\n", '[n]', str_replace(
794 * Output a partial stub message for the caller method
796 * @param $message An optional message to display
799 protected function partialStub ($message = '') {
801 $backtrace = debug_backtrace();
803 // Generate the class::method string
804 $methodName = 'UnknownClass->unknownMethod';
805 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
806 $methodName = $backtrace[1]['class']."->".$backtrace[1]['function'];
809 // Construct the full message
810 $stubMessage = sprintf("[%s:] Partial stub!",
814 // Is the extra message given?
815 if (!empty($message)) {
816 // Then add it as well
817 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
820 // Debug instance is there?
821 if (!is_null($this->getDebugInstance())) {
822 // Output stub message
823 $this->debugOutput($stubMessage);
826 trigger_error($stubMessage."<br />\n");
831 * Outputs a debug backtrace and stops further script execution
835 public function debugBackTrace () {
836 // Sorry, there is no other way getting this nice backtrace
838 debug_print_backtrace();
844 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
846 * @param $message Message we shall send out...
847 * @param $doPrint Wether we shall print or die here which first is the default
850 public function debugOutput ($message, $doPrint = true) {
851 // Get debug instance
852 $debugInstance = $this->getDebugInstance();
854 // Is the debug instance there?
855 if (is_object($debugInstance)) {
856 // Use debug output handler
857 $debugInstance->output($message);
858 if ($doPrint === false) die(); // Die here if not printed
861 if ($doPrint === true) {
864 // DO NOT REWRITE THIS TO app_die() !!!
871 * Converts e.g. a command from URL to a valid class by keeping out bad characters
873 * @param $str The string, what ever it is needs to be converted
874 * @return $className Generated class name
876 public function convertToClassName ($str) {
880 // Convert all dashes in underscores
881 $str = $this->convertDashesToUnderscores($str);
883 // Now use that underscores to get classname parts for hungarian style
884 foreach (explode('_', $str) as $strPart) {
885 // Make the class name part lower case and first upper case
886 $className .= ucfirst(strtolower($strPart));
894 * Converts dashes to underscores, e.g. useable for configuration entries
896 * @param $str The string with maybe dashes inside
897 * @return $str The converted string with no dashed, but underscores
899 public final function convertDashesToUnderscores ($str) {
901 $str = str_replace('-', '_', $str);
903 // Return converted string
908 * Marks up the code by adding e.g. line numbers
910 * @param $phpCode Unmarked PHP code
911 * @return $markedCode Marked PHP code
913 public function markupCode ($phpCode) {
918 $errorArray = error_get_last();
920 // Init the code with error message
921 if (is_array($errorArray)) {
923 $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>",
924 basename($errorArray['file']),
926 $errorArray['message'],
931 // Add line number to the code
932 foreach (explode("\n", $phpCode) as $lineNo => $code) {
934 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
936 htmlentities($code, ENT_QUOTES)
945 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
946 * beatiful for web-based front-ends. If null is given a message id
947 * null_timestamp will be resolved and returned.
949 * @param $timestamp Timestamp to prepare (filter) for display
950 * @return $readable A readable timestamp
952 public function doFilterFormatTimestamp ($timestamp) {
953 // Default value to return
956 // Is the timestamp null?
957 if (is_null($timestamp)) {
958 // Get a message string
959 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
961 switch ($this->getLanguageInstance()->getLanguageCode()) {
962 case 'de': // German format is a bit different to default
963 // Split the GMT stamp up
964 $dateTime = explode(' ', $timestamp );
965 $dateArray = explode('-', $dateTime[0]);
966 $timeArray = explode(':', $dateTime[1]);
968 // Construct the timestamp
969 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
979 default: // Default is pass-through
980 $readable = $timestamp;
990 * Filter a given number into a localized number
992 * @param $value The raw value from e.g. database
993 * @return $localized Localized value
995 public function doFilterFormatNumber ($value) {
996 // Generate it from config and localize dependencies
997 switch ($this->getLanguageInstance()->getLanguageCode()) {
998 case 'de': // German format is a bit different to default
999 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1002 default: // US, etc.
1003 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1012 * "Getter" for databse entry
1014 * @return $entry An array with database entries
1015 * @throws NullPointerException If the database result is not found
1016 * @throws InvalidDatabaseResultException If the database result is invalid
1018 protected final function getDatabaseEntry () {
1019 // Is there an instance?
1020 if (is_null($this->getResultInstance())) {
1021 // Throw an exception here
1022 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1026 $this->getResultInstance()->rewind();
1028 // Do we have an entry?
1029 if ($this->getResultInstance()->valid() === false) {
1030 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1034 $this->getResultInstance()->next();
1037 $entry = $this->getResultInstance()->current();
1044 * Getter for field name
1046 * @param $fieldName Field name which we shall get
1047 * @return $fieldValue Field value from the user
1048 * @throws NullPointerException If the result instance is null
1050 public final function getField ($fieldName) {
1051 // Default field value
1054 // Get result instance
1055 $resultInstance = $this->getResultInstance();
1057 // Is this instance null?
1058 if (is_null($resultInstance)) {
1059 // Then the user instance is no longer valid (expired cookies?)
1060 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1063 // Get current array
1064 $fieldArray = $resultInstance->current();
1065 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1067 // Does the field exist?
1068 if (isset($fieldArray[$fieldName])) {
1070 $fieldValue = $fieldArray[$fieldName];
1078 * Protected setter for user instance
1080 * @param $userInstance An instance of a user class
1083 protected final function setUserInstance (ManageableAccount $userInstance) {
1084 $this->userInstance = $userInstance;
1088 * Getter for user instance
1090 * @return $userInstance An instance of a user class
1092 public final function getUserInstance () {
1093 return $this->userInstance;
1097 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1099 * @param $controllerInstance An instance of the controller
1102 public final function setControllerInstance (Controller $controllerInstance) {
1103 $this->controllerInstance = $controllerInstance;
1107 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1109 * @return $controllerInstance An instance of the controller
1111 public final function getControllerInstance () {
1112 return $this->controllerInstance;
1116 * Flushs all pending updates to the database layer
1120 public function flushPendingUpdates () {
1121 // Get result instance
1122 $resultInstance = $this->getResultInstance();
1124 // Do we have data to update?
1125 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1126 // Get wrapper class name config entry
1127 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1129 // Create object instance
1130 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1132 // Yes, then send the whole result to the database layer
1133 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1138 * Outputs a deprecation warning to the developer.
1140 * @param $message The message we shall output to the developer
1142 * @todo Write a logging mechanism for productive mode
1144 public function deprecationWarning ($message) {
1145 // Is developer mode active?
1146 if (defined('DEVELOPER')) {
1147 // Debug instance is there?
1148 if (!is_null($this->getDebugInstance())) {
1149 // Output stub message
1150 $this->debugOutput($message);
1153 trigger_error($message."<br />\n");
1156 // @TODO Finish this part!
1157 $this->partialStub('Developer mode inactive. Message:' . $message);
1162 * Checks wether the given PHP extension is loaded
1164 * @param $phpExtension The PHP extension we shall check
1165 * @return $isLoaded Wether the PHP extension is loaded
1167 public final function isPhpExtensionLoaded ($phpExtension) {
1169 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1176 * Setter for RNG instance
1178 * @param $rngInstance An instance of a random number generator (RNG)
1181 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1182 $this->rngInstance = $rngInstance;
1186 * Getter for RNG instance
1188 * @return $rngInstance An instance of a random number generator (RNG)
1190 public final function getRngInstance () {
1191 return $this->rngInstance;
1195 * Setter for Iterator instance
1197 * @param $iteratorInstance An instance of an Iterator
1200 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1201 $this->iteratorInstance = $iteratorInstance;
1205 * Getter for Iterator instance
1207 * @return $iteratorInstance An instance of an Iterator
1209 public final function getIteratorInstance () {
1210 return $this->iteratorInstance;
1214 * "Getter" as a time() replacement but with milliseconds. You should use this
1215 * method instead of the encapsulated getimeofday() function.
1217 * @return $milliTime Timestamp with milliseconds
1219 public function getMilliTime () {
1220 // Get the time of day as float
1221 $milliTime = gettimeofday(true);
1228 * Idles (sleeps) for given milliseconds
1230 * @return $hasSlept Wether it goes fine
1232 public function idle ($milliSeconds) {
1233 // Sleep is fine by default
1236 // Idle so long with found function
1237 if (function_exists('time_sleep_until')) {
1238 // Get current time and add idle time
1239 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1241 // New PHP 5.1.0 function found
1242 $hasSlept = time_sleep_until($sleepUntil);
1244 // My Sun Station doesn't have that function even with latest PHP
1246 usleep($milliSeconds * 1000);
1254 * Setter for the list instance
1256 * @param $listInstance A list of Listable
1259 protected final function setListInstance (Listable $listInstance) {
1260 $this->listInstance = $listInstance;
1264 * Getter for the list instance
1266 * @return $listInstance A list of Listable
1268 protected final function getListInstance () {
1269 return $this->listInstance;
1273 * Setter for the menu instance
1275 * @param $menuInstance A RenderableMenu instance
1278 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1279 $this->menuInstance = $menuInstance;
1283 * Getter for the menu instance
1285 * @return $menuInstance A RenderableMenu instance
1287 protected final function getMenuInstance () {
1288 return $this->menuInstance;
1292 * Setter for image instance
1294 * @param $imageInstance An instance of an image
1297 public final function setImageInstance (BaseImage $imageInstance) {
1298 $this->imageInstance = $imageInstance;
1302 * Getter for image instance
1304 * @return $imageInstance An instance of an image
1306 public final function getImageInstance () {
1307 return $this->imageInstance;
1311 * Setter for stacker instance
1313 * @param $stackerInstance An instance of an stacker
1316 public final function setStackerInstance (Stackable $stackerInstance) {
1317 $this->stackerInstance = $stackerInstance;
1321 * Getter for stacker instance
1323 * @return $stackerInstance An instance of an stacker
1325 public final function getStackerInstance () {
1326 return $this->stackerInstance;
1330 * Setter for compressor instance
1332 * @param $compressorInstance An instance of an compressor
1335 public final function setCompressorInstance (Compressor $compressorInstance) {
1336 $this->compressorInstance = $compressorInstance;
1340 * Getter for compressor instance
1342 * @return $compressorInstance An instance of an compressor
1344 public final function getCompressorInstance () {
1345 return $this->compressorInstance;
1349 * Setter for Parseable instance
1351 * @param $parserInstance An instance of an Parseable
1354 public final function setParserInstance (Parseable $parserInstance) {
1355 $this->parserInstance = $parserInstance;
1359 * Getter for Parseable instance
1361 * @return $parserInstance An instance of an Parseable
1363 public final function getParserInstance () {
1364 return $this->parserInstance;
1368 * Setter for ProtocolHandler instance
1370 * @param $protocolInstance An instance of an ProtocolHandler
1373 public final function setProtocolInstance (ProtocolHandler $protocolInstance) {
1374 $this->protocolInstance = $protocolInstance;
1378 * Getter for ProtocolHandler instance
1380 * @return $protocolInstance An instance of an ProtocolHandler
1382 public final function getProtocolInstance () {
1383 return $this->protocolInstance;
1387 * Setter for BaseDatabaseWrapper instance
1389 * @param $wrapperInstance An instance of an BaseDatabaseWrapper
1392 public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
1393 $this->wrapperInstance = $wrapperInstance;
1397 * Getter for BaseDatabaseWrapper instance
1399 * @return $wrapperInstance An instance of an BaseDatabaseWrapper
1401 public final function getWrapperInstance () {
1402 return $this->wrapperInstance;
1406 * Setter for socket resource
1408 * @param $socketResource A valid socket resource
1411 public final function setSocketResource ($socketResource) {
1412 $this->socketResource = $socketResource;
1416 * Getter for socket resource
1418 * @return $socketResource A valid socket resource
1420 public function getSocketResource () {
1421 return $this->socketResource;
1425 * Setter for raw package Data
1427 * @param $packageData Raw package Data
1430 public final function setPackageData (array $packageData) {
1431 $this->packageData = $packageData;
1435 * Getter for raw package Data
1437 * @return $packageData Raw package Data
1439 public function getPackageData () {
1440 return $this->packageData;