| Current Path : /home/h/e/l/helpink/www/components/com_jbusinessdirectory/models/ |
| Current File : /home/h/e/l/helpink/www/components/com_jbusinessdirectory/models/mobileconnector.php |
<?php
/**
* @package J-BusinessDirectory
*
* @author CMSJunkie http://www.cmsjunkie.com/
* @copyright Copyright (C) 2007 - 2022 CMSJunkie. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0.en.html
*/
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modellist');
JTable::addIncludePath(DS.'components'.'com_jbusinessdirectory'.DS.'tables');
class JBusinessDirectoryModelMobileConnector extends JModelList {
protected $appSettings;
/**
* constructor method
*
* @since 5.0.0
*/
public function __construct() {
parent::__construct();
$this->appSettings = JBusinessUtil::getApplicationSettings();
}
/**
* Returns a Table object, always creating it
*
* @param string The table type to instantiate
* @param string A prefix for the table class name. Optional.
* @param array Configuration array for model. Optional.
* @return JTable A database object
* @since 5.0.0
*/
public function getTable($type = 'Company', $prefix = 'JTable', $config = array()) {
return JTable::getInstance($type, $prefix, $config);
}
/**
* Return company types
*
* @return mixed
* @since 5.0.0
*/
public function getCompanyTypes() {
$table = $this->getTable('CompanyTypes');
$types = $table->getOrderedCompanyTypes();
return $types;
}
/**
* Return event types
*
* @return mixed
* @since 5.0.0
*/
public function getEventTypes() {
$table = $this->getTable('EventType');
$types = $table->getOrderedEventTypes();
return $types;
}
/**
* Return offer types
*
* @return mixed
* @since 5.3.1
*/
public function getOfferTypes() {
$table = $this->getTable('OfferType');
$types = $table->getOrderedOfferTypes();
return $types;
}
public function getProviderWorkingHours($serviceId, $providerId, $date) {
$date = JBusinessUtil::convertToMysqlFormat($date); //dd-mm-yyyy
$table = $this->getTable("CompanyServiceProviderHours");
$results = $table->getAvailableHours($serviceId, $providerId, null, $date);
$timeZone = "";
if(!empty($results)){
$timeZone = $results[0]->time_zone;
}
$currentTime = JBusinessUtil::getCurrentTime($timeZone);
$availableHours = JBusinessUtil::processProviderAvailableHours($results);
return $availableHours;
}
/**
* Provides a suggestion list based on the provided search keyword and item type
*
* @param $itemType int type of the item (company/event/offer)
* @param $keyword string search keyword
*
* @return mixed
*
* @since 5.0.0
*/
public function getSuggestions($itemType, $keyword) {
switch ($itemType) {
case ITEM_TYPE_EVENT:
$table = $this->getTable('Event');
break;
case ITEM_TYPE_OFFER:
$table = $this->getTable('Offer');
break;
default:
$table = $this->getTable('Company');
}
// return first 10 results if keyword empty
if (empty($keyword)) {
$keyword = "a";
return $table->getSuggestions($keyword, 0, 10);
}
return $table->getSuggestions($keyword);
}
/**
* Provides a category suggestion list based on the provided search keyword and item type
*
* @param $itemType int type of the item (company/event/offer)
* @param $keyword string search keyword
*
* @return mixed
*
* @since 5.0.0
*/
public function getCategorySuggestions($itemType, $keyword) {
$table = $this->getTable('Category', 'JBusinessTable');
$limit = 2; // limit categories to 2
$suggestionList = $table->getCategorySuggestions($keyword, $itemType, $limit);
return $suggestionList;
}
/**
* Return categories based on item Type
*
* @param $itemType int type of the item (company/event/offer)
*
* @return mixed
* @since 5.0.0
*/
public function getCategories($itemType = ITEM_TYPE_BUSINESS, $lang) {
$table = $this->getTable('Category', 'JBusinessTable');
$items = $table->getMainCategoriesByType($itemType, $lang);
return $items;
}
/**
* Retrieves bookmarks based on the user ID
*
* @param $userId int ID of the user
*
* @return mixed
* @since 5.0.0
*/
public function getUserBookmarks($userId) {
$userId = (int) $userId;
$jinput = JFactory::getApplication()->input;
$limitstart = (int) $jinput->getInt('limitstart', 0);
$limit = (int) $jinput->getInt('limit', 0);
$table = $this->getTable('Bookmark');
$items = $table->getUserBookmarks($userId, $limitstart, $limit);
return $items;
}
/**
* Removes an existing bookmark based on user_id, item_id and item_type.
*
* @param $data array
*
* @return mixed
* @since 5.0.0
*/
public function removeBookmark($data) {
$userId = (int) $data["user_id"];
$itemId = (int) $data["item_id"];
$itemType = (int) $data["item_type"];
$table = $this->getTable('Bookmark');
$result = $table->deleteBookmark($userId, $itemId, $itemType);
return $result;
}
public function removeReview($data) {
$itemId = (int) $data["itemId"];
$table = $this->getTable('Review');
$result = $table->deleteReview($itemId);
return $result;
}
public function storeReviewsPictures($data, $reviewId) {
$picture_ids = array();
foreach ($data['pictures'] as $value) {
$row = $this->getTable('ReviewPictures');
$pic = new stdClass();
$pic->id = 0;
$pic->reviewId = $reviewId;
$pic->picture_info = '';
$pic->picture_path = $value['picture_path'];
$pic->picture_enable = 1;
// $pic->picture_path = JBusinessUtil::moveFile($value['picture_path'], $reviewId, $oldId , REVIEW_BD_PICTURES_PATH);
$pic->picture_path = JBusinessUtil::moveFile($pic->picture_path, $reviewId, $reviewId , REVIEW_BD_PICTURES_PATH);
if (!$row->bind($pic)) {
return false;
}
if (!$row->check()) {
return false;
}
if (!$row->store()) {
return false;
}
$picture_ids[] = $this->_db->insertid();
}
return true;
}
/**
* Checks if an item (company/offer) has been bookmarked or not by a certain
* user
*
* @param int $userId ID of the user
* @param int $itemId ID of the item
* @param int $itemType type of the item (company/offer)
*
* @return bool
* @since 5.0.0
*/
public function isBookmarked($userId, $itemId, $itemType = BOOKMARK_TYPE_BUSINESS) {
$bookmarkTable = $this->getTable('Bookmark');
$bookmark = $bookmarkTable->getBookmark($itemId, $userId, $itemType);
return !empty($bookmark);
}
/**
* Retrieves reviews based on the user ID
*
* @param $userId int ID of the user
*
* @return mixed
* @since 5.0.0
*/
public function getUserReviews($userId) {
$userId = (int) $userId;
$table = $this->getTable('Review');
$items = $table->getUserReviews($userId, $this->appSettings->show_pending_review);
return $items;
}
/**
* Enables/disables the push notification setting of a certain device.
*
* @param $enable int 1 enable 0 disable
* @param $token string device token
*
* @return mixed
*
* @since 5.0.0
*/
public function setPushNotifications($enable, $token) {
$table = $this->getTable('MobileDevice');
$result = $table->updatePushNotification($enable, $token);
return $result;
}
/**
* Set's the firebase token of a user/device (identified by the token)
*
* @param $token string
* @param $firebaseToken string
*
* @return mixed
*
* @since 5.0.0
*/
public function setFirebaseToken($token, $firebaseToken) {
$table = $this->getTable('MobileDevice');
$result = $table->updateFirebaseToken($token, $firebaseToken);
return $result;
}
/**
* Generates a token based on the user and device ids and creates a
* record on the mobile device table for that user.
*
* @param $userId int ID of the user
* @param $deviceId string device ID
*
* @return bool|string token
*
* @since 5.0.0
*/
public function saveMobileUser($userId, $deviceId) {
$mobileDevice = JTable::getInstance('MobileDevice');
$token = $this->generateToken($userId, $deviceId);
// Check if a row with the same deviceId exists
$device = $mobileDevice->getDeviceByDeviceId($deviceId);
if (isset($device)) {
// If the token is already set to the same value, return the token
if ($device->token == $token) {
return $token;
}
// Update the existing row with the new token value
$mobileDevice->id = $device->id;
$mobileDevice->user_id = $userId;
$mobileDevice->token = $token;
if (!$mobileDevice->store()) {
$application = JFactory::getApplication();
$application->enqueueMessage($device->getError(), 'error');
return false;
}
return $token;
}
$device = $mobileDevice->getDeviceByToken($token);
if (!empty($device)) {
return $token;
}
$mobileDevice->id = 0;
$mobileDevice->user_id = $userId;
$mobileDevice->device_id = $deviceId;
$mobileDevice->token = $token;
if (!$mobileDevice->store()) {
$application = JFactory::getApplication();
$application->enqueueMessage($mobileDevice->getError(), 'error');
return false;
}
return $token;
}
/**
* Deletes the device record from the database based on the
* session token.
*
* @param $token string device token
*
* @return mixed
*
* @since 5.0.0
*/
public function logOut($token) {
$table = $this->getTable('MobileDevice');
$result = $table->deleteDeviceByToken($token);
$result = !empty($result) ? true : false;
return $result;
}
/**
* Generates a hash based on the userId and deviceId and returns it.
*
* @param $userId int ID of the user
* @param $deviceId string ID of the device
*
* @return string
*
* @since 5.0.0
*/
public function generateToken($userId, $deviceId) {
$suffix = '!@#$%';
$token = $userId.','.$deviceId.','.$suffix;
$token = md5($token);
return $token;
}
/**
* Retrieves the corresponding devices for a certain user based on his/her ID.
*
* @param $userId int ID of the user
*
* @return mixed
*
* @since 5.0.0
*/
public function getDevicesByUser($userId) {
$userId = (int) $userId;
$table = $this->getTable('MobileDevice');
$devices = $table->getDevicesByUser($userId);
return $devices;
}
/**
* Retrieves the corresponding device record of a token
*
* @param $token string
*
* @return mixed
*
* @since 5.0.0
*/
public function getDeviceByToken($token) {
$table = $this->getTable('MobileDevice');
$device = $table->getDeviceByToken($token);
return $device;
}
/**
* Creates and returns the user object corresponding to a token.
*
* @param $token
*
* @return mixed
*
* @since 5.0.0
*/
public function getUserByToken($token) {
$device = $this->getDeviceByToken($token);
$userId = $device->user_id;
$user = JBusinessUtil::getUser($userId);
return $user;
}
public function processResetRequest($data)
{
$config = JFactory::getConfig();
$data['email'] = JStringPunycode::emailToPunycode($data['email']);
// Find the user id for the given email address.
$db = $this->getDbo();
$query = $db->getQuery(true)
->select('id')
->from($db->quoteName('#__users'))
->where('LOWER(' . $db->quoteName('email') . ') = LOWER(' . $db->quote($data['email']) . ')');
// Get the user object.
$db->setQuery($query);
try
{
$userId = $db->loadResult();
}
catch (RuntimeException $e)
{
$this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR', $e->getMessage()), 500);
return false;
}
// Check for a user.
if (empty($userId))
{
$this->setError(JText::_('COM_USERS_INVALID_EMAIL'));
return false;
}
// Get the user object.
$user = JUser::getInstance($userId);
// Make sure the user isn't blocked.
if ($user->block)
{
$this->setError(JText::_('COM_USERS_USER_BLOCKED'));
return false;
}
// Make sure the user isn't a Super Admin.
if ($user->authorise('core.admin'))
{
$this->setError(JText::_('COM_USERS_REMIND_SUPERADMIN_ERROR'));
return false;
}
// Make sure the user has not exceeded the reset limit
if (!$this->checkResetLimit($user))
{
$resetLimit = (int) JFactory::getApplication()->getParams()->get('reset_time');
$this->setError(JText::plural('COM_USERS_REMIND_LIMIT_ERROR_N_HOURS', $resetLimit));
return false;
}
// Set the confirmation token.
$token = JApplicationHelper::getHash(JUserHelper::genRandomPassword());
$hashedToken = JUserHelper::hashPassword($token);
$user->activation = $hashedToken;
// Save the user to the database.
if (!$user->save(true))
{
return new JException(JText::sprintf('COM_USERS_USER_SAVE_FAILED', $user->getError()), 500);
}
// Assemble the password reset confirmation link.
$mode = $config->get('force_ssl', 0) == 2 ? 1 : (-1);
$link = 'index.php?option=com_users&view=reset&layout=confirm&token=' . $token;
// Put together the email template data.
$data = $user->getProperties();
$data['fromname'] = $config->get('fromname');
$data['mailfrom'] = $config->get('mailfrom');
$data['sitename'] = $config->get('sitename');
$data['link_text'] = JRoute::_($link, false, $mode);
$data['link_html'] = JRoute::_($link, true, $mode);
$data['token'] = $token;
$subject = JText::sprintf(
'LNG_EMAIL_PASSWORD_RESET_SUBJECT',
$data['sitename']
);
$body = JText::sprintf(
'LNG_EMAIL_PASSWORD_RESET_BODY',
$data['sitename'],
$data['token'],
$data['link_text']
);
// Send the password reset request email.
$return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $user->email, $subject, $body);
// Check for an error.
if ($return !== true)
{
return new JException(JText::_('COM_USERS_MAIL_FAILED'), 500);
}
return true;
}
public function reportListing($itemId, $message, $email, $reportCause, $itemType) {
if($itemType == ITEM_TYPE_BUSINESS) {
$companiesTable = $this->getTable("Company");
$company = $companiesTable->getCompany($itemId);
$result = EmailService::sendAbuseEmail($company, $email, $message, $reportCause);
} else if ($itemType == ITEM_TYPE_OFFER){
$offersTable = $this->getTable("Offer");
$offer = $offersTable->getOffer($itemId);
$result = EmailService::sendOfferAbuseEmail($offer, $email, $message, $reportCause);
} else if ($itemType == ITEM_TYPE_EVENT){
$eventsTable = $this->getTable("Event");
$event = $eventsTable->getEvent($itemId);
$result = EmailService::sendEventAbuseEmail($event, $email, $message, $reportCause);
}
return $result;
}
public function checkResetLimit($user)
{
$params = JFactory::getApplication()->getParams();
$maxCount = (int) $params->get('reset_count');
$resetHours = (int) $params->get('reset_time');
$result = true;
$lastResetTime = strtotime($user->lastResetTime) ?: 0;
$hoursSinceLastReset = (strtotime(JFactory::getDate()->toSql()) - $lastResetTime) / 3600;
if ($hoursSinceLastReset > $resetHours)
{
// If it's been long enough, start a new reset count
$user->lastResetTime = JFactory::getDate()->toSql();
$user->resetCount = 1;
}
elseif ($user->resetCount < $maxCount)
{
// If we are under the max count, just increment the counter
++$user->resetCount;
}
else
{
// At this point, we know we have exceeded the maximum resets for the time period
$result = false;
}
return $result;
}
/**
* Method that retrieves the quantity for selling options and create the quantity select box html
*
* @param $data array contains the data that needs to be queried
*
* @return mixed
*
* @since version
*/
public function updateQuantity($data)
{
$offerModel = JModelLegacy::getInstance('Offer', 'JBusinessDirectoryModel', array('ignore_request' => true));
$result = new stdClass();
if (!isset($data['mainCatId'])){
$data['mainCatId'] = 0;
}
$table = JTable::getInstance("OfferStockConfig");
//check if search has been reset. If yes then reset all select filters after the first one
if($data['oldVal'] != $data['newValue']){
foreach ($data['selectedValues'] as &$val){
if ($val != $data['newValue']){
$val = "";
}
}
}
//if we have search values selected than do a search to get the stock configurations
$newSelectedValues = array_values(array_filter($data['selectedValues']));
if (!empty($newSelectedValues)) {
$configurations = $table->getRelatedOfferStock($data['offerId'],$data['selectedValues']);
}else{
$configurations = array();
}
// get all item selling options
$sellingOptions = $offerModel->getSellingOptionsFrontEnd($data['offerId'],$data['mainCatId']);
$allowedOptions = array();
//create the allowed options array for what the user has searched
foreach ($data['selectedValues'] as $val){
if (!empty($val)) {
$allowedOptions[explode('_',$val)[0]][] = explode('_',$val)[1];
}
}
foreach ($configurations as $configuration){
$attrOpts = explode(',',$configuration->attrCombinations);
foreach ($attrOpts as $attrOpt){
$idValAttr = explode('_',$attrOpt);
if (!isset($allowedOptions[$idValAttr[0]])){
$allowedOptions[$idValAttr[0]][] = $idValAttr[1];
}else{
if (!in_array($idValAttr[1],$allowedOptions[$idValAttr[0]])) {
$allowedOptions[$idValAttr[0]][] = $idValAttr[1];
}
}
}
}
//foreach selling options we remove the options that do not have a quantity or that are not part of user search
//except the first attribute option which will have always all the options that have combinations, because it
//will be used to reset also the search
foreach ($sellingOptions as &$sellingOption){
if (!empty($allowedOptions)){
if ($sellingOption->id != explode('_',reset($data['selectedValues']))[0]) {
$attributeOptions = explode("|#", $sellingOption->options);
$attributeOptionsIDS = explode("|#", $sellingOption->optionsIDS);
foreach ($attributeOptionsIDS as $key => $option) {
if (!isset($allowedOptions[$sellingOption->id]) || !in_array($option, $allowedOptions[$sellingOption->id])) {
unset($attributeOptions[$key]);
unset($attributeOptionsIDS[$key]);
}
}
$sellingOption->options = implode("|#", $attributeOptions);
$sellingOption->optionsIDS = implode("|#", $attributeOptionsIDS);
}
foreach ($data['selectedValues'] as $key => $val) {
$explodeIdVal = explode('_',$key);
if ($explodeIdVal[1] == $sellingOption->id) {
$sellingOption->attributeValue = $val;
break;
}else{
$sellingOption->attributeValue = "";
}
}
}else{
$sellingOption->attributeValue = "";
}
$sellingOption->is_mandatory = "1";
$sellingOption->addColDivs = false;
$sellingOption->only_for_admin = false;
$itemOtions1 = explode('|#', $sellingOption->optionsIDS);
foreach ($itemOtions1 as &$opt1) {
$opt1 = $sellingOption->id . '_' . $opt1;
}
$sellingOption->optionsIDS = $itemOtions1; //implode('|#', $itemOtions1)
$sellingOption->options = explode('|#', $sellingOption->options); //implode('|#', $itemOtions1)
}
$result->sellingOptions = $sellingOptions;
$price = "";
$useStockPrice = "";
if (count($newSelectedValues) == count($data['selectedValues'])){
$quantity = $configurations[0];
$price = $quantity->price;
$useStockPrice = $quantity->use_stock_price;
$selected = false;
if ($quantity->qty > 0 || $quantity->qty==0) {
$result->quantity = 0;
$selected = true;
}
$maximum = $quantity->max_sale;
if ($quantity->qty < $quantity->max_sale) {
$maximum = $quantity->qty;
}
$maximum = ($maximum < MAXIMUM_OFFER_QUANTITY_SELLING) ? $maximum : MAXIMUM_OFFER_QUANTITY_SELLING;
if ($quantity->qty > 0) {
$qty = 0;
for ($i = $quantity->min_sale; $i <= $maximum; $i++) {
if ($i == $quantity->min_sale && $selected == false) {
$qty++;
} else {
$qty++;
}
}
$result->quantity = $qty;
}
}else{
$result->quantity = 0;
}
if($useStockPrice && !empty($price)){
$offerTable = $offerModel->getTable();
$currency = $offerTable->getOfferCurrency($data['offerId']);
$result->price = $price;
$result->currency_name =$currency->currency_name;
}
return $result;
}
public function getUser($email) {
$table = JTable::getInstance("UserProfile", "JTable");
$user = $table->getOAuthUser($email);
return $user;
}
public function createUser($userData, $token, $provider) {
$password = base64_encode(random_bytes(8));
$data = array(
"name" => $userData['name'],
"username" => $userData['email'],
"password" => $password,
"password2" => $password,
"email" => $userData['email'],
"block" => 0,
"groups" => array("1", "2")
);
$user = new JUser;
if (!$user->bind($data)) {
throw new Exception($user->getError());
}
if (!$user->save()) {
throw new Exception($user->getError());
}
$userProfileTable = JTable::getInstance('UserProfile', 'JTable');
$userProfileTable->id = 0;
$userProfileTable->token = $token;
$userProfileTable->provider_type = $provider;
$userProfileTable->user_id = $user->id;
if (!$userProfileTable->store()) {
return false;
}
return $user;
}
public function getCustomMenu($language) {
$menusTable = JTable::getInstance("MobileAppMenus", "Table");
$menus = $menusTable->getMobileAppMenus($language);
return $menus;
}
/**
* Retrieves notifications based on the user ID
*
* @param $userId int ID of the user
*
* @return mixed
* @since 5.0.0
*/
public function getUserNotifications($userId, $limitstart, $limit) {
$userId = (int) $userId;
$table = $this->getTable('MobileAppNotifications');
$items = $table->getNotificationsByUser($userId, $limitstart, $limit);
return $items;
}
/**
* Marks a notification as read.
*
* @param int $notificationId The ID of the notification to mark as read.
* @return bool True if the notification was successfully marked as read, false otherwise.
*/
public function readNotification($notificationId) {
$table = $this->getTable('UserNotifications');
$result = $table->readNotification($notificationId);
return $result;
}
/**
* Deletes a notification.
*
* @param int $notificationId The ID of the notification to delete.
* @return bool True if the notification was successfully deleted, false otherwise.
*/
public function deleteNotification($notificationId) {
$table = $this->getTable('UserNotifications');
$result = $table->deleteNotification($notificationId);
return $result;
}
/**
* Blocks a user in the chat system.
*
* @param int $userId The ID of the user to block.
* @return bool True if the user was successfully blocked, false otherwise.
*/
public function blockChatUser($userId, $blockedId) {
$table = $this->getTable('BlockedUsers');
$result = $table->blockUser($userId, $blockedId);
return $result;
}
/**
* Unblocks a user in the chat system.
*
* @param int $userId The ID of the user to unblock.
* @return bool True if the user was successfully unblocked, false otherwise.
*/
public function unblockChatUser($userId, $blockedId) {
$table = $this->getTable('BlockedUsers');
$result = $table->unblockUser($userId, $blockedId);
return $result;
}
}