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