3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\Compressor\Compressor;
8 use CoreFramework\Configuration\FrameworkConfiguration;
9 use CoreFramework\Connection\Database\DatabaseConnection;
10 use CoreFramework\Controller\Controller;
11 use CoreFramework\Criteria\Criteria;
12 use CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use CoreFramework\Crypto\Cryptable;
15 use CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
17 use CoreFramework\Factory\ObjectFactory;
18 use CoreFramework\Filesystem\Block;
19 use CoreFramework\Filesystem\FilePointer;
20 use CoreFramework\Filesystem\FrameworkDirectory;
21 use CoreFramework\Generic\FrameworkInterface;
22 use CoreFramework\Generic\NullPointerException;
23 use CoreFramework\Handler\Stream\IoHandler;
24 use CoreFramework\Index\Indexable;
25 use CoreFramework\Listener\Listenable;
26 use CoreFramework\Lists\Listable;
27 use CoreFramework\Loader\ClassLoader;
28 use CoreFramework\Manager\ManageableApplication;
29 use CoreFramework\Middleware\Compressor\CompressorChannel;
30 use CoreFramework\Middleware\Debug\DebugMiddleware;
31 use CoreFramework\Parser\Parseable;
32 use CoreFramework\Registry\Register;
33 use CoreFramework\Registry\Registry;
34 use CoreFramework\Resolver\Resolver;
35 use CoreFramework\Result\Database\CachedDatabaseResult;
36 use CoreFramework\Result\Search\SearchableResult;
37 use CoreFramework\Stacker\Stackable;
38 use CoreFramework\Stream\Output\OutputStreamer;
39 use CoreFramework\Template\CompileableTemplate;
40 use CoreFramework\User\ManageableAccount;
41 use CoreFramework\Visitor\Visitor;
42 use CoreFramework\Wrapper\Database\DatabaseWrapper;
50 * The simulator system class is the super class of all other classes. This
51 * class handles saving of games etc.
53 * @author Roland Haeder <webmaster@shipsimu.org>
55 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
56 * @license GNU GPL 3.0 or any newer version
57 * @link http://www.shipsimu.org
59 * This program is free software: you can redistribute it and/or modify
60 * it under the terms of the GNU General Public License as published by
61 * the Free Software Foundation, either version 3 of the License, or
62 * (at your option) any later version.
64 * This program is distributed in the hope that it will be useful,
65 * but WITHOUT ANY WARRANTY; without even the implied warranty of
66 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
67 * GNU General Public License for more details.
69 * You should have received a copy of the GNU General Public License
70 * along with this program. If not, see <http://www.gnu.org/licenses/>.
72 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
74 * Length of output from hash()
76 private static $hashLength = NULL;
81 private $realClass = 'BaseFrameworkSystem';
84 * Search criteria instance
86 private $searchInstance = NULL;
89 * Update criteria instance
91 private $updateInstance = NULL;
94 * The file I/O instance for the template loader
96 private $fileIoInstance = NULL;
101 private $resolverInstance = NULL;
104 * Template engine instance
106 private $templateInstance = NULL;
109 * Database result instance
111 private $resultInstance = NULL;
114 * Instance for user class
116 private $userInstance = NULL;
119 * A controller instance
121 private $controllerInstance = NULL;
126 private $rngInstance = NULL;
129 * Instance of a crypto helper
131 private $cryptoInstance = NULL;
134 * Instance of an Iterator class
136 private $iteratorInstance = NULL;
139 * Instance of the list
141 private $listInstance = NULL;
146 private $menuInstance = NULL;
149 * Instance of the image
151 private $imageInstance = NULL;
154 * Instance of the stacker
156 private $stackInstance = NULL;
159 * A Compressor instance
161 private $compressorInstance = NULL;
164 * A Parseable instance
166 private $parserInstance = NULL;
169 * A HandleableProtocol instance
171 private $protocolInstance = NULL;
174 * A database wrapper instance
176 private $databaseInstance = NULL;
179 * A helper instance for the form
181 private $helperInstance = NULL;
184 * An instance of a Source class
186 private $sourceInstance = NULL;
189 * An instance of a UrlSource class
191 private $urlSourceInstance = NULL;
194 * An instance of a InputStream class
196 private $inputStreamInstance = NULL;
199 * An instance of a OutputStream class
201 private $outputStreamInstance = NULL;
204 * Networkable handler instance
206 private $handlerInstance = NULL;
209 * Visitor handler instance
211 private $visitorInstance = NULL;
216 private $dhtInstance = NULL;
219 * An instance of a database wrapper class
221 private $wrapperInstance = NULL;
224 * An instance of a file I/O pointer class (not handler)
226 private $pointerInstance = NULL;
229 * An instance of an Indexable class
231 private $indexInstance = NULL;
234 * An instance of a Block class
236 private $blockInstance = NULL;
241 private $minableInstance = NULL;
244 * A FrameworkDirectory instance
246 private $directoryInstance = NULL;
251 private $listenerInstance = NULL;
254 * An instance of a communicator
256 private $communicatorInstance = NULL;
259 * The concrete output instance
261 private $outputInstance = NULL;
266 private $stateInstance = NULL;
269 * Thousands separator
271 private $thousands = '.'; // German
276 private $decimals = ','; // German
281 private $socketResource = false;
284 * Regular expression to use for validation
286 private $regularExpression = '';
291 private $packageData = array();
296 private $genericArray = array();
301 private $commandName = '';
306 private $controllerName = '';
309 * Name of used protocol
311 private $protocolName = 'invalid';
314 * Array with bitmasks and such for pack/unpack methods to support both
315 * 32-bit and 64-bit systems
317 private $packingData = array(
320 'left' => 0xffff0000,
321 'right' => 0x0000ffff,
327 'left' => 0xffffffff00000000,
328 'right' => 0x00000000ffffffff,
335 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
337 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
339 private $archArrayElement = false;
341 /***********************
342 * Exception codes.... *
343 ***********************/
345 // @todo Try to clean these constants up
346 const EXCEPTION_IS_NULL_POINTER = 0x001;
347 const EXCEPTION_IS_NO_OBJECT = 0x002;
348 const EXCEPTION_IS_NO_ARRAY = 0x003;
349 const EXCEPTION_MISSING_METHOD = 0x004;
350 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
351 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
352 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
353 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
354 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
355 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
356 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
357 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
358 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
359 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
360 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
361 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
362 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
363 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
364 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
365 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
366 const EXCEPTION_PATH_NOT_FOUND = 0x015;
367 const EXCEPTION_INVALID_PATH_NAME = 0x016;
368 const EXCEPTION_READ_PROTECED_PATH = 0x017;
369 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
370 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
371 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
372 const EXCEPTION_INVALID_RESOURCE = 0x01b;
373 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
374 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
375 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
376 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
377 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
378 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
379 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
380 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
381 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
382 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
383 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
384 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
385 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
386 const EXCEPTION_INVALID_STRING = 0x029;
387 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
388 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
389 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
390 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
391 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
392 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
393 const EXCEPTION_MISSING_ELEMENT = 0x030;
394 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
395 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
396 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
397 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
398 const EXCEPTION_FATAL_ERROR = 0x035;
399 const EXCEPTION_FILE_NOT_FOUND = 0x036;
400 const EXCEPTION_ASSERTION_FAILED = 0x037;
401 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
402 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
403 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
404 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
405 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
406 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
409 * Hexadecimal->Decimal translation array
411 private static $hexdec = array(
431 * Decimal->hexadecimal translation array
433 private static $dechex = array(
453 * Startup time in miliseconds
455 private static $startupTime = 0;
458 * Protected super constructor
460 * @param $className Name of the class
463 protected function __construct ($className) {
465 $this->setRealClass($className);
467 // Set configuration instance if no registry ...
468 if (!$this instanceof Register) {
469 // ... because registries doesn't need to be configured
470 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
473 // Is the startup time set? (0 cannot be true anymore)
474 if (self::$startupTime == 0) {
476 self::$startupTime = microtime(true);
480 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
484 * Destructor for all classes. You should not call this method on your own.
488 public function __destruct () {
489 // Flush any updated entries to the database
490 $this->flushPendingUpdates();
492 // Is this object already destroyed?
493 if ($this->__toString() != 'DestructedObject') {
494 // Destroy all informations about this class but keep some text about it alive
495 $this->setRealClass('DestructedObject');
496 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
497 // Already destructed object
498 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
503 // Do not call this twice
504 trigger_error(__METHOD__ . ': Called twice.');
510 * The __call() method where all non-implemented methods end up
512 * @param $methodName Name of the missing method
513 * @args $args Arguments passed to the method
516 public final function __call ($methodName, $args) {
517 return self::__callStatic($methodName, $args);
521 * The __callStatic() method where all non-implemented static methods end up
523 * @param $methodName Name of the missing method
524 * @args $args Arguments passed to the method
527 public static final function __callStatic ($methodName, $args) {
529 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
531 // Init argument string
534 // Is it NULL, empty or an array?
535 if (is_null($args)) {
537 $argsString = 'NULL';
538 } elseif (is_array($args)) {
542 // Some arguments are there
543 foreach ($args as $arg) {
544 // Add data about the argument
545 $argsString .= gettype($arg) . ':';
548 // Found a NULL argument
549 $argsString .= 'NULL';
550 } elseif (is_string($arg)) {
551 // Add length for strings
552 $argsString .= strlen($arg);
553 } elseif ((is_int($arg)) || (is_float($arg))) {
556 } elseif (is_array($arg)) {
557 // .. or size if array
558 $argsString .= count($arg);
559 } elseif (is_object($arg)) {
561 $reflection = new ReflectionClass($arg);
563 // Is an other object, maybe no __toString() available
564 $argsString .= $reflection->getName();
565 } elseif ($arg === true) {
566 // ... is boolean 'true'
567 $argsString .= 'true';
568 } elseif ($arg === false) {
569 // ... is boolean 'false'
570 $argsString .= 'false';
573 // Comma for next one
578 if (substr($argsString, -2, 1) == ',') {
579 $argsString = substr($argsString, 0, -2);
585 // Invalid arguments!
586 $argsString = '!INVALID:' . gettype($args) . '!';
589 // Output stub message
590 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
591 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
601 * Getter for $realClass
603 * @return $realClass The name of the real class (not BaseFrameworkSystem)
605 public function __toString () {
606 return $this->realClass;
610 * Magic method to catch setting of missing but set class fields/attributes
612 * @param $name Name of the field/attribute
613 * @param $value Value to store
616 public final function __set ($name, $value) {
617 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
620 print_r($value, true)
625 * Magic method to catch getting of missing fields/attributes
627 * @param $name Name of the field/attribute
630 public final function __get ($name) {
631 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
637 * Magic method to catch unsetting of missing fields/attributes
639 * @param $name Name of the field/attribute
642 public final function __unset ($name) {
643 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
649 * Magic method to catch object serialization
651 * @return $unsupported Unsupported method
652 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
654 public final function __sleep () {
655 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
659 * Magic method to catch object deserialization
661 * @return $unsupported Unsupported method
662 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
664 public final function __wakeup () {
665 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
669 * Magic method to catch calls when an object instance is called
671 * @return $unsupported Unsupported method
672 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
674 public final function __invoke () {
675 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
679 * Setter for the real class name
681 * @param $realClass Class name (string)
684 public final function setRealClass ($realClass) {
686 $this->realClass = (string) $realClass;
690 * Setter for database result instance
692 * @param $resultInstance An instance of a database result class
694 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
696 protected final function setResultInstance (SearchableResult $resultInstance) {
697 $this->resultInstance = $resultInstance;
701 * Getter for database result instance
703 * @return $resultInstance An instance of a database result class
705 public final function getResultInstance () {
706 return $this->resultInstance;
710 * Setter for template engine instances
712 * @param $templateInstance An instance of a template engine class
715 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
716 $this->templateInstance = $templateInstance;
720 * Getter for template engine instances
722 * @return $templateInstance An instance of a template engine class
724 protected final function getTemplateInstance () {
725 return $this->templateInstance;
729 * Setter for search instance
731 * @param $searchInstance Searchable criteria instance
734 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
735 $this->searchInstance = $searchInstance;
739 * Getter for search instance
741 * @return $searchInstance Searchable criteria instance
743 public final function getSearchInstance () {
744 return $this->searchInstance;
748 * Setter for update instance
750 * @param $updateInstance An instance of a LocalUpdateCriteria clase
753 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
754 $this->updateInstance = $updateInstance;
758 * Getter for update instance
760 * @return $updateInstance Updateable criteria instance
762 public final function getUpdateInstance () {
763 return $this->updateInstance;
767 * Setter for resolver instance
769 * @param $resolverInstance Instance of a command resolver class
772 public final function setResolverInstance (Resolver $resolverInstance) {
773 $this->resolverInstance = $resolverInstance;
777 * Getter for resolver instance
779 * @return $resolverInstance Instance of a command resolver class
781 public final function getResolverInstance () {
782 return $this->resolverInstance;
786 * Setter for language instance
788 * @param $configInstance The configuration instance which shall
789 * be FrameworkConfiguration
792 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
793 Registry::getRegistry()->addInstance('config', $configInstance);
797 * Getter for configuration instance
799 * @return $configInstance Configuration instance
801 public final function getConfigInstance () {
802 $configInstance = Registry::getRegistry()->getInstance('config');
803 return $configInstance;
807 * Setter for debug instance
809 * @param $debugInstance The instance for debug output class
812 public final function setDebugInstance (DebugMiddleware $debugInstance) {
813 Registry::getRegistry()->addInstance('debug', $debugInstance);
817 * Getter for debug instance
819 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
821 public final function getDebugInstance () {
822 // Get debug instance
823 $debugInstance = Registry::getRegistry()->getInstance('debug');
826 return $debugInstance;
830 * Setter for web output instance
832 * @param $webInstance The instance for web output class
835 public final function setWebOutputInstance (OutputStreamer $webInstance) {
836 Registry::getRegistry()->addInstance('web_output', $webInstance);
840 * Getter for web output instance
842 * @return $webOutputInstance - Instance to class WebOutput
844 public final function getWebOutputInstance () {
845 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
846 return $webOutputInstance;
850 * Setter for database instance
852 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
855 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
856 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
860 * Getter for database layer
862 * @return $databaseInstance The database layer instance
864 public final function getDatabaseInstance () {
866 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
869 return $databaseInstance;
873 * Setter for compressor channel
875 * @param $compressorInstance An instance of CompressorChannel
878 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
879 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
883 * Getter for compressor channel
885 * @return $compressorInstance The compressor channel
887 public final function getCompressorChannel () {
888 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
889 return $compressorInstance;
893 * Protected getter for a manageable application helper class
895 * @return $applicationInstance An instance of a manageable application helper class
897 protected final function getApplicationInstance () {
898 $applicationInstance = Registry::getRegistry()->getInstance('app');
899 return $applicationInstance;
903 * Setter for a manageable application helper class
905 * @param $applicationInstance An instance of a manageable application helper class
908 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
909 Registry::getRegistry()->addInstance('application', $applicationInstance);
913 * Private getter for language instance
915 * @return $langInstance An instance to the language sub-system
917 protected final function getLanguageInstance () {
918 $langInstance = Registry::getRegistry()->getInstance('language');
919 return $langInstance;
923 * Setter for language instance
925 * @param $langInstance An instance to the language sub-system
927 * @see LanguageSystem
929 public final function setLanguageInstance (ManageableLanguage $langInstance) {
930 Registry::getRegistry()->addInstance('language', $langInstance);
934 * Private getter for file IO instance
936 * @return $fileIoInstance An instance to the file I/O sub-system
938 protected final function getFileIoInstance () {
939 return $this->fileIoInstance;
943 * Setter for file I/O instance
945 * @param $fileIoInstance An instance to the file I/O sub-system
948 public final function setFileIoInstance (IoHandler $fileIoInstance) {
949 $this->fileIoInstance = $fileIoInstance;
953 * Protected setter for user instance
955 * @param $userInstance An instance of a user class
958 protected final function setUserInstance (ManageableAccount $userInstance) {
959 $this->userInstance = $userInstance;
963 * Getter for user instance
965 * @return $userInstance An instance of a user class
967 public final function getUserInstance () {
968 return $this->userInstance;
972 * Setter for controller instance (this surely breaks a bit the MVC patterm)
974 * @param $controllerInstance An instance of the controller
977 public final function setControllerInstance (Controller $controllerInstance) {
978 $this->controllerInstance = $controllerInstance;
982 * Getter for controller instance (this surely breaks a bit the MVC patterm)
984 * @return $controllerInstance An instance of the controller
986 public final function getControllerInstance () {
987 return $this->controllerInstance;
991 * Setter for RNG instance
993 * @param $rngInstance An instance of a random number generator (RNG)
996 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
997 $this->rngInstance = $rngInstance;
1001 * Getter for RNG instance
1003 * @return $rngInstance An instance of a random number generator (RNG)
1005 public final function getRngInstance () {
1006 return $this->rngInstance;
1010 * Setter for Cryptable instance
1012 * @param $cryptoInstance An instance of a Cryptable class
1015 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1016 $this->cryptoInstance = $cryptoInstance;
1020 * Getter for Cryptable instance
1022 * @return $cryptoInstance An instance of a Cryptable class
1024 public final function getCryptoInstance () {
1025 return $this->cryptoInstance;
1029 * Setter for the list instance
1031 * @param $listInstance A list of Listable
1034 protected final function setListInstance (Listable $listInstance) {
1035 $this->listInstance = $listInstance;
1039 * Getter for the list instance
1041 * @return $listInstance A list of Listable
1043 protected final function getListInstance () {
1044 return $this->listInstance;
1048 * Setter for the menu instance
1050 * @param $menuInstance A RenderableMenu instance
1053 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1054 $this->menuInstance = $menuInstance;
1058 * Getter for the menu instance
1060 * @return $menuInstance A RenderableMenu instance
1062 protected final function getMenuInstance () {
1063 return $this->menuInstance;
1067 * Setter for image instance
1069 * @param $imageInstance An instance of an image
1072 public final function setImageInstance (BaseImage $imageInstance) {
1073 $this->imageInstance = $imageInstance;
1077 * Getter for image instance
1079 * @return $imageInstance An instance of an image
1081 public final function getImageInstance () {
1082 return $this->imageInstance;
1086 * Setter for stacker instance
1088 * @param $stackInstance An instance of an stacker
1091 public final function setStackInstance (Stackable $stackInstance) {
1092 $this->stackInstance = $stackInstance;
1096 * Getter for stacker instance
1098 * @return $stackInstance An instance of an stacker
1100 public final function getStackInstance () {
1101 return $this->stackInstance;
1105 * Setter for compressor instance
1107 * @param $compressorInstance An instance of an compressor
1110 public final function setCompressorInstance (Compressor $compressorInstance) {
1111 $this->compressorInstance = $compressorInstance;
1115 * Getter for compressor instance
1117 * @return $compressorInstance An instance of an compressor
1119 public final function getCompressorInstance () {
1120 return $this->compressorInstance;
1124 * Setter for Parseable instance
1126 * @param $parserInstance An instance of an Parseable
1129 public final function setParserInstance (Parseable $parserInstance) {
1130 $this->parserInstance = $parserInstance;
1134 * Getter for Parseable instance
1136 * @return $parserInstance An instance of an Parseable
1138 public final function getParserInstance () {
1139 return $this->parserInstance;
1143 * Setter for HandleableProtocol instance
1145 * @param $protocolInstance An instance of an HandleableProtocol
1148 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1149 $this->protocolInstance = $protocolInstance;
1153 * Getter for HandleableProtocol instance
1155 * @return $protocolInstance An instance of an HandleableProtocol
1157 public final function getProtocolInstance () {
1158 return $this->protocolInstance;
1162 * Setter for DatabaseWrapper instance
1164 * @param $wrapperInstance An instance of an DatabaseWrapper
1167 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1168 $this->wrapperInstance = $wrapperInstance;
1172 * Getter for DatabaseWrapper instance
1174 * @return $wrapperInstance An instance of an DatabaseWrapper
1176 public final function getWrapperInstance () {
1177 return $this->wrapperInstance;
1181 * Setter for socket resource
1183 * @param $socketResource A valid socket resource
1186 public final function setSocketResource ($socketResource) {
1187 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1188 $this->socketResource = $socketResource;
1192 * Getter for socket resource
1194 * @return $socketResource A valid socket resource
1196 public final function getSocketResource () {
1197 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1198 return $this->socketResource;
1202 * Setter for regular expression
1204 * @param $regularExpression A valid regular expression
1207 public final function setRegularExpression ($regularExpression) {
1208 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1209 $this->regularExpression = $regularExpression;
1213 * Getter for regular expression
1215 * @return $regularExpression A valid regular expression
1217 public final function getRegularExpression () {
1218 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1219 return $this->regularExpression;
1223 * Setter for helper instance
1225 * @param $helperInstance An instance of a helper class
1228 protected final function setHelperInstance (Helper $helperInstance) {
1229 $this->helperInstance = $helperInstance;
1233 * Getter for helper instance
1235 * @return $helperInstance An instance of a helper class
1237 public final function getHelperInstance () {
1238 return $this->helperInstance;
1242 * Setter for a Source instance
1244 * @param $sourceInstance An instance of a Source class
1247 protected final function setSourceInstance (Source $sourceInstance) {
1248 $this->sourceInstance = $sourceInstance;
1252 * Getter for a Source instance
1254 * @return $sourceInstance An instance of a Source class
1256 protected final function getSourceInstance () {
1257 return $this->sourceInstance;
1261 * Setter for a UrlSource instance
1263 * @param $sourceInstance An instance of a UrlSource class
1266 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1267 $this->urlSourceInstance = $urlSourceInstance;
1271 * Getter for a UrlSource instance
1273 * @return $urlSourceInstance An instance of a UrlSource class
1275 protected final function getUrlSourceInstance () {
1276 return $this->urlSourceInstance;
1280 * Getter for a InputStream instance
1282 * @param $inputStreamInstance The InputStream instance
1284 protected final function getInputStreamInstance () {
1285 return $this->inputStreamInstance;
1289 * Setter for a InputStream instance
1291 * @param $inputStreamInstance The InputStream instance
1294 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1295 $this->inputStreamInstance = $inputStreamInstance;
1299 * Getter for a OutputStream instance
1301 * @param $outputStreamInstance The OutputStream instance
1303 protected final function getOutputStreamInstance () {
1304 return $this->outputStreamInstance;
1308 * Setter for a OutputStream instance
1310 * @param $outputStreamInstance The OutputStream instance
1313 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1314 $this->outputStreamInstance = $outputStreamInstance;
1318 * Setter for handler instance
1320 * @param $handlerInstance An instance of a Handleable class
1323 protected final function setHandlerInstance (Handleable $handlerInstance) {
1324 $this->handlerInstance = $handlerInstance;
1328 * Getter for handler instance
1330 * @return $handlerInstance A Networkable instance
1332 protected final function getHandlerInstance () {
1333 return $this->handlerInstance;
1337 * Setter for visitor instance
1339 * @param $visitorInstance A Visitor instance
1342 protected final function setVisitorInstance (Visitor $visitorInstance) {
1343 $this->visitorInstance = $visitorInstance;
1347 * Getter for visitor instance
1349 * @return $visitorInstance A Visitor instance
1351 protected final function getVisitorInstance () {
1352 return $this->visitorInstance;
1356 * Setter for DHT instance
1358 * @param $dhtInstance A Distributable instance
1361 protected final function setDhtInstance (Distributable $dhtInstance) {
1362 $this->dhtInstance = $dhtInstance;
1366 * Getter for DHT instance
1368 * @return $dhtInstance A Distributable instance
1370 protected final function getDhtInstance () {
1371 return $this->dhtInstance;
1375 * Setter for raw package Data
1377 * @param $packageData Raw package Data
1380 public final function setPackageData (array $packageData) {
1381 $this->packageData = $packageData;
1385 * Getter for raw package Data
1387 * @return $packageData Raw package Data
1389 public function getPackageData () {
1390 return $this->packageData;
1395 * Setter for Iterator instance
1397 * @param $iteratorInstance An instance of an Iterator
1400 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1401 $this->iteratorInstance = $iteratorInstance;
1405 * Getter for Iterator instance
1407 * @return $iteratorInstance An instance of an Iterator
1409 public final function getIteratorInstance () {
1410 return $this->iteratorInstance;
1414 * Setter for FilePointer instance
1416 * @param $pointerInstance An instance of an FilePointer class
1419 protected final function setPointerInstance (FilePointer $pointerInstance) {
1420 $this->pointerInstance = $pointerInstance;
1424 * Getter for FilePointer instance
1426 * @return $pointerInstance An instance of an FilePointer class
1428 public final function getPointerInstance () {
1429 return $this->pointerInstance;
1433 * Unsets pointer instance which triggers a call of __destruct() if the
1434 * instance is still there. This is surely not fatal on already "closed"
1435 * file pointer instances.
1437 * I don't want to mess around with above setter by giving it a default
1438 * value NULL as setter should always explicitly only set (existing) object
1439 * instances and NULL is NULL.
1443 protected final function unsetPointerInstance () {
1444 // Simply it to NULL
1445 $this->pointerInstance = NULL;
1449 * Setter for Indexable instance
1451 * @param $indexInstance An instance of an Indexable class
1454 protected final function setIndexInstance (Indexable $indexInstance) {
1455 $this->indexInstance = $indexInstance;
1459 * Getter for Indexable instance
1461 * @return $indexInstance An instance of an Indexable class
1463 public final function getIndexInstance () {
1464 return $this->indexInstance;
1468 * Setter for Block instance
1470 * @param $blockInstance An instance of an Block class
1473 protected final function setBlockInstance (Block $blockInstance) {
1474 $this->blockInstance = $blockInstance;
1478 * Getter for Block instance
1480 * @return $blockInstance An instance of an Block class
1482 public final function getBlockInstance () {
1483 return $this->blockInstance;
1487 * Setter for Minable instance
1489 * @param $minableInstance A Minable instance
1492 protected final function setMinableInstance (Minable $minableInstance) {
1493 $this->minableInstance = $minableInstance;
1497 * Getter for minable instance
1499 * @return $minableInstance A Minable instance
1501 protected final function getMinableInstance () {
1502 return $this->minableInstance;
1506 * Setter for FrameworkDirectory instance
1508 * @param $directoryInstance A FrameworkDirectory instance
1511 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1512 $this->directoryInstance = $directoryInstance;
1516 * Getter for FrameworkDirectory instance
1518 * @return $directoryInstance A FrameworkDirectory instance
1520 protected final function getDirectoryInstance () {
1521 return $this->directoryInstance;
1525 * Setter for listener instance
1527 * @param $listenerInstance A Listenable instance
1530 protected final function setListenerInstance (Listenable $listenerInstance) {
1531 $this->listenerInstance = $listenerInstance;
1535 * Getter for listener instance
1537 * @return $listenerInstance A Listenable instance
1539 protected final function getListenerInstance () {
1540 return $this->listenerInstance;
1544 * Getter for communicator instance
1546 * @return $communicatorInstance An instance of a Communicator class
1548 public final function getCommunicatorInstance () {
1549 return $this->communicatorInstance;
1553 * Setter for communicator instance
1555 * @param $communicatorInstance An instance of a Communicator class
1558 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1559 $this->communicatorInstance = $communicatorInstance;
1563 * Setter for state instance
1565 * @param $stateInstance A Stateable instance
1568 public final function setStateInstance (Stateable $stateInstance) {
1569 $this->stateInstance = $stateInstance;
1573 * Getter for state instance
1575 * @return $stateInstance A Stateable instance
1577 public final function getStateInstance () {
1578 return $this->stateInstance;
1582 * Setter for output instance
1584 * @param $outputInstance The debug output instance
1587 public final function setOutputInstance (OutputStreamer $outputInstance) {
1588 $this->outputInstance = $outputInstance;
1592 * Getter for output instance
1594 * @return $outputInstance The debug output instance
1596 public final function getOutputInstance () {
1597 return $this->outputInstance;
1601 * Setter for command name
1603 * @param $commandName Last validated command name
1606 protected final function setCommandName ($commandName) {
1607 $this->commandName = $commandName;
1611 * Getter for command name
1613 * @return $commandName Last validated command name
1615 protected final function getCommandName () {
1616 return $this->commandName;
1620 * Setter for controller name
1622 * @param $controllerName Last validated controller name
1625 protected final function setControllerName ($controllerName) {
1626 $this->controllerName = $controllerName;
1630 * Getter for controller name
1632 * @return $controllerName Last validated controller name
1634 protected final function getControllerName () {
1635 return $this->controllerName;
1639 * Getter for protocol name
1641 * @return $protocolName Name of used protocol
1643 public final function getProtocolName () {
1644 return $this->protocolName;
1648 * Setter for protocol name
1650 * @param $protocolName Name of used protocol
1653 protected final function setProtocolName ($protocolName) {
1654 $this->protocolName = $protocolName;
1658 * Checks whether an object equals this object. You should overwrite this
1659 * method to implement own equality checks
1661 * @param $objectInstance An instance of a FrameworkInterface object
1662 * @return $equals Whether both objects equals
1664 public function equals (FrameworkInterface $objectInstance) {
1667 $this->__toString() == $objectInstance->__toString()
1669 $this->hashCode() == $objectInstance->hashCode()
1672 // Return the result
1677 * Generates a generic hash code of this class. You should really overwrite
1678 * this method with your own hash code generator code. But keep KISS in mind.
1680 * @return $hashCode A generic hash code respresenting this whole class
1682 public function hashCode () {
1684 return crc32($this->__toString());
1688 * Formats computer generated price values into human-understandable formats
1689 * with thousand and decimal separators.
1691 * @param $value The in computer format value for a price
1692 * @param $currency The currency symbol (use HTML-valid characters!)
1693 * @param $decNum Number of decimals after commata
1694 * @return $price The for the current language formated price string
1695 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1696 * thousands separator
1699 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1700 // Are all required attriutes set?
1701 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1702 // Throw an exception
1703 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1707 $value = (float) $value;
1709 // Reformat the US number
1710 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1712 // Return as string...
1717 * Appends a trailing slash to a string
1719 * @param $str A string (maybe) without trailing slash
1720 * @return $str A string with an auto-appended trailing slash
1722 public final function addMissingTrailingSlash ($str) {
1723 // Is there a trailing slash?
1724 if (substr($str, -1, 1) != '/') {
1728 // Return string with trailing slash
1733 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1734 * application helper instance (ApplicationHelper by default).
1736 * @param $applicationInstance An application helper instance or
1737 * null if we shall use the default
1738 * @return $templateInstance The template engine instance
1739 * @throws NullPointerException If the discovered application
1740 * instance is still null
1742 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1743 // Is the application instance set?
1744 if (is_null($applicationInstance)) {
1745 // Get the current instance
1746 $applicationInstance = Registry::getRegistry()->getInstance('app');
1749 if (is_null($applicationInstance)) {
1750 // Thrown an exception
1751 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1755 // Initialize the template engine
1756 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1758 // Return the prepared instance
1759 return $templateInstance;
1763 * Debugs this instance by putting out it's full content
1765 * @param $message Optional message to show in debug output
1768 public final function debugInstance ($message = '') {
1769 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1770 restore_error_handler();
1775 // Is a message set?
1776 if (!empty($message)) {
1777 // Construct message
1778 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1781 // Generate the output
1782 $content .= sprintf('<pre>%s</pre>',
1785 print_r($this, true)
1791 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">%s debug output:</div><div class="debug_content">%s</div>Loaded includes: <div class="debug_include_list">%s</div>',
1792 $this->__toString(),
1794 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1799 * Replaces control characters with printable output
1801 * @param $str String with control characters
1802 * @return $str Replaced string
1804 protected function replaceControlCharacters ($str) {
1807 chr(13), '[r]', str_replace(
1808 chr(10), '[n]', str_replace(
1818 * Output a partial stub message for the caller method
1820 * @param $message An optional message to display
1823 protected function partialStub ($message = '') {
1824 // Get the backtrace
1825 $backtrace = debug_backtrace();
1827 // Generate the class::method string
1828 $methodName = 'UnknownClass->unknownMethod';
1829 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1830 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1833 // Construct the full message
1834 $stubMessage = sprintf('[%s:] Partial stub!',
1838 // Is the extra message given?
1839 if (!empty($message)) {
1840 // Then add it as well
1841 $stubMessage .= ' Message: ' . $message;
1844 // Debug instance is there?
1845 if (!is_null($this->getDebugInstance())) {
1846 // Output stub message
1847 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1850 trigger_error($stubMessage);
1856 * Outputs a debug backtrace and stops further script execution
1858 * @param $message An optional message to output
1859 * @param $doExit Whether exit the program (true is default)
1862 public function debugBackTrace ($message = '', $doExit = true) {
1863 // Sorry, there is no other way getting this nice backtrace
1864 if (!empty($message)) {
1866 printf('Message: %s<br />' . PHP_EOL, $message);
1870 debug_print_backtrace();
1874 if ($doExit === true) {
1880 * Creates an instance of a debugger instance
1882 * @param $className Name of the class (currently unsupported)
1883 * @param $lineNumber Line number where the call was made
1884 * @return $debugInstance An instance of a debugger class
1885 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1887 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1888 // Is the instance set?
1889 if (!Registry::getRegistry()->instanceExists('debug')) {
1890 // Init debug instance
1891 $debugInstance = NULL;
1895 // Get a debugger instance
1896 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1897 } catch (NullPointerException $e) {
1898 // Didn't work, no instance there
1899 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1902 // Empty string should be ignored and used for testing the middleware
1903 DebugMiddleware::getSelfInstance()->output('');
1905 // Set it in its own class. This will set it in the registry
1906 $debugInstance->setDebugInstance($debugInstance);
1908 // Get instance from registry
1909 $debugInstance = Registry::getRegistry()->getDebugInstance();
1913 return $debugInstance;
1917 * Simple output of a message with line-break
1919 * @param $message Message to output
1922 public function outputLine ($message) {
1924 print($message . PHP_EOL);
1928 * Outputs a debug message whether to debug instance (should be set!) or
1929 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1930 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1932 * @param $message Message we shall send out...
1933 * @param $doPrint Whether print or die here (default: print)
1934 * @paran $stripTags Whether to strip tags (default: false)
1937 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1938 // Set debug instance to NULL
1939 $debugInstance = NULL;
1943 // Get debug instance
1944 $debugInstance = $this->getDebugInstance();
1945 } catch (NullPointerException $e) {
1946 // The debug instance is not set (yet)
1949 // Is the debug instance there?
1950 if (is_object($debugInstance)) {
1951 // Use debug output handler
1952 $debugInstance->output($message, $stripTags);
1954 if ($doPrint === false) {
1955 // Die here if not printed
1959 // Are debug times enabled?
1960 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1962 $message = $this->getPrintableExecutionTime() . $message;
1966 if ($doPrint === true) {
1968 $this->outputLine($message);
1977 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1979 * @param $str The string, what ever it is needs to be converted
1980 * @return $className Generated class name
1982 public static final function convertToClassName ($str) {
1986 // Convert all dashes in underscores
1987 $str = self::convertDashesToUnderscores($str);
1989 // Now use that underscores to get classname parts for hungarian style
1990 foreach (explode('_', $str) as $strPart) {
1991 // Make the class name part lower case and first upper case
1992 $className .= ucfirst(strtolower($strPart));
1995 // Return class name
2000 * Converts dashes to underscores, e.g. useable for configuration entries
2002 * @param $str The string with maybe dashes inside
2003 * @return $str The converted string with no dashed, but underscores
2005 public static final function convertDashesToUnderscores ($str) {
2007 $str = str_replace('-', '_', $str);
2009 // Return converted string
2014 * Marks up the code by adding e.g. line numbers
2016 * @param $phpCode Unmarked PHP code
2017 * @return $markedCode Marked PHP code
2019 public function markupCode ($phpCode) {
2024 $errorArray = error_get_last();
2026 // Init the code with error message
2027 if (is_array($errorArray)) {
2029 $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>',
2030 basename($errorArray['file']),
2031 $errorArray['line'],
2032 $errorArray['message'],
2037 // Add line number to the code
2038 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2040 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2042 htmlentities($code, ENT_QUOTES)
2051 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2052 * beatiful for web-based front-ends. If null is given a message id
2053 * null_timestamp will be resolved and returned.
2055 * @param $timestamp Timestamp to prepare (filter) for display
2056 * @return $readable A readable timestamp
2058 public function doFilterFormatTimestamp ($timestamp) {
2059 // Default value to return
2062 // Is the timestamp null?
2063 if (is_null($timestamp)) {
2064 // Get a message string
2065 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2067 switch ($this->getLanguageInstance()->getLanguageCode()) {
2068 case 'de': // German format is a bit different to default
2069 // Split the GMT stamp up
2070 $dateTime = explode(' ', $timestamp );
2071 $dateArray = explode('-', $dateTime[0]);
2072 $timeArray = explode(':', $dateTime[1]);
2074 // Construct the timestamp
2075 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2085 default: // Default is pass-through
2086 $readable = $timestamp;
2096 * Filter a given number into a localized number
2098 * @param $value The raw value from e.g. database
2099 * @return $localized Localized value
2101 public function doFilterFormatNumber ($value) {
2102 // Generate it from config and localize dependencies
2103 switch ($this->getLanguageInstance()->getLanguageCode()) {
2104 case 'de': // German format is a bit different to default
2105 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2108 default: // US, etc.
2109 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2118 * "Getter" for databse entry
2120 * @return $entry An array with database entries
2121 * @throws NullPointerException If the database result is not found
2122 * @throws InvalidDatabaseResultException If the database result is invalid
2124 protected final function getDatabaseEntry () {
2125 // Is there an instance?
2126 if (!$this->getResultInstance() instanceof SearchableResult) {
2127 // Throw an exception here
2128 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2132 $this->getResultInstance()->rewind();
2134 // Do we have an entry?
2135 if ($this->getResultInstance()->valid() === false) {
2136 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2137 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2141 $this->getResultInstance()->next();
2144 $entry = $this->getResultInstance()->current();
2151 * Getter for field name
2153 * @param $fieldName Field name which we shall get
2154 * @return $fieldValue Field value from the user
2155 * @throws NullPointerException If the result instance is null
2157 public final function getField ($fieldName) {
2158 // Default field value
2161 // Get result instance
2162 $resultInstance = $this->getResultInstance();
2164 // Is this instance null?
2165 if (is_null($resultInstance)) {
2166 // Then the user instance is no longer valid (expired cookies?)
2167 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2170 // Get current array
2171 $fieldArray = $resultInstance->current();
2172 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2174 // Convert dashes to underscore
2175 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2177 // Does the field exist?
2178 if ($this->isFieldSet($fieldName)) {
2180 $fieldValue = $fieldArray[$fieldName2];
2181 } elseif (defined('DEVELOPER')) {
2182 // Missing field entry, may require debugging
2183 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2185 // Missing field entry, may require debugging
2186 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2194 * Checks if given field is set
2196 * @param $fieldName Field name to check
2197 * @return $isSet Whether the given field name is set
2198 * @throws NullPointerException If the result instance is null
2200 public function isFieldSet ($fieldName) {
2201 // Get result instance
2202 $resultInstance = $this->getResultInstance();
2204 // Is this instance null?
2205 if (is_null($resultInstance)) {
2206 // Then the user instance is no longer valid (expired cookies?)
2207 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2210 // Get current array
2211 $fieldArray = $resultInstance->current();
2212 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2214 // Convert dashes to underscore
2215 $fieldName = self::convertDashesToUnderscores($fieldName);
2218 $isSet = isset($fieldArray[$fieldName]);
2225 * Flushs all pending updates to the database layer
2229 public function flushPendingUpdates () {
2230 // Get result instance
2231 $resultInstance = $this->getResultInstance();
2233 // Do we have data to update?
2234 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2235 // Get wrapper class name config entry
2236 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2238 // Create object instance
2239 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2241 // Yes, then send the whole result to the database layer
2242 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2247 * Outputs a deprecation warning to the developer.
2249 * @param $message The message we shall output to the developer
2251 * @todo Write a logging mechanism for productive mode
2253 public function deprecationWarning ($message) {
2254 // Is developer mode active?
2255 if (defined('DEVELOPER')) {
2256 // Debug instance is there?
2257 if (!is_null($this->getDebugInstance())) {
2258 // Output stub message
2259 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2262 trigger_error($message . "<br />\n");
2266 // @TODO Finish this part!
2267 $this->partialStub('Developer mode inactive. Message:' . $message);
2272 * Checks whether the given PHP extension is loaded
2274 * @param $phpExtension The PHP extension we shall check
2275 * @return $isLoaded Whether the PHP extension is loaded
2277 public final function isPhpExtensionLoaded ($phpExtension) {
2279 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2286 * "Getter" as a time() replacement but with milliseconds. You should use this
2287 * method instead of the encapsulated getimeofday() function.
2289 * @return $milliTime Timestamp with milliseconds
2291 public function getMilliTime () {
2292 // Get the time of day as float
2293 $milliTime = gettimeofday(true);
2300 * Idles (sleeps) for given milliseconds
2302 * @return $hasSlept Whether it goes fine
2304 public function idle ($milliSeconds) {
2305 // Sleep is fine by default
2308 // Idle so long with found function
2309 if (function_exists('time_sleep_until')) {
2310 // Get current time and add idle time
2311 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2313 // New PHP 5.1.0 function found, ignore errors
2314 $hasSlept = @time_sleep_until($sleepUntil);
2317 * My Sun station doesn't have that function even with latest PHP
2320 usleep($milliSeconds * 1000);
2327 * Converts a hexadecimal string, even with negative sign as first string to
2328 * a decimal number using BC functions.
2330 * This work is based on comment #86673 on php.net documentation page at:
2331 * <http://de.php.net/manual/en/function.dechex.php#86673>
2333 * @param $hex Hexadecimal string
2334 * @return $dec Decimal number
2336 protected function hex2dec ($hex) {
2337 // Convert to all lower-case
2338 $hex = strtolower($hex);
2340 // Detect sign (negative/positive numbers)
2342 if (substr($hex, 0, 1) == '-') {
2344 $hex = substr($hex, 1);
2347 // Decode the hexadecimal string into a decimal number
2349 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2350 $factor = self::$hexdec[substr($hex, $i, 1)];
2351 $dec = bcadd($dec, bcmul($factor, $e));
2354 // Return the decimal number
2355 return $sign . $dec;
2359 * Converts even very large decimal numbers, also signed, to a hexadecimal
2362 * This work is based on comment #97756 on php.net documentation page at:
2363 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2365 * @param $dec Decimal number, even with negative sign
2366 * @param $maxLength Optional maximum length of the string
2367 * @return $hex Hexadecimal string
2369 protected function dec2hex ($dec, $maxLength = 0) {
2370 // maxLength can be zero or devideable by 2
2371 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2373 // Detect sign (negative/positive numbers)
2380 // Encode the decimal number into a hexadecimal string
2383 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2385 } while ($dec >= 1);
2388 * Leading zeros are required for hex-decimal "numbers". In some
2389 * situations more leading zeros are wanted, so check for both
2392 if ($maxLength > 0) {
2393 // Prepend more zeros
2394 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2395 } elseif ((strlen($hex) % 2) != 0) {
2396 // Only make string's length dividable by 2
2400 // Return the hexadecimal string
2401 return $sign . $hex;
2405 * Converts a ASCII string (0 to 255) into a decimal number.
2407 * @param $asc The ASCII string to be converted
2408 * @return $dec Decimal number
2410 protected function asc2dec ($asc) {
2411 // Convert it into a hexadecimal number
2412 $hex = bin2hex($asc);
2414 // And back into a decimal number
2415 $dec = $this->hex2dec($hex);
2422 * Converts a decimal number into an ASCII string.
2424 * @param $dec Decimal number
2425 * @return $asc An ASCII string
2427 protected function dec2asc ($dec) {
2428 // First convert the number into a hexadecimal string
2429 $hex = $this->dec2hex($dec);
2431 // Then convert it into the ASCII string
2432 $asc = $this->hex2asc($hex);
2439 * Converts a hexadecimal number into an ASCII string. Negative numbers
2442 * @param $hex Hexadecimal string
2443 * @return $asc An ASCII string
2445 protected function hex2asc ($hex) {
2446 // Check for length, it must be devideable by 2
2447 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2448 assert((strlen($hex) % 2) == 0);
2452 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2453 // Get the decimal number of the chunk
2454 $part = hexdec(substr($hex, $idx, 2));
2456 // Add it to the final string
2460 // Return the final string
2465 * Checks whether the given encoded data was encoded with Base64
2467 * @param $encodedData Encoded data we shall check
2468 * @return $isBase64 Whether the encoded data is Base64
2470 protected function isBase64Encoded ($encodedData) {
2472 $isBase64 = (@base64_decode($encodedData, true) !== false);
2479 * Gets a cache key from Criteria instance
2481 * @param $criteriaInstance An instance of a Criteria class
2482 * @param $onlyKeys Only use these keys for a cache key
2483 * @return $cacheKey A cache key suitable for lookup/storage purposes
2485 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2487 $cacheKey = sprintf('%s@%s',
2488 $this->__toString(),
2489 $criteriaInstance->getCacheKey($onlyKeys)
2493 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2498 * Getter for startup time in miliseconds
2500 * @return $startupTime Startup time in miliseconds
2502 protected function getStartupTime () {
2503 return self::$startupTime;
2507 * "Getter" for a printable currently execution time in nice braces
2509 * @return $executionTime Current execution time in nice braces
2511 protected function getPrintableExecutionTime () {
2512 // Caculate the execution time
2513 $executionTime = microtime(true) - $this->getStartupTime();
2515 // Pack it in nice braces
2516 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2519 return $executionTime;
2523 * Hashes a given string with a simple but stronger hash function (no salt)
2524 * and hex-encode it.
2526 * @param $str The string to be hashed
2527 * @return $hash The hash from string $str
2529 public static final function hash ($str) {
2530 // Hash given string with (better secure) hasher
2531 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2538 * "Getter" for length of hash() output. This will be "cached" to speed up
2541 * @return $length Length of hash() output
2543 public static final function getHashLength () {
2545 if (is_null(self::$hashLength)) {
2546 // No, then hash a string and save its length.
2547 self::$hashLength = strlen(self::hash('abc123'));
2551 return self::$hashLength;
2555 * Checks whether the given number is really a number (only chars 0-9).
2557 * @param $num A string consisting only chars between 0 and 9
2558 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2559 * @param $assertMismatch Whether to assert mismatches
2560 * @return $ret The (hopefully) secured numbered value
2562 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2563 // Filter all numbers out
2564 $ret = preg_replace('/[^0123456789]/', '', $num);
2567 if ($castValue === true) {
2568 // Cast to biggest numeric type
2569 $ret = (double) $ret;
2572 // Assert only if requested
2573 if ($assertMismatch === true) {
2574 // Has the whole value changed?
2575 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2583 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2585 * @param $num A string consisting only chars between 0 and 9
2586 * @param $assertMismatch Whether to assert mismatches
2587 * @return $ret The (hopefully) secured hext-numbered value
2589 public function hexval ($num, $assertMismatch = false) {
2590 // Filter all numbers out
2591 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2593 // Assert only if requested
2594 if ($assertMismatch === true) {
2595 // Has the whole value changed?
2596 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2604 * Checks whether start/end marker are set
2606 * @param $data Data to be checked
2607 * @return $isset Whether start/end marker are set
2609 public final function ifStartEndMarkersSet ($data) {
2611 $isset = ((substr($data, 0, strlen(BaseRawDataHandler::STREAM_START_MARKER)) == BaseRawDataHandler::STREAM_START_MARKER) && (substr($data, -1 * strlen(BaseRawDataHandler::STREAM_END_MARKER), strlen(BaseRawDataHandler::STREAM_END_MARKER)) == BaseRawDataHandler::STREAM_END_MARKER));
2613 // ... and return it
2618 * Determines if an element is set in the generic array
2620 * @param $keyGroup Main group for the key
2621 * @param $subGroup Sub group for the key
2622 * @param $key Key to check
2623 * @param $element Element to check
2624 * @return $isset Whether the given key is set
2626 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2628 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2631 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2637 * Determines if a key is set in the generic array
2639 * @param $keyGroup Main group for the key
2640 * @param $subGroup Sub group for the key
2641 * @param $key Key to check
2642 * @return $isset Whether the given key is set
2644 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2646 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2649 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2657 * Determines if a group is set in the generic array
2659 * @param $keyGroup Main group
2660 * @param $subGroup Sub group
2661 * @return $isset Whether the given group is set
2663 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2665 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2668 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2675 * Getter for sub key group
2677 * @param $keyGroup Main key group
2678 * @param $subGroup Sub key group
2679 * @return $array An array with all array elements
2681 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2683 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2684 // No, then abort here
2685 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2690 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2693 return $this->genericArray[$keyGroup][$subGroup];
2697 * Unsets a given key in generic array
2699 * @param $keyGroup Main group for the key
2700 * @param $subGroup Sub group for the key
2701 * @param $key Key to unset
2704 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2706 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2709 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2713 * Unsets a given element in generic array
2715 * @param $keyGroup Main group for the key
2716 * @param $subGroup Sub group for the key
2717 * @param $key Key to unset
2718 * @param $element Element to unset
2721 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2723 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2726 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2730 * Append a string to a given generic array key
2732 * @param $keyGroup Main group for the key
2733 * @param $subGroup Sub group for the key
2734 * @param $key Key to unset
2735 * @param $value Value to add/append
2738 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2740 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true) . ',appendGlue=' . $appendGlue);
2742 // Is it already there?
2743 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2745 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2748 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2753 * Append a string to a given generic array element
2755 * @param $keyGroup Main group for the key
2756 * @param $subGroup Sub group for the key
2757 * @param $key Key to unset
2758 * @param $element Element to check
2759 * @param $value Value to add/append
2762 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2764 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true) . ',appendGlue=' . $appendGlue);
2766 // Is it already there?
2767 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2769 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2772 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2777 * Sets a string in a given generic array element
2779 * @param $keyGroup Main group for the key
2780 * @param $subGroup Sub group for the key
2781 * @param $key Key to unset
2782 * @param $element Element to check
2783 * @param $value Value to add/append
2786 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2788 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true) . ',appendGlue=' . $appendGlue);
2791 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2795 * Initializes given generic array group
2797 * @param $keyGroup Main group for the key
2798 * @param $subGroup Sub group for the key
2799 * @param $key Key to use
2800 * @param $forceInit Optionally force initialization
2803 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2805 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2807 // Is it already set?
2808 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2809 // Already initialized
2810 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2815 $this->genericArray[$keyGroup][$subGroup] = array();
2819 * Initializes given generic array key
2821 * @param $keyGroup Main group for the key
2822 * @param $subGroup Sub group for the key
2823 * @param $key Key to use
2824 * @param $forceInit Optionally force initialization
2827 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2829 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2831 // Is it already set?
2832 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2833 // Already initialized
2834 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2839 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2843 * Initializes given generic array element
2845 * @param $keyGroup Main group for the key
2846 * @param $subGroup Sub group for the key
2847 * @param $key Key to use
2848 * @param $element Element to use
2849 * @param $forceInit Optionally force initialization
2852 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2854 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2856 // Is it already set?
2857 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2858 // Already initialized
2859 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2864 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2868 * Pushes an element to a generic key
2870 * @param $keyGroup Main group for the key
2871 * @param $subGroup Sub group for the key
2872 * @param $key Key to use
2873 * @param $value Value to add/append
2874 * @return $count Number of array elements
2876 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2878 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2881 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2883 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2887 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2890 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2891 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2896 * Pushes an element to a generic array element
2898 * @param $keyGroup Main group for the key
2899 * @param $subGroup Sub group for the key
2900 * @param $key Key to use
2901 * @param $element Element to check
2902 * @param $value Value to add/append
2903 * @return $count Number of array elements
2905 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2907 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true));
2910 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2912 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2916 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2919 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2920 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2925 * Pops an element from a generic group
2927 * @param $keyGroup Main group for the key
2928 * @param $subGroup Sub group for the key
2929 * @param $key Key to unset
2930 * @return $value Last "popped" value
2932 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2934 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2937 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2939 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2944 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2947 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2948 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2953 * Shifts an element from a generic group
2955 * @param $keyGroup Main group for the key
2956 * @param $subGroup Sub group for the key
2957 * @param $key Key to unset
2958 * @return $value Last "popped" value
2960 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2962 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2965 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2967 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2972 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2975 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2976 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2981 * Count generic array group
2983 * @param $keyGroup Main group for the key
2984 * @return $count Count of given group
2986 protected final function countGenericArray ($keyGroup) {
2988 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2991 if (!isset($this->genericArray[$keyGroup])) {
2993 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2998 $count = count($this->genericArray[$keyGroup]);
3001 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3008 * Count generic array sub group
3010 * @param $keyGroup Main group for the key
3011 * @param $subGroup Sub group for the key
3012 * @return $count Count of given group
3014 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3016 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3019 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3021 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3026 $count = count($this->genericArray[$keyGroup][$subGroup]);
3029 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3036 * Count generic array elements
3038 * @param $keyGroup Main group for the key
3039 * @param $subGroup Sub group for the key
3040 * @para $key Key to count
3041 * @return $count Count of given key
3043 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3045 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3048 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3050 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3052 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3054 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3059 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3062 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3069 * Getter for whole generic group array
3071 * @param $keyGroup Key group to get
3072 * @return $array Whole generic array group
3074 protected final function getGenericArray ($keyGroup) {
3076 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3079 if (!isset($this->genericArray[$keyGroup])) {
3081 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3086 return $this->genericArray[$keyGroup];
3090 * Setter for generic array key
3092 * @param $keyGroup Key group to get
3093 * @param $subGroup Sub group for the key
3094 * @param $key Key to unset
3095 * @param $value Mixed value from generic array element
3098 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3100 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3103 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3107 * Getter for generic array key
3109 * @param $keyGroup Key group to get
3110 * @param $subGroup Sub group for the key
3111 * @param $key Key to unset
3112 * @return $value Mixed value from generic array element
3114 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3116 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3119 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3121 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3126 return $this->genericArray[$keyGroup][$subGroup][$key];
3130 * Sets a value in given generic array key/element
3132 * @param $keyGroup Main group for the key
3133 * @param $subGroup Sub group for the key
3134 * @param $key Key to set
3135 * @param $element Element to set
3136 * @param $value Value to set
3139 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3141 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true));
3144 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3148 * Getter for generic array element
3150 * @param $keyGroup Key group to get
3151 * @param $subGroup Sub group for the key
3152 * @param $key Key to look for
3153 * @param $element Element to look for
3154 * @return $value Mixed value from generic array element
3156 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3158 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3161 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3163 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3168 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3172 * Checks if a given sub group is valid (array)
3174 * @param $keyGroup Key group to get
3175 * @param $subGroup Sub group for the key
3176 * @return $isValid Whether given sub group is valid
3178 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3180 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3183 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3190 * Checks if a given key is valid (array)
3192 * @param $keyGroup Key group to get
3193 * @param $subGroup Sub group for the key
3194 * @param $key Key to check
3195 * @return $isValid Whether given sub group is valid
3197 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3199 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3202 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3209 * Initializes the web output instance
3213 protected function initWebOutputInstance () {
3214 // Get application instance
3215 $applicationInstance = Registry::getRegistry()->getInstance('app');
3217 // Init web output instance
3218 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3221 $this->setWebOutputInstance($outputInstance);
3225 * Translates boolean true to 'Y' and false to 'N'
3227 * @param $boolean Boolean value
3228 * @return $translated Translated boolean value
3230 public static final function translateBooleanToYesNo ($boolean) {
3231 // Make sure it is really boolean
3232 assert(is_bool($boolean));
3235 $translated = ($boolean === true) ? 'Y' : 'N';
3237 // ... and return it
3242 * Encodes raw data (almost any type) by "serializing" it and then pack it
3243 * into a "binary format".
3245 * @param $rawData Raw data (almost any type)
3246 * @return $encoded Encoded data
3248 protected function encodeData ($rawData) {
3249 // Make sure no objects or resources pass through
3250 assert(!is_object($rawData));
3251 assert(!is_resource($rawData));
3253 // First "serialize" it (json_encode() is faster than serialize())
3254 $encoded = $this->packString(json_encode($rawData));
3261 * Pack a string into a "binary format". Please execuse me that this is
3262 * widely undocumented. :-(
3264 * @param $str Unpacked string
3265 * @return $packed Packed string
3266 * @todo Improve documentation
3268 protected function packString ($str) {
3270 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3272 // First compress the string (gzcompress is okay)
3273 $str = gzcompress($str);
3278 // And start the "encoding" loop
3279 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3281 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3282 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3284 if (($idx + $i) <= strlen($str)) {
3285 $ord = ord(substr($str, ($idx + $i), 1));
3287 $add = $ord * pow(256, $factor);
3291 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3295 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3296 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3298 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3299 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3305 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3310 * Creates a full-qualified file name (FQFN) for given file name by adding
3311 * a configured temporary file path to it.
3313 * @param $fileName Name for temporary file
3314 * @return $fqfn Full-qualified file name
3315 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3316 * @throws FileIoException If the file cannot be written
3318 protected static function createTempPathForFile ($fileName) {
3320 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3322 // Is the path writeable?
3323 if (!is_writable($basePath)) {
3324 // Path is write-protected
3325 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3329 $fqfn = $basePath . '/' . $fileName;
3332 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3334 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3342 * "Getter" for a printable state name
3344 * @return $stateName Name of the node's state in a printable format
3346 public final function getPrintableState () {
3347 // Default is 'null'
3348 $stateName = 'null';
3350 // Get the state instance
3351 $stateInstance = $this->getStateInstance();
3353 // Is it an instance of Stateable?
3354 if ($stateInstance instanceof Stateable) {
3355 // Then use that state name
3356 $stateName = $stateInstance->getStateName();
3364 * Handles socket error for given socket resource and peer data. This method
3365 * validates $socketResource if it is a valid resource (see is_resource())
3366 * but assumes valid data in array $recipientData, except that
3367 * count($recipientData) is always 2.
3369 * @param $method Value of __METHOD__ from calling method
3370 * @param $line Value of __LINE__ from calling method
3371 * @param $socketResource A valid socket resource
3372 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3374 * @throws InvalidSocketException If $socketResource is no socket resource
3375 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3376 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3378 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3379 // This method handles only socket resources
3380 if (!is_resource($socketResource)) {
3381 // No resource, abort here
3382 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3385 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3386 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, true));
3387 assert(isset($socketData[0]));
3388 assert(isset($socketData[1]));
3390 // Get error code for first validation (0 is not an error)
3391 $errorCode = socket_last_error($socketResource);
3393 // If the error code is zero, someone called this method without an error
3394 if ($errorCode == 0) {
3395 // No error detected (or previously cleared outside this method)
3396 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3399 // Get handler (method) name
3400 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3402 // Call-back the error handler method
3403 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3405 // Finally clear the error because it has been handled
3406 socket_clear_error($socketResource);