public function __construct($config = array()) { parent::__construct($config); $app = JFactory::getApplication(); /** @var $app JApplicationSite */ // Get project id. $this->projectId = $this->input->getUint("pid"); // Prepare log object $registry = Joomla\Registry\Registry::getInstance("com_crowdfunding"); /** @var $registry Joomla\Registry\Registry */ $fileName = $registry->get("logger.file"); $tableName = $registry->get("logger.table"); $file = JPath::clean($app->get("log_path") . DIRECTORY_SEPARATOR . $fileName); $this->log = new Prism\Log\Log(); $this->log->addWriter(new Prism\Log\Writer\Database(JFactory::getDbo(), $tableName)); $this->log->addWriter(new Prism\Log\Writer\File($file)); // Create an object that contains a data used during the payment process. $this->paymentProcessContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $this->projectId; $this->paymentProcess = $app->getUserState($this->paymentProcessContext); // Prepare context $filter = new JFilterInput(); $paymentService = Joomla\String\String::trim(Joomla\String\String::strtolower($this->input->getCmd("payment_service"))); $paymentService = $filter->clean($paymentService, "ALNUM"); $this->context = !empty($paymentService) ? 'com_crowdfunding.notify.' . $paymentService : 'com_crowdfunding.notify'; // Prepare params $this->params = JComponentHelper::getParams("com_crowdfunding"); }
public function save($key = null, $urlVar = null) { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); $data = $this->input->post->get('jform', array(), 'array'); $itemId = JArrayHelper::getValue($data, "id"); $dataFile = $this->input->files->get('jform', array(), 'array'); $image = JArrayHelper::getValue($dataFile, "image", array(), "array"); $imageName = Joomla\String\String::trim(JArrayHelper::getValue($image, 'name')); $redirectOptions = array("task" => $this->getTask(), "id" => $itemId); // Parse formatted amount. $data["amount"] = CrowdfundingHelper::parseAmount($data["amount"]); $model = $this->getModel(); /** @var $model CrowdfundingModelReward */ $form = $model->getForm($data, false); /** @var $form JForm */ if (!$form) { throw new Exception(JText::_("COM_Crowdfunding_ERROR_FORM_CANNOT_BE_LOADED"), 500); } // Validate the form $validData = $model->validate($form, $data); // Check for errors. if ($validData === false) { $this->displayNotice($form->getErrors(), $redirectOptions); return; } $params = JComponentHelper::getParams("com_crowdfunding"); /** @var $params Joomla\Registry\Registry */ try { $itemId = $model->save($validData); $redirectOptions["id"] = $itemId; // Upload an image $imagesAllowed = $params->get("rewards_images", 0); // Upload images. if ($imagesAllowed and !empty($imageName) and !empty($itemId)) { $reward = new Crowdfunding\Reward(JFactory::getDbo()); $reward->load($itemId); // Get the folder where the images will be stored $imagesFolder = CrowdfundingHelper::getImagesFolder($reward->getUserId()); jimport("joomla.filesystem.folder"); if (!JFolder::exists($imagesFolder)) { CrowdfundingHelper::createFolder($imagesFolder); } $images = $model->uploadImage($image, $imagesFolder); if (!empty($images)) { $model->storeImage($images, $imagesFolder, $itemId); } } } catch (RuntimeException $e) { $this->displayError($e->getMessage(), $redirectOptions); return; } catch (Exception $e) { JLog::add($e->getMessage()); throw new Exception(JText::_('COM_Crowdfunding_ERROR_SYSTEM')); } $this->displayMessage(JText::_('COM_Crowdfunding_REWARD_SAVED'), $redirectOptions); }
public static function badge(Gamification\User\Badge $badge, $mediaPath, $tip = false, $placeholders = array()) { $title = ""; $class = ""; $classes = array(); if (!empty($tip) and $badge->getDescription()) { JHtml::_("bootstrap.tooltip"); $classes[] = "hasTooltip"; $description = strip_tags(Joomla\String\String::trim($badge->getDescription($placeholders))); $title = ' title="' . htmlspecialchars($description, ENT_QUOTES, "UTF-8") . '"'; } // Prepare class property if (!empty($classes)) { $class = ' class="' . implode(" ", $classes) . '"'; } // Prepare alt property $alt = strip_tags(Joomla\String\String::trim($badge->getTitle())); if (!empty($alt)) { $alt = ' alt="' . htmlspecialchars($alt, ENT_QUOTES, "UTF-8") . '"'; } $html = '<img src="' . $mediaPath . "/" . $badge->getImage() . '"' . $class . $alt . $title . ' />'; return $html; }
/** * Validate a date * * @param string $string * * @return boolean * @deprecated deprecated since version 1.8 */ public static function isValidDate($string) { $string = Joomla\String\String::trim($string); try { $date = new DateTime($string); } catch (Exception $e) { return false; } $month = $date->format('m'); $day = $date->format('d'); $year = $date->format('Y'); if (checkdate($month, $day, $year)) { return true; } else { return false; } }
/** * Prepare some main filters. * * @param JDatabaseQuery $query */ protected function prepareFilters(&$query) { $db = JFactory::getDbo(); // Filter by featured state. $featured = $this->getState($this->context . ".filter_featured"); if (!is_null($featured)) { if (!$featured) { $query->where('a.featured = 0'); } else { $query->where('a.featured = 1'); } } // Filter by category ID $categoryId = $this->getState($this->context . ".category_id", 0); if (!empty($categoryId)) { $query->where('a.catid = ' . (int) $categoryId); } // Filter by project type $projectTypeId = $this->getState($this->context . ".filter_projecttype", 0); if (!empty($projectTypeId)) { $query->where('a.type_id = ' . (int) $projectTypeId); } // Filter by country $countryCode = $this->getState($this->context . ".filter_country"); if (!empty($countryCode)) { $query->innerJoin($db->quoteName("#__crowdf_locations", "l") . " ON a.location_id = l.id"); $query->where('l.country_code = ' . $db->quote($countryCode)); } // Filter by location $locationId = $this->getState($this->context . ".filter_location"); if (!empty($locationId)) { $query->where('a.location_id = ' . (int) $locationId); } // Filter by funding type $filterFundingType = Joomla\String\String::strtoupper(Joomla\String\String::trim($this->getState($this->context . ".filter_fundingtype"))); if (!empty($filterFundingType)) { $allowedFundingTypes = array("FIXED", "FLEXIBLE"); if (in_array($filterFundingType, $allowedFundingTypes)) { $query->where('a.funding_type = ' . $db->quote($filterFundingType)); } } // Filter by phrase $phrase = $this->getState($this->context . ".filter_phrase"); if (!empty($phrase)) { $escaped = $db->escape($phrase, true); $quoted = $db->quote("%" . $escaped . "%", false); $query->where('a.title LIKE ' . $quoted); } }
public function process() { $app = JFactory::getApplication(); /** @var $app JApplicationSite */ // Check for request forgeries. $requestMethod = $app->input->getMethod(); if (strcmp("POST", $requestMethod) == 0) { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); } else { JSession::checkToken("get") or jexit(JText::_('JINVALID_TOKEN')); } // Get params $params = JComponentHelper::getParams("com_crowdfunding"); /** @var $params Joomla\Registry\Registry */ // Get the data from the form $itemId = $this->input->getInt('id', 0); $rewardId = $this->input->getInt('rid', 0); // Get amount $amount = CrowdfundingHelper::parseAmount($this->input->getString("amount")); // Get user ID $user = JFactory::getUser(); $userId = (int) $user->get("id"); // Anonymous user ID $aUserId = ""; $model = $this->getModel(); /** @var $model CrowdfundingModelBacking */ // Get the item $item = $model->getItem($itemId); $returnUrl = CrowdfundingHelperRoute::getBackingRoute($item->slug, $item->catslug); // Authorise the user if (!$user->authorise("crowdfunding.donate", "com_crowdfunding")) { $this->setRedirect(JRoute::_($returnUrl, false), JText::_('COM_CROWDFUNDING_ERROR_NO_PERMISSIONS'), "notice"); return; } // Check for valid project if (empty($item->id)) { $this->setRedirect(JRoute::_(CrowdfundingHelperRoute::getDiscoverRoute()), JText::_('COM_CROWDFUNDING_ERROR_INVALID_PROJECT'), "notice"); return; } // Check for maintenance (debug) state. if ($params->get("debug_payment_disabled", 0)) { $msg = Joomla\String\String::trim($params->get("debug_disabled_functionality_msg")); if (!$msg) { $msg = JText::_("COM_CROWDFUNDING_DEBUG_MODE_DEFAULT_MSG"); } $this->setRedirect(JRoute::_($returnUrl, false), $msg, "notice"); return; } // Check for agreed conditions from the user. if ($params->get("backing_terms", 0)) { $terms = $this->input->get("terms", 0, "int"); if (!$terms) { $this->setRedirect(JRoute::_($returnUrl, false), JText::_("COM_CROWDFUNDING_ERROR_TERMS_NOT_ACCEPTED"), "notice"); return; } } // Check for valid amount. if (!$amount) { $this->setRedirect(JRoute::_($returnUrl, false), JText::_("COM_CROWDFUNDING_ERROR_INVALID_AMOUNT"), "notice"); return; } // Store payment process data // Get the payment process object and // store the selected data from the user. $paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $item->id; $paymentSessionLocal = $app->getUserState($paymentSessionContext); $paymentSessionLocal->step1 = true; $paymentSessionLocal->amount = $amount; $paymentSessionLocal->rewardId = $rewardId; $app->setUserState($paymentSessionContext, $paymentSessionLocal); // Generate hash user ID used for anonymous payment. if (!$userId) { $aUserId = $app->getUserState("auser_id"); if (!$aUserId) { // Generate a hash ID for anonymous user. $anonymousUserId = new Prism\String(); $anonymousUserId->generateRandomString(32); $aUserId = (string) $anonymousUserId; $app->setUserState("auser_id", $aUserId); } } $date = new JDate(); // Create an intention record. $intentionId = 0; if (!empty($userId)) { $intentionKeys = array("user_id" => $userId, "project_id" => $item->id); $intention = new Crowdfunding\Intention(JFactory::getDbo()); $intention->load($intentionKeys); $intentionData = array("user_id" => $userId, "project_id" => $item->id, "reward_id" => $rewardId, "record_date" => $date->toSql()); $intention->bind($intentionData); $intention->store(); $intentionId = $intention->getId(); } // Create a payment session. $paymentSessionDatabase = new Crowdfunding\Payment\Session(JFactory::getDbo()); $paymentSessionData = array("user_id" => $userId, "auser_id" => $aUserId, "project_id" => $item->id, "reward_id" => $rewardId, "record_date" => $date->toSql(), "session_id" => $paymentSessionLocal->session_id, "intention_id" => $intentionId); $paymentSessionDatabase->bind($paymentSessionData); $paymentSessionDatabase->store(); // Redirect to next page $link = CrowdfundingHelperRoute::getBackingRoute($item->slug, $item->catslug, "payment"); $this->setRedirect(JRoute::_($link, false)); }
/** * Upload images. * * @param array $files * @param string $destFolder * @param array $rewardsIds * * @return array */ public function uploadImages($files, $destFolder, $rewardsIds) { // Load parameters. $params = JComponentHelper::getParams($this->option); /** @var $params Joomla\Registry\Registry */ // Joomla! media extension parameters $mediaParams = JComponentHelper::getParams("com_media"); /** @var $mediaParams Joomla\Registry\Registry */ $KB = 1024 * 1024; $uploadMaxSize = $mediaParams->get("upload_maxsize") * $KB; $mimeTypes = explode(",", $mediaParams->get("upload_mime")); $imageExtensions = explode(",", $mediaParams->get("image_extensions")); $images = array(); foreach ($files as $rewardId => $image) { // If the image is set to not valid reward, continue to next one. // It is impossible to store image to missed reward. if (!in_array($rewardId, $rewardsIds)) { continue; } $uploadedFile = Joomla\Utilities\ArrayHelper::getValue($image, 'tmp_name'); $uploadedName = Joomla\String\String::trim(Joomla\Utilities\ArrayHelper::getValue($image, 'name')); $errorCode = Joomla\Utilities\ArrayHelper::getValue($image, 'error'); $file = new Prism\File\Image(); if (!empty($uploadedName)) { // Prepare size validator. $fileSize = (int) Joomla\Utilities\ArrayHelper::getValue($image, 'size'); // Prepare file size validator. $sizeValidator = new Prism\File\Validator\Size($fileSize, $uploadMaxSize); // Prepare server validator. $serverValidator = new Prism\File\Validator\Server($errorCode, array(UPLOAD_ERR_NO_FILE)); // Prepare image validator. $imageValidator = new Prism\File\Validator\Image($uploadedFile, $uploadedName); // Get allowed mime types from media manager options $imageValidator->setMimeTypes($mimeTypes); // Get allowed image extensions from media manager options $imageValidator->setImageExtensions($imageExtensions); $file->addValidator($sizeValidator)->addValidator($imageValidator)->addValidator($serverValidator); // Validate the file if (!$file->isValid()) { continue; } // Generate temporary file name $ext = Joomla\String\String::strtolower(JFile::makeSafe(JFile::getExt($image['name']))); $generatedName = new Prism\String(); $generatedName->generateRandomString(12, "reward_"); $destFile = JPath::clean($destFolder . DIRECTORY_SEPARATOR . $generatedName . "." . $ext); // Prepare uploader object. $uploader = new Prism\File\Uploader\Local($uploadedFile); $uploader->setDestination($destFile); // Upload temporary file $file->setUploader($uploader); $file->upload(); // Get file $imageSource = $file->getFile(); if (!is_file($imageSource)) { continue; } // Generate thumbnails. // Create thumbnail. $generatedName->generateRandomString(12, "reward_thumb_"); $options = array("width" => $params->get("rewards_image_thumb_width", 200), "height" => $params->get("rewards_image_thumb_height", 200), "scale" => $params->get("image_resizing_scale", JImage::SCALE_INSIDE), "destination" => JPath::clean($destFolder . DIRECTORY_SEPARATOR . $generatedName . "." . $ext)); $thumbSource = $file->createThumbnail($options); // Create square image. $generatedName->generateRandomString(12, "reward_square_"); $options = array("width" => $params->get("rewards_image_square_width", 50), "height" => $params->get("rewards_image_square_height", 50), "scale" => $params->get("image_resizing_scale", JImage::SCALE_INSIDE), "destination" => JPath::clean($destFolder . DIRECTORY_SEPARATOR . $generatedName . "." . $ext)); $squareSource = $file->createThumbnail($options); $names = array("image" => "", "thumb" => "", "square" => ""); $names['image'] = basename($imageSource); $names["thumb"] = basename($thumbSource); $names["square"] = basename($squareSource); $images[$rewardId] = $names; } } return $images; }
/** * Check the system for debug mode */ protected function prepareDebugMode() { // Check for maintenance (debug) state $params = $this->state->get("params"); $this->debugMode = $params->get("debug_project_adding_disabled", 0); if ($this->debugMode) { $msg = Joomla\String\String::trim($params->get("debug_disabled_functionality_msg")); if (!$msg) { $msg = JText::_("COM_CROWDFUNDING_DEBUG_MODE_DEFAULT_MSG"); } $this->app->enqueueMessage($msg, "notice"); $this->disabledButton = 'disabled="disabled"'; } }
/** * @return string */ protected function buildWhere() { $db = JFactory::getDBO(); $querystrings = array(); foreach ($this->getSearchWords() as $searchword) { $searchword = $db->escape(Joomla\String\String::trim($searchword)); if (empty($searchword)) { continue; } $not = ''; $operator = ' OR '; if (substr($searchword, 0, 1) == '-' && strlen($searchword) > 1) { $not = 'NOT'; $operator = 'AND'; $searchword = Joomla\String\String::substr($searchword, 1); } if (!$this->getState('query.titleonly')) { $querystrings[] = "(t.message {$not} LIKE '%{$searchword}%' {$operator} m.subject {$not} LIKE '%{$searchword}%')"; } else { $querystrings[] = "(m.subject {$not} LIKE '%{$searchword}%')"; } } //User searching $username = $this->getState('query.searchuser'); if ($username) { if ($this->getState('query.exactname') == '1') { $querystrings[] = "m.name LIKE '" . $db->escape($username) . "'"; } else { $querystrings[] = "m.name LIKE '%" . $db->escape($username) . "%'"; } } $time = 0; switch ($this->getState('query.searchdate')) { case 'lastvisit': $time = KunenaFactory::GetSession()->lasttime; break; case 'all': break; case '1': case '7': case '14': case '30': case '90': case '180': case '365': $time = time() - 86400 * intval($this->getState('query.searchdate')); //24*3600 break; default: $time = time() - 86400 * 365; } if ($time) { if ($this->getState('query.beforeafter') == 'after') { $querystrings[] = "m.time > '{$time}'"; } else { $querystrings[] = "m.time <= '{$time}'"; } } $topic_id = $this->getState('query.topic_id'); if ($topic_id) { $querystrings[] = "m.id = '{$topic_id}'"; } return implode(' AND ', $querystrings); }
/** * Return payment receiver. * * @param $paymentReceiverOption * @param $itemId * * @return null|string */ protected function getPaymentReceiver($paymentReceiverOption, $itemId) { if ($this->params->get('paypal_sandbox', 1)) { return Joomla\String\String::strtolower(Joomla\String\String::trim($this->params->get('paypal_sandbox_business_name'))); } else { if (strcmp("site_owner", $paymentReceiverOption) == 0) { // Site owner return Joomla\String\String::strtolower(Joomla\String\String::trim($this->params->get('paypal_business_name'))); } else { if (!JComponentHelper::isEnabled("com_crowdfundingfinance")) { return null; } else { $payout = new CrowdfundingFinance\Payout(JFactory::getDbo()); $payout->load($itemId); if (!$payout->getPaypalEmail()) { return null; } return Joomla\String\String::strtolower(Joomla\String\String::trim($payout->getPaypalEmail())); } } } }
/** * Method to save social profiles data. * * @param int $userId * @param array $data * * @return mixed The record id on success, null on failure. * @since 1.6 */ public function saveSocialProfiles($userId, $data) { // Prepare profiles. $profiles = array('facebook' => Joomla\Utilities\ArrayHelper::getValue($data, 'facebook'), 'twitter' => Joomla\Utilities\ArrayHelper::getValue($data, 'twitter'), 'linkedin' => Joomla\Utilities\ArrayHelper::getValue($data, 'linkedin')); $allowedTypes = array('facebook', 'twitter', 'linkedin'); foreach ($profiles as $key => $alias) { $type = Joomla\String\String::trim($key); $alias = Joomla\String\String::trim($alias); if (!in_array($type, $allowedTypes, true)) { continue; } $keys = array('user_id' => (int) $userId, 'type' => $type); // Load a record from the database $row = $this->getTable('SocialProfile'); $row->load($keys); // Remove old if ($row->get('id') > 0 and !$alias) { // If there is a record but there is no alias, remove the record. $row->delete(); } elseif (!$alias) { // If missing alias, continue to next social profile. continue; } else { // Add new if (!$row->get('id')) { $row->set('user_id', (int) $userId); } $row->set('alias', $alias); $row->set('type', $type); $row->store(); } } }
/** * Upload an image. * * @param array $image * @param string $destFolder * * @throws RuntimeException * * @return array */ public function uploadImage($image, $destFolder) { // Load parameters. $params = JComponentHelper::getParams($this->option); /** @var $params Joomla\Registry\Registry */ // Joomla! media extension parameters $mediaParams = JComponentHelper::getParams("com_media"); /** @var $mediaParams Joomla\Registry\Registry */ $names = array("image" => "", "thumb" => "", "square" => ""); $KB = 1024 * 1024; $uploadMaxSize = $mediaParams->get("upload_maxsize") * $KB; $mimeTypes = explode(",", $mediaParams->get("upload_mime")); $imageExtensions = explode(",", $mediaParams->get("image_extensions")); $uploadedFile = JArrayHelper::getValue($image, 'tmp_name'); $uploadedName = Joomla\String\String::trim(JArrayHelper::getValue($image, 'name')); $errorCode = JArrayHelper::getValue($image, 'error'); $file = new Prism\File\Image(); if (!empty($uploadedName)) { // Prepare size validator. $fileSize = (int) JArrayHelper::getValue($image, 'size'); // Prepare file size validator. $sizeValidator = new Prism\File\Validator\Size($fileSize, $uploadMaxSize); // Prepare server validator. $serverValidator = new Prism\File\Validator\Server($errorCode, array(UPLOAD_ERR_NO_FILE)); // Prepare image validator. $imageValidator = new Prism\File\Validator\Image($uploadedFile, $uploadedName); // Get allowed mime types from media manager options $imageValidator->setMimeTypes($mimeTypes); // Get allowed image extensions from media manager options $imageValidator->setImageExtensions($imageExtensions); $file->addValidator($sizeValidator)->addValidator($imageValidator)->addValidator($serverValidator); // Validate the file if (!$file->isValid()) { throw new RuntimeException($file->getError()); } // Generate temporary file name $ext = Joomla\String\String::strtolower(JFile::makeSafe(JFile::getExt($image['name']))); $generatedName = new Prism\String(); $generatedName->generateRandomString(12, "reward_"); $destFile = JPath::clean($destFolder . DIRECTORY_SEPARATOR . $generatedName . "." . $ext); // Prepare uploader object. $uploader = new Prism\File\Uploader\Local($uploadedFile); $uploader->setDestination($destFile); // Upload temporary file $file->setUploader($uploader); $file->upload(); // Get file $imageSource = $file->getFile(); if (!is_file($imageSource)) { throw new RuntimeException(JText::_("COM_CROWDFUNDING_ERROR_FILE_CANT_BE_UPLOADED")); } // Generate thumbnails. // Create thumbnail. $generatedName->generateRandomString(12, "reward_thumb_"); $options = array("width" => $params->get("rewards_image_thumb_width", 200), "height" => $params->get("rewards_image_thumb_height", 200), "destination" => JPath::clean($destFolder . DIRECTORY_SEPARATOR . $generatedName . "." . $ext)); $thumbSource = $file->createThumbnail($options); // Create square image. $generatedName->generateRandomString(12, "reward_square_"); $options = array("width" => $params->get("rewards_image_square_width", 50), "height" => $params->get("rewards_image_square_height", 50), "destination" => JPath::clean($destFolder . DIRECTORY_SEPARATOR . $generatedName . "." . $ext)); $squareSource = $file->createThumbnail($options); $names['image'] = basename($imageSource); $names["thumb"] = basename($thumbSource); $names["square"] = basename($squareSource); } return $names; }
protected function prepareBirthday($data) { $birthdayDay = Joomla\String\String::trim(Joomla\Utilities\ArrayHelper::getValue($data["birthday"], "day")); $birthdayMonth = Joomla\String\String::trim(Joomla\Utilities\ArrayHelper::getValue($data["birthday"], "month")); $birthdayYear = Joomla\String\String::trim(Joomla\Utilities\ArrayHelper::getValue($data["birthday"], "year")); if (!$birthdayDay) { $birthdayDay = "00"; } if (!$birthdayMonth) { $birthdayMonth = "00"; } if (!$birthdayYear) { $birthdayYear = "0000"; } $birthday = $birthdayYear . "-" . $birthdayMonth . "-" . $birthdayDay; $date = new Prism\Validator\Date($birthday); if (!$date->isValid()) { $birthday = "0000-00-00"; } return $birthday; }
/** * Return PayPal API URL. * * @return string */ protected function getApiUrl() { if ($this->params->get("paypal_sandbox", 1)) { return Joomla\String\String::trim($this->params->get("paypal_sandbox_api_url")); } else { return Joomla\String\String::trim($this->params->get("paypal_api_url")); } }
/** * Check the system for debug mode * * @param JData */ protected function prepareDebugMode(&$paymentSession) { // Check for maintenance (debug) state. $params = $this->state->get("params"); if ($params->get("debug_payment_disabled", 0)) { $msg = Joomla\String\String::trim($params->get("debug_disabled_functionality_msg")); if (!$msg) { $msg = JText::_("COM_CROWDFUNDING_DEBUG_MODE_DEFAULT_MSG"); } $this->app->enqueueMessage($msg, "notice"); $this->disabledButton = 'disabled="disabled"'; // Store the new values of the payment process to the user session. $paymentSession->step1 = false; $this->app->setUserState($this->paymentSessionContext, $paymentSession); } }
/** * Import states that are based on not official states data, * and which are not connected to locations IDs. * * @param SimpleXMLElement $content * * @todo remove this in next major version. */ protected function importUnofficialStates($content) { if (!empty($content)) { $states = array(); $db = $this->getDbo(); foreach ($content->city as $item) { // Check for missing ascii characters title $name = Joomla\String\String::trim($item->name); if (!$name) { continue; } $code = Joomla\String\String::trim($item->state_code); $states[$code][] = "(" . $db->quoteName("name") . "=" . $db->quote($name) . " AND " . $db->quoteName("country_code") . "=" . $db->quote("US") . ")"; } foreach ($states as $stateCode => $cities) { $query = $db->getQuery(true); $query->update("#__crowdf_locations")->set($db->quoteName("state_code") . " = " . $db->quote($stateCode))->where(implode(" OR ", $cities)); $db->setQuery($query); $db->execute(); } unset($states); unset($content); } }
/** * This method trigger the event onPaymentsPreparePayment. * The purpose of this method is to load a data and send it to browser. * That data will be used in the process of payment. */ public function preparePaymentAjax() { $app = JFactory::getApplication(); /** @var $app JApplicationSite */ // Get component parameters $params = JComponentHelper::getParams("com_crowdfunding"); /** @var $params Joomla\Registry\Registry */ $response = new Prism\Response\Json(); // Check for disabled payment functionality if ($params->get("debug_payment_disabled", 0)) { // Send response to the browser $response->setTitle(JText::_("COM_CROWDFUNDING_FAIL"))->setText(JText::_("COM_CROWDFUNDING_ERROR_PAYMENT_HAS_BEEN_DISABLED_MESSAGE"))->failure(); echo $response; JFactory::getApplication()->close(); } $output = array(); // Prepare payment service name. $filter = new JFilterInput(); $paymentService = Joomla\String\String::trim(Joomla\String\String::strtolower($this->input->getCmd("payment_service"))); $paymentService = $filter->clean($paymentService, "ALNUM"); // Trigger the event try { $context = 'com_crowdfunding.preparepayment.' . $paymentService; // Import Crowdfunding Payment Plugins $dispatcher = JEventDispatcher::getInstance(); JPluginHelper::importPlugin('crowdfundingpayment'); // Trigger onContentPreparePayment event. $results = $dispatcher->trigger("onPaymentsPreparePayment", array($context, &$params)); // Get the result, that comes from the plugin. if (!empty($results)) { foreach ($results as $result) { if (!is_null($result) and is_array($result)) { $output =& $result; break; } } } } catch (Exception $e) { // Store log data in the database JLog::add($e->getMessage()); // Send response to the browser $response->failure()->setTitle(JText::_("COM_CROWDFUNDING_FAIL"))->setText(JText::_("COM_CROWDFUNDING_ERROR_SYSTEM")); echo $response; JFactory::getApplication()->close(); } // Check the response $success = Joomla\Utilities\ArrayHelper::getValue($output, "success"); if (!$success) { // If there is an error... // Get project id. $projectId = $this->input->getUint("pid"); $paymentProcessContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $projectId; // Initialize the payment process object. $paymentProcess = new JData(); $paymentProcess->step1 = false; $app->setUserState($paymentProcessContext, $paymentProcess); // Send response to the browser $response->failure()->setTitle(Joomla\Utilities\ArrayHelper::getValue($output, "title"))->setText(Joomla\Utilities\ArrayHelper::getValue($output, "text")); } else { // If all is OK... // Send response to the browser $response->success()->setTitle(Joomla\Utilities\ArrayHelper::getValue($output, "title"))->setText(Joomla\Utilities\ArrayHelper::getValue($output, "text"))->setData(Joomla\Utilities\ArrayHelper::getValue($output, "data")); } echo $response; JFactory::getApplication()->close(); }
/** * 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; }