* - Initial release
* ----------------------------------
*/
-class ClassLoader {
+final class ClassLoader {
/**
* Instance of this class
*/
private static $selfInstance = NULL;
/**
- * Array with all found classes
+ * Array with all valid but pending for loading file names (class,
+ * interfaces, traits must start with below prefix).
*/
- private $foundClasses = [];
+ private $pendingFiles = [];
/**
* List of loaded classes
// Skip here if already cached
if ($this->listCached === false) {
// Writes the cache file of our list away
- $cacheContent = json_encode($this->foundClasses);
+ $cacheContent = json_encode($this->pendingFiles);
// Open cache instance
$fileObject = $this->listCacheFile->openFile('w');
//* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$loaderInstance = self::getSelfInstance();
- // "Cache" configuration instance
+ // "Cache" configuration instance and framework base path
$configInstance = FrameworkBootstrap::getConfigurationInstance();
+ $frameworkBasePath = $configInstance->getConfigEntry('framework_base_path');
// Load all classes
+ //* NOISY-DEBUG: */ printf('[%s:%d]: frameworkBasePath=%s,self::$frameworkPaths()=%d,' . PHP_EOL, __METHOD__, __LINE__, $frameworkBasePath, count(self::$frameworkPaths));
foreach (self::$frameworkPaths as $shortPath) {
// Generate full path from it
- //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
+ //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($shortPath), $shortPath);
$realPathName = realpath(sprintf(
'%smain%s%s%s',
- $configInstance->getConfigEntry('framework_base_path'),
+ $frameworkBasePath,
DIRECTORY_SEPARATOR,
$shortPath,
DIRECTORY_SEPARATOR
));
// Is it not false and accessible?
- //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName=%s' . PHP_EOL, __METHOD__, __LINE__, $realPathName);
+ //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
if (is_bool($realPathName)) {
- // Skip this
+ // Skip this, it is not accessible
continue;
} elseif (!is_readable($realPathName)) {
// @TODO Throw exception instead of break
* @return void
*/
public static function scanTestsClasses () {
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
-
// "Cache" configuration instance
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$configInstance = FrameworkBootstrap::getConfigurationInstance();
// Load all classes for the application
foreach (self::$testPaths as $shortPath) {
- // Debug message
- //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
-
// Construct path name
+ //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
$pathName = sprintf(
'%s%s%s',
$configInstance->getConfigEntry('root_base_path'),
* @throws InvalidArgumentException If the class' name does not contain a namespace: Tld\Domain\Project is AT LEAST recommended!
*/
public static function autoLoad (string $className) {
- // The class name should contain at least 2 back-slashes, so split at them
+ // Validate parameter
//* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
+ if (empty($className)) {
+ // Should not be empty
+ throw new InvalidArgumentException('Parameter "className" is empty');
+ }
+
+ // The class name MUST be at least Tld\Domain\Project\Package\SomeFooBar so split at them
$classNameParts = explode("\\", $className);
// At least 3 parts should be there
if ((self::$strictNamingConvention === true) && (count($classNameParts) < 5)) {
- // Namespace scheme is: Project\Package[\SubPackage...]
+ // Namespace scheme is: Tld\Domain\Project\Package[\SubPackage...]
throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $className));
}
// Try to include this class
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Calling self->loadClassFile(%s) ...' . PHP_EOL, __METHOD__, __LINE__, $className);
self::getSelfInstance()->loadClassFile($className);
// Trace message
*/
protected function scanClassPath (string $basePath, array $ignoreList = [] ) {
// Is a list has been restored from cache, don't read it again
+ /* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s,ignoreList()=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $basePath, count($ignoreList));
if ($this->listCached === true) {
// Abort here
+ /* NOISY-DEBUG: */ printf('[%s:%d] this->listCache=true - EXIT!' . PHP_EOL, __METHOD__, __LINE__);
return;
}
// Keep it in class for later usage
$this->ignoreList = $ignoreList;
- /*
- * Ignore .htaccess by default as it is for protection of directories
- * on Apache servers.
- *
- * @deprecated
- */
- array_push($ignoreList, '.htaccess');
-
/*
* Set base directory which holds all our classes, an absolute path
* should be used here so is_dir(), is_file() and so on will always
$basePath2 = realpath($basePath);
// If the basePath is false it is invalid
+ /* NOISY-DEBUG: */ printf('[%s:%d] basePath2[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($basePath2), $basePath2);
if ($basePath2 === false) {
/* @TODO: Do not exit here. */
exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
$iteratorInstance->next();
// Skip non-file entries
- //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
continue;
}
// Is this file wanted?
- //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
// Add it to the list
- //* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
- $this->foundClasses[$fileName] = $currentEntry;
+ //* NOISY-DEBUG: */ printf('[%s:%d] ADD: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
+ $this->pendingFiles[$fileName] = $currentEntry;
} else {
// Not added
- //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
+ //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
}
// Advance to next entry
- //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
$iteratorInstance->next();
}
}
// Is the cache there?
if (FrameworkBootstrap::isReadableFile($this->listCacheFile)) {
// Load and convert it
- $this->foundClasses = json_decode(file_get_contents($this->listCacheFile->getPathname()));
+ $this->pendingFiles = json_decode(file_get_contents($this->listCacheFile->getPathname()));
// List has been restored from cache!
$this->listCached = true;
}
/**
- * Tries to find the given class in our list. This method ignores silently
- * missing classes or interfaces. So if you use class_exists() this method
- * does not interrupt your program.
+ * Tries to find the given class in our list. It will ignore already loaded
+ * (to the program available) class/interface/trait files. But you SHOULD
+ * save below "expensive" code by pre-checking this->loadedClasses[], if
+ * possible.
*
* @param $className The class that shall be loaded
* @return void
$fileName = sprintf('%s%s%s', $this->prefix, $shortClassName, $this->suffix);
// Now look it up in our index
- //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
- if ((isset($this->foundClasses[$fileName])) && (!isset($this->loadedClasses[$this->foundClasses[$fileName]->getPathname()]))) {
+ //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ if ((isset($this->pendingFiles[$fileName])) && (!isset($this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()]))) {
// File is found and not loaded so load it only once
- //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
- FrameworkBootstrap::loadInclude($this->foundClasses[$fileName]);
- //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ FrameworkBootstrap::loadInclude($this->pendingFiles[$fileName]);
+ //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
// Count this loaded class/interface/exception
$this->total++;
// Mark this class as loaded for other purposes than loading it.
- $this->loadedClasses[$this->foundClasses[$fileName]->getPathname()] = true;
+ $this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()] = true;
// Remove it from classes list so it won't be found twice.
- //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
- unset($this->foundClasses[$fileName]);
+ //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ unset($this->pendingFiles[$fileName]);
// Developer mode excludes caching (better debugging)
if (!FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
}
} else {
// Not found
- //* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ //* NOISY-DEBUG: */ printf('[%s:%d] 404: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
}
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d] EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
}
// Execute *very* generic post filters
$this->executePostFilters($requestInstance, $responseInstance);
- } // END - if
+ }
// Flush the buffer out
$responseInstance->flushBuffer();
if (!isset($this->filterChains[$filterChain])) {
// Throw an exception here
throw new InvalidFilterChainException(array($this, $filterChain), self::EXCEPTION_FILTER_CHAIN_INVALID);
- } // END - if
+ }
// Add the filter
$this->filterChains[$filterChain]->addFilter($filterInstance);
if (!isset($this->filterChains[$filterChain])) {
// Throw an exception here
throw new InvalidFilterChainException(array($this, $filterChain), self::EXCEPTION_FILTER_CHAIN_INVALID);
- } // END - if
+ }
// Run all filters
$this->filterChains[$filterChain]->processFilters($requestInstance, $responseInstance);
if ($this->isKeySet($criteriaType, $criteriaKey)) {
// Then use it
$value = $this->getGenericArrayElement('criteria', $criteriaType, 'entries', $criteriaKey);
- } // END - if
+ }
// Return the value
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($criteriaType) . '-CRITERIA: value=' . $value . ' - EXIT!');
if (($key == $criteriaKey) && ($criteriaValue == $entry)) {
// Then count this one up
$counted++;
- } // END - if
+ }
} // END - foreach
} // END - foreach
$criteriaKey,
urlencode($criteriaValue)
);
- } // END - if
+ }
} // END - foreach
// Remove last semicolon
$this->getLimit(),
$this->getSkip()
);
- } // END - if
- } // END - if
+ }
+ }
// Return the cache key
return $cacheKey;
if (empty($primaryKey)) {
// Get uniqueKey
$primaryKey = $this->getUniqueKey();
- } // END - if
+ }
// Return it
return $primaryKey;
// Stop here
throw new UserAuthorizationException($this, self::EXCEPTION_AUTH_DATA_INVALID);
- } // END - if
+ }
// Regular user account
$className = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_class');
// Set class
$className = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('guest_class');
$methodName = 'createGuestByUserName';
- } // END - if
+ }
// Does the guest class exist?
if (!class_exists($className)) {
// Then abort here
throw new NoClassException (array($this, $className), self::EXCEPTION_CLASS_NOT_FOUND);
- } // END - if
+ }
// Now try the dynamic login
$userInstance = call_user_func_array(array($className, $methodName), array($authLogin));
if ($userInstance->getPasswordHash() !== $authHash) {
// Mismatching password
throw new UserPasswordMismatchException(array($this, $userInstance), BaseUser::EXCEPTION_USER_PASS_MISMATCH);
- } // END - if
+ }
// Remember auth and user instances in registry
GenericRegistry::getRegistry()->addInstance('auth', $authInstance);
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Is only second email set?
if ((empty($email1)) && (!empty($email2))) {
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Do both match?
if ($email1 != $email2) {
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Are email and confirmation empty?
if ((empty($email1)) && (empty($email2))) {
// No email change required!
return true;
- } // END - if
+ }
// Now, get a user instance for comparison
$userInstance = GenericRegistry::getRegistry()->getInstance('user');
if ($userEmail == $email1) {
// Nothing has been changed is fine...
return true;
- } // END - if
+ }
// Update the "new_email" field
$this->partialStub('Unfinished part.');
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Is only second pass set?
if ((empty($pass1)) && (!empty($pass2))) {
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Are password and confirmation empty?
if ((empty($pass1)) && (empty($pass2))) {
// Don't change password here
return true;
- } // END - if
+ }
// Do both match?
if ($pass1 != $pass2) {
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Now, get a user instance for comparison
$userInstance = GenericRegistry::getRegistry()->getInstance('user');
// Skip further processing
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
}
}
if ($this->isValidGenericArrayKey('filters', 'generic', 'dummy')) {
// Then get them
$filters = $this->getGenericArrayKey('filters', 'generic', 'dummy');
- } // END - if
+ }
// Return it
return $filters;
if ($this->isValidGenericArrayKey('filters', 'post', 'dummy')) {
// Then get them
$filters = $this->getGenericArrayKey('filters', 'post', 'dummy');
- } // END - if
+ }
// Return it
return $filters;
// Throw exception
throw new EncryptMissingException($this, CryptoHelper::EXCEPTION_ENCRYPT_MISSING);
- } // END - if
+ }
// Decode it fully
$encryptDecoded = base64_decode(str_replace(' ', '+', urldecode($encryptRequest)));
// Throw exception
throw new EncryptInvalidLengthException($this, CryptoHelper::EXCEPTION_ENCRYPT_INVALID);
- } // END - if
+ }
// Write it to the request
$requestInstance->setRequestElement('decrypted', $decryptedString);
// Then set the password to the configured password
$requestInstance->setRequestElement('pass1', FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('guest_login_passwd'));
$requestInstance->setRequestElement('pass2', FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('guest_login_passwd'));
- } // END - if
+ }
}
}
if (is_null($resolverInstance)) {
// Throw an exception here
throw new NullPointerException($filterInstance, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
+ }
// Get the action name from resolver
$actionName = $resolverInstance->getActionName();
if (empty($email1)) {
// Add a message to the response
$responseInstance->addFatalMessage('email1_empty');
- } // END - if
+ }
// Is the confirmation empty?
if (empty($email2)) {
// Add a message to the response
$responseInstance->addFatalMessage('email2_empty');
- } // END - if
+ }
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
if (empty($password1)) {
// Add a message to the response
$responseInstance->addFatalMessage('pass1_empty');
- } // END - if
+ }
// Is the confirmation empty?
if (empty($password2)) {
// Add a message to the response
$responseInstance->addFatalMessage('pass2_empty');
- } // END - if
+ }
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
if ((is_null($userInstance)) || ($userInstance->ifUsernameExists() === false)) {
// This username is still available
$alreadyTaken = false;
- } // END - if
+ }
// Return the result
return $alreadyTaken;
if (FrameworkBootstrap::isReadableFile($cacheFile)) {
// Remove it
unlink($cacheFile->getPathname());
- } // END - if
+ }
// Finish the image and send it to a cache file
imagepng($this->getImageResource(), $cacheFile->getPathname(), 9, PNG_ALL_FILTERS);
if ((!empty($templateName)) && ($this->isGenericArrayElementSet('recipients', $templateName, 'generic', 'subject'))) {
// Then use it
$subjectLine = $this->getGenericArrayElement('recipients', $templateName, 'generic', 'subject');
- } // END - if
+ }
// Return it
return $subjectLine;
foreach ($recipientList['config_vars'] as $variable => $dummy) {
// Load the config value and set it
$templateInstance->assignConfigVariable($variable);
- } // END - if
+ }
// Now do the same with the values but ask the "value instance" instead!
foreach ($recipientList['value_vars'] as $variable => $dummy) {
if (!isset($recipientList['values'][$variable])) {
// Throw exception
throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
+ }
// Get the field from the value instance
$fieldValue = $recipientList['values'][$variable]->getField($variable);
if (is_null($key)) {
// None provided
$key = $this->getRngInstance()->generateKey();
- } // END - if
+ }
// Add some "payload" to the string
switch ($this->getRngInstance()->randomNumber(0, 8)) {
if (is_null($key)) {
// Generate (default) key
$key = $this->getRngInstance()->generateKey();
- } // END - if
+ }
// Decrypt the string
$payloadString = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_ECB, $iv);
if (is_null($key)) {
// None provided
$key = $this->getRngInstance()->generateKey();
- } // END - if
+ }
// Add some "payload" to the string
switch ($this->getRngInstance()->randomNumber(0, 8)) {
if (is_null($key)) {
// Generate (default) key
$key = $this->getRngInstance()->generateKey();
- } // END - if
+ }
// Decrypt the string
$payloadString = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_ECB, $iv);
// End here
exit();
- } // END - if
+ }
// Should we log exceptions? (bad implementation)
if (defined('LOG_EXCEPTIONS')) {
$message,
$this->getHexCode()
));
- } // END - if
+ }
}
/**
// Add only non-array elements
if (!is_array($debug)) {
$info .= $debug . ', ';
- } // END - if
+ }
} // END - foreach
// Remove last chars (commata, space)
$info = substr($info, 0, -2);
- } // END - if
+ }
// Prepare argument infos
$info = '<em id="debug_args_' . $dbgIndex . '">' . $info . '</em>';
$file = 'Unknown file';
if (isset($dbgInfo['file'])) {
$file = basename($dbgInfo['file']);
- } // END - if
+ }
// Line detection
$line = 'Unknown line';
if (isset($dbgInfo['line'])) {
$line = 'line ' . $dbgInfo['line'];
- } // END - if
+ }
// The message
$dbgMsg .= "\t at <em id=\"debug_id_".$dbgIndex."\">".$dbgIndex."</em> <em id=\"debug_file_".$dbgIndex."\">".$file."</em> (<em id=\"debug_line_".$dbgIndex."\">".$line."</em>) -> ".$dbgInfo['function'].'('.$info.")<br />\n";
- } // END - if
+ }
// Add end-message
$dbgMsg .= "Debug backtrace end<br />\n";
if ((isset($classArray[2])) && ($classArray[2] instanceof FrameworkInterface)) {
// Get the class name
$extraClassName = $classArray[2]->__toString();
- } // END - if
+ }
// Add a message around the missing class
$message = sprintf('[%s:%d] Method <u>%s()</u> is unsupported or should not be called. extraInstance=%s',
$attributes = '<em>None</em>';
if ((is_array($classArray[2])) && (count($classArray[2]) > 0)) {
$attributes = implode(', ', $classArray[2]);
- } // END - if
+ }
// Construct our message
$message = sprintf('[%s:%d] Invalid XML node found: %s, attributes: %s.',
if (is_null($tempInstance)) {
// Then skip to the next one
continue;
- } // END - if
+ }
// Set the compressor
$compressorInstance->setCompressor($tempInstance);
// No more searches required because we have found a valid compressor stream
break;
- } // END - if
+ }
} // END - while
// Close the directory
$directoryInstance->closeDirectory();
- } // END - if
+ }
// Check again if there is a compressor
if (
// Set the null compressor handler. This should not be configureable!
// @TODO Is there a configurable fall-back compressor needed, or is NullCompressor okay?
$compressorInstance->setCompressor(ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Compressor\Null\NullCompressor'));
- } // END - if
+ }
// Return the compressor instance
return $compressorInstance;
if ($isInitialized === true) {
// Then set class name
$debugInstance->getOutputInstance()->setLoggerClassName($className);
- } // END - if
+ }
// Return instance
return $debugInstance;
if ($objectInstance instanceof FrameworkInterface) {
// Then use this
$className = $objectInstance->__toString();
- } // END - if
+ }
// Prepare output array
$dataArray = array(
<?php
-// Own namespace
-namespace Com\Wds66\Api;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-
-/**
- * Class for connecting to the Wernis-Portal at http://www.wds66.com
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @todo Out-dated since 0.6-BETA
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-class WernisApi extends BaseFrameworkSystem {
- /**
- * Static base API URL
- */
- private static $apiUrl = 'https://www.wds66.com/api/';
-
- /**
- * API Wernis amount
- */
- private $wernis_amount = 0;
-
- /**
- * API username
- */
- private $w_id = 0;
-
- /**
- * API Wernis password (not account password!)
- */
- private $w_md5 = '';
-
- /**
- * Nickname of the user
- */
- private $w_nick = '';
-
- /**
- * Wernis amount of the user
- */
- private $w_amount = 0;
-
- /**
- * Array with status informations
- */
- private $statusArray = array();
-
- /**
- * Status for 'okay'
- */
- private $statusOkay = 'OK';
-
- /**
- * Protected constructor
- *
- * @return void
- */
- private function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this API class
- *
- * @param $configArray Configuration array
- * @return $apiInstance An instance of this API class
- */
- public static final function createWernisApi (array $configArray) {
- // Create a new instance
- $apiInstance = new WernisApi();
-
- // If not an api_url is given (e.g. on local development system)
- if (!isset($configArray['api_url'])) {
- // ... then set the productive URL
- $configArray['api_url'] = self::$apiUrl;
- }
-
- // Konfiguration uebertragen
- $apiInstance->setCoonfigArray($configArray);
-
- // Return the instance
- return $apiInstance;
- }
-
- /**
- * Setter for gamer data
- *
- * @param $w_id Username (id) of the gamer
- * @param $w_pwd Clear password of the gamer
- * @return void
- */
- public function setUser (int $w_id, string $w_pwd) {
- // Set username (id)
- $this->w_id = $w_id;
-
- // Hash clear password and set it
- $this->w_md5 = md5($w_pwd);
- }
-
- /************************************************
- * The following methods are not yet rewritten! *
- ************************************************/
-
- public function einziehen (int $amount) {
- // amount auf Gueltigkeit pruefen
- if ($amount < $this->config['mineinsatz']) {
- $this->setStatusMessage('low_stakes', sprintf('Dein Einsatz muss mindestens %d Wernis betragen.', $this->config['mineinsatz']));
- return false;
- }
-
- // Abfrage senden
- return $this->executeWithdraw($amount);
- }
-
- public function verschicken (int $amount) {
- // amount auf Gueltigkeit pruefen
- if ($amount < $this->config['mineinsatz']) {
- $this->setStatusMessage('low_stakes', sprintf('Dein Einsatz muss mindestens %d Wernis betragen.', $this->config['mineinsatz']));
- return false;
- }
-
- // Abfrage senden
- return $this->executePayout($amount);
- }
-
- // Script abbrechen mit Zurueck-Buttom
- public function ende () {
- global $_CONFIG;
- include 'templates/zurueck.html';
- include 'templates/fuss.html';
- exit();
- }
-
- // Fehlermeldung ausgeben und beenden
- public function error () {
- print "<div class=\"fehler\">Fehler im Spiel: ".$this->getErrorMessage()."<div><br />\n";
- $this->ende();
- }
-
- // Sets a status message and code
- public function setStatusMessage (string $msg, string $status) {
- $this->statusArray['message'] = $msg;
- $this->statusArray['status'] = $status;
- }
-
- // Get the status message
- public function getErrorMessage () {
- if (isset($this->statusArray['message'])) {
- // Use raw message
- return $this->statusArray['message'];
- } else {
- // Fall-back to status
- return sprintf('Fehler-Code <u>%s</u> ist keiner Nachricht zugewiesen.', $this->getErrorCode());
- }
- }
-
- // Get the status code
- public function getErrorCode () {
- if (isset($this->statusArray['status'])) {
- // Use raw message
- return $this->statusArray['status'];
- } else {
- // Something bad happend
- return 'unknown';
- }
- }
-
- // Sends out a request to the API and returns it's result
- private function sendRequest (string $scriptName, array $requestData = []) {
- // Is the requestData an array?
- if (!is_array($requestData)) {
- // Then abort here!
- return array(
- 'status' => 'failed_general',
- 'message' => 'API-Daten in <strong>config</strong> sind ungültig!'
- );
- }
-
- // Is the API id and MD5 hash there?
- if ((empty($this->config['wernis_api_id'])) || (empty($this->config['wernis_api_key']))) {
- // Abort here...
- return array(
- 'status' => 'failed_general',
- 'message' => 'API-Daten in config.php sind leer!'
- );
- }
-
- // Construct the request string
- $requestString = $this->config['api_url'] . $scriptName . '?api_id=' . $this->config['wernis_api_id'] . '&api_key='.$this->config['wernis_api_key'];
- foreach ($requestData as $key => $value) {
- $requestString .= '&' . $key . '=' . $value;
- }
-
- // Get the raw response from the lower function
- $response = $this->sendRawRequest($requestString);
-
- // Check the response header if all is fine
- if (strpos($response[0], '200') === false) {
- // Something bad happend... :(
- return array(
- 'status' => 'request_error',
- 'message' => sprintf('Servermeldung <u>%s</u> von WDS66-API erhalten.', $response[0])
- );
- }
-
- // All (maybe) fine so remove the response header from server
- for ($idx = (count($response) - 1); $idx > 1; $idx--) {
- $line = trim($response[$idx]);
- if (!empty($line)) {
- $response = $line;
- break;
- }
- }
-
- // Prepare the returning result for higher functions
- if (substr($response, 0, 1) == '&') {
- // Remove the leading & (which can be used in Flash)
- $response = substr($response, 1);
- }
-
- // Bring back the response
- $data = explode('=', $response);
-
- // Default return array (should not stay empty)
- $return = array();
-
- // We use only the first two entries (which shall be fine)
- if ($data[0] === 'error') {
- // The request has failed... :(
- switch ($data[1]) {
- case '404': // Invalid API ID
- case 'AUTH': // Authorization has failed
- $return = array(
- 'status' => 'auth_failed',
- 'message' => 'API-Daten scheinen nicht zu stimmen! (Access Denied)'
- );
- break;
-
- case 'LOCKED': // User account is locked!
- case 'PASS': // Bad passphrase entered
- case 'USER': // Missing account or invalid password
- $return = array(
- 'status' => 'user_failed',
- 'message' => 'Dein eingegebener WDS66-Username stimmt nicht, ist gesperrt oder du hast ein falsches Passwort eingegeben.'
- );
- break;
-
- case 'OWN': // Transfer to own account
- $return = array(
- 'status' => 'own_failed',
- 'message' => 'Du darfst dein eigenes Spiel leider nicht spielen.'
- );
- break;
-
- case 'AMOUNT': // Amount is depleted
- $return = array(
- 'status' => 'amount_failed',
- 'message' => 'Dein Guthaben reicht nicht aus, um das Spiel zu spielen.'
- );
- break;
-
- case 'AMOUNT-SEND': // API amount is depleted
- $return = array(
- 'status' => 'api_amount_failed',
- 'message' => 'Nicht genügend Guthaben auf dem API-Account.'
- );
- break;
-
- default: // Unknown error (maybe new?)
- $return = array(
- 'status' => 'request_failed',
- 'message' => sprintf('Unbekannter Fehler <u>%s</u> von API erhalten.', $data[1])
- );
- break;
- }
- } else {
- // All fine here
- $return = array(
- 'status' => $this->statusOkay,
- 'response' => $response
- );
- }
-
- // Return the result
- return $return;
- }
-
- // Widthdraw this amount
- private function executeWithdraw (int $amount) {
- // First all fails...
- $result = false;
-
- // Prepare the purpose
- $purpose = "\"Bube oder Dame\"-Einsatz gesetzt.";
-
- // Prepare the request data
- $requestData = array(
- 'sub_request' => 'receive',
- 't_uid' => $this->w_id,
- 't_md5' => $this->w_md5,
- 'r_uid' => (int) $this->config['wernis_refid'],
- 'amount' => (int) $amount,
- 'purpose' => urlencode(base64_encode($purpose))
- );
-
- // Return the result from the lower functions
- $return = $this->sendRequest('book.php', $requestData);
-
- if ($return['status'] == $this->statusOkay) {
- // All fine!
- $result = true;
- } else {
- // Status failture text
- $this->setStatusMessage($return['message'], $return['status']);
- }
-
- // Return result
- return $result;
- }
-
- // Payout this amount
- private function executePayout (int $amount) {
- // First all fails...
- $result = false;
-
- // Prepare the purpose
- $purpose = "\"Bube oder Dame\"-Gewinn erhalten.";
-
- // Prepare the request data
- $requestData = array(
- 'sub_request' => 'send',
- 't_uid' => $this->w_id,
- 't_md5' => $this->w_md5,
- 'r_uid' => (int) $this->config['wernis_refid'],
- 'amount' => (int) $amount,
- 'purpose' => urlencode(base64_encode($purpose))
- );
-
- // Return the result from the lower functions
- $return = $this->sendRequest("book.php", $requestData);
-
- if ($return['status'] == $this->statusOkay) {
- // All fine!
- $result = true;
- } else {
- // Status failture text
- $this->setStatusMessage($return['message'], $return['status']);
- }
-
- // Return result
- return $result;
- }
-
- // Send raw GET request
- private function sendRawRequest (string $script) {
- // Use the hostname from script URL as new hostname
- $url = substr($script, 7);
- $extract = explode('/', $url);
-
- // Done extracting the URL :)
- $url = $extract[0];
-
- // Extract host name
- $host = str_replace('http://', '', $url);
- if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
-
- // Generate relative URL
- $script = substr($script, (strlen($url) + 7));
- if (substr($script, 0, 1) == '/') $script = substr($script, 1);
-
- // Open connection
- $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
- if (!$fp) {
- // Failed!
- return array('', '', '');
- }
-
- // Generate request header
- $request = "GET /" . trim($script) . " HTTP/1.0\r\n";
- $request .= "Host: " . $host . "\r\n";
- $request .= sprintf("User-Agent: WernisApi/1.0 by Quix0r [Spieler: %d]\r\n\r\n", $this->w_id);
-
- // Initialize array
- $response = array();
-
- // Write request
- fputs($fp, $request);
-
- // Read response
- while(!feof($fp)) {
- array_push($response, trim(fgets($fp, 1024)));
- } // END - while
-
- // Close socket
- fclose($fp);
-
- // Was the request successfull?
- if ((!ereg('200 OK', $response[0])) && (empty($response[0]))) {
- // Not found / access forbidden
- $response = array('', '', '');
- } // END - if
-
- // Return response
- return $response;
- }
-
-}
+// @DEPRECATED
use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Localization\LanguageSystem;
+use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
use Org\Mxchange\CoreFramework\Loader\ClassLoader;
use Org\Mxchange\CoreFramework\Generic\FrameworkException;
}
// Get some instances
- $tpl = $configInstance->getConfigEntry('html_template_class');
+ $templateClassName = $configInstance->getConfigEntry('html_template_class');
$languageInstance = LanguageSystem::getSelfInstance();
// Initialize template instance here to avoid warnings in IDE
$responseInstance = FrameworkBootstrap::getResponseInstance();
// Is the template engine loaded?
- if ((class_exists($tpl)) && (is_object($languageInstance))) {
+ if ((class_exists($templateClassName)) && ($languageInstance instanceof ManageableLanguage)) {
// Use the template engine for putting out (nicer look) the message
try {
// Get the template instance from our object factory
- $templateInstance = ObjectFactory::createObjectByName($tpl);
+ $templateInstance = ObjectFactory::createObjectByName($templateClassName);
} catch (FrameworkException $e) {
exit(sprintf('[Main:] Could not initialize template engine for reason: <span class="exception_reason">%s</span>',
$e->getMessage()