Debug mailer finished and debug messages removed:
[shipsimu.git] / inc / classes / main / class_BaseFrameworkSystem.php
1 <?php
2 /**
3  * The simulator system class is the super class of all other classes. This
4  * class handles saving of games etc.
5  *
6  * @author              Roland Haeder <webmaster@ship-simu.org>
7  * @version             0.0.0
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
11  *
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.
16  *
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.
21  *
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/>.
24  */
25 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
26         /**
27          * Instance to an application helper class
28          */
29         private static $applicationInstance = null;
30
31         /**
32          * The language instance for the template loader
33          */
34         private static $langInstance = null;
35
36         /**
37          * Debug instance
38          */
39         private static $debugInstance = null;
40
41         /**
42          * Instance of a request class
43          */
44         private $requestInstance = null;
45
46         /**
47          * Instance of a response class
48          */
49         private $responseInstance = null;
50
51         /**
52          * Search criteria instance
53          */
54         private $searchInstance = null;
55
56         /**
57          * The file I/O instance for the template loader
58          */
59         private $fileIoInstance = null;
60
61         /**
62          * Resolver instance
63          */
64         private $resolverInstance = null;
65
66         /**
67          * Template engine instance
68          */
69         private $templateInstance = null;
70
71         /**
72          * Database result instance
73          */
74         private $resultInstance = null;
75
76         /**
77          * The real class name
78          */
79         private $realClass      = "FrameworkSystem";
80
81         /**
82          * A human-readable description for this simulator part
83          */
84         private $objectDescription      = "Namenlose Framework-Einheit";
85
86         /**
87          * The unique ID string for identifying all type of classes
88          */
89         private $uniqueID = "";
90
91         /**
92          * Thousands seperator
93          */
94         private $thousands = "."; // German
95
96         /**
97          * Decimal seperator
98          */
99         private $decimals  = ","; // German
100
101         /***********************
102          * Exception codes.... *
103          ***********************/
104
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;
162
163         /**
164          * In the super constructor these system classes shall be ignored or else
165          * we would get an endless calling loop.
166          *
167          *---------------------------------------------------------------------*
168          * ATTENTION: IF YOU REMOVE ONE OF THEM YOU WILL RUN YOUR SERVER IN AN *
169          * ENDLESS LOOP !!!                                                    *
170          *---------------------------------------------------------------------*
171          */
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
185         );
186
187         /* No longer used:
188         */
189
190         /**
191          * Private super constructor
192          *
193          * @param       $className      Name of the class
194          * @return      void
195          */
196         protected function __construct ($className) {
197                 // Set real class
198                 $this->setRealClass($className);
199
200                 // Initialize the class if the registry is there
201                 if ((class_exists('Registry')) && (Registry::isInitialized() === false)) {
202                         $this->initInstance();
203                 } // END - if
204         }
205
206         /**
207          * Destructor reached...
208          *
209          * @return      void
210          * @todo        This is old code. Do we still need this old lost code?
211          */
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()
223                         ));
224                 }
225         }
226
227         /**
228          * The call method where all non-implemented methods end up
229          *
230          * @return      void
231          */
232         public final function __call ($methodName, $args) {
233                 // Implode all given arguments
234                 $argsString = "";
235                 if (empty($args)) {
236                         // No arguments
237                         $argsString = "NULL";
238                 } elseif (is_array($args)) {
239                         // Some arguments are there
240                         foreach ($args as $arg) {
241                                 // Check the type
242                                 if (is_bool($arg)) {
243                                         // Boolean!
244                                         if ($arg) $argsString .= "true(bool)"; else $argsString .= "false(bool)";
245                                 } elseif (is_int($arg)) {
246                                         // Integer
247                                         $argsString .= $arg."(int)";
248                                 } elseif (is_float($arg)) {
249                                         // Floating point
250                                         $argsString .= $arg."(float)";
251                                 } elseif ($arg instanceof BaseFrameworkSystem) {
252                                         // Own object instance
253                                         $argsString .= $arg->__toString()."(Object)";
254                                 } elseif (is_object($arg)) {
255                                         // External object
256                                         $argsString .= "unknown object(!)";
257                                 } elseif (is_array($arg)) {
258                                         // Array
259                                         $argsString .= "Array(array)";
260                                 } elseif (is_string($arg)) {
261                                         // String
262                                         $argsString .= "\"".$arg."\"(string)";
263                                 } elseif (is_null($arg)) {
264                                         // Null
265                                         $argsString .= "(null)";
266                                 } elseif (is_resource($arg)) {
267                                         // Resource
268                                         $argsString .= "(resource)";
269                                 } else {
270                                         // Unknown type (please report!)
271                                         $argsString .= $arg."(<em>unknown!</em>)";
272                                 }
273
274                                 // Add comma
275                                 $argsString .= ", ";
276                         }
277
278                         // Remove last comma
279                         if (substr($argsString, -2, 1) === ",") {
280                                 $argsString = substr($argsString, 0, -2);
281                         } // END - if
282                 } else {
283                         // Invalid arguments!
284                         $argsString = sprintf("!INVALID:%s!", $args);
285                 }
286
287                 // Output stub message
288                 $this->debugOutput(sprintf("[%s-&gt;%s] Stub! Args: %s",
289                         $this->__toString(),
290                         $methodName,
291                         $argsString
292                 ));
293
294                 // Return nothing
295                 return null;
296         }
297
298         /**
299          * Private initializer for this class
300          *
301          * @return      void
302          */
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');
308
309                         // Set debug instance
310                         $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig('debug_class')));
311
312                         // Get output instance and set it
313                         $outputInstance = ObjectFactory::createObjectByConfiguredName('web_engine', array($this->getConfigInstance()->readConfig('web_content_type')));
314                         $this->setWebOutputInstance($outputInstance);
315
316                         // Set the compressor channel
317                         $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
318                                 PATH,
319                                 $this->getConfigInstance()->readConfig('compressor_base_path')
320                         )));
321
322                         // Initialization done! :D
323                         Registry::isInitialized('OK');
324                 } elseif ($this->__toString() == 'DebugMiddleware') {
325                         // Set configuration instance
326                         $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
327                 }
328         }
329
330         /**
331          * Setter for database result instance
332          *
333          * @param       $resultInstance         An instance of a database result class
334          * @return      void
335          * @todo        SearchableResult and UpdateableResult shall have a super interface to use here
336          */
337         protected final function setResultInstance (SearchableResult $resultInstance) {
338                 $this->resultInstance =  $resultInstance;
339         }
340
341         /**
342          * Getter for database result instance
343          *
344          * @return      $resultInstance         An instance of a database result class
345          */
346         public final function getResultInstance () {
347                 return $this->resultInstance;
348         }
349
350         /**
351          * Setter for template engine instances
352          *
353          * @param       $templateInstance       An instance of a template engine class
354          * @return      void
355          */
356         protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
357                 $this->templateInstance = $templateInstance;
358         }
359
360         /**
361          * Getter for template engine instances
362          *
363          * @return      $templateInstance       An instance of a template engine class
364          */
365         protected final function getTemplateInstance () {
366                 return $this->templateInstance;
367         }
368
369         /**
370          * Setter for search instance
371          *
372          * @param       $searchInstance         Searchable criteria instance
373          * @return      void
374          */
375         public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
376                 $this->searchInstance = $searchInstance;
377         }
378
379         /**
380          * Getter for search instance
381          *
382          * @return      $searchInstance         Searchable criteria instance
383          */
384         public final function getSearchInstance () {
385                 return $this->searchInstance;
386         }
387
388         /**
389          * Setter for resolver instance
390          *
391          * @param       $resolverInstance               Instance of a command resolver class
392          * @return      void
393          */
394         public final function setResolverInstance (Resolver $resolverInstance) {
395                 $this->resolverInstance = $resolverInstance;
396         }
397
398         /**
399          * Getter for resolver instance
400          *
401          * @return      $resolverInstance               Instance of a command resolver class
402          */
403         public final function getResolverInstance () {
404                 return $this->resolverInstance;
405         }
406
407         /**
408          * Setter for language instance
409          *
410          * @param       $configInstance         The configuration instance which shall
411          *                                                              be FrameworkConfiguration
412          * @return      void
413          */
414         public final function setConfigInstance (FrameworkConfiguration $configInstance) {
415                 Registry::getRegistry()->addInstance('config', $configInstance);
416         }
417
418         /**
419          * Getter for configuration instance
420          *
421          * @return      $cfgInstance    Configuration instance
422          */
423         public final function getConfigInstance () {
424                 $cfgInstance = Registry::getRegistry()->getInstance('config');
425                 return $cfgInstance;
426         }
427
428         /**
429          * Setter for debug instance
430          *
431          * @param       $debugInstance  The instance for debug output class
432          * @return      void
433          */
434         public final function setDebugInstance (DebugMiddleware $debugInstance) {
435                 self::$debugInstance = $debugInstance;
436         }
437
438         /**
439          * Getter for debug instance
440          *
441          * @return      $debugInstance  Instance to class DebugConsoleOutput or DebugWebOutput
442          */
443         public final function getDebugInstance () {
444                 return self::$debugInstance;
445         }
446
447         /**
448          * Setter for web output instance
449          *
450          * @param               $webInstance    The instance for web output class
451          * @return      void
452          */
453         public final function setWebOutputInstance (OutputStreamer $webInstance) {
454                 Registry::getRegistry()->addInstance('web_output', $webInstance);
455         }
456
457         /**
458          * Getter for web output instance
459          *
460          * @return      $webOutput - Instance to class WebOutput
461          */
462         public final function getWebOutputInstance () {
463                 return Registry::getRegistry()->getInstance('web_output');
464         }
465
466         /**
467          * Setter for database instance
468          *
469          * @param               $dbInstance     The instance for the database connection
470          *                                      (forced DatabaseConnection)
471          * @return      void
472          */
473         public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
474                 Registry::getRegistry()->addInstance('dbInstance', $dbInstance);
475         }
476
477         /**
478          * Getter for database layer
479          *
480          * @return      $dbInstance     The database layer instance
481          */
482         public final function getDatabaseInstance () {
483                 if ((class_exists('Registry')) && (Registry::isInitialized() === true)) {
484                         return Registry::getRegistry()->getInstance('dbInstance');
485                 } else {
486                         return null;
487                 }
488         }
489
490         /**
491          * Setter for compressor channel
492          *
493          * @param               $compressorChannel      An instance of CompressorChannel
494          * @return      void
495          */
496         public final function setCompressorChannel (CompressorChannel $compressorChannel) {
497                 Registry::getRegistry()->addInstance('compressor', $compressorChannel);
498         }
499
500         /**
501          * Getter for compressor channel
502          *
503          * @return      $compressor     The compressor channel
504          */
505         public final function getCompressorChannel () {
506                 return Registry::getRegistry()->getInstance('compressor');
507         }
508
509         /**
510          * Protected getter for a manageable application helper class
511          *
512          * @return      $applicationInstance    An instance of a manageable application helper class
513          */
514         protected final function getApplicationInstance () {
515                 return self::$applicationInstance;
516         }
517
518         /**
519          * Setter for a manageable application helper class
520          *
521          * @param       $applicationInstance    An instance of a manageable application helper class
522          * @return      void
523          */
524         public final function setApplicationInstance (ManageableApplication $applicationInstance) {
525                 self::$applicationInstance = $applicationInstance;
526         }
527
528         /**
529          * Setter for request instance
530          *
531          * @param       $requestInstance        An instance of a Requestable class
532          * @return      void
533          */
534         public final function setRequestInstance (Requestable $requestInstance) {
535                 $this->requestInstance = $requestInstance;
536         }
537
538         /**
539          * Getter for request instance
540          *
541          * @return      $requestInstance        An instance of a Requestable class
542          */
543         public final function getRequestInstance () {
544                 return $this->requestInstance;
545         }
546
547         /**
548          * Setter for response instance
549          *
550          * @param       $responseInstance       An instance of a Responseable class
551          * @return      void
552          */
553         public final function setResponseInstance (Responseable $responseInstance) {
554                 $this->responseInstance = $responseInstance;
555         }
556
557         /**
558          * Getter for response instance
559          *
560          * @return      $responseInstance       An instance of a Responseable class
561          */
562         public final function getResponseInstance () {
563                 return $this->responseInstance;
564         }
565
566         /**
567          * Getter for $realClass
568          *
569          * @return      $realClass The name of the real class (not BaseFrameworkSystem)
570          */
571         public final function __toString () {
572                 return $this->realClass;
573         }
574
575         /**
576          * Setter for the real class name
577          *
578          * @param               $realClass      Class name (string)
579          * @return      void
580          */
581         public final function setRealClass ($realClass) {
582                 // Cast to string
583                 $realClass = (string) $realClass;
584
585                 // Set real class
586                 $this->realClass = $realClass;
587         }
588
589         /**
590          * Generate unique ID from a lot entropy
591          *
592          * @return      void
593          */
594         public final function generateUniqueId () {
595                 // Is the id set for this class?
596                 if (empty($this->uniqueID)) {
597
598                         // Correct missing class name
599                         $corrected = false;
600                         if ($this->__toString() == "") {
601                                 $this->setRealClass(__CLASS__);
602                                 $corrected = true;
603                         }
604
605                         // Cache datbase instance
606                         $db = $this->getDatabaseInstance();
607
608                         // Generate new id
609                         $tempID = false;
610                         while (true) {
611                                 // Generate a unique ID number
612                                 $tempID = $this->generateIdNumber();
613                                 $isUsed = false;
614
615                                 // Try to figure out if the ID number is not yet used
616                                 try {
617                                         // Is this a registry?
618                                         if ($this->__toString() == "Registry") {
619                                                 // Registry, then abort here
620                                                 break;
621                                         } elseif (is_object($db)) {
622                                                 $isUsed = $db->isUniqueIdUsed($tempID, true);
623                                         }
624                                 } catch (FrameworkException $e) {
625                                         // Catches all and ignores all ;-)
626                                 }
627
628                                 if (
629                                         (
630                                                 $tempID !== false
631                                         ) && (
632                                                 (
633                                                         $db === null
634                                                 ) || (
635                                                         (
636                                                                 is_object($db)
637                                                         ) && (
638                                                                 !$isUsed
639                                                         )
640                                                 )
641                                         )
642                                 ) {
643                                         // Abort the loop
644                                         break;
645                                 }
646                         } // END - while
647
648                         // Apply the new ID
649                         $this->setUniqueID($tempID);
650
651                         // Revert maybe corrected class name
652                         if ($corrected) {
653                                 $this->setRealClass("");
654                         }
655
656                         // Remove system classes if we are in a system class
657                         if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
658                                 // This may save some RAM...
659                                 $this->removeSystemArray();
660                         }
661                 }
662         }
663
664         /**
665          * Generates a new ID number for classes based from the class' real name,
666          * the description and some random data
667          *
668          * @return      $tempID The new (temporary) ID number
669          */
670         private final function generateIdNumber () {
671                 return sprintf("%s@%s",
672                         $this->__toString(),
673                         md5(sprintf("%s:%s:%s:%s:%s:%s",
674                                 $this->__toString(),
675                                 $this->getObjectDescription(),
676                                 time(),
677                                 getenv('REMOTE_ADDR'),
678                                 getenv('SERVER_ADDR'),
679                                 mt_rand()
680                         ))
681                 );
682         }
683
684         /**
685          * Setter for unique ID
686          *
687          * @param               $uniqueID               The newly generated unique ID number
688          * @return      void
689          */
690         private final function setUniqueID ($uniqueID) {
691                 // Cast to string
692                 $uniqueID = (string) $uniqueID;
693
694                 // Set the ID number
695                 $this->uniqueID = $uniqueID;
696         }
697
698         /**
699          * Getter for unique ID
700          *
701          * @return      $uniqueID               The unique ID of this class
702          */
703         public final function getUniqueID () {
704                 return $this->uniqueID;
705         }
706
707         /**
708          * Resets or recreates the unique ID number
709          *
710          * @return      void
711          */
712         public final function resetUniqueID() {
713                 // Sweet and simple... ;-)
714                 $newUniqueID = $this->generateIdNumber();
715                 $this->setUniqueID($newUniqueID);
716         }
717
718         /**
719          * Getter for simulator description
720          *
721          * @return      $objectDescription      The description of this simulation part
722          */
723         public final function getObjectDescription () {
724                 if (isset($this->objectDescription)) {
725                         return $this->objectDescription;
726                 } else {
727                         return null;
728                 }
729         }
730
731         /**
732          * Setter for simulation part description
733          *
734          * @param               $objectDescription      The description as string for this simulation part
735          * @return      void
736          */
737         public final function setObjectDescription ($objectDescription) {
738                 $this->objectDescription = (String) $objectDescription;
739         }
740
741         /**
742          * Validate if given object is the same as current
743          *
744          * @param       $object An object instance for comparison with this class
745          * @return      boolean The result of comparing both's unique ID
746          */
747         public final function equals (FrameworkInterface $object) {
748                 return ($this->getUniqueID() == $object->getUniqueID());
749         }
750
751         /**
752          * Compare if both simulation part description and class name matches
753          * (shall be enougth)
754          *
755          * @param       $itemInstance   An object instance to an other class
756          * @return      boolean                 The result of comparing class name simulation part description
757          */
758         public function itemMatches ($itemInstance) {
759                 return (
760                         (
761                                 $this->__toString()   == $itemInstance->__toString()
762                         ) && (
763                                 $this->getObjectDescription() == $itemInstance->getObjectDescription()
764                         )
765                 );
766         }
767
768         /**
769          * Compare class name of this and given class name
770          *
771          * @param               $className      The class name as string from the other class
772          * @return      boolean The result of comparing both class names
773          */
774         public final function isClass ($className) {
775                 return ($this->__toString() == $className);
776         }
777
778         /**
779          * Stub method (only real cabins shall override it)
780          *
781          * @return      boolean false = is no cabin, true = is a cabin
782          */
783         public function isCabin () {
784                 return false;
785         }
786
787         /**
788          * Stub method for tradeable objects
789          *
790          * @return      boolean false = is not tradeable by the Merchant class,
791          *                                      true  = is a tradeable object
792          */
793         public function isTradeable () {
794                 return false;
795         }
796
797         /**
798          * Formats computer generated price values into human-understandable formats
799          * with thousand and decimal seperators.
800          *
801          * @param       $value          The in computer format value for a price
802          * @param       $currency       The currency symbol (use HTML-valid characters!)
803          * @param       $decNum         Number of decimals after commata
804          * @return      $price          The for the current language formated price string
805          * @throws      MissingDecimalsThousandsSeperatorException      If decimals or
806          *                                                                                              thousands seperator
807          *                                                                                              is missing
808          */
809         public function formatCurrency ($value, $currency = "&euro;", $decNum = 2) {
810                 // Are all required attriutes set?
811                 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
812                         // Throw an exception
813                         throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
814                 }
815
816                 // Cast the number
817                 $value = (float) $value;
818
819                 // Reformat the US number
820                 $price = sprintf("%s %s",
821                         number_format($value, $decNum, $this->decimals, $this->thousands),
822                         $currency
823                 );
824
825                 // Return as string...
826                 return $price;
827         }
828
829         /**
830          * Removes number formating characters
831          *
832          * @return      void
833          */
834         public final function removeNumberFormaters () {
835                 unset($this->thousands);
836                 unset($this->decimals);
837         }
838
839         /**
840          * Private getter for language instance
841          *
842          * @return      $langInstance   An instance to the language sub-system
843          */
844         protected final function getLanguageInstance () {
845                 return self::$langInstance;
846         }
847
848         /**
849          * Setter for language instance
850          *
851          * @param       $langInstance   An instance to the language sub-system
852          * @return      void
853          * @see         LanguageSystem
854          */
855         public final function setLanguageInstance (ManageableLanguage $langInstance) {
856                 self::$langInstance = $langInstance;
857         }
858
859         /**
860          * Remove the $systemClasses array from memory
861          *
862          * @return      void
863          */
864         public final function removeSystemArray () {
865                 unset($this->systemClasses);
866         }
867
868         /**
869          * Create a file name and path name from the object's unique ID number.
870          * The left part of the ID shall always be a valid class name and the
871          * right part an ID number.
872          *
873          * @return      $pfn    The file name with a prepended path name
874          * @throws      NoArrayCreatedException         If explode() fails to create an array
875          * @throws      InvalidArrayCountException      If the array contains less or
876          *                                                                              more than two elements
877          */
878         public final function getPathFileNameFromObject () {
879                 // Get the main object's unique ID. We use this as a path/filename combination
880                 $pathFile = $this->getUniqueID();
881
882                 // Split it up in path and file name
883                 $pathFile = explode("@", $pathFile);
884
885                 // Are there two elements? Index 0 is the path, 1 the file name + global extension
886                 if (!is_array($pathFile)) {
887                         // No array found
888                         throw new NoArrayCreatedException(array($this, 'pathFile'), self::EXCEPTION_ARRAY_EXPECTED);
889                 } elseif (count($pathFile) != 2) {
890                         // Invalid ID returned!
891                         throw new InvalidArrayCountException(array($this, 'pathFile', count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
892                 }
893
894                 // Auto-append missing trailing slash
895                 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
896
897                 // Create the file name and return it
898                 $pfn = ($pathFile[0] . $pathFile[1]);
899                 return $pfn;
900         }
901
902         /**
903          * Appends a trailing slash to a string
904          *
905          * @param       $str            A string (maybe) without trailing slash
906          * @return      $str            A string with an auto-appended trailing slash
907          */
908         public final function addMissingTrailingSlash ($str) {
909                 // Is there a trailing slash?
910                 if (substr($str, -1, 1) != "/") $str .= "/";
911                 return $str;
912         }
913
914         /**
915          * Private getter for file IO instance
916          *
917          * @return      $fileIoInstance An instance to the file I/O sub-system
918          */
919         protected final function getFileIoInstance () {
920                 return $this->fileIoInstance;
921         }
922
923         /**
924          * Setter for file I/O instance
925          *
926          * @param       $fileIoInstance An instance to the file I/O sub-system
927          * @return      void
928          */
929         public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
930                 $this->fileIoInstance = $fileIoInstance;
931         }
932
933         /**
934          * Prepare the template engine (WebTemplateEngine by default) for a given
935          * application helper instance (ApplicationHelper by default).
936          *
937          * @param               $appInstance                    An application helper instance or
938          *                                                                              null if we shall use the default
939          * @return              $templateInstance                               The template engine instance
940          * @throws              NullPointerException    If the template engine could not
941          *                                                                              be initialized
942          * @throws              UnsupportedTemplateEngineException      If $templateInstance is an
943          *                                                                              unsupported template engine
944          * @throws              MissingLanguageHandlerException If the language sub-system
945          *                                                                              is not yet initialized
946          * @throws              NullPointerException    If the discovered application
947          *                                                                              instance is still null
948          */
949         protected function prepareTemplateInstance (BaseFrameworkSystem $appInstance=null) {
950                 // Is the application instance set?
951                 if (is_null($appInstance)) {
952                         // Get the current instance
953                         $appInstance = $this->getApplicationInstance();
954
955                         // Still null?
956                         if (is_null($appInstance)) {
957                                 // Thrown an exception
958                                 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
959                         } // END - if
960                 } // END - if
961
962                 // Generate FQFN for all application templates
963                 $fqfn = sprintf("%s%s/%s/%s",
964                         PATH,
965                         $this->getConfigInstance()->readConfig('application_path'),
966                         strtolower($appInstance->getAppShortName()),
967                         $this->getConfigInstance()->readConfig('tpl_base_path')
968                 );
969
970                 // Are both instances set?
971                 if ($appInstance->getLanguageInstance() === null) {
972                         // Invalid language instance
973                         throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
974                 } elseif ($appInstance->getFileIoInstance() === null) {
975                         // Invalid language instance
976                         throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
977                 }
978
979                 // Initialize the template engine
980                 $templateInstance = ObjectFactory::createObjectByConfiguredName('template_class', array($fqfn, $appInstance->getLanguageInstance(), $appInstance->getFileIoInstance()));
981
982                 // Return the prepared instance
983                 return $templateInstance;
984         }
985
986         /**
987          * Debugs this instance by putting out it's full content
988          *
989          * @return      void
990          */
991         public final function debugInstance () {
992                 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
993                 restore_error_handler();
994
995                 // Generate the output
996                 $content = sprintf("<pre>%s</pre>",
997                         trim(
998                                 htmlentities(
999                                         print_r($this, true)
1000                                 )
1001                         )
1002                 );
1003
1004                 // Output it
1005                 ApplicationEntryPoint::app_die(sprintf("<strong>%s debug output:</strong><div id=\"debug_content\">%s</div>\nLoaded includes: <div id=\"debug_include_list\">%s</div>",
1006                         $this->__toString(),
1007                         $content,
1008                         ClassLoader::getInstance()->getPrintableIncludeList()
1009                 ));
1010         }
1011
1012         /**
1013          * Output a partial stub message for the caller method
1014          *
1015          * @param       $message        An optional message to display
1016          * @return      void
1017          */
1018         protected function partialStub ($message = "") {
1019                 // Get the backtrace
1020                 $backtrace = debug_backtrace();
1021
1022                 // Generate the class::method string
1023                 $methodName = "UnknownClass-&gt;unknownMethod";
1024                 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1025                         $methodName = $backtrace[1]['class']."-&gt;".$backtrace[1]['function'];
1026                 } // END - if
1027
1028                 // Construct the full message
1029                 $stubMessage = sprintf("[%s:] Partial stub!",
1030                         $methodName
1031                 );
1032
1033                 // Is the extra message given?
1034                 if (!empty($message)) {
1035                         // Then add it as well
1036                         $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
1037                 } // END - if
1038
1039                 // Debug instance is there?
1040                 if (!is_null($this->getDebugInstance())) {
1041                         // Output stub message
1042                         $this->debugOutput($stubMessage);
1043                 } else {
1044                         // Trigger an error
1045                         trigger_error($stubMessage."<br />\n");
1046                 }
1047         }
1048
1049         /**
1050          * Outputs a debug backtrace and stops further script execution
1051          *
1052          * @return      void
1053          */
1054         public function debugBackTrace () {
1055                 // Sorry, there is no other way getting this nice backtrace
1056                 print "<pre>\n";
1057                 debug_print_backtrace();
1058                 print "</pre>";
1059                 exit;
1060         }
1061
1062         /**
1063          * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
1064          *
1065          * @param       $message        Message we shall send out...
1066          * @param       $doPrint        Wether we shall print or die here which first is the default
1067          * @return      void
1068          */
1069         public function debugOutput ($message, $doPrint = true) {
1070                 // Get debug instance
1071                 $debugInstance = $this->getDebugInstance();
1072
1073                 // Is the debug instance there?
1074                 if (is_object($debugInstance)) {
1075                         // Use debug output handler
1076                         $debugInstance->output($message);
1077                         if (!$doPrint) die(); // Die here if not printed
1078                 } else {
1079                         // Put directly out
1080                         if ($doPrint) {
1081                                 print($message);
1082                         } else {
1083                                 // DO NOT REWRITE THIS TO app_die() !!!
1084                                 die($message);
1085                         }
1086                 }
1087         }
1088
1089         /**
1090          * Converts e.g. a command from URL to a valid class by keeping out bad characters
1091          *
1092          * @param       $str            The string, what ever it is needs to be converted
1093          * @return      $className      Generated class name
1094          */
1095         public function convertToClassName ($str) {
1096                 // Init class name
1097                 $className = "";
1098
1099                 // Convert all dashes in underscores
1100                 $str = str_replace("-", "_", $str);
1101
1102                 // Now use that underscores to get classname parts for hungarian style
1103                 foreach (explode("_", $str) as $strPart) {
1104                         // Make the class name part lower case and first upper case
1105                         $className .= ucfirst(strtolower($strPart));
1106                 } // END - foreach
1107
1108                 // Return class name
1109                 return $className;
1110         }
1111
1112         /**
1113          * Marks up the code by adding e.g. line numbers
1114          *
1115          * @param       $phpCode                Unmarked PHP code
1116          * @return      $markedCode             Marked PHP code
1117          */
1118         public function markupCode ($phpCode) {
1119                 // Get last error
1120                 $errorArray = error_get_last();
1121
1122                 // Init the code with error message
1123                 $markedCode = "";
1124                 if (is_array($errorArray)) {
1125                         // Get error infos
1126                         $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>",
1127                                 basename($errorArray['file']),
1128                                 $errorArray['line'],
1129                                 $errorArray['message'],
1130                                 $errorArray['type']
1131                         );
1132                 } // END - if
1133
1134                 // Add line number to the code
1135                 foreach (explode("\n", $phpCode) as $lineNo=>$code) {
1136                         // Add line numbers
1137                         $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
1138                                 ($lineNo+1),
1139                                 htmlentities($code, ENT_QUOTES)
1140                         );
1141                 } // END - foreach
1142
1143                 // Return the code
1144                 return $markedCode;
1145         }
1146
1147         /**
1148          * Filter a given timestamp to make it look more beatifull for web-based
1149          * front-ends. If null is given a message id null_timestamp will be
1150          * resolved and returned.
1151          *
1152          * @param       $timestamp      Timestamp to prepare (filter) for display
1153          * @return      $readable       A readable timestamp
1154          */
1155         public function doFilterFormatTimestamp ($timestamp) {
1156                 // Default value to return
1157                 $readable = "???";
1158
1159                 // Is the timestamp null?
1160                 if (is_null($timestamp)) {
1161                         // Get a message string
1162                         $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1163                 } else {
1164                         $this->partialStub("Do further analysis on timestamp {$timestamp}.");
1165                 }
1166
1167                 // Return the stamp
1168                 return $readable;
1169         }
1170
1171         /**
1172          * "Getter" for databse entry
1173          *
1174          * @return      $entry  An array with database entries
1175          * @throws      NullPointerException    If the database result is not found
1176          * @throws      InvalidDatabaseResultException  If the database result is invalid
1177          */
1178         protected final function getDatabaseEntry () {
1179                 // Is there an instance?
1180                 if (is_null($this->getResultInstance())) {
1181                         // Throw an exception here
1182                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1183                 } // END - if
1184
1185                 // Rewind it
1186                 $this->getResultInstance()->rewind();
1187
1188                 // Do we have an entry?
1189                 if (!$this->getResultInstance()->valid()) {
1190                         throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1191                 } // END - if
1192
1193                 // Get next entry
1194                 $this->getResultInstance()->next();
1195
1196                 // Fetch it
1197                 $entry = $this->getResultInstance()->current();
1198
1199                 // And return it
1200                 return $entry;
1201         }
1202
1203         /**
1204          * Getter for field name
1205          *
1206          * @param       $fieldName              Field name which we shall get
1207          * @return      $fieldValue             Field value from the user
1208          * @throws      NullPointerException    If the result instance is null
1209          */
1210         public final function getField ($fieldName) {
1211                 // Default field value
1212                 $fieldValue = null;
1213
1214                 // Get result instance
1215                 $resultInstance = $this->getResultInstance();
1216
1217                 // Is this instance null?
1218                 if (is_null($resultInstance)) {
1219                         // Then the user instance is no longer valid (expired cookies?)
1220                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1221                 } // END - if
1222
1223                 // Get current array
1224                 $fieldArray = $resultInstance->current();
1225
1226                 // Does the field exist?
1227                 if (isset($fieldArray[$fieldName])) {
1228                         // Get it
1229                         $fieldValue = $fieldArray[$fieldName];
1230                 } // END - if
1231
1232                 // Return it
1233                 return $fieldValue;
1234         }
1235
1236         /**
1237          * Updates a given field with new value
1238          *
1239          * @param       $fieldName              Field to update
1240          * @param       $fieldValue             New value to store
1241          * @return      void
1242          * @throws      DatabaseUpdateSupportException  If this class does not support database updates
1243          */
1244         public function updateDatabaseField ($fieldName, $fieldValue) {
1245                 // Is updating database fields allowed by interface?
1246                 if (!$this instanceof Updateable) {
1247                         // Update not supported!
1248                         throw new DatabaseUpdateSupportException($this, self::EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED);
1249                 } // END - if
1250
1251                 // Get a critieria instance
1252                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
1253
1254                 // Add search criteria
1255                 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
1256                 $searchInstance->setLimit(1);
1257
1258                 // Now get another criteria
1259                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
1260
1261                 // And add our both entries
1262                 $updateInstance->addCriteria($fieldName, $fieldValue);
1263
1264                 // Add the search criteria for searching for the right entry
1265                 $updateInstance->setSearchInstance($searchInstance);
1266
1267                 // Remember the update in database result
1268                 $this->getResultInstance()->add2UpdateQueue($updateInstance);
1269         }
1270 }
1271
1272 // [EOF]
1273 ?>