/** * @param int $projectId * @param Joomla\Registry\Registry $params * @param object $paymentSession * * @return stdClass * @throws UnexpectedValueException */ public function prepareItem($projectId, $params, $paymentSession) { $project = new Crowdfunding\Project(JFactory::getDbo()); $project->load($projectId); if (!$project->getId()) { throw new UnexpectedValueException(JText::_("COM_CROWDFUNDING_ERROR_INVALID_PROJECT")); } if ($project->isCompleted()) { throw new UnexpectedValueException(JText::_("COM_CROWDFUNDING_ERROR_COMPLETED_PROJECT")); } // Get currency $currency = Crowdfunding\Currency::getInstance(JFactory::getDbo(), $params->get("project_currency")); // Create amount object. $amount = new Crowdfunding\Amount($params); $amount->setCurrency($currency); $item = new stdClass(); $item->id = $project->getId(); $item->title = $project->getTitle(); $item->slug = $project->getSlug(); $item->catslug = $project->getCatSlug(); $item->rewardId = $paymentSession->rewardId; $item->starting_date = $project->getFundingStart(); $item->ending_date = $project->getFundingEnd(); $item->amount = $paymentSession->amount; $item->currencyCode = $currency->getCode(); $item->amountFormated = $amount->setValue($item->amount)->format(); $item->amountCurrency = $amount->setValue($item->amount)->formatCurrency(); return $item; }
/** * Get the data that is going to be passed to the layout * * @return array */ public function getLayoutData() { // Get the basic field data $data = parent::getLayoutData(); // Load the current username if available. $project = new Crowdfunding\Project(JFactory::getDbo()); $projectTitle = ''; if (is_numeric($this->value)) { $project->load($this->value); $projectTitle = $project->get('title'); } $extraData = array('projectTitle' => $projectTitle); return array_merge($data, $extraData); }
public function onAfterDispatch() { $app = JFactory::getApplication(); /** @var $app JApplicationSite */ if ($app->isAdmin()) { return; } $document = JFactory::getDocument(); /** @var $document JDocumentHtml */ $type = $document->getType(); if (strcmp("html", $type) != 0) { return; } // It works only for GET and POST requests. $method = JString::strtolower($app->input->getMethod()); if (!in_array($method, array("get", "post"))) { return; } // Check component enabled if (!JComponentHelper::isEnabled('com_crowdfunding', true)) { return; } $view = $app->input->getCmd("view"); $option = $app->input->getCmd("option"); $isCrowdfundingComponent = strcmp($option, "com_crowdfunding") == 0; $isDetailsPage = (strcmp($option, "com_crowdfunding") == 0 and strcmp($view, "details") == 0); // Allowed views for the module Crowdfunding Details $allowedViewsModuleDetails = array("backing", "embed", "report"); $allowedViewsModuleFilters = array("discover", "category"); // Hide some modules if it is not details page. if (!$isDetailsPage) { $this->hideModule("mod_crowdfundinginfo"); $this->hideModule("mod_crowdfundingprofile"); $this->hideModule("mod_crowdfundingreporting"); } // Module Crowdfunding Rewards (mod_crowdfundingrewards). if (!$isDetailsPage) { $this->hideModule("mod_crowdfundingrewards"); } else { // Check project type. If the rewards are disable, hide the module. $projectId = $app->input->getInt("id"); if (!empty($projectId)) { $project = Crowdfunding\Project::getInstance(JFactory::getDbo(), $projectId); $type = $project->getType(); // Hide the module Crowdfunding Rewards, if rewards are disabled for this type. if (!is_null($type) and !$type->isRewardsEnabled()) { $this->hideModule("mod_crowdfundingrewards"); } } } // Module Crowdfunding Details (mod_crowdfundingdetails) on backing and embed pages. if (!$isCrowdfundingComponent or strcmp($option, "com_crowdfunding") == 0 and !in_array($view, $allowedViewsModuleDetails)) { $this->hideModule("mod_crowdfundingdetails"); } // Module Crowdfunding Filters (mod_crowdfundingfilters). if (!$isCrowdfundingComponent or strcmp($option, "com_crowdfunding") == 0 and !in_array($view, $allowedViewsModuleFilters)) { $this->hideModule("mod_crowdfundingfilters"); } }
public function save($key = null, $urlVar = null) { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); $data = $this->input->post->get('jform', array(), 'array'); $itemId = Joomla\Utilities\ArrayHelper::getValue($data, "id", 0, "int"); $projectId = Joomla\Utilities\ArrayHelper::getValue($data, "project_id", 0, "int"); $partnerId = Joomla\Utilities\ArrayHelper::getValue($data, "partner_id", 0, "int"); $redirectOptions = array("task" => $this->getTask(), "id" => $itemId); $model = $this->getModel(); /** @var $model CrowdfundingPartnersModelPartner */ $form = $model->getForm($data, false); /** @var $form JForm */ if (!$form) { throw new Exception(JText::_("COM_CROWDFUNDINGPARTNERS_ERROR_FORM_CANNOT_BE_LOADED")); } // Validate the form data $validData = $model->validate($form, $data); // Check for errors if ($validData === false) { $this->displayNotice($form->getErrors(), $redirectOptions); return; } $project = new Crowdfunding\Project(JFactory::getDbo()); $project->load($projectId); if (!$project->getId()) { $this->displayError(JText::_('COM_CROWDFUNDINGPARTNERS_ERROR_INVALID_PROJECT'), $redirectOptions); return; } if ($partnerId == $project->getUserId()) { $this->displayError(JText::_('COM_CROWDFUNDINGPARTNERS_ERROR_CANNOT_ASSIGN_PARTNER'), $redirectOptions); return; } try { $itemId = $model->save($validData); $redirectOptions["id"] = $itemId; } catch (Exception $e) { JLog::add($e->getMessage()); throw new Exception(JText::_('COM_CROWDFUNDINGPARTNERS_ERROR_SYSTEM')); } $this->displayMessage(JText::_('COM_CROWDFUNDINGPARTNERS_PARTNER_SAVED'), $redirectOptions); }
public function send() { // Check for request forgeries. JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); // Get the data from the form POST $data = $this->input->post->get('cfreport', array(), 'array'); $itemId = Joomla\Utilities\ArrayHelper::getValue($data, 'id'); if (!$itemId) { $redirectOptions = array('force_direction' => CrowdfundingHelperRoute::getReportRoute()); $this->displayNotice(JText::_('COM_CROWDFUNDING_ERROR_INVALID_PROJECT'), $redirectOptions); return; } // Get project $item = Crowdfunding\Project::getInstance(JFactory::getDbo(), $itemId); $redirectOptions = array('force_direction' => CrowdfundingHelperRoute::getReportRoute($item->getId())); $model = $this->getModel(); /** @var $model CrowdfundingModelReport */ $form = $model->getForm($data, false); /** @var $form JForm */ if (!$form) { throw new Exception(JText::_('COM_CROWDFUNDING_ERROR_FORM_CANNOT_BE_LOADED')); } // Test if the data is valid. $validData = $model->validate($form, $data); // Check for validation errors. if ($validData === false) { $errors = $form->getErrors(); $error = array_shift($errors); $msg = $error->getMessage(); $this->displayNotice($msg, $redirectOptions); return; } try { $userId = (int) JFactory::getUser()->get('id'); if ($userId > 0) { $validData['user_id'] = $userId; } $model->save($validData); } catch (RuntimeException $e) { $this->displayNotice($e->getMessage(), $redirectOptions); return; } catch (Exception $e) { JLog::add($e->getMessage(), JLog::ERROR, 'com_crowdfunding'); throw new Exception(JText::_('COM_CROWDFUNDING_ERROR_SYSTEM')); } // Redirect to next page $this->displayMessage(JText::_('COM_CROWDFUNDING_REPORT_SENT_SUCCESSFULLY'), $redirectOptions); }
public function save($key = null, $urlVar = null) { // Check for request forgeries. JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); $userId = (int) JFactory::getUser()->get('id'); if (!$userId) { $redirectOptions = array('force_direction' => 'index.php?option=com_users&view=login'); $this->displayNotice(JText::_('COM_CROWDFUNDING_ERROR_NOT_LOG_IN'), $redirectOptions); return; } // Get the data from the form POST $data = $this->input->post->get('jform', array(), 'array'); $itemId = Joomla\Utilities\ArrayHelper::getValue($data, 'project_id', 0, 'int'); // Get project $item = Crowdfunding\Project::getInstance(JFactory::getDbo(), $itemId); $redirectOptions = array('force_direction' => CrowdfundingHelperRoute::getDetailsRoute($item->getSlug(), $item->getCatSlug(), 'updates')); // Check for valid owner. if ($userId !== $item->getUserId()) { $this->displayWarning(JText::_('COM_CROWDFUNDING_ERROR_INVALID_PROJECT'), $redirectOptions); return; } $model = $this->getModel(); /** @var $model CrowdfundingModelUpdate */ $form = $model->getForm($data, false); /** @var $form JForm */ if (!$form) { throw new Exception(JText::_('COM_CROWDFUNDING_ERROR_FORM_CANNOT_BE_LOADED')); } // Test if the data is valid. $validData = $model->validate($form, $data); // Check for validation errors. if ($validData === false) { $errors = $form->getErrors(); $error = array_shift($errors); $msg = $error->getMessage(); $this->displayNotice($msg, $redirectOptions); return; } try { $model->save($validData); } catch (Exception $e) { JLog::add($e->getMessage(), JLog::ERROR, 'com_crowdfunding'); throw new Exception(JText::_('COM_CROWDFUNDING_ERROR_SYSTEM')); } // Redirect to next page $this->displayMessage(JText::_('COM_CROWDFUNDING_UPDATE_SUCCESSFULLY_SAVED'), $redirectOptions); }
public function send() { // Check for request forgeries. JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); $redirectOptions = array("view" => "discover"); $params = JComponentHelper::getParams("com_crowdfunding"); /** @var $params Joomla\Registry\Registry */ if (!$params->get("security_display_friend_form", 0)) { $this->displayNotice(JText::_('COM_CROWDFUNDING_ERROR_CANT_SEND_MAIL'), $redirectOptions); return; } // Get the data from the form POST $data = $this->input->post->get('jform', array(), 'array'); $itemId = Joomla\Utilities\ArrayHelper::getValue($data, "id", 0, "uint"); // Get project $item = Crowdfunding\Project::getInstance(JFactory::getDbo(), $itemId); // Prepare redirect link $link = CrowdfundingHelperRoute::getEmbedRoute($item->getSlug(), $item->getCatSlug(), "email"); $redirectOptions = array("force_direction" => $link); $model = $this->getModel(); /** @var $model CrowdfundingModelFriendMail */ $form = $model->getForm($data, false); /** @var $form JForm */ if (!$form) { throw new Exception(JText::_("COM_CROWDFUNDING_ERROR_FORM_CANNOT_BE_LOADED")); } // Test if the data is valid. $validData = $model->validate($form, $data); // Check for validation errors. if ($validData === false) { $this->displayNotice($form->getErrors(), $redirectOptions); return; } try { $model->send($validData); } catch (Exception $e) { JLog::add($e->getMessage()); throw new Exception(JText::_('COM_CROWDFUNDING_ERROR_SYSTEM')); } // Redirect to next page $this->displayMessage(JText::_("COM_CROWDFUNDING_FRIEND_MAIL_SUCCESSFULLY_SEND"), $redirectOptions); }
/** * Save transaction data. * * @param array $transactionData * @param Crowdfunding\Project $project * * @return null|array */ protected function storeTransaction($transactionData, $project) { // Get transaction by txn ID $keys = array('txn_id' => Joomla\Utilities\ArrayHelper::getValue($transactionData, 'txn_id')); $transaction = new Crowdfunding\Transaction(JFactory::getDbo()); $transaction->load($keys); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_TRANSACTION_OBJECT'), $this->debugType, $transaction->getProperties()) : null; // Check for existed transaction // If the current status if completed, stop the payment process. if ($transaction->getId() and $transaction->isCompleted()) { return null; } // Add extra data. if (array_key_exists('extra_data', $transactionData)) { if (!empty($transactionData['extra_data'])) { $transaction->addExtraData($transactionData['extra_data']); } unset($transactionData['extra_data']); } // Store the new transaction data. $transaction->bind($transactionData); $transaction->store(); // If it is not completed (it might be pending or other status), // stop the process. Only completed transaction will continue // and will process the project, rewards,... if (!$transaction->isCompleted()) { return null; } // Set transaction ID. $transactionData['id'] = $transaction->getId(); // If the new transaction is completed, // update project funded amount. $amount = Joomla\Utilities\ArrayHelper::getValue($transactionData, 'txn_amount'); $project->addFunds($amount); $project->storeFunds(); return $transactionData; }
public static function isRewardsEnabled($projectId) { // Check for enabled rewards by component options. $componentParams = JComponentHelper::getParams('com_crowdfunding'); if (!$componentParams->get('rewards_enabled', 1)) { return false; } // Check for enabled rewards by project type. $project = Crowdfunding\Project::getInstance(JFactory::getDbo(), $projectId); $type = $project->getType(); if ($type === null) { return true; } return (bool) ($type instanceof Crowdfunding\Type and $type->isRewardsEnabled()); }
protected function sendReportMail($report, $emailId) { $app = JFactory::getApplication(); /** @var $app JApplicationSite */ // Send mail to the administrator if (!$emailId) { return false; } // Get website $uri = JUri::getInstance(); $website = $uri->toString(array('scheme', 'host')); $emailMode = $this->params->get('email_mode', 'plain'); // Get project $project = Crowdfunding\Project::getInstance(JFactory::getDbo(), $report->project_id); // Prepare data for parsing $data = array('site_name' => $app->get('sitename'), 'site_url' => JUri::root(), 'item_title' => $project->getTitle(), 'item_url' => $website . JRoute::_(CrowdfundingHelperRoute::getDetailsRoute($project->getSlug(), $project->getCatSlug())), 'report_subject' => $report->subject, 'report_description' => $report->description); $email = new Emailtemplates\Email(); $email->setDb(JFactory::getDbo()); $email->load($emailId); if (!$email->getSenderName()) { $email->setSenderName($app->get('fromname')); } if (!$email->getSenderEmail()) { $email->setSenderEmail($app->get('mailfrom')); } // Prepare recipient data. $componentParams = JComponentHelper::getParams('com_crowdfunding'); /** @var $componentParams Joomla\Registry\Registry */ $recipientId = (int) $componentParams->get('administrator_id'); if ($recipientId > 0) { $recipient = JFactory::getUser($recipientId); $recipientName = $recipient->get('name'); $recipientMail = $recipient->get('email'); } else { $recipientName = $app->get('fromname'); $recipientMail = $app->get('mailfrom'); } // Prepare data for parsing $data['sender_name'] = $email->getSenderName(); $data['sender_email'] = $email->getSenderEmail(); $data['recipient_name'] = $recipientName; $data['recipient_email'] = $recipientMail; $email->parse($data); $subject = $email->getSubject(); $body = $email->getBody($emailMode); $mailer = JFactory::getMailer(); if (strcmp('html', $emailMode) === 0) { // Send as HTML message $result = $mailer->sendMail($email->getSenderEmail(), $email->getSenderName(), $recipientMail, $subject, $body, Prism\Constants::MAIL_MODE_HTML); } else { // Send as plain text. $result = $mailer->sendMail($email->getSenderEmail(), $email->getSenderName(), $recipientMail, $subject, $body, Prism\Constants::MAIL_MODE_PLAIN); } // Log the error. if ($result !== true) { $this->log->add(JText::sprintf('PLG_CONTENT_CROWDFUNDINGADMINMAIL_ERROR_SEND_MAIL', $this->name), 'PLG_CONTENT_ADMIN_EMAIL_ERROR', JText::sprintf('PLG_CONTENT_CROWDFUNDINGADMINMAIL_ERROR_SEND_MAIL_NOTE', $mailer->ErrorInfo)); return false; } return true; }
/** * Store the temporary images to project record. * Remove the old images and move the new ones from temporary folder to the images folder. * * @param int $projectId * @param array $images The names of the pictures. * @param string $source Path to the temporary folder. * * @throws InvalidArgumentException */ public function updateImages($projectId, $images, $source) { $project = Crowdfunding\Project::getInstance(JFactory::getDbo(), $projectId); if (!$project->getId()) { throw new InvalidArgumentException(JText::_('COM_CROWDFUNDING_ERROR_INVALID_PROJECT')); } // Prepare the path to the pictures. $fileImage = $source . DIRECTORY_SEPARATOR . $images['image']; $fileSmall = $source . DIRECTORY_SEPARATOR . $images['image_small']; $fileSquare = $source . DIRECTORY_SEPARATOR . $images['image_square']; if (is_file($fileImage) and is_file($fileSmall) and is_file($fileSquare)) { // Get the folder where the pictures are stored. $params = JComponentHelper::getParams('com_crowdfunding'); /** @var $params Joomla\Registry\Registry */ $imagesFolder = JPath::clean(JPATH_ROOT . DIRECTORY_SEPARATOR . $params->get('images_directory', 'images/crowdfunding')); // Remove an image from the filesystem $oldFileImage = $imagesFolder . DIRECTORY_SEPARATOR . $project->getImage(); $oldFileSmall = $imagesFolder . DIRECTORY_SEPARATOR . $project->getSmallImage(); $oldFileSquare = $imagesFolder . DIRECTORY_SEPARATOR . $project->getSquareImage(); if (JFile::exists($oldFileImage)) { JFile::delete($oldFileImage); } if (JFile::exists($oldFileSmall)) { JFile::delete($oldFileSmall); } if (JFile::exists($oldFileSquare)) { JFile::delete($oldFileSquare); } // Move the new files to the images folder. $newFileImage = $imagesFolder . DIRECTORY_SEPARATOR . $images['image']; $newFileSmall = $imagesFolder . DIRECTORY_SEPARATOR . $images['image_small']; $newFileSquare = $imagesFolder . DIRECTORY_SEPARATOR . $images['image_square']; JFile::move($fileImage, $newFileImage); JFile::move($fileSmall, $newFileSmall); JFile::move($fileSquare, $newFileSquare); // Store the newest pictures. $project->bind($images); $project->store(); } }
/** * @param Crowdfunding\Transaction $transaction * @param Crowdfunding\Project $project * @param array $data * * @return bool */ protected function processVoided(&$transaction, &$project, &$data) { // It is possible only to void a transaction with status "pending". if (!$transaction->isPending()) { return false; } // Set transaction data to canceled. $data['txn_status'] = 'canceled'; // Update the transaction data. // If the current status is pending and the new status is completed, // only store the transaction data, updating the status to completed. $transaction->bind($data, array('extra_data')); $transaction->addExtraData($data['extra_data']); $transaction->store(); $amount = Joomla\Utilities\ArrayHelper::getValue($data, 'txn_amount'); $project->removeFunds($amount); $project->storeFunds(); return true; }
protected function prepareRewards() { $model = JModelLegacy::getInstance("Rewards", "CrowdfundingModel", $config = array('ignore_request' => false)); // Get state $this->state = $model->getState(); // Get params $this->projectId = $this->state->get("rewards.project_id"); // Check if rewards are enabled. if (!$this->rewardsEnabled) { $this->app->enqueueMessage(JText::_("COM_CROWDFUNDING_ERROR_REWARDS_DISABLED"), "notice"); $this->app->redirect(JRoute::_(CrowdfundingHelperRoute::getFormRoute($this->projectId, "manager"), false)); return; } $this->items = $model->getItems($this->projectId); // Get project and validate it $project = Crowdfunding\Project::getInstance(JFactory::getDbo(), $this->projectId); $project = $project->getProperties(); $this->item = Joomla\Utilities\ArrayHelper::toObject($project); // Check if the item exists. if (!$this->isValid()) { return; } // Create a currency object. $this->currency = Crowdfunding\Currency::getInstance(JFactory::getDbo(), $this->params->get("project_currency")); $this->amount = new Crowdfunding\Amount($this->params); $this->amount->setCurrency($this->currency); // Get date format $this->dateFormat = CrowdfundingHelper::getDateFormat(); $this->dateFormatCalendar = CrowdfundingHelper::getDateFormat(true); $language = JFactory::getLanguage(); $languageTag = $language->getTag(); $js = ' // Rewards calendar date format. var projectWizard = { dateFormat: "' . $this->dateFormatCalendar . '", locale: "' . substr($languageTag, 0, 2) . '" }; '; $this->document->addScriptDeclaration($js); // Prepare rewards images. $this->rewardsImagesEnabled = $this->params->get("rewards_images", 0); $this->rewardsImagesUri = CrowdfundingHelper::getImagesFolderUri($this->userId); $this->prepareProjectType(); $this->pathwayName = JText::_("COM_CROWDFUNDING_STEP_REWARDS"); }
/** * @param Crowdfunding\Transaction $transaction * @param Crowdfunding\Project $project * @param array $data * * @return bool */ protected function processVoided(&$transaction, &$project, &$data) { // It is possible only to void a transaction with status "pending". if (!$transaction->isPending()) { return; } // Merge existed extra data with the new one. if (!empty($data["extra_data"])) { $transaction->addExtraData($data["extra_data"]); unset($data["extra_data"]); } // Remove the status reason. $data["status_reason"] = ""; // Update the transaction data. // If the current status is pending and the new status is completed, // only store the transaction data, updating the status to completed. $transaction->bind($data); $transaction->store(); $amount = Joomla\Utilities\ArrayHelper::getValue($data, "txn_amount"); $project->removeFunds($amount); $project->storeFunds(); }
/** * Store the temporary images to project record. * Remove the old images and move the new ones from temporary folder to the images folder. * * @param int $projectId * @param array $images The names of the pictures. * @param string $source Path to the temporary folder. */ public function updateImages($projectId, $images, $source) { $project = Crowdfunding\Project::getInstance(JFactory::getDbo(), $projectId); if (!$project->getId()) { throw new InvalidArgumentException(JText::_("COM_CROWDFUNDING_ERROR_INVALID_PROJECT")); } // Prepare the path to the pictures. $fileImage = $source . DIRECTORY_SEPARATOR . $images["image"]; $fileSmall = $source . DIRECTORY_SEPARATOR . $images["image_small"]; $fileSquare = $source . DIRECTORY_SEPARATOR . $images["image_square"]; if (is_file($fileImage) and is_file($fileSmall) and is_file($fileSquare)) { // Get the folder where the pictures are stored. $imagesFolder = CrowdfundingHelper::getImagesFolder(); // Remove an image from the filesystem $oldFileImage = $imagesFolder . DIRECTORY_SEPARATOR . $project->getImage(); $oldFileSmall = $imagesFolder . DIRECTORY_SEPARATOR . $project->getSmallImage(); $oldFileSquare = $imagesFolder . DIRECTORY_SEPARATOR . $project->getSquareImage(); if (is_file($oldFileImage)) { JFile::delete($oldFileImage); } if (is_file($oldFileSmall)) { JFile::delete($oldFileSmall); } if (is_file($oldFileSquare)) { JFile::delete($oldFileSquare); } // Move the new files to the images folder. $newFileImage = $imagesFolder . DIRECTORY_SEPARATOR . $images["image"]; $newFileSmall = $imagesFolder . DIRECTORY_SEPARATOR . $images["image_small"]; $newFileSquare = $imagesFolder . DIRECTORY_SEPARATOR . $images["image_square"]; JFile::move($fileImage, $newFileImage); JFile::move($fileSmall, $newFileSmall); JFile::move($fileSquare, $newFileSquare); // Store the newest pictures. $project->bind($images); $project->store(); } }
protected function removeTransactions(Crowdfunding\Project $project) { // Create query object $db = $this->getDbo(); $query = $db->getQuery(true); $query->delete($db->quoteName("#__crowdf_transactions"))->where($db->quoteName("project_id") . "=" . (int) $project->getId()); $db->setQuery($query); $db->execute(); }
protected function removeFollowers(Crowdfunding\Project $project) { // Create query object $db = $this->getDbo(); $query = $db->getQuery(true); $query->delete($db->quoteName('#__crowdf_followers'))->where($db->quoteName('project_id') . '=' . (int) $project->getId()); $db->setQuery($query); $db->execute(); }
public function save($key = null, $urlVar = null) { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); $app = JFactory::getApplication(); /** @var $app JApplicationSite */ $response = new Prism\Response\Json(); $data = $this->input->post->get('jform', array(), 'array'); $itemId = Joomla\Utilities\ArrayHelper::getValue($data, "project_id", 0, "int"); $terms = $this->input->post->getInt("terms", 0); $project = new Crowdfunding\Project(JFactory::getDbo()); $project->load($itemId); $returnUrl = CrowdfundingHelperRoute::getBackingRoute($project->getSlug(), $project->getCatSlug()); if (!$project->getId()) { // Send response to the browser $response->setTitle(JText::_("COM_CROWDFUNDINGDATA_FAIL"))->setText(JText::_("COM_CROWDFUNDINGDATA_INVALID_ITEM"))->setRedirectUrl($returnUrl)->failure(); echo $response; JFactory::getApplication()->close(); } $model = $this->getModel(); /** @var $model CrowdfundingDataModelRecord */ $form = $model->getForm($data, false); /** @var $form JForm */ if (!$form) { throw new Exception(JText::_("COM_CROWDFUNDINGDATA_ERROR_FORM_CANNOT_BE_LOADED"), 500); } // Validate the form data $validData = $model->validate($form, $data); // Check for errors if ($validData === false) { $errors_ = $form->getErrors(); $errors = array(); /** @var $error RuntimeException */ foreach ($errors_ as $error) { $errors[] = $error->getMessage(); } // Send response to the browser $response->setTitle(JText::_("COM_CROWDFUNDINGDATA_FAIL"))->setText(implode("\n", $errors))->setRedirectUrl($returnUrl)->failure(); echo $response; JFactory::getApplication()->close(); } // Get the payment session object and session ID. $paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $project->getId(); $paymentSession = $app->getUserState($paymentSessionContext); try { $validData["session_id"] = $paymentSession->session_id; $model->save($validData); } catch (Exception $e) { $response->setTitle(JText::_("COM_CROWDFUNDINGDATA_FAIL"))->setText(JText::_('COM_CROWDFUNDINGDATA_ERROR_SYSTEM'))->setRedirectUrl($returnUrl)->failure(); echo $response; JFactory::getApplication()->close(); } $componentParams = JComponentHelper::getParams("com_crowdfunding"); /** @var $componentParams Joomla\Registry\Registry */ $processUrl = JUri::base() . "index.php?option=com_crowdfunding&task=backing.process&id=" . (int) $project->getId() . "&rid=" . (int) $paymentSession->rewardId . "&amount=" . rawurldecode($paymentSession->amount) . "&" . JSession::getFormToken() . "=1"; // Set the value of terms of use condition. if ($componentParams->get("backing_terms", 0) and !empty($terms)) { $processUrl .= "&terms=1"; } $filter = JFilterInput::getInstance(); $processUrl = $filter->clean($processUrl); $response->setTitle(JText::_("COM_CROWDFUNDINGDATA_SUCCESS"))->setText(JText::_("COM_CROWDFUNDINGDATA_DATA_SAVED_SUCCESSFULLY"))->setRedirectUrl($processUrl)->success(); echo $response; JFactory::getApplication()->close(); }
/** * This method processes transaction data that comes from PayPal instant notifier. * * @param string $context This string gives information about that where it has been executed the trigger. * @param Joomla\Registry\Registry $params The parameters of the component * * @return null|array */ public function onPaymentNotify($context, &$params) { if (strcmp("com_crowdfunding.notify.paypal", $context) != 0) { return null; } if ($this->app->isAdmin()) { return null; } $doc = JFactory::getDocument(); /** @var $doc JDocumentHtml */ // Check document type $docType = $doc->getType(); if (strcmp("raw", $docType) != 0) { return null; } // Validate request method $requestMethod = $this->app->input->getMethod(); if (strcmp("POST", $requestMethod) != 0) { $this->log->add(JText::_($this->textPrefix . "_ERROR_INVALID_REQUEST_METHOD"), $this->debugType, JText::sprintf($this->textPrefix . "_ERROR_INVALID_TRANSACTION_REQUEST_METHOD", $requestMethod)); return null; } // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_RESPONSE"), $this->debugType, $_POST) : null; // Decode custom data $custom = Joomla\Utilities\ArrayHelper::getValue($_POST, "custom"); $custom = json_decode(base64_decode($custom), true); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_CUSTOM"), $this->debugType, $custom) : null; // Verify gateway. Is it PayPal? if (!$this->isPayPalGateway($custom)) { $this->log->add(JText::_($this->textPrefix . "_ERROR_INVALID_PAYMENT_GATEWAY"), $this->debugType, array("custom" => $custom, "_POST" => $_POST)); return null; } // Get PayPal URL if ($this->params->get('paypal_sandbox', 1)) { $url = Joomla\String\String::trim($this->params->get('paypal_sandbox_url', "https://www.sandbox.paypal.com/cgi-bin/webscr")); } else { $url = Joomla\String\String::trim($this->params->get('paypal_url', "https://www.paypal.com/cgi-bin/webscr")); } $paypalIpn = new Prism\Payment\PayPal\Ipn($url, $_POST); $loadCertificate = (bool) $this->params->get("paypal_load_certificate", 0); $paypalIpn->verify($loadCertificate); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_VERIFY_OBJECT"), $this->debugType, $paypalIpn) : null; // Prepare the array that have to be returned by this method. $result = array("project" => null, "reward" => null, "transaction" => null, "payment_session" => null, "payment_service" => $this->paymentService); if ($paypalIpn->isVerified()) { // Get currency $currency = Crowdfunding\Currency::getInstance(JFactory::getDbo(), $params->get("project_currency")); // Get payment session data $paymentSessionId = Joomla\Utilities\ArrayHelper::getValue($custom, "payment_session_id", 0, "int"); $paymentSession = $this->getPaymentSession(array("id" => $paymentSessionId)); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_PAYMENT_SESSION"), $this->debugType, $paymentSession->getProperties()) : null; // Validate transaction data $validData = $this->validateData($_POST, $currency->getCode(), $paymentSession); if (is_null($validData)) { return $result; } // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_VALID_DATA"), $this->debugType, $validData) : null; // Get project. $projectId = Joomla\Utilities\ArrayHelper::getValue($validData, "project_id"); $project = Crowdfunding\Project::getInstance(JFactory::getDbo(), $projectId); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_PROJECT_OBJECT"), $this->debugType, $project->getProperties()) : null; // Check for valid project if (!$project->getId()) { // Log data in the database $this->log->add(JText::_($this->textPrefix . "_ERROR_INVALID_PROJECT"), $this->debugType, $validData); return $result; } // Set the receiver of funds. $validData["receiver_id"] = $project->getUserId(); // Save transaction data. // If it is not completed, return empty results. // If it is complete, continue with process transaction data $transactionData = $this->storeTransaction($validData, $project); if (is_null($transactionData)) { return $result; } // Update the number of distributed reward. $rewardId = Joomla\Utilities\ArrayHelper::getValue($transactionData, "reward_id"); $reward = null; if (!empty($rewardId)) { $reward = $this->updateReward($transactionData); // Validate the reward. if (!$reward) { $transactionData["reward_id"] = 0; } } // Generate object of data, based on the transaction properties. $result["transaction"] = Joomla\Utilities\ArrayHelper::toObject($transactionData); // Generate object of data based on the project properties. $properties = $project->getProperties(); $result["project"] = Joomla\Utilities\ArrayHelper::toObject($properties); // Generate object of data based on the reward properties. if (!empty($reward)) { $properties = $reward->getProperties(); $result["reward"] = Joomla\Utilities\ArrayHelper::toObject($properties); } // Generate data object, based on the payment session properties. $properties = $paymentSession->getProperties(); $result["payment_session"] = Joomla\Utilities\ArrayHelper::toObject($properties); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_RESULT_DATA"), $this->debugType, $result) : null; // Remove payment session. $txnStatus = isset($result["transaction"]->txn_status) ? $result["transaction"]->txn_status : null; $this->closePaymentSession($paymentSession, $txnStatus); } else { // Log error $this->log->add(JText::_($this->textPrefix . "_ERROR_INVALID_TRANSACTION_DATA"), $this->debugType, array("error message" => $paypalIpn->getError(), "paypalVerify" => $paypalIpn, "_POST" => $_POST)); } return $result; }
protected function prepareRewards() { $model = JModelLegacy::getInstance('Rewards', 'CrowdfundingModel', $config = array('ignore_request' => false)); // Get state $this->state = $model->getState(); // Get params $this->projectId = $this->state->get('rewards.project_id'); // Check if rewards are enabled. if (!$this->rewardsEnabled) { $this->app->enqueueMessage(JText::_('COM_CROWDFUNDING_ERROR_REWARDS_DISABLED'), 'notice'); $this->app->redirect(JRoute::_(CrowdfundingHelperRoute::getFormRoute($this->projectId, 'manager'), false)); return; } $this->items = $model->getItems($this->projectId); // Get project and validate it $project = Crowdfunding\Project::getInstance(JFactory::getDbo(), $this->projectId); $project = $project->getProperties(); $this->item = Joomla\Utilities\ArrayHelper::toObject($project); // Check if the item exists. if (!CrowdfundingHelper::isAuthorized($this->userId, $this->item, 'rewards')) { $this->app->enqueueMessage(JText::_('COM_CROWDFUNDING_ERROR_SOMETHING_WRONG'), 'notice'); $this->app->redirect(JRoute::_(CrowdfundingHelperRoute::getDiscoverRoute())); return; } // Create a currency object. $this->currency = Crowdfunding\Currency::getInstance(JFactory::getDbo(), $this->params->get('project_currency')); $this->amount = new Crowdfunding\Amount($this->params); $this->amount->setCurrency($this->currency); // Get date format $this->dateFormat = CrowdfundingHelper::getDateFormat(); $this->dateFormatCalendar = CrowdfundingHelper::getDateFormat(true); $language = JFactory::getLanguage(); $languageTag = $language->getTag(); $js = ' // Rewards calendar date format. var projectWizard = { dateFormat: "' . $this->dateFormatCalendar . '", locale: "' . substr($languageTag, 0, 2) . '" }; '; $this->document->addScriptDeclaration($js); // Prepare rewards images. $this->rewardsImagesEnabled = (bool) $this->params->get('rewards_images', 0); $this->rewardsImagesUri = CrowdfundingHelper::getImagesFolderUri($this->userId); $this->options['column_left'] = (!$this->rewardsImagesEnabled or count($this->items) === 0) ? 12 : 8; $this->options['column_right'] = (!$this->rewardsImagesEnabled or count($this->items) === 0) ? 0 : 4; $this->prepareProjectType(); $this->pathwayName = JText::_('COM_CROWDFUNDING_STEP_REWARDS'); }
$moduleclassSfx = htmlspecialchars($params->get('moduleclass_sfx')); $option = $app->input->get('option'); $view = $app->input->get('view'); $allowedViews = array('backing', 'embed', 'report'); // If option is not 'com_crowdfunding' and view is not one of allowed, // do not display anything. if (strcmp($option, 'com_crowdfunding') !== 0 or !in_array($view, $allowedViews, true)) { echo JText::_('MOD_CROWDFUNDINGDETAILS_ERROR_INVALID_VIEW'); return; } $projectId = $app->input->getInt('id'); if (!$projectId) { return; } // Get project $project = Crowdfunding\Project::getInstance(JFactory::getDbo(), $projectId); if (!$project->getId()) { return; } // Get component params $componentParams = JComponentHelper::getParams('com_crowdfunding'); /** @var $componentParams Joomla\Registry\Registry */ $socialPlatform = $componentParams->get('integration_social_platform'); $imageFolder = $componentParams->get('images_directory', 'images/crowdfunding'); $imageWidth = $componentParams->get('image_width', 200); $imageHeight = $componentParams->get('image_height', 200); // Get currency $currencyId = $componentParams->get('project_currency'); $currency = Crowdfunding\Currency::getInstance(JFactory::getDbo(), $componentParams->get('project_currency')); $amount = new Crowdfunding\Amount($componentParams); $amount->setCurrency($currency);
/** * This method performs the transaction. * * @param string $context * @param Joomla\Registry\Registry $params * * @return null|array */ public function onPaymentNotify($context, &$params) { if (strcmp("com_crowdfunding.notify.banktransfer", $context) != 0) { return null; } if ($this->app->isAdmin()) { return null; } $doc = JFactory::getDocument(); /** @var $doc JDocumentHtml */ // Check document type $docType = $doc->getType(); if (strcmp("raw", $docType) != 0) { return null; } $projectId = $this->app->input->getInt("pid"); $amount = $this->app->input->getFloat("amount"); // Prepare the array that will be returned by this method $result = array("project" => null, "reward" => null, "transaction" => null, "payment_session" => null, "redirect_url" => null, "message" => null); // Get project $project = new Crowdfunding\Project(JFactory::getDbo()); $project->load($projectId); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_PROJECT_OBJECT"), $this->debugType, $project->getProperties()) : null; // Check for valid project if (!$project->getId()) { // Log data in the database $this->log->add(JText::_($this->textPrefix . "_ERROR_INVALID_PROJECT"), $this->debugType, array("PROJECT OBJECT" => $project->getProperties(), "REQUEST METHOD" => $this->app->input->getMethod(), "_REQUEST" => $_REQUEST)); return null; } $currencyId = $params->get("project_currency"); $currency = Crowdfunding\Currency::getInstance(JFactory::getDbo(), $currencyId, $params); // Prepare return URL $result["redirect_url"] = Joomla\String\String::trim($this->params->get('return_url')); if (!$result["redirect_url"]) { $filter = JFilterInput::getInstance(); $uri = JUri::getInstance(); $domain = $filter->clean($uri->toString(array("scheme", "host"))); $result["redirect_url"] = $domain . JRoute::_(CrowdfundingHelperRoute::getBackingRoute($project->getSlug(), $project->getCatslug(), "share"), false); } // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_RETURN_URL"), $this->debugType, $result["redirect_url"]) : null; // Payment Session $userId = JFactory::getUser()->get("id"); $aUserId = $this->app->getUserState("auser_id"); // Reset anonymous user hash ID, // because the payment session based in it will be removed when transaction completes. if (!empty($aUserId)) { $this->app->setUserState("auser_id", ""); } $paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $project->getId(); $paymentSessionLocal = $this->app->getUserState($paymentSessionContext); $paymentSession = $this->getPaymentSession(array("session_id" => $paymentSessionLocal->session_id)); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_PAYMENT_SESSION_OBJECT"), $this->debugType, $paymentSession->getProperties()) : null; // Validate payment session record. if (!$paymentSession->getId()) { // Log data in the database $this->log->add(JText::_($this->textPrefix . "_ERROR_INVALID_PAYMENT_SESSION"), $this->debugType, $paymentSession->getProperties()); // Send response to the browser $response = array("success" => false, "title" => JText::_($this->textPrefix . "_FAIL"), "text" => JText::_($this->textPrefix . "_ERROR_INVALID_PROJECT")); return $response; } // Validate a reward and update the number of distributed ones. // If the user is anonymous, the system will store 0 for reward ID. // The anonymous users can't select rewards. $rewardId = $paymentSession->isAnonymous() ? 0 : (int) $paymentSession->getRewardId(); if (!empty($rewardId)) { $validData = array("reward_id" => $rewardId, "project_id" => $projectId, "txn_amount" => $amount); $reward = $this->updateReward($validData); // Validate the reward. if (!$reward) { $rewardId = 0; } } // Prepare transaction data $transactionId = new Prism\String(); $transactionId->generateRandomString(12, "BT"); $transactionId = Joomla\String\String::strtoupper($transactionId); $transactionData = array("txn_amount" => $amount, "txn_currency" => $currency->getCode(), "txn_status" => "pending", "txn_id" => $transactionId, "project_id" => $projectId, "reward_id" => $rewardId, "investor_id" => (int) $userId, "receiver_id" => (int) $project->getUserId(), "service_provider" => "Bank Transfer"); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_TRANSACTION_DATA"), $this->debugType, $transactionData) : null; // Auto complete transaction if ($this->params->get("auto_complete", 0)) { $transactionData["txn_status"] = "completed"; $project->addFunds($amount); $project->storeFunds(); } // Store transaction data $transaction = new Crowdfunding\Transaction(JFactory::getDbo()); $transaction->bind($transactionData); $transaction->store(); // Generate object of data, based on the transaction properties. $properties = $transaction->getProperties(); $result["transaction"] = Joomla\Utilities\ArrayHelper::toObject($properties); // Generate object of data, based on the project properties. $properties = $project->getProperties(); $result["project"] = Joomla\Utilities\ArrayHelper::toObject($properties); // Generate object of data, based on the reward properties. if (!empty($reward)) { $properties = $reward->getProperties(); $result["reward"] = Joomla\Utilities\ArrayHelper::toObject($properties); } // Generate data object, based on the payment session properties. $properties = $paymentSession->getProperties(); $result["payment_session"] = Joomla\Utilities\ArrayHelper::toObject($properties); // Set message to the user. $result["message"] = JText::sprintf($this->textPrefix . "_TRANSACTION_REGISTERED", $transaction->getTransactionId(), $transaction->getTransactionId()); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_RESULT_DATA"), $this->debugType, $result) : null; // Close payment session and remove payment session record. $txnStatus = isset($result["transaction"]->txn_status) ? $result["transaction"]->txn_status : null; $this->closePaymentSession($paymentSession, $txnStatus); return $result; }