code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public function run(string $file, Node $node): array
{
if ($this->isFunctionCall($node, 'preg_match')) {
$args = $node->children['args']->children;
if (count($args) > 2) {
return [];
}
if (is_string($args[0]) && $this->isUnneededRegExp($args[0])) {
return [new Hint(
self::HINT_TYPE,
self::HINT_MESSAGE,
$file,
$node->lineno,
self::HINT_LINK
)];
}
}
return [];
}
|
Find `preg_match()` which does not need regular expressions.
@param string $file File name to be analyzed.
@param Node $node AST node to be analyzed.
@return Hint[] List of hints obtained from results.
|
private function isUnneededRegExp(string $str): Bool
{
if (substr($str, -1) !== "/") {
return false;
}
return $str === preg_quote($str);
}
|
Check whether it is a regular expression pattern that can use `strpos()`.
The following pattern returns false:
1. Including pattern modifiers.
2. Including meta characters.
@param string $str A regular expression pattern for testing.
@return boolean The result of testing.
|
public function run(string $file, Node $node): array
{
if ($this->isFunctionCall($node, 'crypt')) {
return [new Hint(
self::HINT_TYPE,
self::HINT_MESSAGE,
$file,
$node->lineno,
self::HINT_LINK
)];
}
return [];
}
|
Detect calls to `crypt()` function.
@param string $file File name to be analyzed.
@param Node $node AST node to be analyzed.
@return Hint[] List of hints obtained from results.
|
private function progress($length) {
$bar = $this->output->createProgressBar(0);
$bar->setFormat('[<fg=magenta>%bar%</>] <info>%elapsed%</info>');
$bar->setEmptyBarCharacter('..');
$bar->setProgressCharacter("\xf0\x9f\x8c\x80");
$bar->advance($length);
$bar->finish();
echo "\r\n";
}
|
/*
exec('cd code && composer create-project laravel/laravel my-project');
or
shell_exec('cd code && composer create-project laravel/laravel my-project');
|
public function handle($request, Closure $next, $guard = null) {
if (admin()->user()) {
return redirect(aurl('/'));
}
return $next($request);
}
|
Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param string|null $guard
@return mixed
|
public function boot() {
if (file_exists(base_path('config/itconfiguration.php'))) {
Schema::defaultStringLength(config('itconfiguration.SchemadefaultStringLength'));
if (config('itconfiguration.ForeignKeyConstraints')) {
Schema::enableForeignKeyConstraints();
} else {
Schema::disableForeignKeyConstraints();
}
}
}
|
Bootstrap any application services.
@return void
|
public function store(Request $request) {
$rules = [
'sitename_ar' => 'required',
'sitename_en' => 'required',
'sitename_fr' => 'required',
'email' => 'required',
'logo' => 'sometimes|nullable|'.it()->image(),
'icon' => 'sometimes|nullable|'.it()->image(),
'system_status' => 'required',
'system_message' => '',
];
$data = $this->validate(request(), $rules, [], [
'sitename_ar' => trans('admin.sitename_ar'),
'sitename_en' => trans('admin.sitename_en'),
'sitename_fr' => trans('admin.sitename_fr'),
'email' => trans('admin.email'),
'logo' => trans('admin.logo'),
'icon' => trans('admin.icon'),
'system_status' => trans('admin.system_status'),
'system_message' => trans('admin.system_message'),
]);
if (request()->hasFile('logo')) {
$data['logo'] = it()->upload('logo', 'setting');
}
if (request()->hasFile('icon')) {
$data['icon'] = it()->upload('icon', 'setting');
}
Setting::orderBy('id', 'desc')->update($data);
session()->flash('success', trans('admin.updated'));
return redirect(aurl('settings'));
}
|
Store a newly created resource in storage.
@param \Illuminate\Http\Request $request
@return \Illuminate\Http\Response
|
public static function create(string $filename, string $source): array
{
$annotations = [];
$tokens = token_get_all($source);
$comments = array_filter($tokens, function ($token) {
return in_array($token[0], [T_COMMENT, T_DOC_COMMENT], true);
});
foreach ($comments as $comment) {
$rebel = Rebel::create($comment[1], $comment[2], $filename);
if ($rebel) {
$annotations[] = $rebel;
}
}
return $annotations;
}
|
Annotation facotry method
Get tokens from the source code by `token_get_all`
and return an array of the obtained annotation instance.
@param string $filename A file name.
@param string $source A body of file.
@return Base[] List of annotation instance.
|
public function instruct()
{
foreach ($this->files as $file) {
Logger::getInstance()->info('Parse: '.$file);
try {
$root = \ast\parse_file($file, Config::AST_VERSION);
$this->annotations = Annotation::create($file, file_get_contents($file));
// If file is empty, $root is not instance of Node.
if ($root instanceof Node) {
$this->traverse($file, $root);
}
} catch (\ParseError $exception) {
// When a parsing error occurs, the file is determined to be a syntax error.
Logger::getInstance()->info('Parse error occurred: '.$file);
// SyntaxError is a special tool. Pahout directly generates Hint without checking AST.
if (!in_array('SyntaxError', Config::getInstance()->ignore_tools, true)) {
$this->hints[] = new Hint(
'SyntaxError',
'Syntax error occurred.',
$file,
$exception->getLine(),
Hint::DOCUMENT_LINK."/SyntaxError.md"
);
}
}
}
Logger::getInstance()->info('Hints: '.count($this->hints));
}
|
Tell you about PHP hints.
Parses the file to be analyzed and traverses the obtained AST node with DFS.
@return void
|
private function traverse(string $file, Node $node)
{
Logger::getInstance()->debug('Traverse: '.\ast\get_kind_name($node->kind));
foreach ($this->tools as $tool) {
Logger::getInstance()->debug('Entrypoint check: '.get_class($tool));
if ($tool::ENTRY_POINT !== $node->kind) {
continue;
}
Logger::getInstance()->debug('Run: '.get_class($tool));
$hints = $tool->run($file, $node);
$hints = array_filter($hints, function ($hint) {
foreach ($this->annotations as $annotation) {
if (!($annotation instanceof Annotation\Rebel)) {
continue;
}
if ($annotation->isAffected($hint)) {
Logger::getInstance()->debug('Annotation effecting to hint: line='.$hint->lineno);
return false;
}
}
Logger::getInstance()->debug('Detected hints: line='.$hint->lineno);
return true;
});
if (count($hints) === 0) {
continue;
}
array_push($this->hints, ...$hints);
}
foreach ($node->children as $type => $child) {
if ($child instanceof Node) {
$this->traverse($file, $child);
}
}
}
|
Traverse AST nodes with DFS and check the entrypoint of tools.
Each time it compares the kind of Node with the entry point of tools.
If it matches, it will perform an detection by the tool.
Do this process recursively until the children is not a Node.
@param string $file File name to be analyzed.
@param Node $node AST node to be analyzed.
@return void
@suppress PhanUndeclaredConstant
|
public function run(string $file, Node $node): array
{
$hints = [];
$keys = [];
foreach ($node->children as $elem) {
if (is_null($elem)) {
continue;
}
$key = $elem->children['key'];
// If the array does not have key, ignores this element.
if (!is_null($key)) {
foreach ($keys as $other_key) {
if ($this->isEqualsWithoutLineno($key, $other_key)) {
$hints[] = new Hint(
self::HINT_TYPE,
self::HINT_MESSAGE,
$file,
$elem->lineno,
self::HINT_LINK
);
}
}
$keys[] = $key;
}
}
return $hints;
}
|
Detect duplicate numbers, strings, node key
@param string $file File name to be analyzed.
@param Node $node AST node to be analyzed.
@return Hint[] List of hints obtained from results.
|
public function print()
{
// If there is no hints, print a message for that.
if (count($this->hints) === 0) {
$this->output->writeln('<fg=black;bg=green>Awesome! There is nothing from me to teach you!</>');
$this->output->write("\n");
} else {
foreach ($this->hints as $hint) {
$this->output->writeln('<info>'.$hint->filename.':'.$hint->lineno.'</>');
$this->output->writeln("\t".$hint->type.': '.$hint->message." [$hint->link]");
$this->output->write("\n");
}
}
$this->output->writeln(count($this->files).' files checked, '.count($this->hints).' hints detected.');
}
|
Print hints to the console throught output interface of symfony console.
If there is no hints, a message of blessing will be displayed.
@return void
|
public function boot() {
include __DIR__ .'/helper/it.php';
if (!file_exists(base_path('config').'/itconfiguration.php')) {
$this->publishes([__DIR__ .'/environment/config' => base_path('config')]);
$this->publishes([__DIR__ .'/environment/app' => base_path('app')]);
$this->publishes([__DIR__ .'/environment/database' => base_path('database')]);
$this->publishes([__DIR__ .'/environment/resources' => base_path('resources')]);
$this->publishes([__DIR__ .'/environment/routes' => base_path('routes')]);
}
Route::middleware('web')
->prefix('it')
->group(__DIR__ .'/it_router.php');
require_once __DIR__ .'/helper/it.php';
require_once __DIR__ .'/helper/fontawesome.php';
}
|
Bootstrap services.
@return void
|
public function register() {
$this->app->singleton('command.it', function ($app) {
return new Commands\It;
});
$this->app->singleton('command.it.hey', function ($app) {
return new Commands\ItComeOut;
});
$this->app->singleton('command.it.generate', function ($app) {
return new Commands\Generate;
});
$this->app->singleton('command.it.install', function ($app) {
return new Commands\ItInstaller;
});
$this->app->singleton('command.it.uninstall', function ($app) {
return new Commands\ItUninstall;
});
$this->commands([
Commands\Generate::class ,
Commands\It::class ,
Commands\ItComeOut::class ,
Commands\ItInstaller::class ,
Commands\ItUninstall::class ,
]);
//
}
|
Register services.
@return void
|
public function run(string $file, Node $node): array
{
if ($this->isFunctionCall($node, 'json_decode')) {
$options = $node->children['args']->children[3] ?? null;
if ($this->shouldCheckOption($options) && !$this->isIncludeJSONThrowOnErrorOption($options)) {
return [new Hint(
self::HINT_TYPE,
self::HINT_MESSAGE,
$file,
$node->lineno,
self::HINT_LINK
)];
}
}
if ($this->isFunctionCall($node, 'json_encode')) {
$options = $node->children['args']->children[1] ?? null;
if ($this->shouldCheckOption($options) && !$this->isIncludeJSONThrowOnErrorOption($options)) {
return [new Hint(
self::HINT_TYPE,
self::HINT_MESSAGE,
$file,
$node->lineno,
self::HINT_LINK
)];
}
}
return [];
}
|
Check whether a `json_*` function has `JSON_THROW_ON_ERROR`
@param string $file File name to be analyzed.
@param Node $node AST node to be analyzed.
@return Hint[] List of hints obtained from results.
|
private function shouldCheckOption($node): Bool
{
if (!$node instanceof Node) {
return true;
}
if ($node->kind === \ast\AST_CONST) {
return true;
}
if ($node->kind === \ast\AST_BINARY_OP && $node->flags === \ast\flags\BINARY_BITWISE_OR) {
return true;
}
return false;
}
|
Check whether the passed options node should be checked.
This function is used to suppress false positives.
@param mixed $node Options node.
@return boolean Result.
|
private function isIncludeJSONThrowOnErrorOption($node): Bool
{
if (!$node instanceof Node) {
return false;
}
if ($node->kind === \ast\AST_CONST) {
$name = $node->children["name"];
if ($name->kind === \ast\AST_NAME && $name->children["name"] === "JSON_THROW_ON_ERROR") {
return true;
}
}
if ($node->kind === \ast\AST_BINARY_OP && $node->flags === \ast\flags\BINARY_BITWISE_OR) {
return $this->isIncludeJSONThrowOnErrorOption($node->children["left"])
|| $this->isIncludeJSONThrowOnErrorOption($node->children["right"]);
}
return false;
}
|
Check whether the passed node has `JSON_THROW_ON_ERROR`
This function is also aware of inclusive or.
@param mixed $node Node or others.
@return boolean Result.
|
public function run(string $file, Node $node): array
{
// This inspection only works to top level statements in each file.
if ($this->inspectedFile === $file) {
return [];
}
$found = false;
foreach ($node->children as $child) {
if (!$child instanceof Node) {
continue;
}
if ($child->kind !== \ast\AST_DECLARE) {
continue;
}
$declares = $child->children["declares"];
if ($declares->kind !== \ast\AST_CONST_DECL) {
continue;
}
foreach ($declares->children as $declare) {
if ($declare->kind === \ast\AST_CONST_ELEM && $declare->children["name"] === "strict_types") {
$found = true;
}
}
}
$this->inspectedFile = $file;
if (!$found) {
return [new Hint(
self::HINT_TYPE,
self::HINT_MESSAGE,
$file,
$node->lineno,
self::HINT_LINK
)];
}
return [];
}
|
Check whether the passed node has `strict_types` declaration.
@param string $file File name to be analyzed.
@param Node $node AST node to be analyzed.
@return Hint[] List of hints obtained from results.
|
public function run(string $file, Node $node): array
{
if ($node->flags !== \ast\flags\ARRAY_SYNTAX_LONG) {
Logger::getInstance()->debug('Ignore flags: '.$node->flags);
return [];
}
return [new Hint(
self::HINT_TYPE,
self::HINT_MESSAGE,
$file,
$node->lineno,
self::HINT_LINK
)];
}
|
Detect ARRAY_SYNTAX_LONG node.
@param string $file File name to be analyzed.
@param Node $node AST node to be analyzed.
@return Hint[] List of hints obtained from results.
|
public function addRole(string $role): GroupInterface
{
if (!$this->hasRole($role)) {
$this->roles[] = mb_strtoupper($role);
}
return $this;
}
|
@param string $role
@return $this
|
public function removeRole(string $role): GroupInterface
{
if (false !== $key = array_search(mb_strtoupper($role), $this->roles, true)) {
unset($this->roles[$key]);
$this->roles = array_values($this->roles);
}
return $this;
}
|
@param string $role
@return $this
|
public function run(string $file, Node $node): array
{
$cond = $node->children['cond'];
$true = $node->children['true'];
if ($cond instanceof Node && $cond->kind === \ast\AST_ISSET) {
$var = $cond->children['var'];
// If both are Node (Object), using the comparison operator.
if (is_object($var) && is_object($true)) {
if ($var != $true) {
Logger::getInstance()->debug('Different node found. Ignore it: '.$node->lineno);
return [];
}
// If it is not an object, using the identity operator.
} else {
if ($var !== $true) {
Logger::getInstance()->debug('Ignore: '.$node->lineno);
return [];
}
}
return [new Hint(
self::HINT_TYPE,
self::HINT_MESSAGE,
$file,
$node->lineno,
self::HINT_LINK
)];
}
return [];
}
|
Detects ternary operators with isset().
@param string $file File name to be analyzed.
@param Node $node AST node to be analyzed.
@return Hint[] List of hints obtained from results.
|
public function login(AuthenticationUtils $authenticationUtils)
{
// Check Auth
if ($this->checkAuth()) {
return $this->redirectToRoute($this->getParameter('pd_user.login_redirect'));
}
// Render
return $this->render($this->getParameter('pd_user.template_path') . '/Security/login.html.twig', [
'last_username' => $authenticationUtils->getLastUsername(),
'error' => $authenticationUtils->getLastAuthenticationError(),
]);
}
|
Login.
@return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
|
public function registerConfirm(\Swift_Mailer $mailer, EventDispatcherInterface $dispatcher, TranslatorInterface $translator, $token)
{
// Get Doctrine
$em = $this->getDoctrine()->getManager();
// Find User
$user = $em->getRepository($this->getParameter('pd_user.user_class'))->findOneBy(['confirmationToken' => $token]);
if (null === $user) {
throw $this->createNotFoundException(sprintf($translator->trans('security.token_notfound'), $token));
}
// Enabled User
$user->setConfirmationToken(null);
$user->setEnabled(true);
// Send Welcome
if ($this->getParameter('pd_user.welcome_email')) {
$this->sendEmail($user, $mailer, 'Registration', 'Welcome', 'Welcome');
}
// Update User
$em->persist($user);
$em->flush();
// Dispatch Register Event
if ($response = $dispatcher->dispatch(UserEvent::REGISTER_CONFIRM, new UserEvent($user))->getResponse()) {
return $response;
}
// Register Success
return $this->render($this->getParameter('pd_user.template_path') . '/Registration/registerSuccess.html.twig', [
'user' => $user,
]);
}
|
Registration Confirm Token.
@param $token
@return \Symfony\Component\HttpFoundation\Response
|
public function resettingPassword(Request $request, UserPasswordEncoderInterface $encoder, EventDispatcherInterface $dispatcher, \Swift_Mailer $mailer, TranslatorInterface $translator, $token)
{
// Get Doctrine
$em = $this->getDoctrine()->getManager();
// Find User
$user = $em->getRepository($this->getParameter('pd_user.user_class'))->findOneBy(['confirmationToken' => $token]);
if (null === $user) {
throw $this->createNotFoundException(sprintf($translator->trans('security.token_notfound'), $token));
}
// Build Form
$form = $this->createForm(ResettingPasswordType::class, $user);
// Handle Form Submit
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Encode Password & Set Token
$password = $encoder->encodePassword($user, $form->get('plainPassword')->getData());
$user->setPassword($password)
->setConfirmationToken(null)
->setPasswordRequestedAt(null);
// Save User
$em->persist($user);
$em->flush();
// Dispatch Register Event
if ($response = $dispatcher->dispatch(UserEvent::RESETTING_COMPLETE, new UserEvent($user))->getResponse()) {
return $response;
}
// Send Resetting Complete
$this->sendEmail($user, $mailer, 'Account Password Resetting', 'Password resetting completed.', 'Resetting_Completed');
// Render Success
return $this->render($this->getParameter('pd_user.template_path') . '/Resetting/resettingSuccess.html.twig', [
'sendEmail' => false,
]);
}
// Render
return $this->render($this->getParameter('pd_user.template_path') . '/Resetting/resettingPassword.html.twig', [
'token' => $token,
'form' => $form->createView(),
]);
}
|
Reset Password Form.
@param Request $request
@param $token
@return \Symfony\Component\HttpFoundation\Response
|
private function sendEmail(UserInterface $user, \Swift_Mailer $mailer, $subject, $body, $templateId)
{
if (\is_array($body)) {
$body['email'] = $user->getEmail();
$body['fullname'] = $user->getProfile()->getFullName();
} else {
$body = [
'email' => $user->getEmail(),
'fullname' => $user->getProfile()->getFullName(),
'content' => $body,
];
}
// Create Message
$message = (new PdSwiftMessage())
->setTemplateId($templateId)
->setFrom($this->getParameter('pd_user.mail_sender_address'), $this->getParameter('pd_user.mail_sender_name'))
->setTo($user->getEmail())
->setSubject($subject)
->setBody(serialize($body), 'text/html');
return (bool)$mailer->send($message);
}
|
Send Mail.
@return bool
|
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = oxNew(__CLASS__);
}
return self::$_instance;
}
|
Singleton instance
@return bestitAmazonPay4OxidLoginClient
@throws oxSystemComponentException
|
public function isActive()
{
if ($this->_isActive === null) {
//Checkbox for active Login checked
$this->_isActive = (
(bool)$this->getConfig()->getConfigParam('blAmazonLoginActive') === true
&& (string)$this->getConfig()->getConfigParam('sAmazonLoginClientId') !== ''
&& (string)$this->getConfig()->getConfigParam('sAmazonSellerId') !== ''
);
}
return $this->_isActive;
}
|
Method checks if Amazon Login is active and can be used
@return bool
|
public function showAmazonLoginButton()
{
return (
$this->isActive() === true
&& (bool)$this->getConfig()->isSsl() === true
&& $this->getActiveUser() === false
&& (string)$this->getConfig()->getRequestParameter('cl') !== 'basket'
&& (string)$this->getConfig()->getRequestParameter('cl') !== 'user'
);
}
|
Method checks if Amazon Login button can be showed
@return bool
@throws oxSystemComponentException
|
public function showAmazonPayButton()
{
return (
$this->isActive() === true
&& $this->getConfig()->isSsl() === true
&& $this->getModule()->isActive() === true
&& (string)$this->getSession()->getVariable('amazonOrderReferenceId') === ''
);
}
|
Method checks if Amazon Login button can be showed
@return bool
@throws oxConnectionException
|
public function createOxidUser($oUserData)
{
$aFullName = explode(' ', trim($oUserData->name));
$sLastName = array_pop($aFullName);
$sFirstName = implode(' ', $aFullName);
/** @var oxUser $oUser */
$oUser = $this->getObjectFactory()->createOxidObject('oxUser');
$oUser->assign(array(
'oxregister' => 0,
'oxshopid' => $this->getConfig()->getShopId(),
'oxactive' => 1,
'oxusername' => $oUserData->email,
'oxfname' => $this->getAddressUtil()->encodeString($sFirstName),
'oxlname' => $this->getAddressUtil()->encodeString($sLastName),
'bestitamazonid' => $oUserData->user_id
));
//Set user random password just to have it
$sNewPass = substr(md5(time() . rand(0, 5000)), 0, 8);
$oUser->setPassword($sNewPass);
//Save all user data
$blSuccess = $oUser->save();
//Add user to two default OXID groups
$oUser->addToGroup('oxidnewcustomer');
$oUser->addToGroup('oxidnotyetordered');
return $blSuccess;
}
|
Create new oxid user with details from Amazon
@var stdClass $oUserData
@return boolean
@throws oxSystemComponentException
|
public function cleanAmazonPay()
{
$this->getUtilsServer()->setOxCookie('amazon_Login_state_cache', '', time() - 3600, '/');
$this->getSession()->deleteVariable('amazonLoginToken');
$this->getModule()->cleanAmazonPay();
}
|
Cleans Amazon pay as the selected one, including all related variables, records and values
@throws oxConnectionException
@throws oxSystemComponentException
|
public function getAmazonLanguage()
{
//Get all languages from module settings
$aLanguages = $this->getConfig()->getConfigParam('aAmazonLanguages');
$sLanguageAbbr = $this->getLanguage()->getLanguageAbbr();
//Return Amazon Lang string if it exists in array else return null
return isset($aLanguages[$sLanguageAbbr]) ? $aLanguages[$sLanguageAbbr] : $sLanguageAbbr;
}
|
Method returns language for Amazon GUI elements
@return string
|
public function getLangIdByAmazonLanguage($sAmazonLanguageString)
{
//Get all languages from module settings
$aLanguages = $this->getConfig()->getConfigParam('aAmazonLanguages');
$sAbbreviation = array_search($sAmazonLanguageString, $aLanguages);
$aAllLangIds = $this->getLanguage()->getAllShopLanguageIds();
return array_search($sAbbreviation, $aAllLangIds);
}
|
Returns Language Id by Amazon Language string
@param string $sAmazonLanguageString Amazon Language string
@return int|bool
|
public function getOrderLanguageId(oxOrder $oOrder)
{
//Send GetOrderReferenceDetails request to Amazon to get OrderLanguage string
$oData = $this->getClient()->getOrderReferenceDetails($oOrder, array(), true);
//If request did not return us the language string return the existing Order lang ID
if (isset($oData->GetOrderReferenceDetailsResult->OrderReferenceDetails->OrderLanguage) === false) {
return (int)$oOrder->getFieldData('oxlang');
}
//If we have a language string match it to the one in the language mapping array
$sAmazonLanguageString = (string)$oData->GetOrderReferenceDetailsResult->OrderReferenceDetails->OrderLanguage;
//Get OXID Language Id by Amazon Language string
$iLangId = $this->getLangIdByAmazonLanguage($sAmazonLanguageString);
return ($iLangId !== false) ? (int)$iLangId : (int)$oOrder->getFieldData('oxlang');
}
|
Returns Language ID to use for made order
@param oxOrder $oOrder Order object
@return int
@throws Exception
|
protected static function _getModuleCache(oxModule $oModule)
{
if (self::$_oModuleCache === null) {
self::$_oModuleCache = oxNew('oxModuleCache', $oModule);
}
return self::$_oModuleCache;
}
|
@param oxModule $oModule
@return oxModuleCache
@throws oxSystemComponentException
|
protected static function _getModuleInstaller(oxModuleCache $oModuleCache)
{
if (self::$_oModuleInstaller === null) {
self::$_oModuleInstaller = oxNew('oxModuleInstaller', $oModuleCache);
}
return self::$_oModuleInstaller;
}
|
@param oxModuleCache $oModuleCache
@return oxModuleInstaller
@throws oxSystemComponentException
|
protected static function _deactivateOldModule()
{
$sModule = self::OLD_MODULE_ID;
/**
* @var oxModule $oModule
*/
$oModule = self::_getModule();
if ($oModule->load($sModule) === false) {
self::_getUtilsView()->addErrorToDisplay(new oxException('EXCEPTION_MODULE_NOT_LOADED'));
return false;
}
try {
$oModuleCache = self::_getModuleCache($oModule);
$oModuleInstaller = self::_getModuleInstaller($oModuleCache);
return $oModuleInstaller->deactivate($oModule);
} catch (oxException $oEx) {
self::_getUtilsView()->addErrorToDisplay($oEx);
if (method_exists($oEx, 'debugOut')) {
$oEx->debugOut();
}
}
return false;
}
|
Deactivates the old module.
@return bool
|
protected static function _removeTempVersionNumberFromDatabase()
{
$oConfig = self::_getConfig();
$sModuleId = self::_getDatabase()->quote(self::TMP_DB_ID);
$sQuotedShopId = self::_getDatabase()->quote($oConfig->getShopId());
$sDeleteSql = "DELETE
FROM `oxconfig`
WHERE oxmodule = {$sModuleId}
AND oxshopid = {$sQuotedShopId}";
self::_getDatabase()->execute($sDeleteSql);
}
|
Removes the temporary version number of the module from the database.
@throws oxConnectionException
|
protected static function _executeSqlFile($sFile)
{
$blSuccess = false;
$sFileWithPath = dirname(__FILE__) . '/../../../_db/' . $sFile;
if (file_exists($sFileWithPath)) {
$sSqlFile = file_get_contents($sFileWithPath);
$aSqlRows = explode(';', $sSqlFile);
$aSqlRows = array_map('trim', $aSqlRows);
foreach ($aSqlRows as $sSqlRow) {
if ($sSqlRow !== '') {
self::_getDatabase()->execute($sSqlRow);
}
}
$blSuccess = true;
}
return $blSuccess;
}
|
Executes a sql file.
@param string $sFile
@return bool
@throws oxConnectionException
|
public static function getCurrentVersion()
{
$aVersions = (array)self::_getConfig()->getConfigParam('aModuleVersions');
$aPossibleModuleNames = array(
'jagAmazonPayment4Oxid',
'bestitAmazonPay4Oxid'
);
foreach ($aPossibleModuleNames as $sPossibleModuleName) {
if (isset($aVersions[$sPossibleModuleName]) === true) {
return $aVersions[$sPossibleModuleName];
} elseif (isset($aVersions[strtolower($sPossibleModuleName)]) === true) {
return $aVersions[strtolower($sPossibleModuleName)];
}
}
return null;
}
|
Returns the current installed version.
@return null|string
|
protected static function _streamSafeGlob($sDirectory, $sFilePattern)
{
$sDirectory = rtrim($sDirectory, '/');
$aFiles = scandir($sDirectory);
$aFound = array();
foreach ($aFiles as $sFilename) {
if (fnmatch($sFilePattern, $sFilename)) {
$aFound[] = $sDirectory . '/' . $sFilename;
}
}
return $aFound;
}
|
Glob that is safe with streams (vfs for example)
@param string $sDirectory
@param string $sFilePattern
@return array
|
public static function clearTmp()
{
$sTmpDir = self::_getConfig()->getConfigParam('sCompileDir');
$sTmpDir = rtrim($sTmpDir, '/').'/';
$sSmartyDir = $sTmpDir.'smarty/';
foreach (self::_streamSafeGlob($sTmpDir, '*.txt') as $sFileName) {
unlink($sFileName);
}
foreach (self::_streamSafeGlob($sSmartyDir, '*.php') as $sFileName) {
unlink($sFileName);
}
}
|
Clear tmp dir and smarty cache.
@return void
|
protected function _getAmazonClient($aConfig = array())
{
if ($this->_oAmazonClient === null) {
$aConfig = array_merge(
$aConfig,
array(
'merchant_id' => $this->getConfig()->getConfigParam('sAmazonSellerId'),
'access_key' => $this->getConfig()->getConfigParam('sAmazonAWSAccessKeyId'),
'secret_key' => $this->getConfig()->getConfigParam('sAmazonSignature'),
'client_id' => $this->getConfig()->getConfigParam('sAmazonLoginClientId'),
'region' => $this->getConfig()->getConfigParam('sAmazonLocale')
)
);
$this->_oAmazonClient = new Client($aConfig);
$this->_oAmazonClient->setSandbox((bool)$this->getConfig()->getConfigParam('blAmazonSandboxActive'));
$this->_oAmazonClient->setLogger($this->_getLogger());
}
return $this->_oAmazonClient;
}
|
Returns the amazon api client.
@param array $aConfig
@return Client
@throws Exception
|
public function getAmazonProperty($sPropertyName, $blCommon = false)
{
$sSandboxPrefix = '';
if ($blCommon === false && (bool)$this->getConfig()->getConfigParam('blAmazonSandboxActive') === true) {
$sSandboxPrefix = 'Sandbox';
}
$sAmazonLocale = $this->getConfig()->getConfigParam('sAmazonLocale');
$sPropertyName = '_'.$sPropertyName.$sAmazonLocale.$sSandboxPrefix;
if (property_exists($this, $sPropertyName)) {
return $this->$sPropertyName;
}
return null;
}
|
Returns class property by given property name and other params
@param string $sPropertyName Property name
@param boolean $blCommon Include 'Sandbox' in property name or not
@return mixed
|
public function processOrderReference(oxOrder $oOrder, stdClass $oOrderReference)
{
$sOrderReferenceStatus = $oOrderReference
->OrderReferenceStatus
->State;
//Do re-authorization if order was suspended and now it's opened
if ($sOrderReferenceStatus === 'Open'
&& (string)$oOrder->getFieldData('oxtransstatus') === 'AMZ-Order-Suspended'
) {
$this->authorize($oOrder);
} else {
$oOrder->assign(array('oxtransstatus' => 'AMZ-Order-'.$sOrderReferenceStatus));
$oOrder->save();
}
}
|
Process order reference.
@param oxOrder $oOrder
@param stdClass $oOrderReference
@throws Exception
|
public function getOrderReferenceDetails($oOrder = null, array $aParams = array(), $blReadonly = false)
{
$aRequestParameters = array();
$sAmazonOrderReferenceId = ($oOrder === null) ?
(string)$this->getSession()->getVariable('amazonOrderReferenceId') : '';
if ($oOrder !== null) {
$aRequestParameters['amazon_order_reference_id'] = $oOrder->getFieldData('bestitamazonorderreferenceid');
} elseif ($sAmazonOrderReferenceId !== '') {
$aRequestParameters['amazon_order_reference_id'] = $sAmazonOrderReferenceId;
$sLoginToken = (string)$this->getSession()->getVariable('amazonLoginToken');
if ($sLoginToken !== '') {
$aRequestParameters['address_consent_token'] = $sLoginToken;
}
}
//Make request
$aRequestParameters = array_merge($aRequestParameters, $aParams);
$oData = $this->_convertResponse($this->_getAmazonClient()->getOrderReferenceDetails($aRequestParameters));
//Update Order info
if ($blReadonly === false
&& $oOrder !== null
&& isset($oData->GetOrderReferenceDetailsResult->OrderReferenceDetails->OrderReferenceStatus->State)
) {
$this->processOrderReference(
$oOrder,
$oData->GetOrderReferenceDetailsResult->OrderReferenceDetails
);
}
return $oData;
}
|
Amazon GetOrderReferenceDetails method
@param oxOrder $oOrder
@param array $aParams Custom parameters to send
@param bool $blReadonly
@return stdClass
@throws Exception
|
public function setOrderReferenceDetails($oBasket = null, array $aRequestParameters = array())
{
//Set default params
$aRequestParameters['amazon_order_reference_id'] = $this->getSession()->getVariable('amazonOrderReferenceId');
if ($oBasket !== null) {
$oActiveShop = $this->getConfig()->getActiveShop();
$sShopName = $oActiveShop->getFieldData('oxname');
$sOxidVersion = $oActiveShop->getFieldData('oxversion');
$sModuleVersion = bestitAmazonPay4Oxid_init::getCurrentVersion();
$aRequestParameters = array_merge(
$aRequestParameters,
array(
'amount' => $oBasket->getPrice()->getBruttoPrice(),
'currency_code' => $oBasket->getBasketCurrency()->name,
'platform_id' => 'A26EQAZK19E0U2',
'store_name' => $sShopName,
'custom_information' => "created by best it, OXID eShop v{$sOxidVersion}, v{$sModuleVersion}"
)
);
}
$this->_addSandboxSimulationParams('setOrderReferenceDetails', $aRequestParameters);
return $this->_convertResponse($this->_getAmazonClient()->setOrderReferenceDetails($aRequestParameters));
}
|
Amazon SetOrderReferenceDetails method
@param oxBasket $oBasket OXID Basket object
@param array $aRequestParameters Custom parameters to send
@return stdClass
@throws Exception
|
public function confirmOrderReference(array $aRequestParameters = array())
{
//Set params
$aRequestParameters['amazon_order_reference_id'] = $this->getSession()->getVariable('amazonOrderReferenceId');
return $this->_convertResponse($this->_getAmazonClient()->confirmOrderReference($aRequestParameters));
}
|
Amazon ConfirmOrderReference method
@param array $aRequestParameters Custom parameters to send
@return stdClass response XML
@throws Exception
|
protected function _setOrderTransactionErrorStatus(oxOrder $oOrder, stdClass $oData, $sStatus = null)
{
if (isset($oData->Error->Code) && (bool) $oData->Error->Code !== false) {
if ($sStatus === null) {
$sStatus = 'AMZ-Error-'.$oData->Error->Code;
}
$oOrder->assign(array('oxtransstatus' => $sStatus));
$oOrder->save();
return true;
}
return false;
}
|
Sets the order status
@param oxOrder $oOrder
@param stdClass $oData
@param string $sStatus
@return bool
|
protected function _callOrderRequest(
$sRequestFunction,
$oOrder,
array $aRequestParameters,
array $aFields,
&$blProcessable = false,
$sErrorCode = null
) {
$blProcessable = false;
//Set default params
if ($oOrder !== null) {
$this->_mapOrderToRequestParameters($oOrder, $aRequestParameters, $aFields);
}
//Make request and return result
$this->_addSandboxSimulationParams($sRequestFunction, $aRequestParameters);
$oData = $this->_convertResponse($this->_getAmazonClient()->{$sRequestFunction}($aRequestParameters));
//Update Order info
if ($oOrder !== null) {
$blProcessable = $this->_setOrderTransactionErrorStatus($oOrder, $oData, $sErrorCode) === false;
}
return $oData;
}
|
@param string $sRequestFunction
@param oxOrder $oOrder
@param array $aRequestParameters
@param array $aFields
@param bool $blProcessable
@param null $sErrorCode
@return stdClass
@throws Exception
|
public function closeOrderReference($oOrder = null, $aRequestParameters = array(), $blUpdateOrderStatus = true)
{
$oData = $this->_callOrderRequest(
'closeOrderReference',
$oOrder,
$aRequestParameters,
array('amazon_order_reference_id'),
$blProcessable,
'AMZ-Order-Closed'
);
//Update Order info
if ($blUpdateOrderStatus === true && $blProcessable === true) {
$oOrder->assign(array(
'oxtransstatus' => 'AMZ-Order-Closed'
));
$oOrder->save();
}
return $oData;
}
|
Amazon CloseOrderReference method
@param oxOrder $oOrder OXID Order object
@param array $aRequestParameters Custom parameters to send
@return stdClass
@throws Exception
|
public function authorize($oOrder = null, $aRequestParameters = array(), $blForceSync = false)
{
$sMode = $this->getConfig()->getConfigParam('sAmazonMode');
$aRequestParameters['transaction_timeout'] =
($sMode === bestitAmazonPay4OxidClient::BASIC_FLOW || $blForceSync) ? 0 : 1440;
$oData = $this->_callOrderRequest(
'authorize',
$oOrder,
$aRequestParameters,
array(
'amazon_order_reference_id',
'authorization_amount',
'currency_code',
'authorization_reference_id',
'seller_authorization_note'
),
$blProcessable
);
//Update Order info
if ($blProcessable === true
&& isset($oData->AuthorizeResult->AuthorizationDetails->AuthorizationStatus->State)
) {
$oDetails = $oData->AuthorizeResult->AuthorizationDetails;
$oOrder->assign(array(
'bestitamazonauthorizationid' => $oDetails->AmazonAuthorizationId,
'oxtransstatus' => 'AMZ-Authorize-'.$oDetails->AuthorizationStatus->State
));
$oOrder->save();
}
return $oData;
}
|
Amazon Authorize method
@param oxOrder $oOrder OXID Order object
@param array $aRequestParameters Custom parameters to send
@param bool $blForceSync If true we force the sync mode
@return stdClass
@throws Exception
|
public function processAuthorization(oxOrder $oOrder, stdClass $oAuthorizationDetails)
{
$oAuthorizationStatus = $oAuthorizationDetails->AuthorizationStatus;
//Update Order with primary response info
$oOrder->assign(array('oxtransstatus' => 'AMZ-Authorize-'.$oAuthorizationStatus->State));
$oOrder->save();
// Handle Declined response
if ($oAuthorizationStatus->State === 'Declined'
&& $this->getConfig()->getConfigParam('sAmazonMode') === bestitAmazonPay4OxidClient::OPTIMIZED_FLOW
) {
switch ($oAuthorizationStatus->ReasonCode) {
case "InvalidPaymentMethod":
/** @var bestitAmazonPay4Oxid_oxEmail $oEmail */
$oEmail = $this->getObjectFactory()->createOxidObject('oxEmail');
$oEmail->sendAmazonInvalidPaymentEmail($oOrder);
break;
case "AmazonRejected":
/** @var bestitAmazonPay4Oxid_oxEmail $oEmail */
$oEmail = $this->getObjectFactory()->createOxidObject('oxEmail');
$oEmail->sendAmazonRejectedPaymentEmail($oOrder);
$this->closeOrderReference($oOrder, array(), false);
break;
default:
$this->closeOrderReference($oOrder, array(), false);
}
}
//Authorize handling was selected Direct Capture after Authorize and Authorization status is Open
if ($oAuthorizationStatus->State === 'Open'
&& $this->getConfig()->getConfigParam('sAmazonCapture') === 'DIRECT'
) {
$this->capture($oOrder);
}
}
|
Processes the authorization
@param oxOrder $oOrder
@param stdClass $oAuthorizationDetails
@throws Exception
|
public function getAuthorizationDetails($oOrder = null, array $aRequestParameters = array())
{
$oData = $this->_callOrderRequest(
'getAuthorizationDetails',
$oOrder,
$aRequestParameters,
array('amazon_authorization_id'),
$blProcessable
);
if ($blProcessable === true
&& isset($oData->GetAuthorizationDetailsResult->AuthorizationDetails->AuthorizationStatus->State)
) {
$this->processAuthorization($oOrder, $oData->GetAuthorizationDetailsResult->AuthorizationDetails);
}
return $oData;
}
|
Amazon GetAuthorizationDetails method
@param oxOrder $oOrder OXID Order object
@param array $aRequestParameters Custom parameters to send
@return stdClass
@throws Exception
|
public function setCaptureState(oxOrder $oOrder, stdClass $oCaptureDetails, $blOnlyNotEmpty = false)
{
$aFields = array(
'bestitamazoncaptureid' => $oCaptureDetails->AmazonCaptureId,
'oxtransstatus' => 'AMZ-Capture-'.$oCaptureDetails->CaptureStatus->State
);
//Update paid date
if ($oCaptureDetails->CaptureStatus->State === 'Completed'
&& ($blOnlyNotEmpty === false || $oOrder->getFieldData('oxpaid') !== '0000-00-00 00:00:00')
) {
$aFields['oxpaid'] = date('Y-m-d H:i:s', $this->getUtilsDate()->getTime());
}
$oOrder->assign($aFields);
return $oOrder->save();
}
|
@param oxOrder $oOrder
@param stdClass $oCaptureDetails
@param bool $blOnlyNotEmpty
@return null
|
public function capture($oOrder = null, $aRequestParameters = array())
{
$oData = $this->_callOrderRequest(
'capture',
$oOrder,
$aRequestParameters,
array(
'amazon_authorization_id',
'capture_amount',
'currency_code',
'capture_reference_id',
'seller_capture_note'
),
$blProcessable
);
//Update Order info
if ($blProcessable === true && isset($oData->CaptureResult->CaptureDetails)) {
$this->setCaptureState($oOrder, $oData->CaptureResult->CaptureDetails);
$this->closeOrderReference($oOrder, array(), false);
}
return $oData;
}
|
Amazon Capture method
@param oxOrder $oOrder OXID Order object
@param array $aRequestParameters Custom parameters to send
@return stdClass
@throws Exception
|
public function getCaptureDetails($oOrder = null, $aRequestParameters = array())
{
$oData = $this->_callOrderRequest(
'getCaptureDetails',
$oOrder,
$aRequestParameters,
array('amazon_capture_id'),
$blProcessable
);
//Update Order info
if ($blProcessable === true && isset($oData->GetCaptureDetailsResult->CaptureDetails)) {
$this->setCaptureState($oOrder, $oData->GetCaptureDetailsResult->CaptureDetails, true);
}
return $oData;
}
|
Amazon GetCaptureDetails method
@param oxOrder $oOrder OXID Order object
@param array $aRequestParameters Custom parameters to send
@return stdClass
@throws Exception
|
public function saveCapture($oOrder = null)
{
if ((string)$oOrder->getFieldData('bestitAmazonCaptureId') !== '') {
return $this->getCaptureDetails($oOrder);
} elseif ((string)$oOrder->getFieldData('bestitAmazonAuthorizationId') !== '') {
return $this->capture($oOrder);
}
return false;
}
|
Save capture call.
@param oxOrder $oOrder
@return stdClass|bool
@throws Exception
|
public function refund($oOrder = null, $fPrice, $aRequestParameters = array())
{
//Refund ID
if ($oOrder !== null) {
$aRequestParameters['refund_amount'] = $fPrice;
$this->_mapOrderToRequestParameters(
$oOrder,
$aRequestParameters,
array('amazon_capture_id', 'currency_code', 'refund_reference_id', 'seller_refund_note')
);
}
//Make request
$this->_addSandboxSimulationParams('refund', $aRequestParameters);
$oData = $this->_convertResponse($this->_getAmazonClient()->refund($aRequestParameters));
//Update/Insert Refund info
if ($oData && $oOrder !== null) {
$sError = '';
$sAmazonRefundId = '';
if (isset($oData->Error)) {
$sState = 'Error';
$sError = $oData->Error->Message;
} else {
$sState = $oData->RefundResult->RefundDetails->RefundStatus->State;
$sAmazonRefundId = $oData->RefundResult->RefundDetails->AmazonRefundId;
}
$sId = $oOrder->getFieldData('bestitamazonorderreferenceid').'_'.$this->getUtilsDate()->getTime();
$sQuery = "
INSERT bestitamazonrefunds SET
ID = {$this->getDatabase()->quote($sId)},
OXORDERID = {$this->getDatabase()->quote($oOrder->getId())},
BESTITAMAZONREFUNDID = {$this->getDatabase()->quote($sAmazonRefundId)},
AMOUNT = {$fPrice},
STATE = {$this->getDatabase()->quote($sState)},
ERROR = {$this->getDatabase()->quote($sError)},
TIMESTAMP = NOW()";
$this->getDatabase()->execute($sQuery);
}
return $oData;
}
|
Amazon Refund method
@param oxOrder $oOrder OXID Order object
@param float $fPrice Price to refund
@param array $aRequestParameters Custom parameters to send
@return stdClass
@throws Exception
|
public function getRefundDetails($sAmazonRefundId)
{
//Set default params
$aRequestParameters['amazon_refund_id'] = $sAmazonRefundId;
//Make request
$oData = $this->_convertResponse($this->_getAmazonClient()->getRefundDetails($aRequestParameters));
//Update/Insert Refund info
if ((array)$oData !== array()) {
$sError = '';
if (isset($oData->Error) === true) {
$sState = 'Error';
$sError = $oData->Error->Message;
} else {
$sState = $oData->GetRefundDetailsResult->RefundDetails->RefundStatus->State;
}
$this->updateRefund($sAmazonRefundId, $sState, $sError);
}
return $oData;
}
|
Amazon GetRefundDetails method
@var string $sAmazonRefundId
@return stdClass
@throws Exception
|
public function setOrderAttributes(oxOrder $oOrder, array $aRequestParameters = array())
{
$this->_mapOrderToRequestParameters(
$oOrder,
$aRequestParameters,
array('amazon_order_reference_id', 'seller_order_id')
);
return $this->_getAmazonClient()->setOrderAttributes($aRequestParameters);
}
|
Sets the order attributes.
@param oxOrder $oOrder
@param array $aRequestParameters
@return ResponseParser
@throws Exception
|
public function render()
{
$sOrderReferenceId = $this->_getContainer()->getConfig()->getRequestParameter('amazonOrderReferenceId');
if ($sOrderReferenceId) {
$this->_getContainer()->getSession()->setVariable('amazonOrderReferenceId', $sOrderReferenceId);
}
return parent::render();
}
|
Set Amazon reference ID to session
@return mixed
@throws oxSystemComponentException
|
protected function _parseSingleAddress($sString, $sIsoCountryCode = null)
{
// Array of iso2 codes of countries that have address format <street_no> <street>
$aStreetNoStreetCountries = $this->getConfig()->getConfigParam('aAmazonStreetNoStreetCountries');
if (in_array($sIsoCountryCode, $aStreetNoStreetCountries)) {
// matches streetname/streetnumber like "streetnumber streetname"
preg_match('/\s*(?P<Number>\d[^\s]*)*\s*(?P<Name>[^\d]*[^\d\s])\s*(?P<AddInfo>.*)/', $sString, $aResult);
} else {
// default: matches streetname/streetnumber like "streetname streetnumber"
preg_match('/\s*(?P<Name>[^\d]*[^\d\s])\s*((?P<Number>\d[^\s]*)\s*(?P<AddInfo>.*))*/', $sString, $aResult);
}
return $aResult;
}
|
Returns parsed Street name and Street number in array
@param string $sString Full address
@param string $sIsoCountryCode ISO2 code of country of address
@return string
|
protected function _parseAddressFields($oAmazonData, array &$aResult)
{
// Cleanup address fields and store them to an array
$aAmazonAddresses = array(
1 => is_string($oAmazonData->AddressLine1) ? trim($oAmazonData->AddressLine1) : '',
2 => is_string($oAmazonData->AddressLine2) ? trim($oAmazonData->AddressLine2) : '',
3 => is_string($oAmazonData->AddressLine3) ? trim($oAmazonData->AddressLine3) : ''
);
// Array of iso2 codes of countries that have another addressline order
$aReverseOrderCountries = $this->getConfig()->getConfigParam('aAmazonReverseOrderCountries');
$aMap = array_flip($aReverseOrderCountries);
$aCheckOrder = isset($aMap[$oAmazonData->CountryCode]) === true ? array (2, 1) : array(1, 2);
$sStreet = '';
$sCompany = '';
foreach ($aCheckOrder as $iCheck) {
if ($aAmazonAddresses[$iCheck] !== '') {
if ($sStreet !== '') {
$sCompany = $aAmazonAddresses[$iCheck];
break;
}
$sStreet = $aAmazonAddresses[$iCheck];
}
}
if ($aAmazonAddresses[3] !== '') {
$sCompany = ($sCompany === '') ? $aAmazonAddresses[3] : "{$sCompany}, {$aAmazonAddresses[3]}";
}
$aResult['CompanyName'] = $sCompany;
$aAddress = $this->_parseSingleAddress($sStreet, $oAmazonData->CountryCode);
$aResult['Street'] = isset($aAddress['Name']) === true ? $aAddress['Name'] : '';
$aResult['StreetNr'] = isset($aAddress['Number']) === true ? $aAddress['Number'] : '';
$aResult['AddInfo'] = isset($aAddress['AddInfo']) === true ? $aAddress['AddInfo'] : '';
}
|
Parses the amazon address fields.
@param \stdClass $oAmazonData
@param array $aResult
|
public function parseAmazonAddress($oAmazonData)
{
//Cast to array
$aResult = (array)$oAmazonData;
//Parsing first and last names
$aFullName = explode(' ', trim($oAmazonData->Name));
$aResult['LastName'] = array_pop($aFullName);
$aResult['FirstName'] = implode(' ', $aFullName);
$sTable = getViewName('oxcountry');
$oAmazonData->CountryCode = (string)$oAmazonData->CountryCode === 'UK' ? 'GB' : $oAmazonData->CountryCode;
$sSql = "SELECT OXID
FROM {$sTable}
WHERE OXISOALPHA2 = ".$this->getDatabase()->quote($oAmazonData->CountryCode);
//Country ID
$aResult['CountryId'] = $this->getDatabase()->getOne($sSql);
//Parsing address
$this->_parseAddressFields($oAmazonData, $aResult);
//If shop runs in non UTF-8 mode encode values to ANSI
if ($this->getConfig()->isUtf() === false) {
foreach ($aResult as $sKey => $sValue) {
$aResult[$sKey] = $this->encodeString($sValue);
}
}
return $aResult;
}
|
Returns Parsed address from Amazon by specific rules
@param object $oAmazonData Address object
@return array Parsed Address
@throws oxConnectionException
|
public function encodeString($sString)
{
//If shop is running in UTF-8 nothing to do here
if ($this->getConfig()->isUtf() === true) {
return $sString;
}
$sShopEncoding = $this->getLanguage()->translateString('charset');
return iconv('UTF-8', $sShopEncoding, $sString);
}
|
If shop is using non-Utf8 chars, encode string according used encoding
@param string $sString the string to encode
@return string encoded string
|
public function getActiveUser()
{
if ($this->_oActiveUserObject === null) {
$this->_oActiveUserObject = false;
/** @var oxUser $oUser */
$oUser = $this->getObjectFactory()->createOxidObject('oxUser');
if ($oUser->loadActiveUser() === true) {
$this->_oActiveUserObject = $oUser;
}
}
return $this->_oActiveUserObject;
}
|
Returns the active user object.
@return oxUser|bool
@throws oxSystemComponentException
|
public function getConfig()
{
if ($this->_oConfigObject === null) {
$this->_oConfigObject = oxRegistry::getConfig();
}
return $this->_oConfigObject;
}
|
Returns the config object.
@return oxConfig
|
public function getDatabase()
{
if ($this->_oDatabaseObject === null) {
$this->_oDatabaseObject = oxDb::getDb(oxDb::FETCH_MODE_ASSOC);
}
return $this->_oDatabaseObject;
}
|
Returns the database object.
@return DatabaseInterface
@throws oxConnectionException
|
public function getIpnHandler()
{
if ($this->_oIpnHandlerObject === null) {
$this->_oIpnHandlerObject = oxRegistry::get('bestitAmazonPay4OxidIpnHandler');
}
return $this->_oIpnHandlerObject;
}
|
Returns the ipn handler object.
@return bestitAmazonPay4OxidIpnHandler
|
public function getLanguage()
{
if ($this->_oLanguageObject === null) {
$this->_oLanguageObject = oxRegistry::getLang();
}
return $this->_oLanguageObject;
}
|
Returns the language object.
@return oxLang
|
public function getSession()
{
if ($this->_oSessionObject === null) {
$this->_oSessionObject = oxRegistry::getSession();
}
return $this->_oSessionObject;
}
|
Returns the session object.
@return oxSession
|
public function setPrimaryAmazonUserData()
{
$oUtils = $this->_getContainer()->getUtils();
$sShopSecureHomeUrl = $this->_getContainer()->getConfig()->getShopSecureHomeUrl();
//Get primary user data from Amazon
$oData = $this->_getContainer()->getClient()->getOrderReferenceDetails();
$oOrderReferenceDetail = isset($oData->GetOrderReferenceDetailsResult->OrderReferenceDetails)
? $oData->GetOrderReferenceDetailsResult->OrderReferenceDetails : null;
if ($oOrderReferenceDetail === null
|| isset($oOrderReferenceDetail->Destination->PhysicalDestination) === false
) {
$oUtils->redirect($sShopSecureHomeUrl.'cl=user&fnc=cleanAmazonPay', false);
return;
}
//Creating and(or) logging user
$sStatus = (string)$oOrderReferenceDetail->OrderReferenceStatus->State;
if ($sStatus === 'Draft') {
//Manage primary user data
$oAmazonData = $oOrderReferenceDetail->Destination->PhysicalDestination;
$this->_managePrimaryUserData($oAmazonData);
//Recalculate basket to get shipping price for created user
$this->_getContainer()->getSession()->getBasket()->onUpdate();
//Redirect with registered user or new shipping address to payment page
$oUtils->redirect($sShopSecureHomeUrl.'cl=payment', false);
return;
}
$oUtils->redirect($sShopSecureHomeUrl.'cl=user&fnc=cleanAmazonPay', false);
}
|
Get's primary user details and logins user if one is not logged in
Add's new address if user is logged in.
@throws Exception
|
public function validatePayment()
{
$oSession = $this->_getContainer()->getSession();
$oConfig = $this->_getContainer()->getConfig();
//Don't do anything with order remark if we not under Amazon Pay
if ((string)$oSession->getVariable('amazonOrderReferenceId') === ''
|| (string)$oConfig->getRequestParameter('paymentid') !== 'bestitamazon'
) {
return parent::validatePayment();
}
// order remark
$sOrderRemark = (string)$oConfig->getRequestParameter('order_remark', true);
if ($sOrderRemark !== '') {
$oSession->setVariable('ordrem', $sOrderRemark);
} else {
$oSession->deleteVariable('ordrem');
}
return parent::validatePayment();
}
|
Set's order remark to session
@return mixed
@throws oxSystemComponentException
|
public function getOrderRemark()
{
// if already connected, we can use the session
if ($this->_getContainer()->getActiveUser() !== false) {
$sOrderRemark = $this->_getContainer()->getSession()->getVariable('ordrem');
} else {
// not connected so nowhere to save, we're gonna use what we get from post
$sOrderRemark = $this->_getContainer()->getConfig()->getRequestParameter('order_remark', true);
}
if (!empty($sOrderRemark)) {
return $this->_getContainer()->getConfig()->checkParamSpecialChars($sOrderRemark);
}
return false;
}
|
Template variable getter. Returns order remark
@return string
@throws oxSystemComponentException
|
protected function _addToMessages($sText)
{
$aViewData = $this->getViewData();
$aViewData['sMessage'] = isset($aViewData['sMessage']) ? $aViewData['sMessage'].$sText : $sText;
$this->setViewData($aViewData);
}
|
Adds the text to the message.
@param $sText
|
protected function _processOrderStates($sQuery, $sClientFunction)
{
$aResponses = array();
$aResult = $this->_getContainer()->getDatabase()->getAll($sQuery);
foreach ($aResult as $aRow) {
$oOrder = $this->_getContainer()->getObjectFactory()->createOxidObject('oxOrder');
if ($oOrder->load($aRow['OXID'])) {
$oData = $this->_getContainer()->getClient()->{$sClientFunction}($oOrder);
$aResponses[$aRow['OXORDERNR']] = $oData;
}
}
return $aResponses;
}
|
Processes the order states.
@param string $sQuery
@param string $sClientFunction
@return array
@throws oxSystemComponentException
@throws oxConnectionException
|
protected function _updateAuthorizedOrders()
{
$aProcessed = $this->_processOrderStates(
"SELECT OXID, OXORDERNR FROM oxorder
WHERE BESTITAMAZONORDERREFERENCEID != ''
AND BESTITAMAZONAUTHORIZATIONID != ''
AND OXTRANSSTATUS = 'AMZ-Authorize-Pending'",
'getAuthorizationDetails'
);
foreach ($aProcessed as $sOrderNumber => $oData) {
if (isset($oData->GetAuthorizationDetailsResult->AuthorizationDetails->AuthorizationStatus->State)) {
$sState = $oData->GetAuthorizationDetailsResult
->AuthorizationDetails
->AuthorizationStatus->State;
$this->_addToMessages("Authorized Order #{$sOrderNumber} - Status updated to: {$sState}<br/>");
}
}
}
|
Authorize unauthorized orders or orders with pending status
@throws oxSystemComponentException
@throws oxConnectionException
|
protected function _updateSuspendedOrders()
{
$aProcessed = $this->_processOrderStates(
"SELECT OXID, OXORDERNR FROM oxorder
WHERE BESTITAMAZONORDERREFERENCEID != ''
AND BESTITAMAZONAUTHORIZATIONID != ''
AND OXTRANSSTATUS = 'AMZ-Order-Suspended'",
'getOrderReferenceDetails'
);
foreach ($aProcessed as $sOrderNumber => $oData) {
if (isset($oData->GetOrderReferenceDetailsResult->OrderReferenceDetails->OrderReferenceStatus->State)) {
$sState = $oData->GetOrderReferenceDetailsResult
->OrderReferenceDetails
->OrderReferenceStatus->State;
$this->_addToMessages("Suspended Order #{$sOrderNumber} - Status updated to: {$sState}<br/>");
}
}
}
|
Update suspended orders
@throws oxSystemComponentException
@throws oxConnectionException
|
protected function _captureOrders()
{
$sSQLAddShippedCase = '';
//Capture orders if in module settings was set to capture just shipped orders
if ((string)$this->_getContainer()->getConfig()->getConfigParam('sAmazonCapture') === 'SHIPPED') {
$sSQLAddShippedCase = ' AND OXSENDDATE > 0';
}
$aProcessed = $this->_processOrderStates(
"SELECT OXID, OXORDERNR
FROM oxorder
WHERE BESTITAMAZONAUTHORIZATIONID != ''
AND OXTRANSSTATUS = 'AMZ-Authorize-Open' {$sSQLAddShippedCase}",
'capture'
);
foreach ($aProcessed as $sOrderNumber => $oData) {
if (isset($oData->CaptureResult->CaptureDetails->CaptureStatus->State)) {
$sState = $oData->CaptureResult->CaptureDetails->CaptureStatus->State;
$this->_addToMessages("Capture Order #{$sOrderNumber} - Status updated to: {$sState}<br/>");
}
}
}
|
Capture orders with Authorize status=open
@throws oxSystemComponentException
@throws oxConnectionException
|
protected function _updateRefundDetails()
{
$sQuery = "SELECT BESTITAMAZONREFUNDID
FROM bestitamazonrefunds
WHERE STATE = 'Pending'
AND BESTITAMAZONREFUNDID != ''";
$aResult = $this->_getContainer()->getDatabase()->getAll($sQuery);
foreach ($aResult as $aRow) {
$oData = $this->_getContainer()->getClient()->getRefundDetails($aRow['BESTITAMAZONREFUNDID']);
if (isset($oData->GetRefundDetailsResult->RefundDetails->RefundStatus->State)) {
$this->_addToMessages(
"Refund ID: {$oData->GetRefundDetailsResult->RefundDetails->RefundReferenceId} - "
."Status: {$oData->GetRefundDetailsResult->RefundDetails->RefundStatus->State}<br/>"
);
}
}
}
|
Check and update refund details for made refunds
@throws Exception
|
protected function _closeOrders()
{
$aProcessed = $this->_processOrderStates(
"SELECT OXID, OXORDERNR FROM oxorder
WHERE BESTITAMAZONORDERREFERENCEID != ''
AND BESTITAMAZONAUTHORIZATIONID != ''
AND OXTRANSSTATUS = 'AMZ-Capture-Completed'",
'closeOrderReference'
);
foreach ($aProcessed as $sOrderNumber => $oData) {
if (isset($oData->CloseOrderReferenceResult, $oData->ResponseMetadata->RequestId)) {
$this->_addToMessages("Order #{$sOrderNumber} - Closed<br/>");
}
}
}
|
Update suspended orders
@throws oxSystemComponentException
@throws oxConnectionException
|
public function render()
{
//Increase execution time for the script to run without timeouts
set_time_limit(3600);
//If ERP mode is enabled do nothing, if IPN or CRON authorize unauthorized orders
if ((bool)$this->_getContainer()->getConfig()->getConfigParam('blAmazonERP') === true) {
$this->setViewData(array('sError' => 'ERP mode is ON (Module settings)'));
} elseif ((string)$this->_getContainer()->getConfig()->getConfigParam('sAmazonAuthorize') !== 'CRON') {
$this->setViewData(array('sError' => 'Trigger Authorise via Cronjob mode is turned Off (Module settings)'));
} else {
//Authorize unauthorized or Authorize-Pending orders
$this->_updateAuthorizedOrders();
//Check for declined orders
$this->_updateDeclinedOrders();
//Check for suspended orders
$this->_updateSuspendedOrders();
//Capture handling
$this->_captureOrders();
//Check refund stats
$this->_updateRefundDetails();
//Check for order which can be closed
$this->_closeOrders();
$this->_addToMessages('Done');
}
return $this->_sThisTemplate;
}
|
The render function
@throws Exception
@throws oxSystemComponentException
|
protected function _getOperationName()
{
$operation = lcfirst($this->_getContainer()->getConfig()->getRequestParameter('operation'));
if (method_exists($this->_getContainer()->getClient(), $operation)) {
return $operation;
}
$this->setViewData(array('sError' => "Operation '{$operation}' does not exist"));
return false;
}
|
Method returns Operation name
@return mixed
@throws oxSystemComponentException
|
protected function _getOrder()
{
$sOrderId = $this->_getContainer()->getConfig()->getRequestParameter('oxid');
if ($sOrderId !== null) {
/** @var oxOrder $oOrder */
$oOrder = $this->_getContainer()->getObjectFactory()->createOxidObject('oxOrder');
if ($oOrder->load($sOrderId) === true) {
return $oOrder;
}
}
return null;
}
|
Method returns Order object
@return null|oxOrder
@throws oxSystemComponentException
|
protected function _getParams()
{
$aResult = array();
$aParams = (array)$this->_getContainer()->getConfig()->getRequestParameter('aParams');
foreach ($aParams as $sKey => $sValue) {
$aResult[html_entity_decode($sKey)] = html_entity_decode($sValue);
}
return $aResult;
}
|
Method returns Parameters from GET aParam array
@return array
@throws oxSystemComponentException
|
public function amazonCall()
{
$sOperation = $this->_getOperationName();
if ($sOperation !== false) {
$oResult = $this->_getContainer()->getClient()->{$sOperation}(
$this->_getOrder(),
$this->_getParams()
);
$this->_addToMessages('<pre>'.print_r($oResult, true).'</pre>');
return;
}
$this->setViewData(array(
'sError' => 'Please specify operation you want to call (&operation=) '
.'and use &oxid= parameter to specify order ID or use &aParams[\'key\']=value'
));
}
|
Makes request to Amazon methods
amazonCall method Calling examples:
index.php?cl=bestitamazoncron&fnc=amazonCall&operation=Authorize&oxid=87feca21ce31c34f0d3dceb8197a2375
index.php?cl=bestitamazoncron&fnc=amazonCall&operation=Authorize&aParams[AmazonOrderReferenceId]=51fd6a7381e7a0220b0f166fe331e420&aParams[AmazonAuthorizationId]=S02-8774768-9373076-A060413
@throws oxSystemComponentException
|
protected function _processError($sError)
{
$this->_getContainer()->getIpnHandler()->logIPNResponse(Logger::ERROR, $sError);
$this->setViewData(array('sError' => $sError));
return $this->_sThisTemplate;
}
|
@param string $sError
@return string
@throws oxSystemComponentException
@throws Exception
|
public function render()
{
//If ERP mode is enabled do nothing, if IPN or CRON authorize unauthorized orders
if ($this->_getContainer()->getConfig()->getConfigParam('blAmazonERP') === true) {
return $this->_processError('IPN response handling disabled - ERP mode is ON (Module settings)');
}
//Check if IPN response handling is turned ON
if ($this->_getContainer()->getConfig()->getConfigParam('sAmazonAuthorize') !== 'IPN') {
return $this->_processError('IPN response handling disabled (Module settings)');
}
//Get SNS message
$sBody = file_get_contents($this->_sInput);
if ($sBody === '') {
return $this->_processError('SNS message empty or Error while reading SNS message occurred');
}
//Perform IPN action
if ($this->_getContainer()->getIpnHandler()->processIPNAction($sBody) !== true) {
return $this->_processError('Error while handling Amazon response');
}
return $this->_sThisTemplate;
}
|
The controller entry point.
@return string
@throws Exception
@throws oxConnectionException
@throws oxSystemComponentException
|
protected function _setErrorAndRedirect($sError, $sRedirectUrl)
{
/** @var oxUserException $oEx */
$oEx = $this->_getContainer()->getObjectFactory()->createOxidObject('oxUserException');
$oEx->setMessage($sError);
$this->_getContainer()->getUtilsView()->addErrorToDisplay($oEx, false, true);
$this->_getContainer()->getUtils()->redirect($sRedirectUrl, false);
}
|
@param string $sError
@param string $sRedirectUrl
@throws oxSystemComponentException
@throws oxSystemComponentException
@throws oxSystemComponentException
|
public function getIsSelectedCurrencyAvailable()
{
$oConfig = $this->getConfig();
$blEnableMultiCurrency = (bool)$oConfig->getConfigParam('blBestitAmazonPay4OxidEnableMultiCurrency');
if ($blEnableMultiCurrency === true) {
return true;
}
if ($this->_isSelectedCurrencyAvailable === null) {
$this->_isSelectedCurrencyAvailable = true;
$aMap = array(
'DE' => 'EUR',
'UK' => 'GBP',
'US' => 'USD'
);
$sLocale = (string)$oConfig->getConfigParam('sAmazonLocale');
$sCurrency = (string)$this->getSession()->getBasket()->getBasketCurrency()->name;
//If Locale is DE and currency is not EURO don't allow Amazon checkout process
if (isset($aMap[$sLocale]) && $aMap[$sLocale] !== $sCurrency) {
$this->_isSelectedCurrencyAvailable = false;
}
}
return $this->_isSelectedCurrencyAvailable;
}
|
Returns true if currency meets locale
@return boolean
|
public function cleanAmazonPay()
{
//Delete our created user for Amazon checkout
$oUser = $this->getActiveUser();
$sAmazonUserName = $this->getSession()->getVariable('amazonOrderReferenceId') . '@amazon.com';
if ($oUser !== false && $oUser->getFieldData('oxusername') === $sAmazonUserName) {
$oUser->delete();
}
//Delete several session variables to clean up Amazon data in session
$this->getSession()->deleteVariable('amazonOrderReferenceId');
$this->getSession()->deleteVariable('sAmazonSyncResponseState');
$this->getSession()->deleteVariable('sAmazonSyncResponseAuthorizationId');
$this->getSession()->deleteVariable('blAmazonSyncChangePayment');
$this->getSession()->deleteVariable('sAmazonBasketHash');
//General cleanup of user accounts that has been created for orders and wos not used
$this->cleanUpUnusedAccounts();
}
|
Cleans Amazon pay as the selected one, including all related variables, records and values
@throws oxConnectionException
@throws oxSystemComponentException
|
public function cleanUpUnusedAccounts()
{
$sTable = getViewName('oxuser');
$sSql = "SELECT oxid, oxusername
FROM {$sTable}
WHERE oxusername LIKE '%-%-%@amazon.com'
AND oxcreate < (NOW() - INTERVAL 1440 MINUTE)";
$aData = $this->getDatabase()->getAll($sSql);
foreach ($aData as $aUser) {
//Delete user from OXID
$oUser = $this->getObjectFactory()->createOxidObject('oxUser');
if ($oUser->load($aUser['oxid'])) {
$oUser->delete();
}
}
}
|
Deletes previously created user accounts which was not used
@throws oxConnectionException
@throws oxSystemComponentException
|
protected function _performAmazonActions($blAuthorizeAsync)
{
$oContainer = $this->_getContainer();
$oSession = $oContainer->getSession();
$oConfig = $oContainer->getConfig();
//Save Amazon reference ID to oxorder table
$this->_setFieldData('bestitamazonorderreferenceid', $oSession->getVariable('amazonOrderReferenceId'));
$this->save();
$oContainer->getClient()->setOrderAttributes($this);
//If ERP mode is enabled do nothing just set oxorder->oxtransstatus to specified value
if ((bool)$oConfig->getConfigParam('blAmazonERP') === true) {
$this->_setFieldData('oxtransstatus', $oConfig->getConfigParam('sAmazonERPModeStatus'));
$this->save();
return;
}
//If we had Sync mode enabled don't call Authorize once again
if ($blAuthorizeAsync === false) {
$sAmazonSyncResponseState = (string)$oSession->getVariable('sAmazonSyncResponseState');
$sAmazonSyncResponseAuthorizationId = (string)$oSession->getVariable('sAmazonSyncResponseAuthorizationId');
if ($sAmazonSyncResponseState !== '' && $sAmazonSyncResponseAuthorizationId !== '') {
$this->assign(array(
'bestitamazonauthorizationid' => $sAmazonSyncResponseAuthorizationId,
'oxtransstatus' => 'AMZ-Authorize-'.$sAmazonSyncResponseState
));
$this->save();
}
//If Capture handling was set to "Direct Capture after Authorize" and Authorization status is Open
if ((string)$oConfig->getConfigParam('sAmazonCapture') === 'DIRECT'
&& (string)$oSession->getVariable('sAmazonSyncResponseState') === 'Open'
) {
$oContainer->getClient()->capture($this);
}
return;
}
//Call Amazon authorize (Dedicated for Async mode)
$oContainer->getClient()->authorize($this);
return;
}
|
Async Authorize call and data update
@param bool $blAuthorizeAsync
@throws Exception
@throws oxSystemComponentException
|
protected function _parentFinalizeOrder(Basket $oBasket, $oUser, $blRecalculatingOrder = false)
{
return parent::finalizeOrder($oBasket, $oUser, $blRecalculatingOrder);
}
|
@param Basket $oBasket
@param User $oUser
@param bool $blRecalculatingOrder
@return int
|
public function finalizeOrder(Basket $oBasket, $oUser, $blRecalculatingOrder = false)
{
if ($this->_preFinalizeOrder($oBasket, $oUser, $blIsAmazonOrder, $blAuthorizeAsync) === false) {
return oxOrder::ORDER_STATE_PAYMENTERROR;
}
//Original OXID method which creates and order
$iRet = $this->_parentFinalizeOrder($oBasket, $oUser, $blRecalculatingOrder);
//If order was successfull perform some Amazon actions
if ($blIsAmazonOrder === true) {
//If order was successfull update order details with reference ID
if ($iRet < 2) {
$this->_performAmazonActions($blAuthorizeAsync);
} else {
$this->_getContainer()->getClient()->cancelOrderReference($this);
}
}
return $iRet;
}
|
Confirm Order details to Amazon if payment id is bestitamazon and amazonreferenceid exists
Update user details with the full details received from amazon
@param Basket $oBasket
@param User $oUser
@param bool|false $blRecalculatingOrder
@return int
@throws Exception
|
public function validateDeliveryAddress($oUser)
{
$oBasket = $this->_getContainer()->getSession()->getBasket();
if ($oBasket && (string)$oBasket->getPaymentId() === 'bestitamazon') {
return 0;
} else {
return parent::validateDeliveryAddress($oUser);
}
}
|
Skips delivery address validation when payment==bestitamazon
@param oxUser $oUser user object
@return int
@throws oxSystemComponentException
|
public function getAmazonChangePaymentLink()
{
$oClient = $this->_getContainer()->getClient();
//Main part of the link related to selected locale in config
$sLink = $oClient->getAmazonProperty('sAmazonPayChangeLink', true);
//Send GetOrderReferenceDetails request to Amazon to get OrderLanguage string
$oData = $oClient->getOrderReferenceDetails($this, array(), true);
//If we have language string add it to link
if (!empty($oData->GetOrderReferenceDetailsResult->OrderReferenceDetails->OrderLanguage)) {
$sAmazonLanguageString = (string)$oData->GetOrderReferenceDetailsResult->OrderReferenceDetails->OrderLanguage;
$sLink .= str_replace('-', '_', $sAmazonLanguageString);
}
return $sLink;
}
|
Method returns payment method change link for Invalid payment method order
@return string
@throws Exception
|
protected function _getPaymentType(oxOrder $oOrder)
{
$oUserPayment = $oOrder->getPaymentType();
$sPaymentType = $oOrder->getFieldData('oxpaymenttype');
if ($oUserPayment === false && $sPaymentType) {
$oPayment = $this->_getContainer()->getObjectFactory()->createOxidObject('oxPayment');
if ($oPayment->load($sPaymentType)) {
// in case due to security reasons payment info was not kept in db
$oUserPayment = $this->_getContainer()->getObjectFactory()->createOxidObject('oxUserPayment');
$oUserPayment->assign(array('oxdesc' => $oPayment->getFieldData('oxdesc')));
}
}
return $oUserPayment;
}
|
Returns user payment used for current order. In case current order was executed using
credit card and user payment info is not stored in db (if $this->_getContainer()->getConfig()->blStoreCreditCardInfo = false),
just for preview user payment is set from oxPayment
@param oxOrder $oOrder Order object
@return oxUserPayment
@throws oxSystemComponentException
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.