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 - 2011 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 a crypto helper
84 private $cryptoInstance = null;
87 * Instance of an Iterator class
89 private $iteratorInstance = null;
92 * Instance of the list
94 private $listInstance = null;
99 private $menuInstance = null;
102 * Instance of the image
104 private $imageInstance = null;
107 * Instance of the stacker
109 private $stackerInstance = null;
112 * A Compressor instance
114 private $compressorInstance = null;
117 * A Parseable instance
119 private $parserInstance = null;
122 * A ProtocolHandler instance
124 private $protocolInstance = null;
127 * A database wrapper instance
129 private $databaseInstance = null;
132 * The real class name
134 private $realClass = 'BaseFrameworkSystem';
137 * Thousands seperator
139 private $thousands = '.'; // German
144 private $decimals = ','; // German
149 private $socketResource = false;
154 private $packageData = array();
156 /***********************
157 * Exception codes.... *
158 ***********************/
159 // @todo Try to clean these constants up
160 const EXCEPTION_IS_NULL_POINTER = 0x001;
161 const EXCEPTION_IS_NO_OBJECT = 0x002;
162 const EXCEPTION_IS_NO_ARRAY = 0x003;
163 const EXCEPTION_MISSING_METHOD = 0x004;
164 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
165 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
166 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
167 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
168 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
169 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
170 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
171 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
172 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
173 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
174 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
175 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
176 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
177 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
178 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
179 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
180 const EXCEPTION_PATH_NOT_FOUND = 0x015;
181 const EXCEPTION_INVALID_PATH_NAME = 0x016;
182 const EXCEPTION_READ_PROTECED_PATH = 0x017;
183 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
184 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
185 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
186 const EXCEPTION_INVALID_RESOURCE = 0x01b;
187 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
188 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
189 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
190 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
191 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
192 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
193 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
194 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
195 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
196 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
197 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
198 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
199 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
200 const EXCEPTION_INVALID_STRING = 0x029;
201 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
202 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
203 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
204 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
205 const EXCEPTION_MISSING_ELEMENT = 0x030;
206 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
207 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
208 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
209 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
210 const EXCEPTION_FATAL_ERROR = 0x035;
211 const EXCEPTION_FILE_NOT_FOUND = 0x036;
212 const EXCEPTION_ASSERTION_FAILED = 0x037;
213 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
214 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
215 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x040;
218 * Protected super constructor
220 * @param $className Name of the class
223 protected function __construct ($className) {
225 $this->setRealClass($className);
227 // Set configuration instance if no registry ...
228 if (!$this instanceof Register) {
229 // ... because registries doesn't need to be configured
230 $this->setConfigInstance(FrameworkConfiguration::getInstance());
235 * Destructor reached...
239 public function __destruct() {
240 // Flush any updated entries to the database
241 $this->flushPendingUpdates();
243 // Is this object already destroyed?
244 if ($this->__toString() != 'DestructedObject') {
245 // Destroy all informations about this class but keep some text about it alive
246 $this->setRealClass('DestructedObject');
247 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
248 // Already destructed object
249 $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
257 * The __call() method where all non-implemented methods end up
259 * @param $methodName Name of the missing method
260 * @args $args Arguments passed to the method
263 public final function __call ($methodName, $args) {
264 // Implode all given arguments
268 $argsString = 'NULL';
269 } elseif (is_array($args)) {
270 // Some arguments are there
271 foreach ($args as $arg) {
273 $argsString .= $this->replaceControlCharacters($arg) . ' (' . gettype($arg);
275 // Add length if type is string
276 if (is_string($arg)) {
277 $argsString .= ', '.strlen($arg);
281 $argsString .= '), ';
285 if (substr($argsString, -2, 1) == ',') {
286 $argsString = substr($argsString, 0, -2);
289 // Invalid arguments!
290 $argsString = '!INVALID:' . gettype($args) . '!';
293 // Output stub message
294 $this->debugOutput(sprintf("[%s->%s] Stub! Args: %s",
305 * Getter for $realClass
307 * @return $realClass The name of the real class (not BaseFrameworkSystem)
309 public function __toString () {
310 return $this->realClass;
314 * Magic function to catch setting of missing but set class fields/attributes
316 * @param $name Name of the field/attribute
317 * @param $value Value to store
320 public final function __set ($name, $value) {
321 $this->debugOutput(sprintf("Tried to set a missing field. name=%s, value[%s]=%s",
329 * Magic function to catch getting of missing fields/attributes
331 * @param $name Name of the field/attribute
334 public final function __get ($name) {
335 $this->debugOutput(sprintf("Tried to get a missing field. name=%s",
341 * Setter for database result instance
343 * @param $resultInstance An instance of a database result class
345 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
347 protected final function setResultInstance (SearchableResult $resultInstance) {
348 $this->resultInstance = $resultInstance;
352 * Getter for database result instance
354 * @return $resultInstance An instance of a database result class
356 public final function getResultInstance () {
357 return $this->resultInstance;
361 * Setter for template engine instances
363 * @param $templateInstance An instance of a template engine class
366 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
367 $this->templateInstance = $templateInstance;
371 * Getter for template engine instances
373 * @return $templateInstance An instance of a template engine class
375 protected final function getTemplateInstance () {
376 return $this->templateInstance;
380 * Setter for search instance
382 * @param $searchInstance Searchable criteria instance
385 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
386 $this->searchInstance = $searchInstance;
390 * Getter for search instance
392 * @return $searchInstance Searchable criteria instance
394 public final function getSearchInstance () {
395 return $this->searchInstance;
399 * Setter for update instance
401 * @param $updateInstance Searchable criteria instance
404 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
405 $this->updateInstance = $updateInstance;
409 * Getter for update instance
411 * @return $updateInstance Updateable criteria instance
413 public final function getUpdateInstance () {
414 return $this->updateInstance;
418 * Setter for resolver instance
420 * @param $resolverInstance Instance of a command resolver class
423 public final function setResolverInstance (Resolver $resolverInstance) {
424 $this->resolverInstance = $resolverInstance;
428 * Getter for resolver instance
430 * @return $resolverInstance Instance of a command resolver class
432 public final function getResolverInstance () {
433 return $this->resolverInstance;
437 * Setter for language instance
439 * @param $configInstance The configuration instance which shall
440 * be FrameworkConfiguration
443 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
444 Registry::getRegistry()->addInstance('config', $configInstance);
448 * Getter for configuration instance
450 * @return $configInstance Configuration instance
452 public final function getConfigInstance () {
453 $configInstance = Registry::getRegistry()->getInstance('config');
454 return $configInstance;
458 * Setter for debug instance
460 * @param $debugInstance The instance for debug output class
463 public final function setDebugInstance (DebugMiddleware $debugInstance) {
464 Registry::getRegistry()->addInstance('debug', $debugInstance);
468 * Getter for debug instance
470 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
472 public final function getDebugInstance () {
473 // Get debug instance
474 $debugInstance = Registry::getRegistry()->getInstance('debug');
477 return $debugInstance;
481 * Setter for web output instance
483 * @param $webInstance The instance for web output class
486 public final function setWebOutputInstance (OutputStreamer $webInstance) {
487 Registry::getRegistry()->addInstance('web_output', $webInstance);
491 * Getter for web output instance
493 * @return $webOutputInstance - Instance to class WebOutput
495 public final function getWebOutputInstance () {
496 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
497 return $webOutputInstance;
501 * Setter for database instance
503 * @param $dbInstance The instance for the database connection (forced DatabaseConnection)
506 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
507 Registry::getRegistry()->addInstance('db_instance', $dbInstance);
511 * Getter for database layer
513 * @return $dbInstance The database layer instance
515 public final function getDatabaseInstance () {
517 $dbInstance = Registry::getRegistry()->getInstance('db_instance');
524 * Setter for compressor channel
526 * @param $compressorInstance An instance of CompressorChannel
529 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
530 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
534 * Getter for compressor channel
536 * @return $compressorInstance The compressor channel
538 public final function getCompressorChannel () {
539 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
540 return $compressorInstance;
544 * Protected getter for a manageable application helper class
546 * @return $applicationInstance An instance of a manageable application helper class
548 protected final function getApplicationInstance () {
549 $applicationInstance = Registry::getRegistry()->getInstance('application');
550 return $applicationInstance;
554 * Setter for a manageable application helper class
556 * @param $applicationInstance An instance of a manageable application helper class
559 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
560 Registry::getRegistry()->addInstance('application', $applicationInstance);
564 * Setter for request instance
566 * @param $requestInstance An instance of a Requestable class
569 public final function setRequestInstance (Requestable $requestInstance) {
570 $this->requestInstance = $requestInstance;
574 * Getter for request instance
576 * @return $requestInstance An instance of a Requestable class
578 public final function getRequestInstance () {
579 return $this->requestInstance;
583 * Setter for response instance
585 * @param $responseInstance An instance of a Responseable class
588 public final function setResponseInstance (Responseable $responseInstance) {
589 $this->responseInstance = $responseInstance;
593 * Getter for response instance
595 * @return $responseInstance An instance of a Responseable class
597 public final function getResponseInstance () {
598 return $this->responseInstance;
602 * Setter for the real class name
604 * @param $realClass Class name (string)
607 public final function setRealClass ($realClass) {
609 $realClass = (string) $realClass;
612 $this->realClass = $realClass;
616 * Checks wether an object equals this object. You should overwrite this
617 * method to implement own equality checks
619 * @param $objectInstance An instance of a FrameworkInterface object
620 * @return $equals Wether both objects equals
622 public function equals (FrameworkInterface $objectInstance) {
625 $this->__toString() == $objectInstance->__toString()
627 $this->hashCode() == $objectInstance->hashCode()
635 * Generates a generic hash code of this class. You should really overwrite
636 * this method with your own hash code generator code. But keep KISS in mind.
638 * @return $hashCode A generic hash code respresenting this whole class
640 public function hashCode () {
642 return crc32($this->__toString());
646 * Formats computer generated price values into human-understandable formats
647 * with thousand and decimal seperators.
649 * @param $value The in computer format value for a price
650 * @param $currency The currency symbol (use HTML-valid characters!)
651 * @param $decNum Number of decimals after commata
652 * @return $price The for the current language formated price string
653 * @throws MissingDecimalsThousandsSeperatorException If decimals or
654 * thousands seperator
657 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
658 // Are all required attriutes set?
659 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
660 // Throw an exception
661 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
665 $value = (float) $value;
667 // Reformat the US number
668 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
670 // Return as string...
675 * Private getter for language instance
677 * @return $langInstance An instance to the language sub-system
679 protected final function getLanguageInstance () {
680 $langInstance = Registry::getRegistry()->getInstance('language');
681 return $langInstance;
685 * Setter for language instance
687 * @param $langInstance An instance to the language sub-system
689 * @see LanguageSystem
691 public final function setLanguageInstance (ManageableLanguage $langInstance) {
692 Registry::getRegistry()->addInstance('language', $langInstance);
696 * Appends a trailing slash to a string
698 * @param $str A string (maybe) without trailing slash
699 * @return $str A string with an auto-appended trailing slash
701 public final function addMissingTrailingSlash ($str) {
702 // Is there a trailing slash?
703 if (substr($str, -1, 1) != '/') {
707 // Return string with trailing slash
712 * Private getter for file IO instance
714 * @return $fileIoInstance An instance to the file I/O sub-system
716 protected final function getFileIoInstance () {
717 return $this->fileIoInstance;
721 * Setter for file I/O instance
723 * @param $fileIoInstance An instance to the file I/O sub-system
726 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
727 $this->fileIoInstance = $fileIoInstance;
731 * Prepare the template engine (WebTemplateEngine by default) for a given
732 * application helper instance (ApplicationHelper by default).
734 * @param $applicationInstance An application helper instance or
735 * null if we shall use the default
736 * @return $templateInstance The template engine instance
737 * @throws NullPointerException If the discovered application
738 * instance is still null
740 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = null) {
741 // Is the application instance set?
742 if (is_null($applicationInstance)) {
743 // Get the current instance
744 $applicationInstance = $this->getApplicationInstance();
747 if (is_null($applicationInstance)) {
748 // Thrown an exception
749 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
753 // Initialize the template engine
754 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
756 // Return the prepared instance
757 return $templateInstance;
761 * Debugs this instance by putting out it's full content
763 * @param $message Optional message to show in debug output
766 public final function debugInstance ($message = '') {
767 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
768 restore_error_handler();
774 if (!empty($message)) {
776 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
779 // Generate the output
780 $content .= sprintf("<pre>%s</pre>",
789 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>",
792 ClassLoader::getInstance()->getPrintableIncludeList()
797 * Replaces control characters with printable output
799 * @param $str String with control characters
800 * @return $str Replaced string
802 protected function replaceControlCharacters ($str) {
805 "\r", '[r]', str_replace(
806 "\n", '[n]', str_replace(
816 * Output a partial stub message for the caller method
818 * @param $message An optional message to display
821 protected function partialStub ($message = '') {
823 $backtrace = debug_backtrace();
825 // Generate the class::method string
826 $methodName = 'UnknownClass->unknownMethod';
827 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
828 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
831 // Construct the full message
832 $stubMessage = sprintf("[%s:] Partial stub!",
836 // Is the extra message given?
837 if (!empty($message)) {
838 // Then add it as well
839 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
842 // Debug instance is there?
843 if (!is_null($this->getDebugInstance())) {
844 // Output stub message
845 $this->debugOutput($stubMessage);
848 trigger_error($stubMessage . "<br />\n");
853 * Outputs a debug backtrace and stops further script execution
857 public function debugBackTrace () {
858 // Sorry, there is no other way getting this nice backtrace
860 debug_print_backtrace();
866 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
868 * @param $message Message we shall send out...
869 * @param $doPrint Wether we shall print or die here which first is the default
872 public function debugOutput ($message, $doPrint = true) {
873 // Get debug instance
874 $debugInstance = $this->getDebugInstance();
876 // Is the debug instance there?
877 if (is_object($debugInstance)) {
878 // Use debug output handler
879 $debugInstance->output($message);
881 if ($doPrint === false) {
882 // Die here if not printed
887 if ($doPrint === true) {
890 // DO NOT REWRITE THIS TO app_die() !!!
897 * Converts e.g. a command from URL to a valid class by keeping out bad characters
899 * @param $str The string, what ever it is needs to be converted
900 * @return $className Generated class name
902 public function convertToClassName ($str) {
906 // Convert all dashes in underscores
907 $str = $this->convertDashesToUnderscores($str);
909 // Now use that underscores to get classname parts for hungarian style
910 foreach (explode('_', $str) as $strPart) {
911 // Make the class name part lower case and first upper case
912 $className .= ucfirst(strtolower($strPart));
920 * Converts dashes to underscores, e.g. useable for configuration entries
922 * @param $str The string with maybe dashes inside
923 * @return $str The converted string with no dashed, but underscores
925 public final function convertDashesToUnderscores ($str) {
927 $str = str_replace('-', '_', $str);
929 // Return converted string
934 * Marks up the code by adding e.g. line numbers
936 * @param $phpCode Unmarked PHP code
937 * @return $markedCode Marked PHP code
939 public function markupCode ($phpCode) {
944 $errorArray = error_get_last();
946 // Init the code with error message
947 if (is_array($errorArray)) {
949 $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>",
950 basename($errorArray['file']),
952 $errorArray['message'],
957 // Add line number to the code
958 foreach (explode("\n", $phpCode) as $lineNo => $code) {
960 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
962 htmlentities($code, ENT_QUOTES)
971 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
972 * beatiful for web-based front-ends. If null is given a message id
973 * null_timestamp will be resolved and returned.
975 * @param $timestamp Timestamp to prepare (filter) for display
976 * @return $readable A readable timestamp
978 public function doFilterFormatTimestamp ($timestamp) {
979 // Default value to return
982 // Is the timestamp null?
983 if (is_null($timestamp)) {
984 // Get a message string
985 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
987 switch ($this->getLanguageInstance()->getLanguageCode()) {
988 case 'de': // German format is a bit different to default
989 // Split the GMT stamp up
990 $dateTime = explode(' ', $timestamp );
991 $dateArray = explode('-', $dateTime[0]);
992 $timeArray = explode(':', $dateTime[1]);
994 // Construct the timestamp
995 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1005 default: // Default is pass-through
1006 $readable = $timestamp;
1016 * Filter a given number into a localized number
1018 * @param $value The raw value from e.g. database
1019 * @return $localized Localized value
1021 public function doFilterFormatNumber ($value) {
1022 // Generate it from config and localize dependencies
1023 switch ($this->getLanguageInstance()->getLanguageCode()) {
1024 case 'de': // German format is a bit different to default
1025 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1028 default: // US, etc.
1029 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1038 * "Getter" for databse entry
1040 * @return $entry An array with database entries
1041 * @throws NullPointerException If the database result is not found
1042 * @throws InvalidDatabaseResultException If the database result is invalid
1044 protected final function getDatabaseEntry () {
1045 // Is there an instance?
1046 if (is_null($this->getResultInstance())) {
1047 // Throw an exception here
1048 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1052 $this->getResultInstance()->rewind();
1054 // Do we have an entry?
1055 if ($this->getResultInstance()->valid() === false) {
1056 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1060 $this->getResultInstance()->next();
1063 $entry = $this->getResultInstance()->current();
1070 * Getter for field name
1072 * @param $fieldName Field name which we shall get
1073 * @return $fieldValue Field value from the user
1074 * @throws NullPointerException If the result instance is null
1076 public final function getField ($fieldName) {
1077 // Default field value
1080 // Get result instance
1081 $resultInstance = $this->getResultInstance();
1083 // Is this instance null?
1084 if (is_null($resultInstance)) {
1085 // Then the user instance is no longer valid (expired cookies?)
1086 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1089 // Get current array
1090 $fieldArray = $resultInstance->current();
1091 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1093 // Does the field exist?
1094 if (isset($fieldArray[$fieldName])) {
1096 $fieldValue = $fieldArray[$fieldName];
1104 * Protected setter for user instance
1106 * @param $userInstance An instance of a user class
1109 protected final function setUserInstance (ManageableAccount $userInstance) {
1110 $this->userInstance = $userInstance;
1114 * Getter for user instance
1116 * @return $userInstance An instance of a user class
1118 public final function getUserInstance () {
1119 return $this->userInstance;
1123 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1125 * @param $controllerInstance An instance of the controller
1128 public final function setControllerInstance (Controller $controllerInstance) {
1129 $this->controllerInstance = $controllerInstance;
1133 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1135 * @return $controllerInstance An instance of the controller
1137 public final function getControllerInstance () {
1138 return $this->controllerInstance;
1142 * Flushs all pending updates to the database layer
1146 public function flushPendingUpdates () {
1147 // Get result instance
1148 $resultInstance = $this->getResultInstance();
1150 // Do we have data to update?
1151 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1152 // Get wrapper class name config entry
1153 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1155 // Create object instance
1156 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1158 // Yes, then send the whole result to the database layer
1159 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1164 * Outputs a deprecation warning to the developer.
1166 * @param $message The message we shall output to the developer
1168 * @todo Write a logging mechanism for productive mode
1170 public function deprecationWarning ($message) {
1171 // Is developer mode active?
1172 if (defined('DEVELOPER')) {
1173 // Debug instance is there?
1174 if (!is_null($this->getDebugInstance())) {
1175 // Output stub message
1176 $this->debugOutput($message);
1179 trigger_error($message . "<br />\n");
1182 // @TODO Finish this part!
1183 $this->partialStub('Developer mode inactive. Message:' . $message);
1188 * Checks wether the given PHP extension is loaded
1190 * @param $phpExtension The PHP extension we shall check
1191 * @return $isLoaded Wether the PHP extension is loaded
1193 public final function isPhpExtensionLoaded ($phpExtension) {
1195 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1202 * Setter for RNG instance
1204 * @param $rngInstance An instance of a random number generator (RNG)
1207 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1208 $this->rngInstance = $rngInstance;
1212 * Getter for RNG instance
1214 * @return $rngInstance An instance of a random number generator (RNG)
1216 public final function getRngInstance () {
1217 return $this->rngInstance;
1221 * Setter for Cryptable instance
1223 * @param $cryptoInstance An instance of a Cryptable class
1226 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1227 $this->cryptoInstance = $cryptoInstance;
1231 * Getter for Cryptable instance
1233 * @return $cryptoInstance An instance of a Cryptable class
1235 public final function getCryptoInstance () {
1236 return $this->cryptoInstance;
1240 * Setter for Iterator instance
1242 * @param $iteratorInstance An instance of an Iterator
1245 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1246 $this->iteratorInstance = $iteratorInstance;
1250 * Getter for Iterator instance
1252 * @return $iteratorInstance An instance of an Iterator
1254 public final function getIteratorInstance () {
1255 return $this->iteratorInstance;
1259 * "Getter" as a time() replacement but with milliseconds. You should use this
1260 * method instead of the encapsulated getimeofday() function.
1262 * @return $milliTime Timestamp with milliseconds
1264 public function getMilliTime () {
1265 // Get the time of day as float
1266 $milliTime = gettimeofday(true);
1273 * Idles (sleeps) for given milliseconds
1275 * @return $hasSlept Wether it goes fine
1277 public function idle ($milliSeconds) {
1278 // Sleep is fine by default
1281 // Idle so long with found function
1282 if (function_exists('time_sleep_until')) {
1283 // Get current time and add idle time
1284 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1286 // New PHP 5.1.0 function found
1287 $hasSlept = time_sleep_until($sleepUntil);
1289 // My Sun Station doesn't have that function even with latest PHP
1291 usleep($milliSeconds * 1000);
1299 * Setter for the list instance
1301 * @param $listInstance A list of Listable
1304 protected final function setListInstance (Listable $listInstance) {
1305 $this->listInstance = $listInstance;
1309 * Getter for the list instance
1311 * @return $listInstance A list of Listable
1313 protected final function getListInstance () {
1314 return $this->listInstance;
1318 * Setter for the menu instance
1320 * @param $menuInstance A RenderableMenu instance
1323 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1324 $this->menuInstance = $menuInstance;
1328 * Getter for the menu instance
1330 * @return $menuInstance A RenderableMenu instance
1332 protected final function getMenuInstance () {
1333 return $this->menuInstance;
1337 * Setter for image instance
1339 * @param $imageInstance An instance of an image
1342 public final function setImageInstance (BaseImage $imageInstance) {
1343 $this->imageInstance = $imageInstance;
1347 * Getter for image instance
1349 * @return $imageInstance An instance of an image
1351 public final function getImageInstance () {
1352 return $this->imageInstance;
1356 * Setter for stacker instance
1358 * @param $stackerInstance An instance of an stacker
1361 public final function setStackerInstance (Stackable $stackerInstance) {
1362 $this->stackerInstance = $stackerInstance;
1366 * Getter for stacker instance
1368 * @return $stackerInstance An instance of an stacker
1370 public final function getStackerInstance () {
1371 return $this->stackerInstance;
1375 * Setter for compressor instance
1377 * @param $compressorInstance An instance of an compressor
1380 public final function setCompressorInstance (Compressor $compressorInstance) {
1381 $this->compressorInstance = $compressorInstance;
1385 * Getter for compressor instance
1387 * @return $compressorInstance An instance of an compressor
1389 public final function getCompressorInstance () {
1390 return $this->compressorInstance;
1394 * Setter for Parseable instance
1396 * @param $parserInstance An instance of an Parseable
1399 public final function setParserInstance (Parseable $parserInstance) {
1400 $this->parserInstance = $parserInstance;
1404 * Getter for Parseable instance
1406 * @return $parserInstance An instance of an Parseable
1408 public final function getParserInstance () {
1409 return $this->parserInstance;
1413 * Setter for ProtocolHandler instance
1415 * @param $protocolInstance An instance of an ProtocolHandler
1418 public final function setProtocolInstance (ProtocolHandler $protocolInstance) {
1419 $this->protocolInstance = $protocolInstance;
1423 * Getter for ProtocolHandler instance
1425 * @return $protocolInstance An instance of an ProtocolHandler
1427 public final function getProtocolInstance () {
1428 return $this->protocolInstance;
1432 * Setter for BaseDatabaseWrapper instance
1434 * @param $wrapperInstance An instance of an BaseDatabaseWrapper
1437 public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
1438 $this->wrapperInstance = $wrapperInstance;
1442 * Getter for BaseDatabaseWrapper instance
1444 * @return $wrapperInstance An instance of an BaseDatabaseWrapper
1446 public final function getWrapperInstance () {
1447 return $this->wrapperInstance;
1451 * Setter for socket resource
1453 * @param $socketResource A valid socket resource
1456 public final function setSocketResource ($socketResource) {
1457 $this->socketResource = $socketResource;
1461 * Getter for socket resource
1463 * @return $socketResource A valid socket resource
1465 public function getSocketResource () {
1466 return $this->socketResource;
1470 * Setter for raw package Data
1472 * @param $packageData Raw package Data
1475 public final function setPackageData (array $packageData) {
1476 $this->packageData = $packageData;
1480 * Getter for raw package Data
1482 * @return $packageData Raw package Data
1484 public function getPackageData () {
1485 return $this->packageData;