/** * Helper Function - set mail from address * @param $request PKPRequest * @param MailTemplate $mail */ function _setMailFrom($request, &$mail) { $site = $request->getSite(); $press = $request->getPress(); // Set the sender based on the current context if ($press && $press->getSetting('supportEmail')) { $mail->setReplyTo($press->getSetting('supportEmail'), $press->getSetting('supportName')); } else { $mail->setReplyTo($site->getLocalizedContactEmail(), $site->getLocalizedContactName()); } }
function sendReminder($subscription, $journal, $emailKey) { $userDao = DAORegistry::getDAO('UserDAO'); $subscriptionTypeDao = DAORegistry::getDAO('SubscriptionTypeDAO'); $journalName = $journal->getLocalizedName(); $user = $userDao->getById($subscription->getUserId()); if (!isset($user)) { return false; } $subscriptionType = $subscriptionTypeDao->getSubscriptionType($subscription->getTypeId()); $subscriptionName = $journal->getSetting('subscriptionName'); $subscriptionEmail = $journal->getSetting('subscriptionEmail'); $subscriptionPhone = $journal->getSetting('subscriptionPhone'); $subscriptionMailingAddress = $journal->getSetting('subscriptionMailingAddress'); $subscriptionContactSignature = $subscriptionName; AppLocale::requireComponents(LOCALE_COMPONENT_PKP_USER, LOCALE_COMPONENT_APP_COMMON); if ($subscriptionMailingAddress != '') { $subscriptionContactSignature .= "\n" . $subscriptionMailingAddress; } if ($subscriptionPhone != '') { $subscriptionContactSignature .= "\n" . AppLocale::Translate('user.phone') . ': ' . $subscriptionPhone; } $subscriptionContactSignature .= "\n" . AppLocale::Translate('user.email') . ': ' . $subscriptionEmail; $paramArray = array('subscriberName' => $user->getFullName(), 'journalName' => $journalName, 'subscriptionType' => $subscriptionType->getSummaryString(), 'expiryDate' => $subscription->getDateEnd(), 'username' => $user->getUsername(), 'subscriptionContactSignature' => $subscriptionContactSignature); import('lib.pkp.classes.mail.MailTemplate'); $mail = new MailTemplate($emailKey, $journal->getPrimaryLocale(), $journal, false); $mail->setReplyTo($subscriptionEmail, $subscriptionName); $mail->addRecipient($user->getEmail(), $user->getFullName()); $mail->setSubject($mail->getSubject($journal->getPrimaryLocale())); $mail->setBody($mail->getBody($journal->getPrimaryLocale())); $mail->assignParams($paramArray); $mail->send(); }
function sendNotification($users, $journal, $issue) { if ($users->getCount() != 0) { import('lib.pkp.classes.mail.MailTemplate'); $email = new MailTemplate('OPEN_ACCESS_NOTIFY', $journal->getPrimaryLocale()); $email->setSubject($email->getSubject($journal->getPrimaryLocale())); $email->setReplyTo(null); $email->addRecipient($journal->getSetting('contactEmail'), $journal->getSetting('contactName')); $paramArray = array('journalName' => $journal->getLocalizedName(), 'journalUrl' => Request::url($journal->getPath()), 'editorialContactSignature' => $journal->getSetting('contactName') . "\n" . $journal->getLocalizedName()); $email->assignParams($paramArray); $publishedArticleDao = DAORegistry::getDAO('PublishedArticleDAO'); $publishedArticles = $publishedArticleDao->getPublishedArticlesInSections($issue->getId()); $mimeBoundary = '==boundary_' . md5(microtime()); $templateMgr = TemplateManager::getManager(); $templateMgr->assign('body', $email->getBody($journal->getPrimaryLocale())); $templateMgr->assign('templateSignature', $journal->getSetting('emailSignature')); $templateMgr->assign('mimeBoundary', $mimeBoundary); $templateMgr->assign('issue', $issue); $templateMgr->assign('publishedArticles', $publishedArticles); $email->addHeader('MIME-Version', '1.0'); $email->setContentType('multipart/alternative; boundary="' . $mimeBoundary . '"'); $email->setBody($templateMgr->fetch('subscription/openAccessNotifyEmail.tpl')); while ($user = $users->next()) { $email->addBcc($user->getEmail(), $user->getFullName()); } $email->send(); } }
/** * Send email to a book for review author */ function sendReminder($book, $journal, $emailKey) { $journalId = $journal->getId(); $paramArray = array('authorName' => strip_tags($book->getUserFullName()), 'bookForReviewTitle' => '"' . strip_tags($book->getLocalizedTitle()) . '"', 'bookForReviewDueDate' => date('l, F j, Y', strtotime($book->getDateDue())), 'submissionUrl' => Request::url(null, 'author', 'submit'), 'editorialContactSignature' => strip_tags($book->getEditorContactSignature())); import('classes.mail.MailTemplate'); $mail = new MailTemplate($emailKey); $mail->setReplyTo($book->getEditorEmail(), $book->getEditorFullName()); $mail->addRecipient($book->getUserEmail(), $book->getUserFullName()); $mail->setSubject($mail->getSubject($journal->getPrimaryLocale())); $mail->setBody($mail->getBody($journal->getPrimaryLocale())); $mail->assignParams($paramArray); $mail->send(); }
/** * Send the email * @param $args array * @param $request PKPRequest */ function execute($args, $request) { $userDao = DAORegistry::getDAO('UserDAO'); $toUser = $userDao->getById($this->userId); $fromUser = $request->getUser(); import('lib.pkp.classes.mail.MailTemplate'); $email = new MailTemplate(); $email->addRecipient($toUser->getEmail(), $toUser->getFullName()); $email->setReplyTo($fromUser->getEmail(), $fromUser->getFullName()); $email->setSubject($this->getData('subject')); $email->setBody($this->getData('message')); $email->send(); }
/** * Send email to object for review author * @param $ofrAssignment ObjectForReviewAssignment * @param $journal Journal * @param $emailKey string */ function sendReminder($ofrAssignment, $journal, $emailKey) { $journalId = $journal->getId(); $author =& $ofrAssignment->getUser(); $objectForReview =& $ofrAssignment->getObjectForReview(); $editor =& $objectForReview->getEditor(); $paramArray = array('authorName' => strip_tags($author->getFullName()), 'objectForReviewTitle' => '"' . strip_tags($objectForReview->getTitle()) . '"', 'objectForReviewDueDate' => date('l, F j, Y', strtotime($ofrAssignment->getDateDue())), 'submissionUrl' => Request::url($journal->getPath(), 'author', 'submit'), 'editorialContactSignature' => strip_tags($editor->getContactSignature())); import('classes.mail.MailTemplate'); $mail = new MailTemplate($emailKey); $mail->setReplyTo($editor->getEmail(), $editor->getFullName()); $mail->addRecipient($author->getEmail(), $author->getFullName()); $mail->setSubject($mail->getSubject($journal->getPrimaryLocale())); $mail->setBody($mail->getBody($journal->getPrimaryLocale())); $mail->assignParams($paramArray); $mail->send(); $ofrAssignment->setDateReminded(Core::getCurrentDate()); $ofrAssignmentDao =& DAORegistry::getDAO('ObjectForReviewAssignmentDAO'); $ofrAssignmentDao->updateObject($ofrAssignment); }
/** * Handle incoming requests/notifications * @param $args array * @param $request PKPRequest */ function handle($args, $request) { $templateMgr = TemplateManager::getManager($request); $journal = $request->getJournal(); if (!$journal) { return parent::handle($args, $request); } // Just in case we need to contact someone import('lib.pkp.classes.mail.MailTemplate'); // Prefer technical support contact $contactName = $journal->getSetting('supportName'); $contactEmail = $journal->getSetting('supportEmail'); if (!$contactEmail) { // Fall back on primary contact $contactName = $journal->getSetting('contactName'); $contactEmail = $journal->getSetting('contactEmail'); } $mail = new MailTemplate('PAYPAL_INVESTIGATE_PAYMENT'); $mail->setReplyTo(null); $mail->addRecipient($contactEmail, $contactName); $paymentStatus = $request->getUserVar('payment_status'); switch (array_shift($args)) { case 'ipn': // Build a confirmation transaction. $req = 'cmd=_notify-validate'; if (get_magic_quotes_gpc()) { foreach ($_POST as $key => $value) { $req .= '&' . urlencode(stripslashes($key)) . '=' . urlencode(stripslashes($value)); } } else { foreach ($_POST as $key => $value) { $req .= '&' . urlencode($key) . '=' . urlencode($value); } } // Create POST response $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->getSetting($journal->getId(), 'paypalurl')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent: PKP PayPal Service', 'Content-Type: application/x-www-form-urlencoded', 'Content-Length: ' . strlen($req))); curl_setopt($ch, CURLOPT_POSTFIELDS, $req); $ret = curl_exec($ch); $curlError = curl_error($ch); curl_close($ch); // Check the confirmation response and handle as necessary. if (strcmp($ret, 'VERIFIED') == 0) { switch ($paymentStatus) { case 'Completed': $payPalDao = DAORegistry::getDAO('PayPalDAO'); $transactionId = $request->getUserVar('txn_id'); if ($payPalDao->transactionExists($transactionId)) { // A duplicate transaction was received; notify someone. $mail->assignParams(array('journalName' => $journal->getLocalizedName(), 'postInfo' => print_r($_POST, true), 'additionalInfo' => "Duplicate transaction ID: {$transactionId}", 'serverVars' => print_r($_SERVER, true))); $mail->send(); exit; } else { // New transaction succeeded. Record it. $payPalDao->insertTransaction($transactionId, $request->getUserVar('txn_type'), String::strtolower($request->getUserVar('payer_email')), String::strtolower($request->getUserVar('receiver_email')), $request->getUserVar('item_number'), $request->getUserVar('payment_date'), $request->getUserVar('payer_id'), $request->getUserVar('receiver_id')); $queuedPaymentId = $request->getUserVar('custom'); import('classes.payment.ojs.OJSPaymentManager'); $ojsPaymentManager = new OJSPaymentManager($request); // Verify the cost and user details as per PayPal spec. $queuedPayment =& $ojsPaymentManager->getQueuedPayment($queuedPaymentId); if (!$queuedPayment) { // The queued payment entry is missing. Complain. $mail->assignParams(array('journalName' => $journal->getLocalizedName(), 'postInfo' => print_r($_POST, true), 'additionalInfo' => "Missing queued payment ID: {$queuedPaymentId}", 'serverVars' => print_r($_SERVER, true))); $mail->send(); exit; } //NB: if/when paypal subscriptions are enabled, these checks will have to be adjusted // because subscription prices may change over time $queuedAmount = $queuedPayment->getAmount(); $grantedAmount = $request->getUserVar('mc_gross'); $queuedCurrency = $queuedPayment->getCurrencyCode(); $grantedCurrency = $request->getUserVar('mc_currency'); $grantedEmail = String::strtolower($request->getUserVar('receiver_email')); $queuedEmail = String::strtolower($this->getSetting($journal->getId(), 'selleraccount')); if ($queuedAmount != $grantedAmount && $queuedAmount > 0 || $queuedCurrency != $grantedCurrency || $grantedEmail != $queuedEmail) { // The integrity checks for the transaction failed. Complain. $mail->assignParams(array('journalName' => $journal->getLocalizedName(), 'postInfo' => print_r($_POST, true), 'additionalInfo' => "Granted amount: {$grantedAmount}\n" . "Queued amount: {$queuedAmount}\n" . "Granted currency: {$grantedCurrency}\n" . "Queued currency: {$queuedCurrency}\n" . "Granted to PayPal account: {$grantedEmail}\n" . "Configured PayPal account: {$queuedEmail}", 'serverVars' => print_r($_SERVER, true))); $mail->send(); exit; } // Update queued amount if amount set by user (e.g. donation) if ($queuedAmount == 0 && $grantedAmount > 0) { $queuedPaymentDao = DAORegistry::getDAO('QueuedPaymentDAO'); $queuedPayment->setAmount($grantedAmount); $queuedPayment->setCurrencyCode($grantedCurrency); $queuedPaymentDao->updateQueuedPayment($queuedPaymentId, $queuedPayment); } // Fulfill the queued payment. if ($ojsPaymentManager->fulfillQueuedPayment($request, $queuedPayment, $this->getName())) { exit; } // If we're still here, it means the payment couldn't be fulfilled. $mail->assignParams(array('journalName' => $journal->getLocalizedName(), 'postInfo' => print_r($_POST, true), 'additionalInfo' => "Queued payment ID {$queuedPaymentId} could not be fulfilled.", 'serverVars' => print_r($_SERVER, true))); $mail->send(); } exit; case 'Pending': // Ignore. exit; default: // An unhandled payment status was received; notify someone. $mail->assignParams(array('journalName' => $journal->getLocalizedName(), 'postInfo' => print_r($_POST, true), 'additionalInfo' => "Payment status: {$paymentStatus}", 'serverVars' => print_r($_SERVER, true))); $mail->send(); exit; } } else { // An unknown confirmation response was received; notify someone. $mail->assignParams(array('journalName' => $journal->getLocalizedName(), 'postInfo' => print_r($_POST, true), 'additionalInfo' => "Confirmation return: {$ret}\nCURL error: {$curlError}", 'serverVars' => print_r($_SERVER, true))); $mail->send(); exit; } case 'cancel': Handler::setupTemplate(); $templateMgr->assign(array('currentUrl' => $request->url(null, 'index'), 'pageTitle' => 'plugins.paymethod.paypal.purchase.cancelled.title', 'message' => 'plugins.paymethod.paypal.purchase.cancelled', 'backLink' => $request->getUserVar('ojsReturnUrl'), 'backLinkLabel' => 'common.continue')); $templateMgr->display('frontend/pages/message.tpl'); exit; } parent::handle($args, $request); // Don't know what to do with it }
/** * Send notification email to Subscription Manager when online payment is completed. */ function sendOnlinePaymentNotificationEmail($request, &$subscription, $mailTemplateKey) { $validKeys = array('SUBSCRIPTION_PURCHASE_INDL', 'SUBSCRIPTION_PURCHASE_INSTL', 'SUBSCRIPTION_RENEW_INDL', 'SUBSCRIPTION_RENEW_INSTL'); if (!in_array($mailTemplateKey, $validKeys)) { return false; } $journal = $request->getJournal(); $subscriptionContactName = $journal->getSetting('subscriptionName'); $subscriptionContactEmail = $journal->getSetting('subscriptionEmail'); if (empty($subscriptionContactEmail)) { $subscriptionContactEmail = $journal->getSetting('contactEmail'); $subscriptionContactName = $journal->getSetting('contactName'); } if (empty($subscriptionContactEmail)) { return false; } $userDao = DAORegistry::getDAO('UserDAO'); $user = $userDao->getById($subscription->getUserId()); $subscriptionTypeDao = DAORegistry::getDAO('SubscriptionTypeDAO'); $subscriptionType =& $subscriptionTypeDao->getSubscriptionType($subscription->getTypeId()); $roleDao = DAORegistry::getDAO('RoleDAO'); $role = $roleDao->newDataObject(); if ($roleDao->getJournalUsersRoleCount($journal->getId(), ROLE_ID_SUBSCRIPTION_MANAGER) > 0) { $role->setId(ROLE_ID_SUBSCRIPTION_MANAGER); $rolePath = $role->getPath(); } else { $role->setId(ROLE_ID_MANAGER); $rolePath = $role->getPath(); } $paramArray = array('subscriptionType' => $subscriptionType->getSummaryString(), 'userDetails' => $user->getContactSignature(), 'membership' => $subscription->getMembership()); switch ($mailTemplateKey) { case 'SUBSCRIPTION_PURCHASE_INDL': case 'SUBSCRIPTION_RENEW_INDL': $paramArray['subscriptionUrl'] = $request->url($journal->getPath(), $rolePath, 'editSubscription', 'individual', array($subscription->getId())); break; case 'SUBSCRIPTION_PURCHASE_INSTL': case 'SUBSCRIPTION_RENEW_INSTL': $paramArray['subscriptionUrl'] = $request->rl($journal->getPath(), $rolePath, 'editSubscription', 'institutional', array($subscription->getId())); $paramArray['institutionName'] = $subscription->getInstitutionName(); $paramArray['institutionMailingAddress'] = $subscription->getInstitutionMailingAddress(); $paramArray['domain'] = $subscription->getDomain(); $paramArray['ipRanges'] = $subscription->getIPRangesString(); break; } import('lib.pkp.classes.mail.MailTemplate'); $mail = new MailTemplate($mailTemplateKey); $mail->setReplyTo($subscriptionContactEmail, $subscriptionContactName); $mail->addRecipient($subscriptionContactEmail, $subscriptionContactName); $mail->setSubject($mail->getSubject($journal->getPrimaryLocale())); $mail->setBody($mail->getBody($journal->getPrimaryLocale())); $mail->assignParams($paramArray); $mail->send(); }
/** * Register a new user. */ function execute() { $userDao =& DAORegistry::getDAO('UserDAO'); $journal =& Request::getJournal(); if (isset($this->userId)) { $user =& $userDao->getById($this->userId); } if (!isset($user)) { $user = new User(); } $user->setSalutation($this->getData('salutation')); $user->setFirstName($this->getData('firstName')); $user->setMiddleName($this->getData('middleName')); $user->setLastName($this->getData('lastName')); $user->setInitials($this->getData('initials')); $user->setGender($this->getData('gender')); $user->setAffiliation($this->getData('affiliation'), null); // Localized $user->setSignature($this->getData('signature'), null); // Localized $user->setEmail($this->getData('email')); $user->setData('orcid', $this->getData('orcid')); $user->setUrl($this->getData('userUrl')); $user->setPhone($this->getData('phone')); $user->setFax($this->getData('fax')); $user->setMailingAddress($this->getData('mailingAddress')); $user->setCountry($this->getData('country')); $user->setBiography($this->getData('biography'), null); // Localized $user->setGossip($this->getData('gossip'), null); // Localized $user->setMustChangePassword($this->getData('mustChangePassword') ? 1 : 0); $user->setAuthId((int) $this->getData('authId')); $site =& Request::getSite(); $availableLocales = $site->getSupportedLocales(); $locales = array(); foreach ($this->getData('userLocales') as $locale) { if (AppLocale::isLocaleValid($locale) && in_array($locale, $availableLocales)) { array_push($locales, $locale); } } $user->setLocales($locales); if ($user->getAuthId()) { $authDao =& DAORegistry::getDAO('AuthSourceDAO'); $auth =& $authDao->getPlugin($user->getAuthId()); } if ($user->getId() != null) { $userId = $user->getId(); if ($this->getData('password') !== '') { if (isset($auth)) { $auth->doSetUserPassword($user->getUsername(), $this->getData('password')); $user->setPassword(Validation::encryptCredentials($userId, Validation::generatePassword())); // Used for PW reset hash only } else { $user->setPassword(Validation::encryptCredentials($user->getUsername(), $this->getData('password'))); } } if (isset($auth)) { // FIXME Should try to create user here too? $auth->doSetUserInfo($user); } $userDao->updateObject($user); } else { $user->setUsername($this->getData('username')); if ($this->getData('generatePassword')) { $password = Validation::generatePassword(); $sendNotify = true; } else { $password = $this->getData('password'); $sendNotify = $this->getData('sendNotify'); } if (isset($auth)) { $user->setPassword($password); // FIXME Check result and handle failures $auth->doCreateUser($user); $user->setAuthId($auth->authId); $user->setPassword(Validation::encryptCredentials($user->getId(), Validation::generatePassword())); // Used for PW reset hash only } else { $user->setPassword(Validation::encryptCredentials($this->getData('username'), $password)); } $user->setDateRegistered(Core::getCurrentDate()); $userId = $userDao->insertUser($user); $isManager = Validation::isJournalManager(); if (!empty($this->_data['enrollAs'])) { foreach ($this->getData('enrollAs') as $roleName) { // Enroll new user into an initial role $roleDao =& DAORegistry::getDAO('RoleDAO'); $roleId = $roleDao->getRoleIdFromPath($roleName); if (!$isManager && $roleId != ROLE_ID_READER) { continue; } if ($roleId != null) { $role = new Role(); $role->setJournalId($journal->getId()); $role->setUserId($userId); $role->setRoleId($roleId); $roleDao->insertRole($role); } } } if ($sendNotify) { // Send welcome email to user import('classes.mail.MailTemplate'); $mail = new MailTemplate('USER_REGISTER'); $mail->setReplyTo(null); $mail->assignParams(array('username' => $this->getData('username'), 'password' => $password, 'userFullName' => $user->getFullName())); $mail->addRecipient($user->getEmail(), $user->getFullName()); $mail->send(); } } // Insert the user interests $interests = $this->getData('interestsKeywords') ? $this->getData('interestsKeywords') : $this->getData('interestsTextOnly'); import('lib.pkp.classes.user.InterestManager'); $interestManager = new InterestManager(); $interestManager->setInterestsForUser($user, $interests); }
/** * Create or update a user. * @param $args array * @param $request PKPRequest */ function &execute($args, $request) { parent::execute($request); $userDao = DAORegistry::getDAO('UserDAO'); $context = $request->getContext(); if (isset($this->userId)) { $userId = $this->userId; $user = $userDao->getById($userId); } if (!isset($user)) { $user = $userDao->newDataObject(); $user->setInlineHelp(1); // default new users to having inline help visible } $user->setSalutation($this->getData('salutation')); $user->setFirstName($this->getData('firstName')); $user->setMiddleName($this->getData('middleName')); $user->setLastName($this->getData('lastName')); $user->setSuffix($this->getData('suffix')); $user->setInitials($this->getData('initials')); $user->setGender($this->getData('gender')); $user->setAffiliation($this->getData('affiliation'), null); // Localized $user->setSignature($this->getData('signature'), null); // Localized $user->setEmail($this->getData('email')); $user->setUrl($this->getData('userUrl')); $user->setPhone($this->getData('phone')); $user->setOrcid($this->getData('orcid')); $user->setMailingAddress($this->getData('mailingAddress')); $user->setCountry($this->getData('country')); $user->setBiography($this->getData('biography'), null); // Localized $user->setMustChangePassword($this->getData('mustChangePassword') ? 1 : 0); $user->setAuthId((int) $this->getData('authId')); $site = $request->getSite(); $availableLocales = $site->getSupportedLocales(); $locales = array(); foreach ($this->getData('userLocales') as $locale) { if (AppLocale::isLocaleValid($locale) && in_array($locale, $availableLocales)) { array_push($locales, $locale); } } $user->setLocales($locales); if ($user->getAuthId()) { $authDao = DAORegistry::getDAO('AuthSourceDAO'); $auth =& $authDao->getPlugin($user->getAuthId()); } if ($user->getId() != null) { if ($this->getData('password') !== '') { if (isset($auth)) { $auth->doSetUserPassword($user->getUsername(), $this->getData('password')); $user->setPassword(Validation::encryptCredentials($user->getId(), Validation::generatePassword())); // Used for PW reset hash only } else { $user->setPassword(Validation::encryptCredentials($user->getUsername(), $this->getData('password'))); } } if (isset($auth)) { // FIXME Should try to create user here too? $auth->doSetUserInfo($user); } $userDao->updateObject($user); } else { $user->setUsername($this->getData('username')); if ($this->getData('generatePassword')) { $password = Validation::generatePassword(); $sendNotify = true; } else { $password = $this->getData('password'); $sendNotify = $this->getData('sendNotify'); } if (isset($auth)) { $user->setPassword($password); // FIXME Check result and handle failures $auth->doCreateUser($user); $user->setAuthId($auth->authId); $user->setPassword(Validation::encryptCredentials($user->getId(), Validation::generatePassword())); // Used for PW reset hash only } else { $user->setPassword(Validation::encryptCredentials($this->getData('username'), $password)); } $user->setDateRegistered(Core::getCurrentDate()); $userId = $userDao->insertObject($user); if ($sendNotify) { // Send welcome email to user import('lib.pkp.classes.mail.MailTemplate'); $mail = new MailTemplate('USER_REGISTER'); $mail->setReplyTo($context->getSetting('contactEmail'), $context->getSetting('contactName')); $mail->assignParams(array('username' => $this->getData('username'), 'password' => $password, 'userFullName' => $user->getFullName())); $mail->addRecipient($user->getEmail(), $user->getFullName()); $mail->send(); } } import('lib.pkp.classes.user.InterestManager'); $interestManager = new InterestManager(); $interestManager->setInterestsForUser($user, $this->getData('interests')); return $user; }
/** * Internal function to prepare notification email * @param $emailTemplateKey string */ function _prepareNotificationEmail($mailTemplateKey) { $userDao = DAORegistry::getDAO('UserDAO'); $subscriptionTypeDao = DAORegistry::getDAO('SubscriptionTypeDAO'); $journalSettingsDao = DAORegistry::getDAO('JournalSettingsDAO'); $journal = Request::getJournal(); $journalName = $journal->getLocalizedTitle(); $journalId = $journal->getId(); $user = $userDao->getById($this->subscription->getUserId()); $subscriptionType =& $subscriptionTypeDao->getSubscriptionType($this->subscription->getTypeId()); $subscriptionName = $journalSettingsDao->getSetting($journalId, 'subscriptionName'); $subscriptionEmail = $journalSettingsDao->getSetting($journalId, 'subscriptionEmail'); $subscriptionPhone = $journalSettingsDao->getSetting($journalId, 'subscriptionPhone'); $subscriptionMailingAddress = $journalSettingsDao->getSetting($journalId, 'subscriptionMailingAddress'); $subscriptionContactSignature = $subscriptionName; if ($subscriptionMailingAddress != '') { $subscriptionContactSignature .= "\n" . $subscriptionMailingAddress; } if ($subscriptionPhone != '') { $subscriptionContactSignature .= "\n" . __('user.phone') . ': ' . $subscriptionPhone; } $subscriptionContactSignature .= "\n" . __('user.email') . ': ' . $subscriptionEmail; $paramArray = array('subscriberName' => $user->getFullName(), 'journalName' => $journalName, 'subscriptionType' => $subscriptionType->getSummaryString(), 'username' => $user->getUsername(), 'subscriptionContactSignature' => $subscriptionContactSignature); import('lib.pkp.classes.mail.MailTemplate'); $mail = new MailTemplate($mailTemplateKey); $mail->setReplyTo($subscriptionEmail, $subscriptionName); $mail->addRecipient($user->getEmail(), $user->getFullName()); $mail->setSubject($mail->getSubject($journal->getPrimaryLocale())); $mail->setBody($mail->getBody($journal->getPrimaryLocale())); $mail->assignParams($paramArray); return $mail; }
/** * Fulfill a queued payment. * @param $request PKPRequest * @param $queuedPayment QueuedPayment * @param $payMethodPluginName string Name of payment plugin. * @return mixed Dependent on payment type. */ function fulfillQueuedPayment($request, &$queuedPayment, $payMethodPluginName = null) { $returner = false; if ($queuedPayment) { switch ($queuedPayment->getType()) { case PAYMENT_TYPE_MEMBERSHIP: $userDao = DAORegistry::getDAO('UserDAO'); $user =& $userDao->getById($queuedPayment->getuserId()); $userDao->renewMembership($user); $returner = true; break; case PAYMENT_TYPE_PURCHASE_SUBSCRIPTION: $subscriptionId = $queuedPayment->getAssocId(); $institutionalSubscriptionDao = DAORegistry::getDAO('InstitutionalSubscriptionDAO'); $individualSubscriptionDao = DAORegistry::getDAO('IndividualSubscriptionDAO'); if ($institutionalSubscriptionDao->subscriptionExists($subscriptionId)) { $subscription =& $institutionalSubscriptionDao->getSubscription($subscriptionId); $institutional = true; } else { $subscription =& $individualSubscriptionDao->getSubscription($subscriptionId); $institutional = false; } if (!$subscription || $subscription->getUserId() != $queuedPayment->getUserId() || $subscription->getJournalId() != $queuedPayment->getJournalId()) { // FIXME: Is this supposed to be here? error_log(print_r($subscription, true)); return false; } // Update subscription end date now that payment is completed if ($institutional) { // Still requires approval from JM/SM since includes domain and IP ranges import('classes.subscription.InstitutionalSubscription'); $subscription->setStatus(SUBSCRIPTION_STATUS_NEEDS_APPROVAL); if ($subscription->isNonExpiring()) { $institutionalSubscriptionDao->updateSubscription($subscription); } else { $institutionalSubscriptionDao->renewSubscription($subscription); } // Notify JM/SM of completed online purchase $journalSettingsDao = DAORegistry::getDAO('JournalSettingsDAO'); if ($journalSettingsDao->getSetting($subscription->getJournalId(), 'enableSubscriptionOnlinePaymentNotificationPurchaseInstitutional')) { import('classes.subscription.SubscriptionAction'); SubscriptionAction::sendOnlinePaymentNotificationEmail($request, $subscription, 'SUBSCRIPTION_PURCHASE_INSTL'); } } else { import('classes.subscription.IndividualSubscription'); $subscription->setStatus(SUBSCRIPTION_STATUS_ACTIVE); if ($subscription->isNonExpiring()) { $individualSubscriptionDao->updateSubscription($subscription); } else { $individualSubscriptionDao->renewSubscription($subscription); } // Notify JM/SM of completed online purchase $journalSettingsDao = DAORegistry::getDAO('JournalSettingsDAO'); if ($journalSettingsDao->getSetting($subscription->getJournalId(), 'enableSubscriptionOnlinePaymentNotificationPurchaseIndividual')) { import('classes.subscription.SubscriptionAction'); SubscriptionAction::sendOnlinePaymentNotificationEmail($request, $subscription, 'SUBSCRIPTION_PURCHASE_INDL'); } } $returner = true; break; case PAYMENT_TYPE_RENEW_SUBSCRIPTION: $subscriptionId = $queuedPayment->getAssocId(); $institutionalSubscriptionDao = DAORegistry::getDAO('InstitutionalSubscriptionDAO'); $individualSubscriptionDao = DAORegistry::getDAO('IndividualSubscriptionDAO'); if ($institutionalSubscriptionDao->subscriptionExists($subscriptionId)) { $subscription =& $institutionalSubscriptionDao->getSubscription($subscriptionId); $institutional = true; } else { $subscription =& $individualSubscriptionDao->getSubscription($subscriptionId); $institutional = false; } if (!$subscription || $subscription->getUserId() != $queuedPayment->getUserId() || $subscription->getJournalId() != $queuedPayment->getJournalId()) { // FIXME: Is this supposed to be here? error_log(print_r($subscription, true)); return false; } if ($institutional) { $institutionalSubscriptionDao->renewSubscription($subscription); // Notify JM/SM of completed online purchase $journalSettingsDao = DAORegistry::getDAO('JournalSettingsDAO'); if ($journalSettingsDao->getSetting($subscription->getJournalId(), 'enableSubscriptionOnlinePaymentNotificationRenewInstitutional')) { import('classes.subscription.SubscriptionAction'); SubscriptionAction::sendOnlinePaymentNotificationEmail($request, $subscription, 'SUBSCRIPTION_RENEW_INSTL'); } } else { $individualSubscriptionDao->renewSubscription($subscription); // Notify JM/SM of completed online purchase $journalSettingsDao = DAORegistry::getDAO('JournalSettingsDAO'); if ($journalSettingsDao->getSetting($subscription->getJournalId(), 'enableSubscriptionOnlinePaymentNotificationRenewIndividual')) { import('classes.subscription.SubscriptionAction'); SubscriptionAction::sendOnlinePaymentNotificationEmail($request, $subscription, 'SUBSCRIPTION_RENEW_INDL'); } } $returner = true; break; case PAYMENT_TYPE_FASTTRACK: $articleDao = DAORegistry::getDAO('ArticleDAO'); $article = $articleDao->getById($queuedPayment->getAssocId(), $queuedPayment->getJournalId()); $article->setFastTracked(true); $articleDao->updateObject($article); $returner = true; break; case PAYMENT_TYPE_GIFT: $giftId = $queuedPayment->getAssocId(); $giftDao = DAORegistry::getDAO('GiftDAO'); $gift =& $giftDao->getGift($giftId); if (!$gift) { return false; } $password = null; // Suppress scrutinizer warn $journalDao = DAORegistry::getDAO('JournalDAO'); $journalId = $gift->getAssocId(); $journal = $journalDao->getById($journalId); if (!$journal) { return false; } // Check if user account corresponding to recipient email exists in the system $userDao = DAORegistry::getDAO('UserDAO'); $roleDao = DAORegistry::getDAO('RoleDAO'); $recipientFirstName = $gift->getRecipientFirstName(); $recipientEmail = $gift->getRecipientEmail(); $newUserAccount = false; if ($userDao->userExistsByEmail($recipientEmail)) { // User already has account, check if enrolled as reader in journal $user = $userDao->getUserByEmail($recipientEmail); $userId = $user->getId(); if (!$roleDao->userHasRole($journalId, $userId, ROLE_ID_READER)) { // User not enrolled as reader, enroll as reader $role = new Role(); $role->setJournalId($journalId); $role->setUserId($userId); $role->setRoleId(ROLE_ID_READER); $roleDao->insertRole($role); } } else { // User does not have an account. Create one and enroll as reader. $recipientLastName = $gift->getRecipientLastName(); $username = Validation::suggestUsername($recipientFirstName, $recipientLastName); $password = Validation::generatePassword(); $user = $userDao->newDataObject(); $user->setUsername($username); $user->setPassword(Validation::encryptCredentials($username, $password)); $user->setFirstName($recipientFirstName); $user->setMiddleName($gift->getRecipientMiddleName()); $user->setLastName($recipientLastName); $user->setEmail($recipientEmail); $user->setDateRegistered(Core::getCurrentDate()); $userDao->insertObject($user); $userId = $user->getId(); $role = new Role(); $role->setJournalId($journalId); $role->setUserId($userId); $role->setRoleId(ROLE_ID_READER); $roleDao->insertRole($role); $newUserAccount = true; } // Update gift status (make it redeemable) and add recipient user account reference import('classes.gift.Gift'); $gift->setStatus(GIFT_STATUS_NOT_REDEEMED); $gift->setRecipientUserId($userId); $giftDao->updateObject($gift); // Send gift available email to recipient, cc buyer $giftNoteTitle = $gift->getGiftNoteTitle(); $buyerFullName = $gift->getBuyerFullName(); $giftNote = $gift->getGiftNote(); $giftLocale = $gift->getLocale(); AppLocale::requireComponents(LOCALE_COMPONENT_APP_COMMON, $giftLocale); $giftDetails = $gift->getGiftName($giftLocale); $giftJournalName = $journal->getName($giftLocale); $giftContactSignature = $journal->getSetting('contactName'); import('lib.pkp.classes.mail.MailTemplate'); $mail = new MailTemplate('GIFT_AVAILABLE', $giftLocale); $mail->setReplyTo(null); $mail->assignParams(array('giftJournalName' => $giftJournalName, 'giftNoteTitle' => $giftNoteTitle, 'recipientFirstName' => $recipientFirstName, 'buyerFullName' => $buyerFullName, 'giftDetails' => $giftDetails, 'giftNote' => $giftNote, 'giftContactSignature' => $giftContactSignature)); $mail->addRecipient($recipientEmail, $user->getFullName()); $mail->addCc($gift->getBuyerEmail(), $gift->getBuyerFullName()); $mail->send(); unset($mail); // Send gift login details to recipient $params = array('giftJournalName' => $giftJournalName, 'recipientFirstName' => $recipientFirstName, 'buyerFullName' => $buyerFullName, 'giftDetails' => $giftDetails, 'giftUrl' => $request->url($journal->getPath(), 'user', 'gifts'), 'username' => $user->getUsername(), 'giftContactSignature' => $giftContactSignature); if ($newUserAccount) { $mail = new MailTemplate('GIFT_USER_REGISTER', $giftLocale); $params['password'] = $password; } else { $mail = new MailTemplate('GIFT_USER_LOGIN', $giftLocale); } $mail->setReplyTo(null); $mail->assignParams($params); $mail->addRecipient($recipientEmail, $user->getFullName()); $mail->send(); unset($mail); $returner = true; break; case PAYMENT_TYPE_PURCHASE_ARTICLE: case PAYMENT_TYPE_PURCHASE_ISSUE: case PAYMENT_TYPE_DONATION: case PAYMENT_TYPE_SUBMISSION: case PAYMENT_TYPE_PUBLICATION: $returner = true; break; default: // Invalid payment type assert(false); } } $completedPaymentDao = DAORegistry::getDAO('OJSCompletedPaymentDAO'); $completedPayment =& $this->createCompletedPayment($queuedPayment, $payMethodPluginName); $completedPaymentDao->insertCompletedPayment($completedPayment); $queuedPaymentDao = DAORegistry::getDAO('QueuedPaymentDAO'); $queuedPaymentDao->deleteQueuedPayment($queuedPayment->getId()); return $returner; }
/** * Static function to send an email to a mailing list user e.g. regarding signup * @param $request PKPRequest * @param $email string * @param $token string the user's token (for confirming and unsubscribing) * @param $template string The mail template to use */ function sendMailingListEmail(&$request, $email, $token, $template) { import('classes.mail.MailTemplate'); $site = $request->getSite(); $router =& $request->getRouter(); $dispatcher =& $router->getDispatcher(); $params = array('siteTitle' => $site->getLocalizedTitle(), 'unsubscribeLink' => $dispatcher->url($request, ROUTE_PAGE, null, 'notification', 'unsubscribeMailList', array($token))); if ($template == 'NOTIFICATION_MAILLIST_WELCOME') { $router =& $request->getRouter(); $dispatcher =& $router->getDispatcher(); $confirmLink = $dispatcher->url($request, ROUTE_PAGE, null, 'notification', 'confirmMailListSubscription', array($token)); $params["confirmLink"] = $confirmLink; } $mail = new MailTemplate($template); $mail->setReplyTo($site->getLocalizedContactEmail(), $site->getLocalizedContactName()); $mail->assignParams($params); $mail->addRecipient($email); $mail->send(); }
/** * Handle incoming requests/notifications * @param $args array * @param $request PKPRequest */ function handle($args, &$request) { $user =& $request->getUser(); $templateMgr =& TemplateManager::getManager(); $journal =& $request->getJournal(); if (!$journal) { return parent::handle($args, $request); } // Just in case we need to contact someone import('classes.mail.MailTemplate'); // Prefer technical support contact $contactName = $journal->getSetting('supportName'); $contactEmail = $journal->getSetting('supportEmail'); if (!$contactEmail) { // Fall back on primary contact $contactName = $journal->getSetting('contactName'); $contactEmail = $journal->getSetting('contactEmail'); } $mail = new MailTemplate('DPS_INVESTIGATE_PAYMENT'); $mail->setReplyTo(null); $mail->addRecipient($contactEmail, $contactName); $paymentStatus = $request->getUserVar('payment_status'); @session_start(); switch (array_shift($args)) { case 'purchase': error_log("Forming XML for transaction API call"); try { # get access to queuedPayment $orderId = $_SESSION['dps_plugin_payment_id']; import('classes.payment.ojs.OJSPaymentManager'); $ojsPaymentManager = new OJSPaymentManager($request); $queuedPayment =& $ojsPaymentManager->getQueuedPayment($orderId); if (!$queuedPayment) { throw new Exception("OJS: DPS: No order for this transaction or transaction ID lost from session. See DPS statement for OJS order number: TxnData1."); } $amount = sprintf("%01.2f", $queuedPayment->amount); $domDoc = new DOMDocument('1.0', 'UTF-8'); $rootElt = $domDoc->createElement('GenerateRequest'); $rootNode = $domDoc->appendChild($rootElt); $rootNode->appendChild($domDoc->createElement('PxPayUserId', $this->getSetting($journal->getId(), 'dpsuser'))); $rootNode->appendChild($domDoc->createElement('PxPayKey', $this->getSetting($journal->getId(), 'dpskey'))); $rootNode->appendChild($domDoc->createElement('MerchantReference', $this->getSetting($journal->getId(), 'dpsmerchant'))); $rootNode->appendChild($domDoc->createElement('AmountInput', $amount)); $rootNode->appendChild($domDoc->createElement('CurrencyInput', 'NZD')); $rootNode->appendChild($domDoc->createElement('TxnType', 'Purchase')); $rootNode->appendChild($domDoc->createElement('TxnData1', $orderId)); $rootNode->appendChild($domDoc->createElement('TxnData2', $user->getUserName())); $rootNode->appendChild($domDoc->createElement('EmailAddress', $user->getEmail())); $rootNode->appendChild($domDoc->createElement('UrlSuccess', $request->url(null, 'payment', 'plugin', array($this->getName(), 'success')))); $rootNode->appendChild($domDoc->createElement('UrlFail', $request->url(null, 'payment', 'plugin', array($this->getName(), 'failure')))); $xmlRequest = $domDoc->saveXML(); if (!$xmlRequest) { throw new Exception("DPS: Generating XML API call failed ", "119"); } error_log("xmlrequest: " . print_r($xmlRequest, true)); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->getSetting($journal->getId(), 'dpsurl')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $domDoc->saveXML()); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_CAINFO, $this->getSetting($journal->getId(), 'dpscertpath')); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $result = curl_exec($ch); $curlError = curl_error($ch); $curlErrorNo = curl_errno($ch); curl_close($ch); # check that we got a response if ($result == false) { error_log("DPS error: {$curlError} ({$curlErrorNo})"); throw new Exception("DPS error: {$curlError}", $curlErrorNo); } # make sure response is valid. error_log("Parsing response XML"); libxml_use_internal_errors(true); $rexml = simplexml_load_string($result); error_log("XML response: " . print_r($rexml, true)); if (!$rexml) { error_log("Invalid XML response from DPS"); throw new Exception("Invalid XML response from DPS"); } # check URL exists in response if (!isset($rexml->URI[0])) { throw new Exception("URI not returned: " . $rexml->ResponseText[0]); } $payment_url = (string) $rexml->URI[0]; # redirect to that URL header("Location: {$payment_url}"); exit; } catch (exception $e) { @curl_close($ch); error_log("Fatal error with credit card entry stage: " . $e->getCode() . ": " . $e->getMessage()); # create a notification about this error $params = array('contents' => "Fatal error with DPS response stage: " . $e->getMessage() . ". User:"******". Email:" . $user->getEmail() . "."); if (!$this->sendNotifications($params, $request)) { error_log("Failed to send notifications to journal managers"); } AppLocale::requireComponents(LOCALE_COMPONENT_APPLICATION_COMMON); $templateMgr =& TemplateManager::getManager(); $templateMgr->assign(array('pageTitle' => 'plugins.paymethod.dps.purchase.failure.title', 'detail' => $e->getMessage(), 'backLink' => $request->url(null, 'user', 'subscriptions'))); $templateMgr->display($this->getTemplatePath() . 'failure.tpl'); exit; } break; case 'success': try { error_log("Forming XML ProcessResponse"); $domDoc = new DOMDocument('1.0', 'UTF-8'); $rootElt = $domDoc->createElement('ProcessResponse'); $rootNode = $domDoc->appendChild($rootElt); $rootNode->appendChild($domDoc->createElement('PxPayUserId', $this->getSetting($journal->getId(), 'dpsuser'))); $rootNode->appendChild($domDoc->createElement('PxPayKey', $this->getSetting($journal->getId(), 'dpskey'))); $rootNode->appendChild($domDoc->createElement('Response', $request->getUserVar('result'))); $xmlRequest = $domDoc->saveXML(); if (!$xmlRequest) { throw new Exception("Failed to generate XML transaction response"); } # send confirmation to DPS error_log("Forming curl API request"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->getSetting($journal->getId(), 'dpsurl')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $domDoc->saveXML()); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_CAINFO, $this->getSetting($journal->getId(), 'dpscertpath')); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_TIMEOUT, 10); # check response is OK $result = curl_exec($ch); $curlError = curl_error($ch); $curlErrorNo = curl_errno($ch); curl_close($ch); if ($result == false) { error_log("Transaction response call failed: {$curlError} ({$curlErrorNo})"); throw new Exception("Transaction response call failed: {$curlError}", $curlErrorNo); } error_log("Processing response"); libxml_use_internal_errors(true); $rexml = simplexml_load_string($result); # check xml is valid if (!$rexml) { throw new Exception('Response from DPS not valid XML ', '130'); } # check for success value if ($rexml->Success[0] == null) { throw new Exception('Response code not returned by DPS', '130'); } # check for failed transaction $code = (int) $rexml->Success[0]; if ($code != 1) { throw new Exception('Transaction failed: ' . $rexml->ResponseText[0]); } if ($rexml->ResponseText[0] == null) { throw new Exception('OJS: DPS: Response text not returned from transaction confirmation'); } if ($rexml->TxnId[0] == null) { throw new Exception('OJS: DPS: Reference number (txnId) not returned from transaction confirmation'); } if ($rexml->MerchantReference[0] == null) { throw new Exception('OJS: DPS: Merchant reference not returned from transaction confirmation'); } # sanity / double checks # get access to queuedPayment to check that details match $queuedPaymentId = $_SESSION['dps_plugin_payment_id']; import('classes.payment.ojs.OJSPaymentManager'); $ojsPaymentManager = new OJSPaymentManager($request); $queuedPayment =& $ojsPaymentManager->getQueuedPayment($queuedPaymentId); if (!$queuedPayment) { throw new Exception("OJS: DPS: No order for this transaction or transaction ID lost from session. See DPS statement for OJS order number: TxnData1."); } $amount = $queuedPayment->amount; $paidAmount = (string) $rexml->AmountSettlement[0]; $pattern = "/[0-9]+(\\.[0-9]{2})?/"; if ($paidAmount == null) { throw new Exception('Paid amount not returned by DPS', '160'); } if (!preg_match($pattern, $paidAmount)) { # check format whether correct for paid amount, etc: no negative throw new Exception('Paid amount format error: negative? badly formed decimal: ' . $paidAmount, '170'); } # check userid returned by DPS if ($rexml->TxnData2[0] == null) { throw new Exception('Validation failure due to user id is not returned by DPS', '180'); } # check user id and amount match if (number_format($paidAmount, 2, '.', '') != $amount) { throw new Exception('Payment amount mismatch on transaction. Expected: ' . $amount . ' got: ' . $paidAmount); } $userId = (string) $rexml->TxnData2[0]; if ($user->getUserName() != $userId) { throw new Exception('User identity mismatch on transaction. Expected: ' . $user->getUserName() . ' got: ' . $userId); } # clear session vars - avoid replay unset($_SESSION['dps_plugin_payment_id']); # tick off queued payment as paid if (!$ojsPaymentManager->fulfillQueuedPayment($queuedPayment, $this->getName())) { throw new Exception('Could not fulill the queued payment in OJS'); } error_log("All validation tests pass. Transaction is OK."); # show success page with details AppLocale::requireComponents(LOCALE_COMPONENT_PKP_COMMON, LOCALE_COMPONENT_PKP_USER, LOCALE_COMPONENT_APPLICATION_COMMON); $templateMgr->assign(array('pageTitle' => 'plugins.paymethod.dps.purchase.success.title', 'message' => 'plugins.paymethod.dps.purchase.success', 'backLink' => $request->url(null, 'index'), 'backLinkLabel' => 'common.continue')); $templateMgr->display($this->getTemplatePath() . 'success.tpl'); exit; break; } catch (exception $e) { @curl_close($ch); error_log("Fatal error with payment processing stage: " . $e->getCode() . ": " . $e->getMessage()); # make notification $params = array('contents' => "Fatal error with DPS response stage: " . $e->getMessage() . ". User:"******". Email:" . $user->getEmail() . "."); if (!$this->sendNotifications($params, $request)) { error_log("Failed to send notifications to journal managers"); } # render failure page to user AppLocale::requireComponents(LOCALE_COMPONENT_APPLICATION_COMMON); $templateMgr =& TemplateManager::getManager(); $templateMgr->assign(array('pageTitle' => 'plugins.paymethod.dps.purchase.failure.title', 'detail' => $e->getMessage(), 'backLink' => $request->url(null, 'user', 'subscriptions'))); $templateMgr->display($this->getTemplatePath() . 'failure.tpl'); exit; } break; # DPS requested our failure URL - eg user canceled form # DPS requested our failure URL - eg user canceled form case 'failure': AppLocale::requireComponents(LOCALE_COMPONENT_APPLICATION_COMMON); $templateMgr =& TemplateManager::getManager(); $templateMgr->assign(array('pageTitle' => 'plugins.paymethod.dps.purchase.failure.title', 'backLink' => $request->url(null, 'user', 'subscriptions'))); $templateMgr->display($this->getTemplatePath() . 'cancel.tpl'); break; } parent::handle($args, $request); // Don't know what to do with it }
/** * Save review assignment * @param $args array * @param $request PKPRequest */ function execute($args, $request) { $userDao = DAORegistry::getDAO('UserDAO'); $user = $userDao->newDataObject(); $user->setFirstName($this->getData('firstName')); $user->setMiddleName($this->getData('middleName')); $user->setLastName($this->getData('lastName')); $user->setEmail($this->getData('email')); $authDao = DAORegistry::getDAO('AuthSourceDAO'); $auth = $authDao->getDefaultPlugin(); $user->setAuthId($auth ? $auth->getAuthId() : 0); $user->setInlineHelp(1); // default new reviewers to having inline help visible $user->setUsername($this->getData('username')); $password = Validation::generatePassword(); if (isset($auth)) { $user->setPassword($password); // FIXME Check result and handle failures $auth->doCreateUser($user); $user->setAuthId($auth->authId); $user->setPassword(Validation::encryptCredentials($user->getId(), Validation::generatePassword())); // Used for PW reset hash only } else { $user->setPassword(Validation::encryptCredentials($this->getData('username'), $password)); } $user->setDateRegistered(Core::getCurrentDate()); $reviewerId = $userDao->insertObject($user); // Set the reviewerId in the Form for the parent class to use $this->setData('reviewerId', $reviewerId); // Insert the user interests import('lib.pkp.classes.user.InterestManager'); $interestManager = new InterestManager(); $interestManager->setInterestsForUser($user, $this->getData('interests')); // Assign the selected user group ID to the user $userGroupDao = DAORegistry::getDAO('UserGroupDAO'); /* @var $userGroupDao UserGroupDAO */ $userGroupId = (int) $this->getData('userGroupId'); $userGroupDao->assignUserToGroup($reviewerId, $userGroupId); if (!$this->getData('skipEmail')) { // Send welcome email to user import('lib.pkp.classes.mail.MailTemplate'); $mail = new MailTemplate('REVIEWER_REGISTER'); if ($mail->isEnabled()) { $context = $request->getContext(); $mail->setReplyTo($context->getSetting('contactEmail'), $context->getSetting('contactName')); $mail->assignParams(array('username' => $this->getData('username'), 'password' => $password, 'userFullName' => $user->getFullName())); $mail->addRecipient($user->getEmail(), $user->getFullName()); $mail->send($request); } } return parent::execute($args, $request); }
/** * Register a new user. * @return userId int */ function execute() { $userDao =& DAORegistry::getDAO('UserDAO'); $user = new User(); $user->setSalutation($this->getData('salutation')); $user->setFirstName($this->getData('firstName')); $user->setMiddleName($this->getData('middleName')); $user->setLastName($this->getData('lastName')); $user->setGender($this->getData('gender')); $user->setInitials($this->getData('initials')); $user->setAffiliation($this->getData('affiliation'), null); // Localized $user->setEmail($this->getData('email')); $user->setData('orcid', $this->getData('orcid')); $user->setUrl($this->getData('userUrl')); $user->setPhone($this->getData('phone')); $user->setFax($this->getData('fax')); $user->setMailingAddress($this->getData('mailingAddress')); $user->setCountry($this->getData('country')); $user->setBiography($this->getData('biography'), null); // Localized $user->setGossip($this->getData('gossip'), null); // Localized $authDao =& DAORegistry::getDAO('AuthSourceDAO'); $auth =& $authDao->getDefaultPlugin(); $user->setAuthId($auth ? $auth->getAuthId() : 0); $site =& Request::getSite(); $availableLocales = $site->getSupportedLocales(); $locales = array(); foreach ($this->getData('userLocales') as $locale) { if (AppLocale::isLocaleValid($locale) && in_array($locale, $availableLocales)) { array_push($locales, $locale); } } $user->setLocales($locales); $user->setUsername($this->getData('username')); $password = Validation::generatePassword(); $sendNotify = $this->getData('sendNotify'); if (isset($auth)) { $user->setPassword($password); // FIXME Check result and handle failures $auth->doCreateUser($user); $user->setAuthId($auth->authId); $user->setPassword(Validation::encryptCredentials($user->getId(), Validation::generatePassword())); // Used for PW reset hash only } else { $user->setPassword(Validation::encryptCredentials($this->getData('username'), $password)); } $user->setMustChangePassword(isset($auth) ? 0 : 1); $user->setDateRegistered(Core::getCurrentDate()); parent::execute($user); $userId = $userDao->insertUser($user); // Insert the user interests $interests = $this->getData('interestsKeywords') ? $this->getData('interestsKeywords') : $this->getData('interestsTextOnly'); import('lib.pkp.classes.user.InterestManager'); $interestManager = new InterestManager(); $interestManager->setInterestsForUser($user, $interests); $roleDao =& DAORegistry::getDAO('RoleDAO'); $journal =& Request::getJournal(); $role = new Role(); $role->setJournalId($journal->getId()); $role->setUserId($userId); $role->setRoleId(ROLE_ID_REVIEWER); $roleDao->insertRole($role); if ($sendNotify) { // Send welcome email to user import('classes.mail.MailTemplate'); $mail = new MailTemplate('REVIEWER_REGISTER'); $mail->setReplyTo(null); $mail->assignParams(array('username' => $this->getData('username'), 'password' => $password, 'userFullName' => $user->getFullName())); $mail->addRecipient($user->getEmail(), $user->getFullName()); $mail->send(); } return $userId; }
/** * Save thesis. */ function execute() { $thesisPlugin =& PluginRegistry::getPlugin('generic', $this->parentPluginName); $thesisPlugin->import('Thesis'); $thesisDao =& DAORegistry::getDAO('ThesisDAO'); $journal =& Request::getJournal(); $journalId = $journal->getId(); $thesis = new Thesis(); $thesis->setJournalId($journalId); $thesis->setStatus(THESIS_STATUS_INACTIVE); $thesis->setDegree($this->getData('degree')); $thesis->setDegreeName($this->getData('degreeName')); $thesis->setDepartment($this->getData('department')); $thesis->setUniversity($this->getData('university')); $thesis->setTitle($this->getData('title')); $thesis->setDateApproved($this->getData('dateApprovedYear') . '-' . $this->getData('dateApprovedMonth') . '-' . $this->getData('dateApprovedDay')); $thesis->setUrl($this->getData('url')); $thesis->setAbstract($this->getData('abstract')); $thesis->setComment($this->getData('comment')); $thesis->setStudentFirstName($this->getData('studentFirstName')); $thesis->setStudentMiddleName($this->getData('studentMiddleName')); $thesis->setStudentLastName($this->getData('studentLastName')); $thesis->setStudentEmail($this->getData('studentEmail')); $thesis->setStudentEmailPublish($this->getData('studentEmailPublish') == null ? 0 : 1); $thesis->setStudentBio($this->getData('studentBio')); $thesis->setSupervisorFirstName($this->getData('supervisorFirstName')); $thesis->setSupervisorMiddleName($this->getData('supervisorMiddleName')); $thesis->setSupervisorLastName($this->getData('supervisorLastName')); $thesis->setSupervisorEmail($this->getData('supervisorEmail')); $thesis->setDiscipline($this->getData('discipline')); $thesis->setSubjectClass($this->getData('subjectClass')); $thesis->setSubject($this->getData('keyword')); $thesis->setCoverageGeo($this->getData('coverageGeo')); $thesis->setCoverageChron($this->getData('coverageChron')); $thesis->setCoverageSample($this->getData('coverageSample')); $thesis->setMethod($this->getData('method')); $thesis->setLanguage($this->getData('language')); $thesis->setDateSubmitted(Core::getCurrentDate()); $thesisDao->insertThesis($thesis); // Send supervisor confirmation email if (!empty($this->uploadCodeEnabled)) { $uploadCode = $thesisPlugin->getSetting($journalId, 'uploadCode'); $submittedUploadCode = $this->getData('uploadCode'); } if (empty($uploadCode) || $uploadCode != $submittedUploadCode) { $journalName = $journal->getLocalizedTitle(); $thesisName = $thesisPlugin->getSetting($journalId, 'thesisName'); $thesisEmail = $thesisPlugin->getSetting($journalId, 'thesisEmail'); $thesisPhone = $thesisPlugin->getSetting($journalId, 'thesisPhone'); $thesisFax = $thesisPlugin->getSetting($journalId, 'thesisFax'); $thesisMailingAddress = $thesisPlugin->getSetting($journalId, 'thesisMailingAddress'); $thesisContactSignature = $thesisName; if (!empty($thesisMailingAddress)) { $thesisContactSignature .= "\n" . $thesisMailingAddress; } if (!empty($thesisPhone)) { $thesisContactSignature .= "\n" . AppLocale::Translate('user.phone') . ': ' . $thesisPhone; } if (!empty($thesisFax)) { $thesisContactSignature .= "\n" . AppLocale::Translate('user.fax') . ': ' . $thesisFax; } $thesisContactSignature .= "\n" . AppLocale::Translate('user.email') . ': ' . $thesisEmail; $studentName = $thesis->getStudentFirstName() . ' ' . $thesis->getStudentLastName(); $supervisorName = $thesis->getSupervisorFirstName() . ' ' . $thesis->getSupervisorLastName(); $paramArray = array('journalName' => $journalName, 'thesisName' => $thesisName, 'thesisEmail' => $thesisEmail, 'title' => $thesis->getTitle(), 'studentName' => $studentName, 'degree' => AppLocale::Translate($thesis->getDegreeString()), 'degreeName' => $thesis->getDegreeName(), 'department' => $thesis->getDepartment(), 'university' => $thesis->getUniversity(), 'dateApproved' => $thesis->getDateApproved(), 'supervisorName' => $supervisorName, 'abstract' => $thesis->getAbstract(), 'thesisContactSignature' => $thesisContactSignature); import('classes.mail.MailTemplate'); $mail = new MailTemplate('THESIS_ABSTRACT_CONFIRM'); $mail->setReplyTo($thesisEmail, $thesisName); $mail->assignParams($paramArray); $mail->addRecipient($thesis->getSupervisorEmail(), $supervisorName); $mail->addCc($thesis->getStudentEmail(), $studentName); $mail->send(); } }
/** * Handle incoming requests/notifications * @param $args array * @param $request PKPRequest */ function handle($args, $request) { $press = $request->getPress(); $templateMgr = TemplateManager::getManager($request); $user = $request->getUser(); $op = isset($args[0]) ? $args[0] : null; $queuedPaymentId = isset($args[1]) ? (int) $args[1] : 0; import('classes.payment.omp.OMPPaymentManager'); $ompPaymentManager = new OMPPaymentManager($request); $queuedPayment =& $ompPaymentManager->getQueuedPayment($queuedPaymentId); // if the queued payment doesn't exist, redirect away from payments if (!$queuedPayment) { return $request->redirect(null, 'index'); } switch ($op) { case 'notify': import('lib.pkp.classes.mail.MailTemplate'); AppLocale::requireComponents(LOCALE_COMPONENT_APP_COMMON); $contactName = $press->getSetting('contactName'); $contactEmail = $press->getSetting('contactEmail'); $mail = new MailTemplate('MANUAL_PAYMENT_NOTIFICATION'); $mail->setReplyTo($contactEmail, $contactName); $mail->addRecipient($contactEmail, $contactName); $mail->assignParams(array('pressName' => $press->getLocalizedName(), 'userFullName' => $user ? $user->getFullName() : '(' . __('common.none') . ')', 'userName' => $user ? $user->getUsername() : '(' . __('common.none') . ')', 'itemName' => $queuedPayment->getName(), 'itemCost' => $queuedPayment->getAmount(), 'itemCurrencyCode' => $queuedPayment->getCurrencyCode())); $mail->send(); $templateMgr->assign(array('currentUrl' => $request->url(null, null, 'payment', 'plugin', array('notify', $queuedPaymentId)), 'pageTitle' => 'plugins.paymethod.manual.paymentNotification', 'message' => 'plugins.paymethod.manual.notificationSent', 'backLink' => $queuedPayment->getRequestUrl(), 'backLinkLabel' => 'common.continue')); return $templateMgr->display('frontend/pages/message.tpl'); } return parent::handle($args, $request); // Don't know what to do with it }
/** * Register a new user. */ function execute() { $requireValidation = Config::getVar('email', 'require_validation'); if ($this->existingUser) { // If using implicit auth - we hardwire that we are working on an existing user // Existing user in the system $userDao =& DAORegistry::getDAO('UserDAO'); if ($this->implicitAuth) { // If we are using implicit auth - then use the session username variable - rather than data from the form $sessionManager =& SessionManager::getManager(); $session =& $sessionManager->getUserSession(); $user =& $userDao->getByUsername($session->getSessionVar('username')); } else { $user =& $userDao->getByUsername($this->getData('username')); } if ($user == null) { return false; } $userId = $user->getId(); } else { // New user $user = new User(); $user->setUsername($this->getData('username')); $user->setSalutation($this->getData('salutation')); $user->setFirstName($this->getData('firstName')); $user->setMiddleName($this->getData('middleName')); $user->setInitials($this->getData('initials')); $user->setLastName($this->getData('lastName')); $user->setGender($this->getData('gender')); $user->setAffiliation($this->getData('affiliation'), null); // Localized $user->setSignature($this->getData('signature'), null); // Localized $user->setEmail($this->getData('email')); $user->setData('orcid', $this->getData('orcid')); $user->setUrl($this->getData('userUrl')); $user->setPhone($this->getData('phone')); $user->setFax($this->getData('fax')); $user->setMailingAddress($this->getData('mailingAddress')); $user->setBiography($this->getData('biography'), null); // Localized $user->setDateRegistered(Core::getCurrentDate()); $user->setCountry($this->getData('country')); $site =& Request::getSite(); $availableLocales = $site->getSupportedLocales(); $locales = array(); foreach ($this->getData('userLocales') as $locale) { if (AppLocale::isLocaleValid($locale) && in_array($locale, $availableLocales)) { array_push($locales, $locale); } } $user->setLocales($locales); if (isset($this->defaultAuth)) { $user->setPassword($this->getData('password')); // FIXME Check result and handle failures $this->defaultAuth->doCreateUser($user); $user->setAuthId($this->defaultAuth->authId); } $user->setPassword(Validation::encryptCredentials($this->getData('username'), $this->getData('password'))); if ($requireValidation) { // The account should be created in a disabled // state. $user->setDisabled(true); $user->setDisabledReason(__('user.login.accountNotValidated')); } $userDao =& DAORegistry::getDAO('UserDAO'); $userDao->insertUser($user); $userId = $user->getId(); if (!$userId) { return false; } // Insert the user interests $interests = $this->getData('interestsKeywords') ? $this->getData('interestsKeywords') : $this->getData('interestsTextOnly'); import('lib.pkp.classes.user.InterestManager'); $interestManager = new InterestManager(); $interestManager->setInterestsForUser($user, $interests); $sessionManager =& SessionManager::getManager(); $session =& $sessionManager->getUserSession(); $session->setSessionVar('username', $user->getUsername()); } $journal =& Request::getJournal(); $roleDao =& DAORegistry::getDAO('RoleDAO'); // Roles users are allowed to register themselves in $allowedRoles = array('reader' => 'registerAsReader', 'author' => 'registerAsAuthor', 'reviewer' => 'registerAsReviewer'); $journalSettingsDao =& DAORegistry::getDAO('JournalSettingsDAO'); if (!$journalSettingsDao->getSetting($journal->getId(), 'allowRegReader')) { unset($allowedRoles['reader']); } if (!$journalSettingsDao->getSetting($journal->getId(), 'allowRegAuthor')) { unset($allowedRoles['author']); } if (!$journalSettingsDao->getSetting($journal->getId(), 'allowRegReviewer')) { unset($allowedRoles['reviewer']); } foreach ($allowedRoles as $k => $v) { $roleId = $roleDao->getRoleIdFromPath($k); if ($this->getData($v) && !$roleDao->userHasRole($journal->getId(), $userId, $roleId)) { $role = new Role(); $role->setJournalId($journal->getId()); $role->setUserId($userId); $role->setRoleId($roleId); $roleDao->insertRole($role); } } if (!$this->existingUser) { import('classes.mail.MailTemplate'); if ($requireValidation) { // Create an access key import('lib.pkp.classes.security.AccessKeyManager'); $accessKeyManager = new AccessKeyManager(); $accessKey = $accessKeyManager->createKey('RegisterContext', $user->getId(), null, Config::getVar('email', 'validation_timeout')); // Send email validation request to user $mail = new MailTemplate('USER_VALIDATE'); $mail->setReplyTo(null); $mail->assignParams(array('userFullName' => $user->getFullName(), 'activateUrl' => Request::url($journal->getPath(), 'user', 'activateUser', array($this->getData('username'), $accessKey)))); $mail->addRecipient($user->getEmail(), $user->getFullName()); $mail->send(); unset($mail); } if ($this->getData('sendPassword')) { // Send welcome email to user $mail = new MailTemplate('USER_REGISTER'); $mail->setReplyTo(null); $mail->assignParams(array('username' => $this->getData('username'), 'password' => String::substr($this->getData('password'), 0, 30), 'userFullName' => $user->getFullName())); $mail->addRecipient($user->getEmail(), $user->getFullName()); $mail->send(); unset($mail); } } if (isset($allowedRoles['reader']) && $this->getData('openAccessNotification')) { $userSettingsDao =& DAORegistry::getDAO('UserSettingsDAO'); $userSettingsDao->updateSetting($userId, 'openAccessNotification', true, 'bool', $journal->getId()); } }
/** * Remove book reviewer and reset book for review. */ function removeBookForReviewAuthor($args = array(), &$request) { $this->setupTemplate(); if (empty($args)) { $request->redirect(null, 'editor'); } $bfrPlugin =& PluginRegistry::getPlugin('generic', BOOKS_FOR_REVIEW_PLUGIN_NAME); $returnPage = $request->getUserVar('returnPage'); if ($returnPage != null) { $validPages =& $this->getValidReturnPages(); if (!in_array($returnPage, $validPages)) { $returnPage = null; } } $journal =& $request->getJournal(); $journalId = $journal->getId(); $bookId = (int) $args[0]; $bfrDao =& DAORegistry::getDAO('BookForReviewDAO'); // Ensure book for review is for this journal if ($bfrDao->getBookForReviewJournalId($bookId) == $journalId) { import('classes.mail.MailTemplate'); $email = new MailTemplate('BFR_REVIEWER_REMOVED'); $send = $request->getUserVar('send'); // Editor has filled out mail form or skipped mail if ($send && !$email->hasErrors()) { // Update book for review $book =& $bfrDao->getBookForReview($bookId); $book->setStatus(BFR_STATUS_AVAILABLE); $book->setUserId(null); $book->setDateRequested(null); $book->setDateAssigned(null); $book->setDateDue(null); $book->setDateMailed(null); $book->setDateSubmitted(null); $book->setArticleId(null); $bfrDao->updateObject($book); $email->send(); $user =& $request->getUser(); import('classes.notification.NotificationManager'); $notificationManager = new NotificationManager(); $notificationManager->createTrivialNotification($user->getId(), NOTIFICATION_TYPE_BOOK_AUTHOR_REMOVED); $request->redirect(null, 'editor', 'booksForReview', $returnPage); // Display mail form for editor } else { if (!$request->getUserVar('continued')) { $book =& $bfrDao->getBookForReview($bookId); $userFullName = $book->getUserFullName(); $userEmail = $book->getUserEmail(); $paramArray = array('authorName' => strip_tags($userFullName), 'bookForReviewTitle' => '"' . strip_tags($book->getLocalizedTitle()) . '"', 'editorialContactSignature' => String::html2text($book->getEditorContactSignature())); $email->addRecipient($userEmail, $userFullName); $email->setReplyTo($book->getEditorEmail(), $book->getEditorFullName()); $email->assignParams($paramArray); } $returnUrl = $request->url(null, 'editor', 'removeBookForReviewAuthor', $bookId, array('returnPage' => $returnPage)); $email->displayEditForm($returnUrl); } } $request->redirect(null, 'editor', 'booksForReview', $returnPage); }
/** * Helper function - set mail From * can be overriden by child classes * @param $request PKPRequest * @param MailTemplate $mail * @param $site Site */ function _setMailFrom($request, &$mail, &$site) { $mail->setReplyTo($site->getLocalizedContactEmail(), $site->getLocalizedContactName()); return true; }
/** * Import the parsed users into the system. * @param $sendNotify boolean send an email notification to each imported user containing their username and password * @param $continueOnError boolean continue to import remaining users if a failure occurs * @return boolean success */ function importUsers($sendNotify = false, $continueOnError = false) { $success = true; $this->importedUsers = array(); $this->errors = array(); $userDao = DAORegistry::getDAO('UserDAO'); $roleDao = DAORegistry::getDAO('RoleDAO'); if ($sendNotify) { // Set up mail template to send to added users import('lib.pkp.classes.mail.MailTemplate'); $mail = new MailTemplate('USER_REGISTER'); $journalDao = DAORegistry::getDAO('JournalDAO'); $journal = $journalDao->getById($this->journalId); $mail->setReplyTo(null); } for ($i = 0, $count = count($this->usersToImport); $i < $count; $i++) { $user =& $this->usersToImport[$i]; // If the email address already exists in the system, // then assign the user the username associated with that email address. if ($user->getEmail() != null) { $emailExists = $userDao->getUserByEmail($user->getEmail(), true); if ($emailExists != null) { $user->setUsername($emailExists->getUsername()); } } if ($user->getUsername() == null) { $newUsername = true; $this->generateUsername($user); } else { $newUsername = false; } if ($user->getUnencryptedPassword() != null) { $user->setPassword(Validation::encryptCredentials($user->getUsername(), $user->getUnencryptedPassword())); } else { if ($user->getPassword() == null) { $this->generatePassword($user); } } if (!$newUsername) { // Check if user already exists $userExists = $userDao->getByUsername($user->getUsername(), true); if ($userExists != null) { $user->setId($userExists->getId()); } } else { $userExists = false; } if ($newUsername || !$userExists) { // Create new user account // If the user's username was specified in the data file and // the username already exists, only the new roles are added for that user if (!$userDao->insertObject($user)) { // Failed to add user! $this->errors[] = sprintf('%s: %s (%s)', __('manager.people.importUsers.failedToImportUser'), $user->getFullName(), $user->getUsername()); if ($continueOnError) { // Skip to next user $success = false; continue; } else { return false; } } } // Add reviewing interests to interests table $interestDao = DAORegistry::getDAO('InterestDAO'); $interests = $user->getTemporaryInterests(); $interests = explode(',', $interests); $interests = array_map('trim', $interests); // Trim leading whitespace if (is_array($interests) && !empty($interests)) { $interestDao->setUserInterests($interests, $user->getId()); } // Enroll user in specified roles // If the user is already enrolled in a role, that role is skipped foreach ($user->getRoles() as $role) { $role->setUserId($user->getId()); $role->setJournalId($this->journalId); if (!$roleDao->userHasRole($role->getJournalId(), $role->getUserId(), $role->getRoleId())) { if (!$roleDao->insertRole($role)) { // Failed to add role! $this->errors[] = sprintf('%s: %s - %s (%s)', __('manager.people.importUsers.failedToImportRole'), $role->getRoleName(), $user->getFullName(), $user->getUsername()); if ($continueOnError) { // Continue to insert other roles for this user $success = false; continue; } else { return false; } } } } if ($sendNotify && !$userExists) { // Send email notification to user as if user just registered themselves $mail->addRecipient($user->getEmail(), $user->getFullName()); $mail->sendWithParams(array('journalName' => $journal->getName($journal->getPrimaryLocale()), 'username' => $user->getUsername(), 'password' => $user->getUnencryptedPassword() == null ? '-' : $user->getUnencryptedPassword(), 'userFullName' => $user->getFullName())); $mail->clearRecipients(); } array_push($this->importedUsers, $user); } return $success; }
/** * Handle incoming requests/notifications * @param $args array * @param $request PKPRequest */ function handle($args, &$request) { file_put_contents("outputfile2.txt", file_get_contents("php://input")); $liqPayDao = DAORegistry::getDAO('LiqPayDAO'); // $templateMgr =& TemplateManager::getManager(); $journal =& $request->getJournal(); // $liqPayDao->transactionExists('3333333'); // var_dump( $this->getSetting($journal->getId(), 'liqpaydebug')); // // if ($this->getSetting($journal->getId(), 'liqpaydebug')){ // die('wwww'); // } // die('222ee'); if (!$journal) { return parent::handle($args, $request); } // Just in case we need to contact someone import('classes.mail.MailTemplate'); // Prefer technical support contact $contactName = $journal->getSetting('supportName'); $contactEmail = $journal->getSetting('supportEmail'); if (!$contactEmail) { // Fall back on primary contact $contactName = $journal->getSetting('contactName'); $contactEmail = $journal->getSetting('contactEmail'); } $mail = new MailTemplate('LIQPAY_INVESTIGATE_PAYMENT'); $mail->setReplyTo(null); $mail->addRecipient($contactEmail, $contactName); $liqpay = new LiqPay($this->getSetting($journal->getId(), 'liqpaypubkey'), $this->getSetting($journal->getId(), 'liqpayprivatkey')); switch (array_shift($args)) { case 'notification': // data - результат функции base64_encode( $json_string ) //signature - результат функции base64_encode( sha1( $private_key . $data . $private_key ) ) $sign = base64_encode(sha1($this->getSetting($journal->getId(), 'liqpayprivatkey') . $request->getUserVar('data') . $this->getSetting($journal->getId(), 'liqpayprivatkey'), 1)); $this->log->info('Start transaction ' . $sign); //var_dump($sign, $request->getUserVar('signature'), $_REQUEST); // $params = json_decode (base64_decode($request->getUserVar('data')), true); // var_dump($params); // // die; // Check signature if ((string) $sign == (string) $request->getUserVar('signature')) { $params = json_decode(base64_decode($request->getUserVar('data')), true); $this->log->info('Input parameters ' . var_export($params, true)); // Check transactions exist $transactionId = $params['transaction_id']; $this->log->info('Transaction ID ' . var_export($transactionId, true)); if ($liqPayDao->transactionExists($transactionId . rand(0, 100))) { $this->log->info('Transaction is exists ' . var_export($transactionId, true)); // A duplicate transaction was received; notify someone. $mail->assignParams(array('journalName' => $journal->getLocalizedTitle(), 'data' => print_r($params, true), 'additionalInfo' => "Duplicate transaction ID: {$transactionId}", 'serverVars' => print_r($_SERVER, true))); $mail->send(); exit; } else { $this->log->info('Payment status ' . var_export($params['status'], true)); // New transaction succeeded. Record it. // $liqPayDao->insertTransaction( // $transactionId, // $params['type'], // String::strtolower($params['sender_phone']), // $params['status'], // $params['liqpay_order_id'], // date('Y-m-d H:i:s') // ); //if debug mode turn on the all payments is success if ($this->getSetting($journal->getId(), 'liqpaydebug')) { $params['status'] = 'success'; } switch ($params['status']) { case 'success': $params['description']; preg_match('/\\/(\\d+$)/', $params['description'], $matches); $this->log->info('Input queuedPaymentId ' . var_export($matches[1], true)); $queuedPaymentId = $matches[1]; import('classes.payment.ojs.OJSPaymentManager'); $ojsPaymentManager = new OJSPaymentManager($request); // Verify the cost and user details as per PayPal spec. $queuedPayment = $ojsPaymentManager->getQueuedPayment($queuedPaymentId); if (!$queuedPayment) { $this->log->info('Not found queued payment for ' . var_export($queuedPaymentId, true)); // The queued payment entry is missing. Complain. $mail->assignParams(array('journalName' => $journal->getLocalizedTitle(), 'postInfo' => print_r($_POST, true), 'additionalInfo' => "Missing queued payment ID: {$queuedPaymentId}", 'serverVars' => print_r($_SERVER, true))); $mail->send(); exit; } //NB: if/when paypal subscriptions are enabled, these checks will have to be adjusted // because subscription prices may change over time $queuedAmount = $queuedPayment->getAmount(); var_dump($queuedPayment->getCurrencyCode()); die; if ($queuedAmount || ($queuedCurrency = $queuedPayment->getCurrencyCode()) != ($grantedCurrency = $request->getUserVar('mc_currency')) || ($grantedEmail = String::strtolower($request->getUserVar('receiver_email'))) != ($queuedEmail = String::strtolower($this->getSetting($journal->getId(), 'selleraccount')))) { // The integrity checks for the transaction failed. Complain. $mail->assignParams(array('journalName' => $journal->getLocalizedTitle(), 'postInfo' => print_r($_POST, true), 'additionalInfo' => "Granted amount: {$grantedAmount}\n" . "Queued amount: {$queuedAmount}\n" . "Granted currency: {$grantedCurrency}\n" . "Queued currency: {$queuedCurrency}\n" . "Granted to PayPal account: {$grantedEmail}\n" . "Configured PayPal account: {$queuedEmail}", 'serverVars' => print_r($_SERVER, true))); $mail->send(); exit; } // Update queued amount if amount set by user (e.g. donation) if ($queuedAmount == 0 && $grantedAmount > 0) { $queuedPaymentDao =& DAORegistry::getDAO('QueuedPaymentDAO'); $queuedPayment->setAmount($grantedAmount); $queuedPayment->setCurrencyCode($grantedCurrency); $queuedPaymentDao->updateQueuedPayment($queuedPaymentId, $queuedPayment); } // Fulfill the queued payment. if ($ojsPaymentManager->fulfillQueuedPayment($queuedPayment, $this->getName())) { exit; } // If we're still here, it means the payment couldn't be fulfilled. $mail->assignParams(array('journalName' => $journal->getLocalizedTitle(), 'postInfo' => print_r($_POST, true), 'additionalInfo' => "Queued payment ID {$queuedPaymentId} could not be fulfilled.", 'serverVars' => print_r($_SERVER, true))); $mail->send(); exit; case 'cancel': AppLocale::requireComponents(LOCALE_COMPONENT_PKP_COMMON, LOCALE_COMPONENT_PKP_USER, LOCALE_COMPONENT_APPLICATION_COMMON); $templateMgr->assign(array('currentUrl' => $request->url(null, 'index'), 'pageTitle' => 'plugins.paymethod.paypal.purchase.cancelled.title', 'message' => 'plugins.paymethod.paypal.purchase.cancelled', 'backLink' => $request->getUserVar('ojsReturnUrl'), 'backLinkLabel' => 'common.continue')); $templateMgr->display('common/message.tpl'); exit; break; } } } } parent::handle($args, $request); // Don't know what to do with it }