Minor code improvements:
[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                 // Default is invalid db instance
484                 $dbInstance = null;
485
486                 // Is the registry there and initialized?
487                 if ((class_exists('Registry')) && (Registry::isInitialized() === true)) {
488                         $dbInstance = Registry::getRegistry()->getInstance('dbInstance');
489                 } // END - if
490
491                 // Return instance
492                 return $dbInstance;
493         }
494
495         /**
496          * Setter for compressor channel
497          *
498          * @param               $compressorChannel      An instance of CompressorChannel
499          * @return      void
500          */
501         public final function setCompressorChannel (CompressorChannel $compressorChannel) {
502                 Registry::getRegistry()->addInstance('compressor', $compressorChannel);
503         }
504
505         /**
506          * Getter for compressor channel
507          *
508          * @return      $compressor     The compressor channel
509          */
510         public final function getCompressorChannel () {
511                 return Registry::getRegistry()->getInstance('compressor');
512         }
513
514         /**
515          * Protected getter for a manageable application helper class
516          *
517          * @return      $applicationInstance    An instance of a manageable application helper class
518          */
519         protected final function getApplicationInstance () {
520                 return self::$applicationInstance;
521         }
522
523         /**
524          * Setter for a manageable application helper class
525          *
526          * @param       $applicationInstance    An instance of a manageable application helper class
527          * @return      void
528          */
529         public final function setApplicationInstance (ManageableApplication $applicationInstance) {
530                 self::$applicationInstance = $applicationInstance;
531         }
532
533         /**
534          * Setter for request instance
535          *
536          * @param       $requestInstance        An instance of a Requestable class
537          * @return      void
538          */
539         public final function setRequestInstance (Requestable $requestInstance) {
540                 $this->requestInstance = $requestInstance;
541         }
542
543         /**
544          * Getter for request instance
545          *
546          * @return      $requestInstance        An instance of a Requestable class
547          */
548         public final function getRequestInstance () {
549                 return $this->requestInstance;
550         }
551
552         /**
553          * Setter for response instance
554          *
555          * @param       $responseInstance       An instance of a Responseable class
556          * @return      void
557          */
558         public final function setResponseInstance (Responseable $responseInstance) {
559                 $this->responseInstance = $responseInstance;
560         }
561
562         /**
563          * Getter for response instance
564          *
565          * @return      $responseInstance       An instance of a Responseable class
566          */
567         public final function getResponseInstance () {
568                 return $this->responseInstance;
569         }
570
571         /**
572          * Getter for $realClass
573          *
574          * @return      $realClass The name of the real class (not BaseFrameworkSystem)
575          */
576         public final function __toString () {
577                 return $this->realClass;
578         }
579
580         /**
581          * Setter for the real class name
582          *
583          * @param               $realClass      Class name (string)
584          * @return      void
585          */
586         public final function setRealClass ($realClass) {
587                 // Cast to string
588                 $realClass = (string) $realClass;
589
590                 // Set real class
591                 $this->realClass = $realClass;
592         }
593
594         /**
595          * Generate unique ID from a lot entropy
596          *
597          * @return      void
598          */
599         public final function generateUniqueId () {
600                 // Is the id set for this class?
601                 if (empty($this->uniqueID)) {
602
603                         // Correct missing class name
604                         $corrected = false;
605                         if ($this->__toString() == "") {
606                                 $this->setRealClass(__CLASS__);
607                                 $corrected = true;
608                         }
609
610                         // Cache datbase instance
611                         $db = $this->getDatabaseInstance();
612
613                         // Generate new id
614                         $tempID = false;
615                         while (true) {
616                                 // Generate a unique ID number
617                                 $tempID = $this->generateIdNumber();
618                                 $isUsed = false;
619
620                                 // Try to figure out if the ID number is not yet used
621                                 try {
622                                         // Is this a registry?
623                                         if ($this->__toString() == "Registry") {
624                                                 // Registry, then abort here
625                                                 break;
626                                         } elseif (is_object($db)) {
627                                                 $isUsed = $db->isUniqueIdUsed($tempID, true);
628                                         }
629                                 } catch (FrameworkException $e) {
630                                         // Catches all and ignores all ;-)
631                                 }
632
633                                 if (
634                                         (
635                                                 $tempID !== false
636                                         ) && (
637                                                 (
638                                                         $db === null
639                                                 ) || (
640                                                         (
641                                                                 is_object($db)
642                                                         ) && (
643                                                                 !$isUsed
644                                                         )
645                                                 )
646                                         )
647                                 ) {
648                                         // Abort the loop
649                                         break;
650                                 }
651                         } // END - while
652
653                         // Apply the new ID
654                         $this->setUniqueID($tempID);
655
656                         // Revert maybe corrected class name
657                         if ($corrected) {
658                                 $this->setRealClass("");
659                         }
660
661                         // Remove system classes if we are in a system class
662                         if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
663                                 // This may save some RAM...
664                                 $this->removeSystemArray();
665                         }
666                 }
667         }
668
669         /**
670          * Generates a new ID number for classes based from the class' real name,
671          * the description and some random data
672          *
673          * @return      $tempID The new (temporary) ID number
674          */
675         private final function generateIdNumber () {
676                 return sprintf("%s@%s",
677                         $this->__toString(),
678                         md5(sprintf("%s:%s:%s:%s:%s:%s",
679                                 $this->__toString(),
680                                 $this->getObjectDescription(),
681                                 time(),
682                                 getenv('REMOTE_ADDR'),
683                                 getenv('SERVER_ADDR'),
684                                 mt_rand()
685                         ))
686                 );
687         }
688
689         /**
690          * Setter for unique ID
691          *
692          * @param               $uniqueID               The newly generated unique ID number
693          * @return      void
694          */
695         private final function setUniqueID ($uniqueID) {
696                 // Cast to string
697                 $uniqueID = (string) $uniqueID;
698
699                 // Set the ID number
700                 $this->uniqueID = $uniqueID;
701         }
702
703         /**
704          * Getter for unique ID
705          *
706          * @return      $uniqueID               The unique ID of this class
707          */
708         public final function getUniqueID () {
709                 return $this->uniqueID;
710         }
711
712         /**
713          * Resets or recreates the unique ID number
714          *
715          * @return      void
716          */
717         public final function resetUniqueID() {
718                 // Sweet and simple... ;-)
719                 $newUniqueID = $this->generateIdNumber();
720                 $this->setUniqueID($newUniqueID);
721         }
722
723         /**
724          * Getter for simulator description
725          *
726          * @return      $objectDescription      The description of this simulation part
727          */
728         public final function getObjectDescription () {
729                 return $this->objectDescription;
730         }
731
732         /**
733          * Setter for simulation part description
734          *
735          * @param               $objectDescription      The description as string for this simulation part
736          * @return      void
737          */
738         public final function setObjectDescription ($objectDescription) {
739                 $this->objectDescription = (String) $objectDescription;
740         }
741
742         /**
743          * Validate if given object is the same as current
744          *
745          * @param       $object An object instance for comparison with this class
746          * @return      boolean The result of comparing both's unique ID
747          */
748         public final function equals (FrameworkInterface $object) {
749                 return ($this->getUniqueID() == $object->getUniqueID());
750         }
751
752         /**
753          * Compare if both simulation part description and class name matches
754          * (shall be enough)
755          *
756          * @param       $itemInstance   An object instance to an other class
757          * @return      boolean                 The result of comparing class name simulation part description
758          */
759         public function itemMatches ($itemInstance) {
760                 return (
761                         (
762                                 $this->__toString()   == $itemInstance->__toString()
763                         ) && (
764                                 $this->getObjectDescription() == $itemInstance->getObjectDescription()
765                         )
766                 );
767         }
768
769         /**
770          * Compare class name of this and given class name
771          *
772          * @param               $className      The class name as string from the other class
773          * @return      boolean The result of comparing both class names
774          */
775         public final function isClass ($className) {
776                 return ($this->__toString() == $className);
777         }
778
779         /**
780          * Stub method (only real cabins shall override it)
781          *
782          * @return      boolean false = is no cabin, true = is a cabin
783          */
784         public function isCabin () {
785                 return false;
786         }
787
788         /**
789          * Stub method for tradeable objects
790          *
791          * @return      boolean false = is not tradeable by the Merchant class,
792          *                                      true  = is a tradeable object
793          */
794         public function isTradeable () {
795                 return false;
796         }
797
798         /**
799          * Formats computer generated price values into human-understandable formats
800          * with thousand and decimal seperators.
801          *
802          * @param       $value          The in computer format value for a price
803          * @param       $currency       The currency symbol (use HTML-valid characters!)
804          * @param       $decNum         Number of decimals after commata
805          * @return      $price          The for the current language formated price string
806          * @throws      MissingDecimalsThousandsSeperatorException      If decimals or
807          *                                                                                              thousands seperator
808          *                                                                                              is missing
809          */
810         public function formatCurrency ($value, $currency = "&euro;", $decNum = 2) {
811                 // Are all required attriutes set?
812                 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
813                         // Throw an exception
814                         throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
815                 }
816
817                 // Cast the number
818                 $value = (float) $value;
819
820                 // Reformat the US number
821                 $price = sprintf("%s %s",
822                         number_format($value, $decNum, $this->decimals, $this->thousands),
823                         $currency
824                 );
825
826                 // Return as string...
827                 return $price;
828         }
829
830         /**
831          * Removes number formating characters
832          *
833          * @return      void
834          */
835         public final function removeNumberFormaters () {
836                 unset($this->thousands);
837                 unset($this->decimals);
838         }
839
840         /**
841          * Private getter for language instance
842          *
843          * @return      $langInstance   An instance to the language sub-system
844          */
845         protected final function getLanguageInstance () {
846                 return self::$langInstance;
847         }
848
849         /**
850          * Setter for language instance
851          *
852          * @param       $langInstance   An instance to the language sub-system
853          * @return      void
854          * @see         LanguageSystem
855          */
856         public final function setLanguageInstance (ManageableLanguage $langInstance) {
857                 self::$langInstance = $langInstance;
858         }
859
860         /**
861          * Remove the $systemClasses array from memory
862          *
863          * @return      void
864          */
865         public final function removeSystemArray () {
866                 unset($this->systemClasses);
867         }
868
869         /**
870          * Create a file name and path name from the object's unique ID number.
871          * The left part of the ID shall always be a valid class name and the
872          * right part an ID number.
873          *
874          * @return      $pfn    The file name with a prepended path name
875          * @throws      NoArrayCreatedException         If explode() fails to create an array
876          * @throws      InvalidArrayCountException      If the array contains less or
877          *                                                                              more than two elements
878          */
879         public final function getPathFileNameFromObject () {
880                 // Get the main object's unique ID. We use this as a path/filename combination
881                 $pathFile = $this->getUniqueID();
882
883                 // Split it up in path and file name
884                 $pathFile = explode("@", $pathFile);
885
886                 // Are there two elements? Index 0 is the path, 1 the file name + global extension
887                 if (!is_array($pathFile)) {
888                         // No array found
889                         throw new NoArrayCreatedException(array($this, 'pathFile'), self::EXCEPTION_ARRAY_EXPECTED);
890                 } elseif (count($pathFile) != 2) {
891                         // Invalid ID returned!
892                         throw new InvalidArrayCountException(array($this, 'pathFile', count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
893                 }
894
895                 // Auto-append missing trailing slash
896                 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
897
898                 // Create the file name and return it
899                 $pfn = ($pathFile[0] . $pathFile[1]);
900                 return $pfn;
901         }
902
903         /**
904          * Appends a trailing slash to a string
905          *
906          * @param       $str            A string (maybe) without trailing slash
907          * @return      $str            A string with an auto-appended trailing slash
908          */
909         public final function addMissingTrailingSlash ($str) {
910                 // Is there a trailing slash?
911                 if (substr($str, -1, 1) != "/") $str .= "/";
912                 return $str;
913         }
914
915         /**
916          * Private getter for file IO instance
917          *
918          * @return      $fileIoInstance An instance to the file I/O sub-system
919          */
920         protected final function getFileIoInstance () {
921                 return $this->fileIoInstance;
922         }
923
924         /**
925          * Setter for file I/O instance
926          *
927          * @param       $fileIoInstance An instance to the file I/O sub-system
928          * @return      void
929          */
930         public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
931                 $this->fileIoInstance = $fileIoInstance;
932         }
933
934         /**
935          * Prepare the template engine (WebTemplateEngine by default) for a given
936          * application helper instance (ApplicationHelper by default).
937          *
938          * @param               $appInstance                    An application helper instance or
939          *                                                                              null if we shall use the default
940          * @return              $templateInstance                               The template engine instance
941          * @throws              NullPointerException    If the template engine could not
942          *                                                                              be initialized
943          * @throws              UnsupportedTemplateEngineException      If $templateInstance is an
944          *                                                                              unsupported template engine
945          * @throws              MissingLanguageHandlerException If the language sub-system
946          *                                                                              is not yet initialized
947          * @throws              NullPointerException    If the discovered application
948          *                                                                              instance is still null
949          */
950         protected function prepareTemplateInstance (BaseFrameworkSystem $appInstance=null) {
951                 // Is the application instance set?
952                 if (is_null($appInstance)) {
953                         // Get the current instance
954                         $appInstance = $this->getApplicationInstance();
955
956                         // Still null?
957                         if (is_null($appInstance)) {
958                                 // Thrown an exception
959                                 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
960                         } // END - if
961                 } // END - if
962
963                 // Generate FQFN for all application templates
964                 $fqfn = sprintf("%s%s/%s/%s",
965                         PATH,
966                         $this->getConfigInstance()->readConfig('application_path'),
967                         strtolower($appInstance->getAppShortName()),
968                         $this->getConfigInstance()->readConfig('tpl_base_path')
969                 );
970
971                 // Are both instances set?
972                 if ($appInstance->getLanguageInstance() === null) {
973                         // Invalid language instance
974                         throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
975                 } elseif ($appInstance->getFileIoInstance() === null) {
976                         // Invalid language instance
977                         throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
978                 }
979
980                 // Initialize the template engine
981                 $templateInstance = ObjectFactory::createObjectByConfiguredName('template_class', array($fqfn, $appInstance->getLanguageInstance(), $appInstance->getFileIoInstance()));
982
983                 // Return the prepared instance
984                 return $templateInstance;
985         }
986
987         /**
988          * Debugs this instance by putting out it's full content
989          *
990          * @return      void
991          */
992         public final function debugInstance () {
993                 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
994                 restore_error_handler();
995
996                 // Generate the output
997                 $content = sprintf("<pre>%s</pre>",
998                         trim(
999                                 htmlentities(
1000                                         print_r($this, true)
1001                                 )
1002                         )
1003                 );
1004
1005                 // Output it
1006                 ApplicationEntryPoint::app_die(sprintf("<strong>%s debug output:</strong><div id=\"debug_content\">%s</div>\nLoaded includes: <div id=\"debug_include_list\">%s</div>",
1007                         $this->__toString(),
1008                         $content,
1009                         ClassLoader::getInstance()->getPrintableIncludeList()
1010                 ));
1011         }
1012
1013         /**
1014          * Output a partial stub message for the caller method
1015          *
1016          * @param       $message        An optional message to display
1017          * @return      void
1018          */
1019         protected function partialStub ($message = "") {
1020                 // Get the backtrace
1021                 $backtrace = debug_backtrace();
1022
1023                 // Generate the class::method string
1024                 $methodName = "UnknownClass-&gt;unknownMethod";
1025                 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1026                         $methodName = $backtrace[1]['class']."-&gt;".$backtrace[1]['function'];
1027                 } // END - if
1028
1029                 // Construct the full message
1030                 $stubMessage = sprintf("[%s:] Partial stub!",
1031                         $methodName
1032                 );
1033
1034                 // Is the extra message given?
1035                 if (!empty($message)) {
1036                         // Then add it as well
1037                         $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
1038                 } // END - if
1039
1040                 // Debug instance is there?
1041                 if (!is_null($this->getDebugInstance())) {
1042                         // Output stub message
1043                         $this->debugOutput($stubMessage);
1044                 } else {
1045                         // Trigger an error
1046                         trigger_error($stubMessage."<br />\n");
1047                 }
1048         }
1049
1050         /**
1051          * Outputs a debug backtrace and stops further script execution
1052          *
1053          * @return      void
1054          */
1055         public function debugBackTrace () {
1056                 // Sorry, there is no other way getting this nice backtrace
1057                 print "<pre>\n";
1058                 debug_print_backtrace();
1059                 print "</pre>";
1060                 exit;
1061         }
1062
1063         /**
1064          * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
1065          *
1066          * @param       $message        Message we shall send out...
1067          * @param       $doPrint        Wether we shall print or die here which first is the default
1068          * @return      void
1069          */
1070         public function debugOutput ($message, $doPrint = true) {
1071                 // Get debug instance
1072                 $debugInstance = $this->getDebugInstance();
1073
1074                 // Is the debug instance there?
1075                 if (is_object($debugInstance)) {
1076                         // Use debug output handler
1077                         $debugInstance->output($message);
1078                         if (!$doPrint) die(); // Die here if not printed
1079                 } else {
1080                         // Put directly out
1081                         if ($doPrint) {
1082                                 print($message);
1083                         } else {
1084                                 // DO NOT REWRITE THIS TO app_die() !!!
1085                                 die($message);
1086                         }
1087                 }
1088         }
1089
1090         /**
1091          * Converts e.g. a command from URL to a valid class by keeping out bad characters
1092          *
1093          * @param       $str            The string, what ever it is needs to be converted
1094          * @return      $className      Generated class name
1095          */
1096         public function convertToClassName ($str) {
1097                 // Init class name
1098                 $className = "";
1099
1100                 // Convert all dashes in underscores
1101                 $str = str_replace("-", "_", $str);
1102
1103                 // Now use that underscores to get classname parts for hungarian style
1104                 foreach (explode("_", $str) as $strPart) {
1105                         // Make the class name part lower case and first upper case
1106                         $className .= ucfirst(strtolower($strPart));
1107                 } // END - foreach
1108
1109                 // Return class name
1110                 return $className;
1111         }
1112
1113         /**
1114          * Marks up the code by adding e.g. line numbers
1115          *
1116          * @param       $phpCode                Unmarked PHP code
1117          * @return      $markedCode             Marked PHP code
1118          */
1119         public function markupCode ($phpCode) {
1120                 // Get last error
1121                 $errorArray = error_get_last();
1122
1123                 // Init the code with error message
1124                 $markedCode = "";
1125                 if (is_array($errorArray)) {
1126                         // Get error infos
1127                         $markedCode = sprintf("<div id=\"error_header\">File: <span id=\"error_data\">%s</span>, Line: <span id=\"error_data\">%s</span>, Message: <span id=\"error_data\">%s</span>, Type: <span id=\"error_data\">%s</span></div>",
1128                                 basename($errorArray['file']),
1129                                 $errorArray['line'],
1130                                 $errorArray['message'],
1131                                 $errorArray['type']
1132                         );
1133                 } // END - if
1134
1135                 // Add line number to the code
1136                 foreach (explode("\n", $phpCode) as $lineNo=>$code) {
1137                         // Add line numbers
1138                         $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
1139                                 ($lineNo+1),
1140                                 htmlentities($code, ENT_QUOTES)
1141                         );
1142                 } // END - foreach
1143
1144                 // Return the code
1145                 return $markedCode;
1146         }
1147
1148         /**
1149          * Filter a given timestamp to make it look more beatifull for web-based
1150          * front-ends. If null is given a message id null_timestamp will be
1151          * resolved and returned.
1152          *
1153          * @param       $timestamp      Timestamp to prepare (filter) for display
1154          * @return      $readable       A readable timestamp
1155          */
1156         public function doFilterFormatTimestamp ($timestamp) {
1157                 // Default value to return
1158                 $readable = "???";
1159
1160                 // Is the timestamp null?
1161                 if (is_null($timestamp)) {
1162                         // Get a message string
1163                         $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1164                 } else {
1165                         $this->partialStub("Do further analysis on timestamp {$timestamp}.");
1166                 }
1167
1168                 // Return the stamp
1169                 return $readable;
1170         }
1171
1172         /**
1173          * "Getter" for databse entry
1174          *
1175          * @return      $entry  An array with database entries
1176          * @throws      NullPointerException    If the database result is not found
1177          * @throws      InvalidDatabaseResultException  If the database result is invalid
1178          */
1179         protected final function getDatabaseEntry () {
1180                 // Is there an instance?
1181                 if (is_null($this->getResultInstance())) {
1182                         // Throw an exception here
1183                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1184                 } // END - if
1185
1186                 // Rewind it
1187                 $this->getResultInstance()->rewind();
1188
1189                 // Do we have an entry?
1190                 if (!$this->getResultInstance()->valid()) {
1191                         throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1192                 } // END - if
1193
1194                 // Get next entry
1195                 $this->getResultInstance()->next();
1196
1197                 // Fetch it
1198                 $entry = $this->getResultInstance()->current();
1199
1200                 // And return it
1201                 return $entry;
1202         }
1203
1204         /**
1205          * Getter for field name
1206          *
1207          * @param       $fieldName              Field name which we shall get
1208          * @return      $fieldValue             Field value from the user
1209          * @throws      NullPointerException    If the result instance is null
1210          */
1211         public final function getField ($fieldName) {
1212                 // Default field value
1213                 $fieldValue = null;
1214
1215                 // Get result instance
1216                 $resultInstance = $this->getResultInstance();
1217
1218                 // Is this instance null?
1219                 if (is_null($resultInstance)) {
1220                         // Then the user instance is no longer valid (expired cookies?)
1221                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1222                 } // END - if
1223
1224                 // Get current array
1225                 $fieldArray = $resultInstance->current();
1226
1227                 // Does the field exist?
1228                 if (isset($fieldArray[$fieldName])) {
1229                         // Get it
1230                         $fieldValue = $fieldArray[$fieldName];
1231                 } // END - if
1232
1233                 // Return it
1234                 return $fieldValue;
1235         }
1236
1237         /**
1238          * Updates a given field with new value
1239          *
1240          * @param       $fieldName              Field to update
1241          * @param       $fieldValue             New value to store
1242          * @return      void
1243          * @throws      DatabaseUpdateSupportException  If this class does not support database updates
1244          */
1245         public function updateDatabaseField ($fieldName, $fieldValue) {
1246                 // Is updating database fields allowed by interface?
1247                 if (!$this instanceof Updateable) {
1248                         // Update not supported!
1249                         throw new DatabaseUpdateSupportException($this, self::EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED);
1250                 } // END - if
1251
1252                 // Get a critieria instance
1253                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
1254
1255                 // Add search criteria
1256                 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
1257                 $searchInstance->setLimit(1);
1258
1259                 // Now get another criteria
1260                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
1261
1262                 // And add our both entries
1263                 $updateInstance->addCriteria($fieldName, $fieldValue);
1264
1265                 // Add the search criteria for searching for the right entry
1266                 $updateInstance->setSearchInstance($searchInstance);
1267
1268                 // Remember the update in database result
1269                 $this->getResultInstance()->add2UpdateQueue($updateInstance);
1270         }
1271 }
1272
1273 // [EOF]
1274 ?>