Exemplo n.º 1
0
 public function getItemValue($index)
 {
     $info = $this->details->properties['items']->value;
     $item = array('sid' => isset($info['products'][$index]) ? $info['products'][$index] : null, 'qty' => isset($info['qty'][$index]) ? $info['qty'][$index] : null, 'amount' => isset($info['amount'][$index]) ? $info['amount'][$index] : 0, 'shoppingCartRecord' => isset($info['custom_info'][$index]['shoppingCartRecord']) ? $info['custom_info'][$index]['shoppingCartRecord'] : null, 'custom_info' => isset($info['custom_info'][$index]) ? $info['custom_info'][$index] : null, 'banner_info' => isset($info['custom_info'][$index]['banner_info']) ? $info['custom_info'][$index]['banner_info'] : null);
     $productInfo = SJB_ProductsManager::getProductInfoBySID($info['products'][$index]);
     if (empty($productInfo['price'])) {
         $productInfo['price'] = $item['amount'];
     }
     return array_merge($productInfo, $item);
 }
Exemplo n.º 2
0
 public function execute()
 {
     $templateProcessor = SJB_System::getTemplateProcessor();
     $listingSid = isset($_REQUEST['listing_id']) ? $_REQUEST['listing_id'] : null;
     $listing = SJB_ListingManager::getObjectBySID($listingSid);
     if (!is_null($listing) && !$listing->isActive()) {
         $listingInfo = SJB_ListingManager::getListingInfoBySID($listingSid);
         $productInfo = !empty($listingInfo['product_info']) ? unserialize($listingInfo['product_info']) : array();
         if (isset($listingInfo['complete']) && $listingInfo['complete'] == 1 && $listingInfo['checkouted'] == 1) {
             $subTotalPrice = 0;
             // проверить истек ли листинг, если истек , прайс прировнять к renewal_price
             if (SJB_ListingManager::getIfListingHasExpiredBySID($listing->getID()) && isset($productInfo['renewal_price'])) {
                 $subTotalPrice = $productInfo['renewal_price'];
             }
             $userSid = $listing->getUserSID();
             $productSid = $productInfo['product_sid'];
             $listingTitle = $listing->getProperty('Title')->getValue();
             $listingTypeSid = $listing->getListingTypeSID();
             $listingTypeId = SJB_ListingTypeManager::getListingTypeIDBySID($listingTypeSid);
             $newProductName = "Reactivation of \"{$listingTitle}\" {$listingTypeId}";
             $newProductInfo = SJB_ShoppingCart::createInfoForCustomProduct($userSid, $productSid, $listingSid, $subTotalPrice, $newProductName, 'activateListing');
             if ($subTotalPrice <= 0) {
                 if (SJB_ListingManager::activateListingBySID($listing->getSID())) {
                     SJB_Notifications::sendUserListingActivatedLetter($listing, $listing->getUserSID());
                 }
             } else {
                 SJB_ShoppingCart::createCustomProduct($newProductInfo, $userSid);
                 $shoppingUrl = SJB_System::getSystemSettings('SITE_URL') . '/shopping-cart/';
                 SJB_HelperFunctions::redirect($shoppingUrl);
             }
             $templateProcessor->assign('listingTypeID', SJB_ListingTypeManager::getListingTypeIDBySID($listingTypeSid));
         } elseif ($listingInfo['checkouted'] == 0) {
             $productsInfoFromShopppingCart = SJB_ShoppingCart::getProductsInfoFromCartByProductSID($productInfo['product_sid'], $listing->getUserSID());
             if (empty($productsInfoFromShopppingCart)) {
                 $productInfoToShopCart = SJB_ProductsManager::getProductInfoBySID($productInfo['product_sid']);
                 $productInfo['number_of_listings'] = 1;
                 $productObj = new SJB_Product($productInfoToShopCart, $productInfoToShopCart['product_type']);
                 $productObj->setNumberOfListings($productInfoToShopCart['number_of_listings']);
                 $productInfoToShopCart['price'] = $productObj->getPrice();
                 SJB_ShoppingCart::addToShoppingCart($productInfoToShopCart, $listing->getUserSID());
             }
             SJB_HelperFunctions::redirect(SJB_System::getSystemsettings('SITE_URL') . '/shopping-cart/');
         } else {
             $errors['LISTING_IS_NOT_COMPLETE'] = 1;
         }
     } elseif (is_null($listingSid)) {
         $errors['INVALID_LISTING_ID'] = 1;
     } elseif (!is_null($listing) && $listing->isActive()) {
         $errors['LISTING_ALREADY_ACTIVE'] = 1;
     } else {
         $errors['WRONG_LISTING_ID_SPECIFIED'] = 1;
     }
     $templateProcessor->assign("errors", isset($errors) ? $errors : null);
     $templateProcessor->display("pay_for_listing.tpl");
 }
Exemplo n.º 3
0
 public static function generateExportData($parameters)
 {
     $exportProperties = $aliases = $sid = null;
     extract($parameters);
     $exportData = array();
     $userInfo = SJB_UserManager::getUserInfoBySID($sid);
     $userInfo['id'] = $userInfo['sid'];
     $userInfo = $aliases->changePropertiesInfo($userInfo);
     if (!empty($userInfo['product'])) {
         $contracts = $userInfo['product'];
         $userInfo['product'] = array();
         foreach ($contracts as $contract) {
             $productInfo = SJB_ProductsManager::getProductInfoBySID($contract['product_sid']);
             if ($productInfo) {
                 $extraInfo = !empty($contract['serialized_extra_info']) ? unserialize($contract['serialized_extra_info']) : null;
                 $userInfo['product'][] = serialize(array('name' => $productInfo['name'], 'creation_date' => $contract['creation_date'], 'expired_date' => $contract['expired_date'], 'price' => $contract['price'], 'number_of_postings' => $contract['number_of_postings'], 'number_of_listings' => $extraInfo ? $extraInfo['number_of_listings'] : 0, 'status' => $contract['status']));
             }
         }
         $userInfo['product'] = implode(',', $userInfo['product']);
     } else {
         $userInfo['product'] = '';
     }
     // this data is necessary for additional properties : like tree
     $exportData[$sid][self::USER_OPTIONS_INDEX]['user_group_id'] = SJB_Array::get($userInfo, 'user_group');
     foreach ($exportProperties as $propertyId => $value) {
         $exportData[$sid][$propertyId] = isset($userInfo[$propertyId]) ? $userInfo[$propertyId] : null;
     }
     self::changeTreeProperties($exportData);
     self::changeListProperties($exportData);
     self::cleanOptions($exportData);
     self::changeMonetaryProperties($exportProperties, $exportData);
     self::changeFileProperties($exportProperties, $exportData, 'file');
     self::changeFileProperties($exportProperties, $exportData, 'video');
     self::changeFileProperties($exportProperties, $exportData, 'Logo');
     self::changeLocationProperties($exportProperties, $exportData);
     return $exportData[$sid];
 }
Exemplo n.º 4
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $template = SJB_Request::getVar('template', 'users.tpl');
     $searchTemplate = SJB_Request::getVar('search_template', 'user_search_form.tpl');
     $passedParametersViaUri = SJB_UrlParamProvider::getParams();
     $userGroupID = $passedParametersViaUri ? array_shift($passedParametersViaUri) : false;
     $userGroupSID = $userGroupID ? SJB_UserGroupManager::getUserGroupSIDByID($userGroupID) : null;
     $errors = array();
     /********** A C T I O N S   W I T H   U S E R S **********/
     $action = SJB_Request::getVar('action_name');
     if (!empty($action)) {
         $users_sids = SJB_Request::getVar('users', array());
         $_REQUEST['restore'] = 1;
         switch ($action) {
             case 'approve':
                 foreach ($users_sids as $user_sid => $value) {
                     $username = SJB_UserManager::getUserNameByUserSID($user_sid);
                     SJB_UserManager::setApprovalStatusByUserName($username, 'Approved');
                     SJB_UserManager::activateUserByUserName($username);
                     SJB_UserDBManager::deleteActivationKeyByUsername($username);
                     if (!SJB_SocialPlugin::getProfileSocialID($user_sid)) {
                         SJB_Notifications::sendUserWelcomeLetter($user_sid);
                     } else {
                         SJB_Notifications::sendUserApprovedLetter($user_sid);
                     }
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI());
                 break;
             case 'reject':
                 $rejection_reason = SJB_Request::getVar('rejection_reason', '');
                 foreach ($users_sids as $user_sid => $value) {
                     $username = SJB_UserManager::getUserNameByUserSID($user_sid);
                     SJB_UserManager::setApprovalStatusByUserName($username, 'Rejected', $rejection_reason);
                     SJB_UserManager::deactivateUserByUserName($username);
                     SJB_Notifications::sendUserRejectedLetter($user_sid);
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI());
                 break;
             case 'activate':
                 foreach ($users_sids as $user_sid => $value) {
                     $username = SJB_UserManager::getUserNameByUserSID($user_sid);
                     $userinfo = SJB_UserManager::getUserInfoByUserName($username);
                     SJB_UserManager::activateUserByUserName($username);
                     if ($userinfo['approval'] == 'Approved') {
                         SJB_UserDBManager::deleteActivationKeyByUsername($username);
                         SJB_Notifications::sendUserApprovedLetter($user_sid);
                     }
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI());
                 break;
             case 'deactivate':
                 foreach ($users_sids as $user_sid => $value) {
                     $username = SJB_UserManager::getUserNameByUserSID($user_sid);
                     SJB_UserManager::deactivateUserByUserName($username);
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI());
                 break;
             case 'delete':
                 foreach (array_keys($users_sids) as $user_sid) {
                     try {
                         SJB_UserManager::deleteUserById($user_sid);
                     } catch (Exception $e) {
                         $errors[] = $e->getMessage();
                     }
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI());
                 break;
             case 'send_activation_letter':
                 foreach ($users_sids as $user_sid => $value) {
                     SJB_Notifications::sendUserActivationLetter($user_sid);
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI());
                 break;
             case 'change_product':
                 $productToChange = SJB_Request::getVar('product_to_change');
                 if (empty($productToChange)) {
                     $productToChange = 0;
                 }
                 foreach ($users_sids as $user_sid => $value) {
                     $user = SJB_UserManager::getObjectBySID($user_sid);
                     // UNSUBSCRIBE selected
                     if ($productToChange == 0) {
                         SJB_ContractManager::deleteAllContractsByUserSID($user_sid);
                     } else {
                         $productInfo = SJB_ProductsManager::getProductInfoBySID($productToChange);
                         $listingNumber = SJB_Request::getVar('number_of_listings', null);
                         if (is_null($listingNumber) && !empty($productInfo['number_of_listings'])) {
                             $listingNumber = $productInfo['number_of_listings'];
                         }
                         $contract = new SJB_Contract(array('product_sid' => $productToChange, 'numberOfListings' => $listingNumber, 'is_recurring' => 0));
                         $contract->setUserSID($user_sid);
                         $contract->saveInDB();
                         if ($contract->isFeaturedProfile()) {
                             SJB_UserManager::makeFeaturedBySID($user_sid);
                         }
                     }
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI());
                 break;
             case 'ban_ip':
                 $cantBanUsers = array();
                 foreach ($users_sids as $user_sid => $value) {
                     $user = SJB_UserManager::getUserInfoBySID($user_sid);
                     if ($user['ip'] && !SJB_IPManager::getBannedIPByValue($user['ip'])) {
                         SJB_IPManager::makeIPBanned($user['ip']);
                     } else {
                         $cantBanUsers[] = $user['username'];
                     }
                 }
                 if ($cantBanUsers) {
                     $tp->assign('cantBanUsers', $cantBanUsers);
                 } else {
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI());
                 }
                 break;
             case 'unban_ip':
                 $cantUnbanIPs = array();
                 foreach ($users_sids as $user_sid => $value) {
                     $user = SJB_UserManager::getUserInfoBySID($user_sid);
                     if ($user['ip'] !== '') {
                         if (SJB_IPManager::getBannedIPByValue($user['ip'])) {
                             SJB_IPManager::makeIPEnabledByValue($user['ip']);
                         } elseif (SJB_UserManager::checkBan($errors, $user['ip'])) {
                             $cantUnbanIPs[] = $user['ip'];
                         }
                     }
                 }
                 if ($cantUnbanIPs) {
                     $tp->assign('rangeIPs', $cantUnbanIPs);
                 } else {
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI());
                 }
                 break;
             default:
                 unset($_REQUEST['restore']);
                 break;
         }
         if (empty($errors)) {
             SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . SJB_Navigator::getURI());
         }
     }
     /***************************************************************/
     $_REQUEST['action'] = 'search';
     $user = new SJB_User(array(), $userGroupSID);
     $user->addProperty(array('id' => 'user_group', 'type' => 'list', 'value' => '', 'is_system' => true, 'list_values' => SJB_UserGroupManager::getAllUserGroupsIDsAndCaptions()));
     $user->addProperty(array('id' => 'registration_date', 'type' => 'date', 'value' => '', 'is_system' => true));
     $user->addProperty(array('id' => 'approval', 'caption' => 'Approval', 'type' => 'list', 'list_values' => array(array('id' => 'Pending', 'caption' => 'Pending'), array('id' => 'Approved', 'caption' => 'Approved'), array('id' => 'Rejected', 'caption' => 'Rejected')), 'length' => '10', 'is_required' => false, 'is_system' => true));
     // get array of accessible products
     $productsSIDs = SJB_ProductsManager::getProductsIDsByUserGroupSID($userGroupSID);
     $products = array();
     foreach ($productsSIDs as $key => $productSID) {
         $product = SJB_ProductsManager::getProductInfoBySID($productSID);
         $products[$key] = $product;
         if (!empty($product['pricing_type']) && $product['pricing_type'] == 'volume_based' && !empty($product['volume_based_pricing'])) {
             $volumeBasedPricing = $product['volume_based_pricing'];
             $minListings = min($volumeBasedPricing['listings_range_from']);
             $maxListings = max($volumeBasedPricing['listings_range_to']);
             $countListings = array();
             for ($i = $minListings; $i <= $maxListings; $i++) {
                 $countListings[] = $i;
             }
             $products[$key]['count_listings'] = $countListings;
         }
     }
     $user->addProperty(array('id' => 'product', 'type' => 'list', 'value' => '', 'list_values' => $products, 'is_system' => true));
     $aliases = new SJB_PropertyAliases();
     $aliases->addAlias(array('id' => 'user_group', 'real_id' => 'user_group_sid', 'transform_function' => 'SJB_UserGroupManager::getUserGroupSIDByID'));
     $aliases->addAlias(array('id' => 'product', 'real_id' => 'product_sid'));
     $_REQUEST['user_group']['equal'] = $userGroupSID;
     $search_form_builder = new SJB_SearchFormBuilder($user);
     $criteria_saver = new SJB_UserCriteriaSaver();
     if (isset($_REQUEST['restore'])) {
         $_REQUEST = array_merge($_REQUEST, $criteria_saver->getCriteria());
     }
     $criteria = $search_form_builder->extractCriteriaFromRequestData($_REQUEST, $user);
     $search_form_builder->setCriteria($criteria);
     $search_form_builder->registerTags($tp);
     $userGroupInfo = SJB_UserGroupManager::getUserGroupInfoBySID($userGroupSID);
     if (SJB_Request::getVar('online', '') == '1') {
         $tp->assign("online", true);
     }
     $tp->assign('userGroupInfo', $userGroupInfo);
     $tp->assign('products', $products);
     $tp->assign('selectedProduct', isset($_REQUEST['product']['simple_equal']) ? $_REQUEST['product']['simple_equal'] : '');
     $tp->display($searchTemplate);
     /********************** S O R T I N G *********************/
     $paginator = new SJB_UsersPagination($userGroupInfo, SJB_Request::getVar('online', ''), $template);
     $firstLastName = '';
     if (!empty($_REQUEST['FirstName']['equal'])) {
         $name['FirstName']['any_words'] = $name['LastName']['any_words'] = $_REQUEST['FirstName']['equal'];
         $firstLastName = $_REQUEST['FirstName'];
         unset($_REQUEST['FirstName']);
         $_REQUEST['FirstName']['fields_or'] = $name;
     }
     $criteria = $search_form_builder->extractCriteriaFromRequestData($_REQUEST, $user);
     $inner_join = false;
     // if search by product field
     if (isset($_REQUEST['product']['simple_equal']) && $_REQUEST['product']['simple_equal'] != '') {
         $inner_join = array('contracts' => array('join_field' => 'user_sid', 'join_field2' => 'sid', 'join' => 'INNER JOIN'));
     }
     if (SJB_Request::getVar('online', '') == '1') {
         $maxLifeTime = ini_get("session.gc_maxlifetime");
         $currentTime = time();
         $innerJoinOnline = array('user_session_data_storage' => array('join_field' => 'user_sid', 'join_field2' => 'sid', 'select_field' => 'session_id', 'join' => 'INNER JOIN', 'where' => "AND unix_timestamp(`user_session_data_storage`.`last_activity`) + {$maxLifeTime} > {$currentTime}"));
         if ($inner_join) {
             $inner_join = array_merge($inner_join, $innerJoinOnline);
         } else {
             $inner_join = $innerJoinOnline;
         }
     }
     $searcher = new SJB_UserSearcher(array('limit' => ($paginator->currentPage - 1) * $paginator->itemsPerPage, 'num_rows' => $paginator->itemsPerPage), $paginator->sortingField, $paginator->sortingOrder, $inner_join);
     $found_users = array();
     $found_users_sids = array();
     if (SJB_Request::getVar('action', '') == 'search') {
         $found_users = $searcher->getObjectsSIDsByCriteria($criteria, $aliases);
         $criteria_saver->setSession($_REQUEST, $searcher->getFoundObjectSIDs());
     } elseif (isset($_REQUEST['restore'])) {
         $found_users = $criteria_saver->getObjectsFromSession();
     }
     foreach ($found_users as $id => $userID) {
         $user_info = SJB_UserManager::getUserInfoBySID($userID);
         $contractInfo = SJB_ContractManager::getAllContractsInfoByUserSID($user_info['sid']);
         $user_info['products'] = count($contractInfo);
         $found_users[$id] = $user_info;
     }
     $paginator->setItemsCount($searcher->getAffectedRows());
     $sorted_found_users_sids = $found_users_sids;
     /****************************************************************/
     $tp->assign("userGroupInfo", $userGroupInfo);
     $tp->assign("found_users", $found_users);
     $searchFields = '';
     foreach ($_REQUEST as $key => $val) {
         if (is_array($val)) {
             foreach ($val as $fieldName => $fieldValue) {
                 if (is_array($fieldValue)) {
                     foreach ($fieldValue as $fieldSubName => $fieldSubValue) {
                         $searchFields .= "&{$key}[{$fieldSubName}]=" . array_pop($fieldSubValue);
                     }
                 } else {
                     $searchFields .= "&{$key}[{$fieldName}]={$fieldValue}";
                 }
             }
         }
     }
     $tp->assign('paginationInfo', $paginator->getPaginationInfo());
     $tp->assign("searchFields", $searchFields);
     $tp->assign("found_users_sids", $sorted_found_users_sids);
     $tp->assign('errors', $errors);
     $tp->display($template);
 }
Exemplo n.º 5
0
 public static function createInvoiceTemplate($invoiceInfo)
 {
     $items = array();
     foreach ($invoiceInfo['items']['products'] as $key => $productSID) {
         if ($productSID > -1) {
             $product_info = SJB_ProductsManager::getProductInfoBySID($productSID);
             $items[$key]['product'] = $product_info['name'];
             $items[$key]['show_qty'] = $product_info['product_type'] == 'post_listings' && $product_info['pricing_type'] == 'volume_based';
         } else {
             $items[$key]['product'] = $invoiceInfo['items']['custom_item'][$key];
             $items[$key]['show_qty'] = true;
         }
         $items[$key]['qty'] = !empty($invoiceInfo['items']['qty'][$key]) ? $invoiceInfo['items']['qty'][$key] : 'unlimited';
         $items[$key]['amount'] = $invoiceInfo['items']['amount'][$key];
     }
     $invoiceInfo['date'] = SJB_I18N::getInstance()->getDate($invoiceInfo['date']);
     $invoiceInfo['items'] = $items;
     if ($invoiceInfo['include_tax']) {
         $invoiceInfo['tax_amount'] = $invoiceInfo['tax_info']['tax_amount'];
         $invoiceInfo['tax_name'] = $invoiceInfo['tax_info']['tax_name'];
         $invoiceInfo['taxSid'] = $invoiceInfo['tax_info']['sid'];
     } else {
         $invoiceInfo['taxSid'] = false;
     }
     return $invoiceInfo;
 }
Exemplo n.º 6
0
 /**
  * @param array $promotions
  */
 public static function preparePromotionsInfoForLog(&$promotions)
 {
     foreach ($promotions as &$promotionData) {
         $userInfo = SJB_UserManager::getUserInfoBySID(SJB_Array::get($promotionData, 'user_sid'));
         if ($userInfo) {
             $userGroupInfo = SJB_UserGroupManager::getUserGroupInfoBySID(SJB_Array::get($userInfo, 'user_group_sid'));
             $promotionData['user'] = array('username' => $userInfo['username'], 'userGroupID' => $userGroupInfo['id']);
         }
         $productsNames = array();
         $productsSIDs = explode(',', SJB_Array::get($promotionData, 'product_sid'));
         if ($productsSIDs) {
             foreach ($productsSIDs as $productSID) {
                 if (is_numeric($productSID)) {
                     $productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
                     if (!empty($productInfo)) {
                         array_push($productsNames, SJB_Array::get($productInfo, 'name'));
                     }
                 } else {
                     array_push($productsNames, $productSID);
                 }
             }
         }
         $promotionData['products'] = $productsNames;
         $savedPromotionCodeInfo = unserialize($promotionData['code_info']);
         $promotionData['type'] = SJB_Array::get($savedPromotionCodeInfo, 'type');
         $promotionData['code'] = SJB_Array::get($savedPromotionCodeInfo, 'code');
         unset($promotionData['code_info']);
     }
 }
Exemplo n.º 7
0
 public static function getSalesStatistics($period, $filter, $sorting_field, $sorting_order)
 {
     $where = '';
     if (!empty($period['from'])) {
         $period['from'] = SJB_I18N::getInstance()->getInput('date', $period['from']);
         $time = "00:00:00";
         $where .= " AND s.`date` >= '{$period['from']} {$time}' ";
     }
     if (!empty($period['to'])) {
         $period['to'] = SJB_I18N::getInstance()->getInput('date', $period['to']);
         $time = "23:59:59";
         $where .= " AND s.`date` <= '{$period['to']} {$time}' ";
     }
     $join = '';
     $groupBy = '';
     $query = '';
     if (in_array($filter, array('Location_Country', 'Location_State', 'Location_City'))) {
         $fieldInfo = SJB_ListingFieldDBManager::getLocationFieldsInfoById($filter);
     } else {
         $fieldInfo = SJB_ListingFieldDBManager::getListingFieldInfoByID($filter);
     }
     if (strstr($filter, 'userGroup_')) {
         $userGroupSID = str_replace('userGroup_', '', $filter);
         $userGroupID = SJB_UserGroupManager::getUserGroupIDBySID($userGroupSID);
         $join = " INNER JOIN `users` u ON s.`user_sid` = u.`sid` ";
         $where .= " AND u.`user_group_sid` = '{$userGroupSID}'";
         $groupBy = " u.`sid`";
         $query = ', u.* ';
     } elseif (!empty($fieldInfo['type']) && $fieldInfo['type'] == 'list' && empty($fieldInfo['parent_sid'])) {
         $join = " INNER JOIN `users` u ON s.`user_sid` = u.`sid` INNER JOIN `user_profile_field_list` ufl ON u.`{$filter}` = ufl.`sid` ";
         $groupBy = " `{$filter}` ";
         $query = ", ufl.`value` as {$filter} ";
     } elseif (!empty($fieldInfo['type']) && $fieldInfo['type'] == 'list' && !empty($fieldInfo['parent_sid'])) {
         if ($filter == 'Location_Country') {
             $join = " INNER JOIN `users` u ON s.`user_sid` = u.`sid` INNER JOIN `countries` c ON u.`{$filter}` = c.`sid` ";
             $query = ", c.`country_name` as {$filter} ";
         } else {
             $join = " INNER JOIN `users` u ON s.`user_sid` = u.`sid` INNER JOIN `states` st ON u.`{$filter}` = st.`sid` ";
             $query = ", st.`state_name` as {$filter} ";
         }
         $groupBy = " `{$filter}` ";
     } elseif ($filter == 'sid') {
         $join = " INNER JOIN `products` p ON s.`object_sid` = p.`sid` ";
         $where .= " AND s.type = 'product' ";
         $groupBy = " s.`object_sid`, s.`featured`, s.`priority`, s.`reactivate` ";
         $query = ', p.* ';
     } else {
         $join = " INNER JOIN `users` u ON s.`user_sid` = u.`sid` ";
         $where .= " AND u.`{$filter}` != '' AND u.`{$filter}` IS NOT NULL ";
         $groupBy = " u.`{$filter}` ";
         $query = ', u.* ';
     }
     $orderBy = '';
     if ($sorting_field == 'username') {
         if (strstr($filter, 'userGroup_')) {
             if ($userGroupID == 'Employer') {
                 $orderBy = "ORDER BY `CompanyName` {$sorting_order}";
             } else {
                 $orderBy = "ORDER BY `FirstName`, `LastName` {$sorting_order}";
             }
         }
     } else {
         $orderBy = "ORDER BY {$sorting_field} {$sorting_order}";
     }
     $statisticsInfo = array();
     $total = $totalSum = SJB_DB::query("SELECT sum(s.`price`*s.`count`) as total, sum(s.`count`) as units_sold, 'Total' as totalSum, 0 as `sid` FROM `statistics` s {$join} WHERE s.`event` = 'payment' {$where}");
     $total = $total ? array_pop($total) : array('total' => 0);
     $percent = $total['total'] != 0 ? 100 / $total['total'] : 0;
     if ($filter == 'sid') {
         $statisticsInfo = SJB_DB::query("SELECT s.*, sum(s.`price`*s.`count`) as total, sum(s.`price`*s.`count`)*{$percent} as percent, sum(s.`count`) as units_sold {$query} \n\t\t\t\t\t\t\t\t\t\t\t\t FROM `statistics` s {$join} \n\t\t\t\t\t\t\t\t\t\t\t\t WHERE s.`event` = 'payment' {$where} \n\t\t\t\t\t\t\t\t\t\t\t\t GROUP BY {$groupBy} {$orderBy}");
     } else {
         $statisticsSIDs = SJB_DB::query("SELECT {$groupBy} as sid, sum(s.`price`*s.`count`) as total FROM `statistics` s {$join} WHERE s.`event` = 'payment' {$where} GROUP BY {$groupBy} ORDER BY total DESC LIMIT 10");
         foreach ($statisticsSIDs as $info) {
             $SIDs[] = "'" . $info['sid'] . "'";
         }
         if (isset($SIDs)) {
             $SIDs = implode(',', $SIDs);
             $statisticsInfo = SJB_DB::query("SELECT s.*, sum(s.`price`*s.`count`) as total, sum(s.`price`*s.`count`)*{$percent} as percent, sum(s.`count`) as units_sold {$query} \n\t\t\t\t\t\t\t\t\t\t\t\t FROM `statistics` s {$join} \n\t\t\t\t\t\t\t\t\t\t\t\t WHERE {$groupBy} in ({$SIDs}) AND s.`event` = 'payment' {$where} \n\t\t\t\t\t\t\t\t\t\t\t\t GROUP BY {$groupBy} {$orderBy}");
             $ohter = SJB_DB::query("SELECT s.*, sum(s.`price`*s.`count`) as total, sum(s.`price`*s.`count`)*{$percent} as percent, sum(s.`count`) as units_sold, 'Other' as other {$query} FROM `statistics` s {$join} WHERE {$groupBy} not in ({$SIDs}) AND s.`event` = 'payment' {$where}");
             if (!empty($ohter[0]['sid'])) {
                 $statisticsInfo = array_merge($statisticsInfo, $ohter);
             }
         }
     }
     $statisticsInfo = array_merge($statisticsInfo, $totalSum);
     $statistics = array();
     foreach ($statisticsInfo as $key => $statisticInfo) {
         if ($filter == 'sid') {
             $productInfo = SJB_ProductsManager::getProductInfoBySID($statisticInfo['sid']);
             $statisticInfo['product_type'] = SJB_ProductsManager::getProductTypeByID($productInfo['product_type']);
         }
         $statistics[$key] = $statisticInfo;
         if (isset($statisticInfo['other'])) {
             $statistics[$key]['generalColumn'] = 'Other';
         } elseif (isset($statisticInfo['totalSum'])) {
             $statistics[$key]['generalColumn'] = 'Total';
             $statistics[$key]['name'] = 'Total';
             $statistics[$key]['percent'] = '100%';
         } elseif (strstr($filter, 'userGroup_')) {
             if ($userGroupID == 'Employer') {
                 $statistics[$key]['generalColumn'] = !empty($statisticInfo['CompanyName']) ? $statisticInfo['CompanyName'] : $statisticInfo['username'];
             } else {
                 $statistics[$key]['generalColumn'] = !empty($statisticInfo['FirstName']) && !empty($statisticInfo['LastName']) ? $statisticInfo['FirstName'] . " " . $statisticInfo['LastName'] : $statisticInfo['username'];
             }
         } elseif ($filter == 'sid') {
             $statistics[$key]['generalColumn'] = $statisticInfo['name'];
         } else {
             $statistics[$key]['generalColumn'] = $statisticInfo[$filter];
         }
         $statistics[$key]['percent'] = round($statistics[$key]['percent'], 2);
         if ($statistics[$key]['percent'] == 99.98999999999999) {
             $statistics[$key]['percent'] = 100;
         }
     }
     return $statistics;
 }
Exemplo n.º 8
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $userSID = SJB_Request::getVar('user_sid', false);
     $includeTax = SJB_Request::getVar('include_tax', SJB_Settings::getSettingByName('enable_taxes'));
     $errors = array();
     $invoiceErrors = array();
     $template = 'add_invoice.tpl';
     $userInfo = SJB_UserManager::getUserInfoBySID($userSID);
     if ($userInfo) {
         if (!empty($userInfo['parent_sid'])) {
             $parent_sid = $userInfo['parent_sid'];
             $username = $userInfo['username'] . '/' . $userInfo['email'];
         } else {
             $parent_sid = $userSID;
             $username = $userInfo['FirstName'] . ' ' . $userInfo['LastName'] . ' ' . $userInfo['ContactName'] . ' ' . $userInfo['CompanyName'] . '/' . $userInfo['email'];
         }
         $formSubmitted = SJB_Request::getVar('action', '') == 'save';
         $productsSIDs = SJB_ProductsManager::getProductsIDsByUserGroupSID($userInfo['user_group_sid']);
         $products = array();
         foreach ($productsSIDs as $key => $productSID) {
             $productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
             if (!empty($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'volume_based') {
                 $volumeBasedPricing = $productInfo['volume_based_pricing'];
                 $minListings = min($volumeBasedPricing['listings_range_from']);
                 $maxListings = max($volumeBasedPricing['listings_range_to']);
                 $countListings = array();
                 for ($i = $minListings; $i <= $maxListings; $i++) {
                     $countListings[$i]['number_of_listings'] = $i;
                     for ($j = 1; $j <= count($volumeBasedPricing['listings_range_from']); $j++) {
                         if ($i >= $volumeBasedPricing['listings_range_from'][$j] && $i <= $volumeBasedPricing['listings_range_to'][$j]) {
                             $countListings[$i]['price'] = $volumeBasedPricing['price_per_unit'][$j];
                         }
                     }
                 }
                 $productInfo['count_listings'] = $countListings;
             } elseif (!empty($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'fixed') {
                 unset($productInfo['volume_based_pricing']);
             }
             $products[$key] = $productInfo;
         }
         $total = SJB_I18N::getInstance()->getInput('float', SJB_Request::getVar('total', 0));
         $taxInfo = SJB_TaxesManager::getTaxInfoByUserSidAndPrice($parent_sid, $total);
         $invoice = new SJB_Invoice($_REQUEST);
         $addForm = new SJB_Form($invoice);
         $addForm->registerTags($tp);
         if ($formSubmitted) {
             $invoiceErrors = $invoice->isValid();
             if (empty($invoiceErrors) && $addForm->isDataValid($errors)) {
                 $invoice->setFloatNumbersIntoValidFormat();
                 $invoice->setPropertyValue('success_page_url', SJB_System::getSystemSettings('USER_SITE_URL') . '/create-contract/');
                 SJB_InvoiceManager::saveInvoice($invoice);
                 if (SJB_Request::getVar('send_invoice', false)) {
                     SJB_Notifications::sendInvoiceToCustomer($invoice->getSID(), $userSID);
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings("SITE_URL") . '/manage-invoices/');
             } else {
                 $invoiceDate = SJB_I18N::getInstance()->getInput('date', $invoice->getPropertyValue('date'));
                 $invoice->setPropertyValue('date', $invoiceDate);
             }
         } else {
             $invoice->setPropertyValue('date', date('Y-m-d'));
             $invoice->setPropertyValue('status', SJB_Invoice::INVOICE_STATUS_UNPAID);
         }
         $invoice->setFloatNumbersIntoValidFormat();
         $tp->assign('username', $username);
         $tp->assign('user_sid', $userSID);
         $tp->assign('products', $products);
         $tp->assign('tax', $taxInfo);
         $tp->assign('include_tax', $includeTax);
     } else {
         $errors[] = 'CUSTOMER_NOT_SELECTED';
         $tp->assign('action', 'add');
         $template = 'errors.tpl';
     }
     $tp->assign("errors", array_merge($errors, $invoiceErrors));
     $tp->display($template);
 }
Exemplo n.º 9
0
 public static function sendRemindSubscriptionExpirationLetter($userSID, $contractInfo, $days)
 {
     $user = SJB_UserManager::getObjectBySID($userSID);
     $userGroupSID = $user->getUserGroupSID();
     $emailTplSID = SJB_UserGroupManager::getEmailTemplateSIDByUserGroupAndField($userGroupSID, 'notify_subscription_expire_date');
     $product = array();
     $productInfo = SJB_ProductsManager::getProductInfoBySID(SJB_Array::get($contractInfo, 'product_sid'));
     if ($productInfo) {
         $productExtraInfo = SJB_ProductsManager::getProductExtraInfoBySID($productInfo['sid']);
         $productInfo = array_merge($productInfo, $productExtraInfo);
         $fields = SJB_ProductsManager::createTemplateStructureForProductForEmailTpl($productInfo);
         $product = array_merge($fields, $productExtraInfo);
     }
     $user_info = SJB_UserManager::createTemplateStructureForUser($user);
     $data = array('type' => 'contract', 'user' => $user_info, 'days' => $days, 'contractInfo' => $contractInfo, 'product' => $product);
     $email = SJB_EmailTemplateEditor::getEmail($user_info['email'], $emailTplSID, $data);
     return $email->send('Remind Subscription Expiration');
 }
Exemplo n.º 10
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $listingTypeID = SJB_Request::getVar('listing_type_id', null);
     $listingTypeSID = SJB_ListingTypeManager::getListingTypeSIDByID($listingTypeID);
     $listingTypeInfo = SJB_ListingTypeManager::getListingTypeInfoBySID($listingTypeSID);
     $productSID = SJB_Request::getVar('product_sid', false);
     $editUser = SJB_Request::getVar('edit_user', false);
     $action = SJB_Request::getVar('action', false);
     $username = SJB_Request::getVar('username', false);
     $errors = array();
     if ($username && ($userSID = SJB_UserManager::getUserSIDbyUsername($username))) {
         $userInfo = SJB_UserManager::getUserInfoBySID($userSID);
         $userGroupInfo = SJB_UserGroupManager::getUserGroupInfoBySID($userInfo['user_group_sid']);
         if (!$productSID) {
             $products = SJB_ProductsManager::getProductsInfoByUserGroupSID($userGroupInfo['sid']);
             foreach ($products as $key => $product) {
                 if (empty($product['listing_type_sid']) || $product['listing_type_sid'] != $listingTypeSID) {
                     unset($products[$key]);
                 }
             }
             if ($action == 'productVerify') {
                 $errors['PRODUCT_NOT_SELECTED'] = 1;
             }
             $tp->assign('errors', $errors);
             $tp->assign('username', $username);
             $tp->assign('products', $products);
             $tp->assign('edit_user', $editUser);
             $tp->assign('userSID', $userSID);
             $tp->assign('userGroupInfo', $userGroupInfo);
             $tp->assign('listingType', SJB_ListingTypeManager::createTemplateStructure($listingTypeInfo));
             $tp->display('select_product.tpl');
         } else {
             $form_submitted = SJB_Request::getVar('action', '') == 'add';
             $tmp_listing_id_from_request = SJB_Request::getVar('listing_id', false, 'default', 'int');
             if (!empty($tmp_listing_id_from_request)) {
                 $tmp_listing_sid = $tmp_listing_id_from_request;
             } elseif (!$tmp_listing_id_from_request) {
                 $tmp_listing_sid = time();
             }
             $productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
             $extraInfo = is_null($productInfo['serialized_extra_info']) ? null : unserialize($productInfo['serialized_extra_info']);
             if (!empty($extraInfo)) {
                 $extraInfo['product_sid'] = $productSID;
             }
             $_REQUEST['featured'] = !empty($_REQUEST['featured']) ? $_REQUEST['featured'] : $productInfo['featured'];
             $_REQUEST['priority'] = !empty($_REQUEST['priority']) ? $_REQUEST['priority'] : $productInfo['priority'];
             $listing = new SJB_Listing($_REQUEST, $listingTypeSID);
             $properties = $listing->getPropertyList();
             foreach ($properties as $property) {
                 $propertyInfo = $listing->getPropertyInfo($property);
                 $propertyInfo['user_sid'] = $userSID;
                 if ($propertyInfo['type'] == 'location') {
                     $child = $listing->getChild($property);
                     $childProperties = $child->getPropertyList();
                     foreach ($childProperties as $childProperty) {
                         $childPropertyInfo = $child->getPropertyInfo($childProperty);
                         $childPropertyInfo['user_sid'] = $userSID;
                         $child->setPropertyInfo($childProperty, $childPropertyInfo);
                     }
                 }
                 $listing->setPropertyInfo($property, $propertyInfo);
             }
             $listing->deleteProperty('status');
             $listing->deleteProperty('reject_reason');
             $access_type = $listing->getProperty('access_type');
             if ($form_submitted) {
                 if (!empty($access_type)) {
                     $listing->addProperty(array('id' => 'access_list', 'type' => 'multilist', 'value' => SJB_Request::getVar("list_emp_ids"), 'is_system' => true));
                 }
             }
             $screening_questionnaires = SJB_ScreeningQuestionnaires::getList($userSID);
             if (SJB_Acl::getInstance()->isAllowed('use_screening_questionnaires') && $screening_questionnaires) {
                 $issetQuestionnairyField = $listing->getProperty('screening_questionnaire');
                 if ($issetQuestionnairyField) {
                     $value = SJB_Request::getVar("screening_questionnaire");
                     $listing_info = $_REQUEST;
                     $value = $value ? $value : isset($listing_info['screening_questionnaire']) ? $listing_info['screening_questionnaire'] : '';
                     $listing->addProperty(array('id' => 'screening_questionnaire', 'type' => 'list', 'caption' => 'Screening Questionnaire', 'value' => $value, 'list_values' => SJB_ScreeningQuestionnaires::getListSIDsAndCaptions($userSID), 'is_system' => true));
                 }
             } else {
                 $listing->deleteProperty('screening_questionnaire');
             }
             if ($listing->getProperty('captcha')) {
                 $listing->deleteProperty('captcha');
             }
             $add_listing_form = new SJB_Form($listing);
             $add_listing_form->registerTags($tp);
             $field_errors = array();
             if ($form_submitted && $add_listing_form->isDataValid($field_errors)) {
                 $listing->addProperty(array('id' => 'complete', 'type' => 'integer', 'value' => 1, 'is_system' => true));
                 $listing->setUserSID($userSID);
                 $listing->setProductInfo($extraInfo);
                 if (empty($access_type->value)) {
                     $listing->setPropertyValue('access_type', 'everyone');
                 }
                 SJB_ListingManager::saveListing($listing);
                 SJB_Statistics::addStatistics('addListing', $listing->getListingTypeSID(), $listing->getSID(), false, $_REQUEST['featured'], $_REQUEST['priority'], $userSID);
                 if (isset($_SESSION['tmp_file_storage'])) {
                     foreach ($_SESSION['tmp_file_storage'] as $v) {
                         SJB_DB::query("UPDATE `listings_pictures` SET `listing_sid` = ?n WHERE `picture_saved_name` = ?s", $listing->getSID(), $v['picture_saved_name']);
                         SJB_DB::query("UPDATE `listings_pictures` SET `listing_sid` = ?n WHERE `thumb_saved_name` = ?s", $listing->getSID(), $v['thumb_saved_name']);
                     }
                     SJB_Session::unsetValue('tmp_file_storage');
                 }
                 $formToken = SJB_Request::getVar('form_token');
                 $sessionFilesStorage = SJB_Session::getValue('tmp_uploads_storage');
                 $uploadedFields = SJB_Array::getPath($sessionFilesStorage, $formToken);
                 if (!empty($uploadedFields)) {
                     foreach ($uploadedFields as $fieldId => $fieldValue) {
                         // get field of listing
                         $isComplex = false;
                         if (strpos($fieldId, ':') !== false) {
                             $isComplex = true;
                         }
                         $tmpUploadedFileId = $fieldValue['file_id'];
                         // rename it to real listing field value
                         $newFileId = $fieldId . "_" . $listing->getSID();
                         SJB_DB::query("UPDATE `uploaded_files` SET `id` = ?s WHERE `id` =?s", $newFileId, $tmpUploadedFileId);
                         if ($isComplex) {
                             list($parentField, $subField, $complexStep) = explode(':', $fieldId);
                             $parentProp = $listing->getProperty($parentField);
                             $parentValue = $parentProp->getValue();
                             // look for complex property with current $fieldID and set it to new value of property
                             if (!empty($parentValue)) {
                                 foreach ($parentValue as $id => $value) {
                                     if ($id == $subField) {
                                         $parentValue[$id][$complexStep] = $newFileId;
                                     }
                                 }
                                 $listing->setPropertyValue($parentField, $parentValue);
                             }
                         } else {
                             $listing->setPropertyValue($fieldId, $newFileId);
                         }
                         // unset value from session temporary storage
                         $sessionFilesStorage = SJB_Array::unsetValueByPath($sessionFilesStorage, "{$formToken}/{$fieldId}");
                     }
                     //and remove token key from temporary storage
                     $sessionFilesStorage = SJB_Array::unsetValueByPath($sessionFilesStorage, "{$formToken}");
                     SJB_Session::setValue('tmp_uploads_storage', $sessionFilesStorage);
                     SJB_ListingManager::saveListing($listing);
                 }
                 SJB_ListingManager::activateListingBySID($listing->getSID());
                 SJB_ProductsManager::incrementPostingsNumber($productSID);
                 $listingSid = $listing->getSID();
                 SJB_Event::dispatch('listingSaved', $listingSid);
                 if ($editUser) {
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/edit-user/?user_sid=" . $userSID);
                 } else {
                     if ($listingTypeID == 'resume' || $listingTypeID == 'job') {
                         $link = "manage-" . strtolower($listingTypeID) . "s";
                     } else {
                         $link = "manage-" . strtolower($listingTypeID) . "-listings";
                     }
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/{$link}/?action=search&listing_type_sid=" . $listingTypeSID);
                 }
             } else {
                 $listing->deleteProperty('access_list');
                 $listing->deleteProperty('contract_id');
                 $add_listing_form = new SJB_Form($listing);
                 if ($form_submitted) {
                     $add_listing_form->isDataValid($field_errors);
                 }
                 $add_listing_form->registerTags($tp);
                 $form_fields = $add_listing_form->getFormFieldsInfo();
                 $pages = SJB_PostingPagesManager::getPagesByListingTypeSID($listingTypeSID);
                 $formFieldsSorted = array();
                 $formFieldsSorted['featured'] = $form_fields['featured'];
                 $formFieldsSorted['priority'] = $form_fields['priority'];
                 foreach ($pages as $page) {
                     $listing_fields = SJB_PostingPagesManager::getAllFieldsByPageSIDForForm($page['sid']);
                     foreach (array_keys($listing_fields) as $field) {
                         if ($listing->propertyIsSet($field)) {
                             $formFieldsSorted[$field] = $form_fields[$field];
                         }
                     }
                 }
                 $form_fields = $formFieldsSorted;
                 //SJB_HelperFunctions::d($form_fields);
                 $employers_list = SJB_Request::getVar('list_emp_ids', false);
                 $employers = array();
                 if (is_array($employers_list)) {
                     foreach ($employers_list as $emp) {
                         $currEmp = SJB_UserManager::getUserInfoBySID($emp);
                         $employers[] = array('user_id' => $emp, 'value' => $currEmp['CompanyName']);
                     }
                     sort($employers);
                 }
                 $numberOfPictures = isset($extraInfo['number_of_pictures']) ? $extraInfo['number_of_pictures'] : 0;
                 $tp->assign("pic_limit", $numberOfPictures);
                 $tp->assign("listing_id", $tmp_listing_sid);
                 $tp->assign("listing_access_list", $employers);
                 $tp->assign("errors", $field_errors);
                 $tp->assign("form_fields", $form_fields);
                 $metaDataProvider = SJB_ObjectMother::getMetaDataProvider();
                 $tp->assign("METADATA", array("form_fields" => $metaDataProvider->getFormFieldsMetadata($form_fields)));
             }
             $tp->assign("uploadMaxFilesize", SJB_UploadFileManager::getIniUploadMaxFilesize());
             $tp->assign('edit_user', $editUser);
             $tp->assign('productInfo', $productInfo);
             $tp->assign('username', $username);
             $tp->assign('product_sid', $productSID);
             $tp->assign('userSID', $userSID);
             $tp->assign('userGroupInfo', $userGroupInfo);
             $tp->assign('listingType', SJB_ListingTypeManager::createTemplateStructure($listingTypeInfo));
             $tp->display('input_form.tpl');
         }
     } else {
         if ($username && !$userSID) {
             $errors['USER_NOT_FOUND'] = 1;
         } elseif ($action == 'userVerify') {
             $errors['USER_NOT_SELECTED'] = 1;
         }
         $tp->assign('errors', $errors);
         $tp->assign('username', $username);
         $tp->assign('listingType', SJB_ListingTypeManager::createTemplateStructure($listingTypeInfo));
         $tp->display('select_user.tpl');
     }
 }
Exemplo n.º 11
0
 public function execute()
 {
     ini_set('max_execution_time', 0);
     $tp = SJB_System::getTemplateProcessor();
     $file_info = isset($_FILES['import_file']) ? $_FILES['import_file'] : null;
     $encodingFromCharset = SJB_Request::getVar('encodingFromCharset', 'UTF-8');
     $listingTypeID = SJB_Request::getVar('listing_type_id', null);
     $productSID = SJB_Request::getVar('product_sid', 0);
     $errors = array();
     if ($listingTypeID && $productSID) {
         $acl = SJB_Acl::getInstance();
         $resource = 'post_' . strtolower($listingTypeID);
         if (!$acl->isAllowed($resource, $productSID, 'product')) {
             $errors[] = 'You cannot import listings of this type under the selected product';
         }
     }
     if (!empty($file_info)) {
         $extension = SJB_Request::getVar('file_type');
         if (!SJB_ImportFile::isValidFileExtensionByFormat($extension, $file_info)) {
             $errors['DO_NOT_MATCH_SELECTED_FILE_FORMAT'] = true;
         }
     }
     if (empty($file_info) || $file_info['error'] || $errors) {
         if (isset($file_info['error']) && $file_info['error'] > 0) {
             $errors[SJB_UploadFileManager::getErrorId($file_info['error'])] = 1;
         }
         $listing_types = SJB_ListingTypeManager::getAllListingTypesInfo();
         $products = SJB_ProductsManager::getProductsByProductType('post_listings');
         $tp->assign("uploadMaxFilesize", SJB_UploadFileManager::getIniUploadMaxFilesize());
         $tp->assign('listing_types', $listing_types);
         $tp->assign('products', $products);
         $tp->assign('errors', $errors);
         $tp->assign('charSets', SJB_HelperFunctions::getCharSets());
         $tp->display('import_listings.tpl');
     } else {
         $i18n = SJB_I18N::getInstance();
         $csv_delimiter = SJB_Request::getVar('csv_delimiter', null);
         $activeStatus = SJB_Request::getVar('active', 0);
         $activationDate = SJB_Request::getVar('activation_date', date('Y-m-d'));
         $activationDate = $i18n->getInput('date', $activationDate);
         $non_existed_values_flag = SJB_Request::getVar('non_existed_values', null);
         $productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
         if (empty($productInfo['listing_duration'])) {
             $expirationDate = '';
         } else {
             $timestamp = strtotime($activationDate . ' + ' . $productInfo['listing_duration'] . ' days');
             $expirationDate = $i18n->getDate(date('Y-m-d', $timestamp));
         }
         $extension = $_REQUEST['file_type'];
         if ($extension == 'xls') {
             $import_file = new SJB_ImportFileXLS($file_info);
         } elseif ($extension == 'csv') {
             $import_file = new SJB_ImportFileCSV($file_info, $csv_delimiter);
         }
         $import_file->parse($encodingFromCharset);
         $listing = $this->CreateListing(array(), $listingTypeID);
         $imported_data = $import_file->getData();
         $isFileImported = true;
         $count = 0;
         $addedListingsSids = array();
         $nonExistentUsers = array();
         foreach ($imported_data as $key => $importedColumn) {
             if ($key == 1) {
                 $imported_data_processor = new SJB_ImportedDataProcessor($importedColumn, $listing);
                 continue;
             }
             if (!$importedColumn) {
                 continue;
             }
             $count++;
             $listingInfo = $imported_data_processor->getData($non_existed_values_flag, $importedColumn);
             $doc = new DOMDocument();
             foreach ($listing->getProperties() as $property) {
                 if ($property->getType() == 'complex' && !empty($listingInfo[$property->id])) {
                     $childFields = SJB_ListingComplexFieldManager::getListingFieldsInfoByParentSID($property->sid);
                     $doc->loadXML($listingInfo[$property->id]);
                     $results = $doc->getElementsByTagName($property->id . 's');
                     $listingInfo[$property->id] = array();
                     foreach ($results as $complexparent) {
                         $i = 1;
                         foreach ($complexparent->getElementsByTagName($property->id) as $result) {
                             $resultXML = simplexml_import_dom($result);
                             foreach ($childFields as $childField) {
                                 if (isset($resultXML->{$childField}['id'])) {
                                     $listingInfo[$property->id][$childField['id']][$i] = XML_Util::reverseEntities((string) $resultXML->{$childField}['id']);
                                 }
                             }
                             $i++;
                         }
                     }
                 } elseif ($property->getType() == 'monetary' && !empty($listingInfo[$property->id])) {
                     $value = $listingInfo[$property->id];
                     $listingInfo[$property->id] = array();
                     $listingInfo[$property->id]['value'] = $value;
                     $defaultCurrency = SJB_CurrencyManager::getDefaultCurrency();
                     $currencyCode = !empty($listingInfo[$property->id . "Currency"]) ? $listingInfo[$property->id . "Currency"] : $defaultCurrency['currency_code'];
                     $currency = SJB_CurrencyManager::getCurrencyByCurrCode($currencyCode);
                     $listingInfo[$property->id]['add_parameter'] = !empty($currency['sid']) ? $currency['sid'] : '';
                     if (isset($listingInfo[$property->id . "Currency"])) {
                         unset($listingInfo[$property->id . "Currency"]);
                     }
                 } elseif ($property->getType() == 'location') {
                     $locationFields = array($property->id . '.Country', $property->id . '.State', $property->id . '.City', $property->id . '.ZipCode');
                     $locationFieldAdded = array();
                     foreach ($locationFields as $locationField) {
                         if (array_key_exists($locationField, $listingInfo)) {
                             switch ($locationField) {
                                 case $property->id . '.Country':
                                     $value = SJB_CountriesManager::getCountrySIDByCountryName($listingInfo[$locationField]);
                                     if (!$value) {
                                         $value = SJB_CountriesManager::getCountrySIDByCountryCode($listingInfo[$locationField]);
                                     }
                                     break;
                                 case $property->id . '.State':
                                     $value = SJB_StatesManager::getStateSIDByStateName($listingInfo[$locationField]);
                                     if (!$value) {
                                         $value = SJB_StatesManager::getStateSIDByStateCode($listingInfo[$locationField]);
                                     }
                                     break;
                                 default:
                                     $value = $listingInfo[$locationField];
                                     break;
                             }
                             $listingInfo[$property->id][str_replace($property->id . '.', '', $locationField)] = $value;
                             $locationFieldAdded[] = str_replace($property->id . '.', '', $locationField);
                         }
                     }
                     if ($property->id == 'Location') {
                         $locationFields = array('Country', 'State', 'City', 'ZipCode');
                         foreach ($locationFields as $locationField) {
                             if (array_key_exists($locationField, $listingInfo) && !in_array($locationField, $locationFieldAdded) && !$listing->getProperty($locationField)) {
                                 switch ($locationField) {
                                     case 'Country':
                                         $value = SJB_CountriesManager::getCountrySIDByCountryName($listingInfo[$locationField]);
                                         if (!$value) {
                                             $value = SJB_CountriesManager::getCountrySIDByCountryCode($listingInfo[$locationField]);
                                         }
                                         break;
                                     case 'State':
                                         $value = SJB_StatesManager::getStateSIDByStateName($listingInfo[$locationField]);
                                         if (!$value) {
                                             $value = SJB_StatesManager::getStateSIDByStateCode($listingInfo[$locationField]);
                                         }
                                         break;
                                     default:
                                         $value = $listingInfo[$locationField];
                                         break;
                                 }
                                 $listingInfo[$property->id][$locationField] = $value;
                             }
                         }
                     }
                 }
             }
             $listing = $this->CreateListing($listingInfo, $listingTypeID);
             $pictures = array();
             if (isset($listingInfo['pictures'])) {
                 $listing->addPicturesProperty();
                 $explodedPictures = explode(';', $listingInfo['pictures']);
                 foreach ($explodedPictures as $picture) {
                     if (!empty($picture)) {
                         $pictures[] = $picture;
                     }
                 }
                 $listing->setPropertyValue('pictures', count($pictures));
             }
             $listing->addActiveProperty($activeStatus);
             $listing->addActivationDateProperty($activationDate);
             $listing->addExpirationDateProperty($expirationDate);
             SJB_ListingDBManager::setListingExpirationDateBySid($listing->sid);
             $listing->setProductInfo(SJB_ProductsManager::getProductExtraInfoBySID($productSID));
             $listing->setPropertyValue('access_type', 'everyone');
             $listing->setPropertyValue('status', 'approved');
             foreach ($listing->getProperties() as $property) {
                 if ($property->getType() == 'tree' && $property->value !== '') {
                     try {
                         $treeImportHelper = new SJB_FieldTreeImportHelper($property->value);
                         $treeValues = $treeImportHelper->parseAndGetValues();
                         $listing->setPropertyValue($property->id, $treeValues);
                         $listing->details->properties[$property->id]->type->property_info['value'] = $treeValues;
                     } catch (Exception $e) {
                         $listing->setPropertyValue($property->id, '');
                         $listing->details->properties[$property->id]->type->property_info['value'] = '';
                         SJB_Error::writeToLog('Listing Import. Tree Field Value Error: ' . $e->getMessage());
                     }
                 } elseif ($property->id == 'ApplicationSettings' && !empty($listingInfo['ApplicationSettings'])) {
                     if (preg_match("^[a-z0-9\\._-]+@[a-z0-9\\._-]+\\.[a-z]{2,}\$^iu", $listingInfo['ApplicationSettings'])) {
                         $listingInfo['ApplicationSettings'] = array('value' => $listingInfo['ApplicationSettings'], 'add_parameter' => 1);
                     } elseif (preg_match("^(https?:\\/\\/)^", $listingInfo['ApplicationSettings'])) {
                         $listingInfo['ApplicationSettings'] = array('value' => $listingInfo['ApplicationSettings'], 'add_parameter' => 2);
                     } else {
                         $listingInfo['ApplicationSettings'] = array('value' => '', 'add_parameter' => '');
                     }
                     //put empty if not valid email or url
                     $listing->details->properties[$property->id]->type->property_info['value'] = $listingInfo['ApplicationSettings'];
                 } elseif ($property->getType() == 'complex') {
                     $childFields = SJB_ListingComplexFieldManager::getListingFieldsInfoByParentSID($property->sid);
                     $complexChildValues = $property->value;
                     foreach ($childFields as $childField) {
                         if ($childField['type'] == 'complexfile' && !empty($complexChildValues[$childField['id']])) {
                             $fieldInfo = SJB_ListingComplexFieldManager::getFieldInfoBySID($childField['sid']);
                             if (!SJB_UploadFileManager::fileImport($listingInfo, $fieldInfo, $property->id)) {
                                 $isFileImported = false;
                             }
                         }
                         if ($property->type->complex->details->properties[$childField['id']]->value == null) {
                             $property->type->complex->details->properties[$childField['id']]->value = array(1 => '');
                             $property->type->complex->details->properties[$childField['id']]->type->property_info['value'] = array(1 => '');
                         }
                     }
                 }
                 // The import of files at import of listings
                 if (in_array($property->getType(), array('file', 'logo', 'video')) && $property->value !== '') {
                     $fieldInfo = SJB_ListingFieldDBManager::getListingFieldInfoByID($property->id);
                     if (!SJB_UploadFileManager::fileImport($listingInfo, $fieldInfo)) {
                         $isFileImported = false;
                     }
                 }
             }
             if ($non_existed_values_flag == 'add') {
                 $this->UpdateListValues($listing);
             }
             if ($listing->getUserSID()) {
                 SJB_ListingManager::saveListing($listing);
                 $listingSid = $listing->getSID();
                 SJB_Statistics::addStatistics('addListing', $listing->getListingTypeSID(), $listingSid);
                 SJB_ListingManager::activateListingBySID($listingSid, false);
                 if (!$this->fillGallery($listingSid, $pictures)) {
                     $isFileImported = false;
                 }
                 $addedListingsSids[] = $listingSid;
             } else {
                 $nonExistentUsers[] = $listingInfo['username'];
                 $count--;
             }
         }
         SJB_BrowseDBManager::addListings($addedListingsSids);
         SJB_ProductsManager::incrementPostingsNumber($productSID, count($addedListingsSids));
         if ($isFileImported && file_exists(SJB_System::getSystemSettings('IMPORT_FILES_DIRECTORY'))) {
             SJB_Filesystem::delete(SJB_System::getSystemSettings('IMPORT_FILES_DIRECTORY'));
         }
         $tp->assign('imported_listings_count', $count);
         $tp->assign('nonExistentUsers', $nonExistentUsers);
         $tp->display('import_listings_result.tpl');
     }
 }
Exemplo n.º 12
0
 /**
  * Add new banner to table
  *
  * @param string $title
  * @param string $link target link of banner
  * @param string $imagePath
  * @param integer $sx
  * @param integer $sy
  * @param string $type
  * @param integer $active as boolean - 1 or 0
  * @param int|string $groupSID
  * @param array $params
  * @param null $userSID
  * @param int $contractSID
  * @return boolean
  */
 function addBanner($title, $link, $imagePath, $sx, $sy, $type, $active, $groupSID = '', $params, $userSID = null, $contractSID = 0)
 {
     $status = "approved";
     $link = preg_replace("|\\.\\./|u", '', $link);
     $productInfo = SJB_ProductsManager::getProductInfoBySID($params['product_sid']);
     $productExtraInfo = unserialize($productInfo['serialized_extra_info']);
     if (!empty($productExtraInfo['approve_by_admin'])) {
         $status = "pending";
     }
     return SJB_DB::query("\n\t\t\tINSERT INTO `{$this->bannersTable}`\n\t\t\tSET  `title` = ?s, `link` = ?s, `image_path` = ?s, `type` = ?s, `width` = ?n, `height` = ?n, `active`=?n, `groupSID`=?n, openBannerIn =?s, bannerType = ?s, code = ?s, `user_sid` = ?n, `status` = ?s, `contract_sid` = ?n", $title, $link, $imagePath, $type, $sx, $sy, $active, $groupSID, $params['openBannerIn'], $params['bannerType'], $params['code'], $userSID, $status, $contractSID);
 }
Exemplo n.º 13
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $action = SJB_Request::getVar('action', false);
     $updateUsers = SJB_Request::getVar('update_users', 0);
     $sid = SJB_Request::getVar('sid', 0);
     $errors = array();
     $productErrors = array();
     $productInfo = SJB_ProductsManager::getProductInfoBySID($sid);
     if ($productInfo) {
         if ($productInfo['product_type'] == 'featured_user') {
             $_REQUEST['user_group_sid'] = SJB_UserGroupManager::getUserGroupSIDByID('Employer');
         }
         $productInfo = array_merge($productInfo, $_REQUEST);
         $product = new SJB_Product($productInfo, $productInfo['product_type']);
         $product->setSID($sid);
         $pages = $product->getProductPages();
         $editProductForm = new SJB_Form($product);
         $editProductForm->registerTags($tp);
         $form_submitted = $action == 'save' || $action == 'apply_product';
         $activeError = array();
         if ($form_submitted && ($productInfo['active'] = 1)) {
             if (!empty($productInfo['availability_to']) && SJB_I18N::getInstance()->getInput('date', $productInfo['availability_to']) <= date('Y-m-d')) {
                 $activeError['INVALID_ACTIVATION'] = 'The product cannot be activated. Please change the availability date.';
             }
         }
         if ($form_submitted) {
             $productErrors = $product->isValid($product);
             $activeError = array_merge($activeError, $productErrors);
             if (in_array($productInfo['product_type'], array('access_listings', 'featured_user', 'banners', 'custom_product'))) {
                 $periodName = $product->getPropertyValue('period_name');
                 if ($periodName == 'unlimited') {
                     $product->makePropertyNotRequired('period');
                 }
             }
         }
         if ($form_submitted && $editProductForm->isDataValid($errors) && !$activeError) {
             $product->saveProduct($product);
             $product->savePermissions($_REQUEST);
             if ($updateUsers) {
                 $contracts = SJB_ContractManager::getAllContractsByProductSID($product->getSID());
                 if ($contracts) {
                     $contractsSIDs = array();
                     foreach ($contracts as $contract) {
                         $contractsSIDs[] = $contract['id'];
                     }
                     $contractsSIDs = implode(',', $contractsSIDs);
                     SJB_ContractSQL::updateAllContractsExtraInfoByProductSID($contractsSIDs, $product->getSID());
                 }
             }
             if ($action == 'save') {
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/products/');
             }
         } else {
             $product->setFloatNumbersIntoValidFormat();
         }
         $errors = array_merge($errors, $activeError);
         $formFieldsInfo = $editProductForm->getFormFieldsInfo();
         $formFields = array();
         foreach ($pages as $pageID => $page) {
             foreach ($formFieldsInfo as $formFieldInfo) {
                 if (in_array($formFieldInfo['id'], $page['fields'])) {
                     $formFields[$pageID][] = $formFieldInfo;
                 }
             }
             if (!isset($formFields[$pageID])) {
                 $formFields[$pageID] = array();
             }
         }
         $tp->assign('form_fields', $formFields);
         $tp->assign('product_info', $productInfo);
         $tp->assign('product_type', $productInfo['product_type']);
         $tp->assign('params', http_build_query($_REQUEST));
         $tp->assign('pageTab', SJB_Request::getVar('page', false));
         $tp->assign('pages', $pages);
         $tp->assign("errors", $errors);
         $tp->display('edit_product.tpl');
     }
 }
Exemplo n.º 14
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $action = SJB_Request::getVar('action', false);
     $sid = SJB_Request::getVar('sid', 0);
     $errors = array();
     $productErrors = array();
     $productInfo = SJB_ProductsManager::getProductInfoBySID($sid);
     if ($productInfo) {
         if ($productInfo['product_type'] == 'featured_user') {
             $_REQUEST['user_group_sid'] = SJB_UserGroupManager::getUserGroupSIDByID('Employer');
         }
         $productInfo = array_merge($productInfo, $_REQUEST);
         $product = new SJB_Product($productInfo, $productInfo['product_type']);
         $pages = $product->getProductPages();
         $editProductForm = new SJB_Form($product);
         $editProductForm->registerTags($tp);
         $form_submitted = SJB_Request::getVar('action', '') == 'save';
         if ($form_submitted && in_array($productInfo['product_type'], array('access_listings', 'featured_user', 'banners', 'custom_product'))) {
             $periodName = $product->getPropertyValue('period_name');
             if ($periodName == 'unlimited') {
                 $product->makePropertyNotRequired('period');
             }
         }
         $activeError = array();
         if ($form_submitted && ($productInfo['active'] = 1)) {
             if (!empty($productInfo['availability_to']) && SJB_I18N::getInstance()->getInput('date', $productInfo['availability_to']) <= date('Y-m-d')) {
                 $activeError['INVALID_ACTIVATION'] = 'The product cannot be activated. Please change the availability date.';
             }
         }
         if ($form_submitted) {
             $productErrors = $product->isValid($product);
             $activeError = array_merge($activeError, $productErrors);
         }
         if ($form_submitted && $editProductForm->isDataValid($errors) && !$activeError) {
             $product->addProperty(array('id' => 'product_type', 'type' => 'string', 'value' => $productInfo['product_type'], 'is_system' => true));
             $product->saveProduct($product, $_REQUEST);
             $product->savePermissions($_REQUEST);
             SJB_HelperFunctions::redirect(SJB_System::getSystemSettings("SITE_URL") . '/edit-product/?sid=' . $product->getSID());
         }
         $errors = array_merge($errors, $activeError);
         $formFieldsInfo = $editProductForm->getFormFieldsInfo();
         $formFields = array();
         foreach ($pages as $pageID => $page) {
             foreach ($formFieldsInfo as $formFieldInfo) {
                 if (in_array($formFieldInfo['id'], $page['fields'])) {
                     $formFields[$pageID][] = $formFieldInfo;
                 }
             }
             if (!isset($formFields[$pageID])) {
                 $formFields[$pageID] = array();
             }
         }
         $tp->assign('form_fields', $formFields);
         $tp->assign('product_info', $productInfo);
         $tp->assign('product_type', $productInfo['product_type']);
         $tp->assign('pages', $pages);
         $tp->assign('pageTab', SJB_Request::getVar('page', false));
         $tp->assign("errors", $errors);
         $tp->display('clone_product.tpl');
     }
 }
Exemplo n.º 15
0
 public static function updateExpirationPeriod($contractSID)
 {
     $contractInfo = self::getInfo($contractSID);
     if ($contractInfo) {
         $productInfo = SJB_ProductsManager::getProductInfoBySID($contractInfo['product_sid']);
         $product = new SJB_Product($productInfo, $productInfo['product_type']);
         $is_recurring = !empty($productInfo['is_recurring']) ? $productInfo['is_recurring'] : false;
         $expirationPeriod = $product->getExpirationPeriod();
         if ($expirationPeriod) {
             if ($is_recurring) {
                 // Для рекьюринг планов, делаем запас для проплаты в 1 день
                 $expirationPeriod++;
             }
             $expired_date = date("Y-m-d", strtotime("+" . $expirationPeriod . " day"));
             SJB_DB::query("UPDATE `contracts` SET `expired_date` = ?s WHERE `id` = ?n", $expired_date, $contractSID);
         }
     }
 }
Exemplo n.º 16
0
 public static function createTemplateStructureForProduct($productInfo)
 {
     if (!empty($productInfo)) {
         $productInfo = unserialize($productInfo);
         $productInfo = !empty($productInfo['product_sid']) ? SJB_ProductsManager::getProductInfoBySID($productInfo['product_sid']) : $productInfo;
         $productInfo = $productInfo ? $productInfo : array();
         $METADATA = array('METADATA' => array('caption' => array('type' => 'string', 'propertyID' => 'caption'), 'short_description' => array('type' => 'text', 'propertyID' => 'short_description')));
         return array_merge($productInfo, $METADATA);
     }
     return array();
 }
Exemplo n.º 17
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     if (!SJB_UserManager::isUserLoggedIn()) {
         $errors['NOT_LOGGED_IN'] = true;
         $tp->assign("ERRORS", $errors);
         $tp->display("../classifieds/error.tpl");
         return;
     }
     if (SJB_Request::getVar('subscriptionComplete') == 'false') {
         $this->errors['SUBSCRIPTION_IS_FAIL'] = 1;
     }
     $currentUser = SJB_UserManager::getCurrentUser();
     $contractsInfo = SJB_ContractManager::getAllContractsInfoByUserSID($currentUser->getSID());
     $cancelRecurringContract = SJB_Request::getVar('cancelRecurringContract', false);
     if ($cancelRecurringContract) {
         $tp->assign('cancelRecurringContractId', $cancelRecurringContract);
     }
     $listingTypes = SJB_ListingTypeManager::getAllListingTypesInfo();
     $contractSIDs = array();
     foreach ($contractsInfo as $key => $contractInfo) {
         $contractInfo['extra_info'] = unserialize($contractInfo['serialized_extra_info']);
         $contractInfo['avalaibleViews'] = array();
         $contractInfo['avalaibleContactViews'] = array();
         $contractInfo['listingAmount'] = array();
         foreach ($listingTypes as $listingType) {
             $listingTypeID = $listingType['id'];
             if ($this->acl->isAllowed('view_' . $listingTypeID . '_details', $contractInfo['id'], 'contract')) {
                 $contractInfo['avalaibleViews'][$listingTypeID]['name'] = $listingType['name'];
                 $permissionParam = $this->acl->getPermissionParams('view_' . $listingTypeID . '_details', $contractInfo['id'], 'contract');
                 $contractInfo['avalaibleViews'][$listingTypeID]['numOfViews'] = SJB_ContractManager::getNumbeOfPagesViewed($currentUser->getSID(), array($contractInfo['id']), false, $listingType['sid']);
                 if (empty($permissionParam)) {
                     $contractInfo['avalaibleViews'][$listingTypeID]['count'] = 'unlimited';
                     $contractInfo['avalaibleViews'][$listingTypeID]['viewsLeft'] = 'unlimited';
                 } else {
                     $contractInfo['avalaibleViews'][$listingTypeID]['count'] = $permissionParam;
                     $contractInfo['avalaibleViews'][$listingTypeID]['viewsLeft'] = $permissionParam - $contractInfo['avalaibleViews'][$listingTypeID]['numOfViews'];
                 }
             }
             if ($this->acl->isAllowed('post_' . $listingTypeID, $contractInfo['id'], 'contract')) {
                 $contractInfo['listingAmount'][$listingTypeID]['name'] = $listingType['name'];
                 $permissionParam = $this->acl->getPermissionParams('post_' . $listingTypeID, $contractInfo['id'], 'contract');
                 $contractInfo['listingAmount'][$listingTypeID]['numPostings'] = $contractInfo['number_of_postings'];
                 if (empty($permissionParam)) {
                     $contractInfo['listingAmount'][$listingTypeID]['count'] = 'unlimited';
                     $contractInfo['listingAmount'][$listingTypeID]['listingsLeft'] = 'unlimited';
                 } else {
                     $contractInfo['listingAmount'][$listingTypeID]['count'] = $permissionParam;
                     $contractInfo['listingAmount'][$listingTypeID]['listingsLeft'] = max($contractInfo['listingAmount'][$listingTypeID]['count'] - $contractInfo['listingAmount'][$listingTypeID]['numPostings'], 0);
                 }
             }
             if ($this->acl->isAllowed('view_' . $listingTypeID . '_contact_info', $contractInfo['id'], 'contract')) {
                 $permissionParam = $this->acl->getPermissionParams('view_' . $listingTypeID . '_contact_info', $contractInfo['id'], 'contract');
                 $contractInfo['avalaibleContactViews'][$listingTypeID]['name'] = $listingType['name'];
                 $contractInfo['avalaibleContactViews'][$listingTypeID]['numOfViews'] = SJB_ContractManager::getNumbeOfPagesViewed($currentUser->getSID(), array($contractInfo['id']), 'view_' . $listingTypeID . '_contact_info');
                 if (empty($permissionParam)) {
                     $contractInfo['avalaibleContactViews'][$listingTypeID]['count'] = 'unlimited';
                     $contractInfo['avalaibleContactViews'][$listingTypeID]['viewsLeft'] = 'unlimited';
                 } else {
                     $contractInfo['avalaibleContactViews'][$listingTypeID]['count'] = $permissionParam;
                     $contractInfo['avalaibleContactViews'][$listingTypeID]['viewsLeft'] = $contractInfo['avalaibleContactViews'][$listingTypeID]['count'] - $contractInfo['avalaibleContactViews'][$listingTypeID]['numOfViews'];
                 }
             }
         }
         $contractsInfo[$key] = $contractInfo;
         $contractsInfo[$key]['product_info'] = SJB_ProductsManager::getProductInfoBySID($contractInfo['extra_info']['product_sid']);
         $contractSIDs[] = $contractInfo['id'];
     }
     $statistics = array();
     foreach ($listingTypes as $listingType) {
         $listingTypeID = $listingType['id'];
         if ($this->acl->isAllowed('view_' . $listingTypeID . '_details')) {
             $statistics['avalaibleViews'][$listingTypeID]['name'] = $listingType['name'];
             $permissionParam = $this->acl->getPermissionParams('view_' . $listingTypeID . '_details');
             $statistics['avalaibleViews'][$listingTypeID]['numOfViews'] = SJB_ContractManager::getNumbeOfPagesViewed($currentUser->getSID(), $contractSIDs, false, $listingType['sid']);
             if (empty($permissionParam)) {
                 $statistics['avalaibleViews'][$listingTypeID]['count'] = 'unlimited';
                 $statistics['avalaibleViews'][$listingTypeID]['viewsLeft'] = 'unlimited';
             } else {
                 $statistics['avalaibleViews'][$listingTypeID]['count'] = $permissionParam;
                 $statistics['avalaibleViews'][$listingTypeID]['viewsLeft'] = $statistics['avalaibleViews'][$listingTypeID]['count'] - $statistics['avalaibleViews'][$listingTypeID]['numOfViews'];
             }
         }
         if ($this->acl->isAllowed('post_' . $listingTypeID)) {
             $statistics['listingAmount'][$listingTypeID]['name'] = $listingType['name'];
             $permissionParam = $this->acl->getPermissionParams('post_' . $listingTypeID);
             $statistics['listingAmount'][$listingTypeID]['numPostings'] = SJB_ContractManager::getListingsNumberByContractSIDsListingType($contractSIDs, $listingTypeID);
             if (empty($permissionParam)) {
                 $statistics['listingAmount'][$listingTypeID]['count'] = 'unlimited';
                 $statistics['listingAmount'][$listingTypeID]['listingsLeft'] = 'unlimited';
             } else {
                 $statistics['listingAmount'][$listingTypeID]['count'] = $permissionParam;
                 $statistics['listingAmount'][$listingTypeID]['listingsLeft'] = $statistics['listingAmount'][$listingTypeID]['count'] - $statistics['listingAmount'][$listingTypeID]['numPostings'];
             }
         }
         if ($this->acl->isAllowed('view_' . $listingTypeID . '_contact_info')) {
             $permissionParam = $this->acl->getPermissionParams('view_' . $listingTypeID . '_contact_info');
             $statistics['avalaibleContactViews'][$listingTypeID]['name'] = $listingType['name'];
             $statistics['avalaibleContactViews'][$listingTypeID]['numOfViews'] = SJB_ContractManager::getNumbeOfPagesViewed($currentUser->getSID(), $contractSIDs, 'view_' . $listingTypeID . '_contact_info');
             if (empty($permissionParam)) {
                 $statistics['avalaibleContactViews'][$listingTypeID]['count'] = 'unlimited';
                 $statistics['avalaibleContactViews'][$listingTypeID]['viewsLeft'] = 'unlimited';
             } else {
                 $statistics['avalaibleContactViews'][$listingTypeID]['count'] = $this->acl->getPermissionParams('view_' . $listingTypeID . '_contact_info');
                 $statistics['avalaibleContactViews'][$listingTypeID]['viewsLeft'] = $statistics['avalaibleContactViews'][$listingTypeID]['count'] - $statistics['avalaibleContactViews'][$listingTypeID]['numOfViews'];
             }
         }
     }
     $productsFailedList = urldecode(SJB_Request::getVar('failedProducts'));
     if ($productsFailedList != '') {
         $productsFailedArray = explode(',', $productsFailedList);
         if (!empty($productsFailedArray)) {
             $tp->assign('productsFailed', $productsFailedArray);
         }
     }
     $tp->assign('statistics', $statistics);
     $tp->assign("contracts_info", $contractsInfo);
     $tp->assign('errors', $this->errors);
     $tp->display("my_products.tpl");
 }
Exemplo n.º 18
0
 private function redirectToMyProductsPage($callbackData)
 {
     $invoice_sid = isset($callbackData['item_number']) ? $callbackData['item_number'] : null;
     $invoice = SJB_InvoiceManager::getObjectBySID($invoice_sid);
     $paymentStatus = $invoice->getStatus();
     $invoice->setCallbackData($callbackData);
     $items = $invoice->getPropertyValue('items');
     $countOfProducts = 0;
     $gatewayId = $this->details->getProperty('id');
     $invoice->setPropertyValue('payment_method', $gatewayId->getValue());
     $userSid = $invoice->getUserSID();
     if ($paymentStatus == SJB_Invoice::INVOICE_STATUS_PENDING) {
         foreach ($items['products'] as $key => $product) {
             if ("SUCCESS" == strtoupper($callbackData['http_post_response'][$countOfProducts]["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($callbackData['http_post_response'][$countOfProducts]["ACK"])) {
                 $product_info = $invoice->getItemValue($key);
                 $countOfProducts += 1;
                 SJB_ShoppingCart::deleteItemFromCartBySID($product_info['shoppingCartRecord'], $userSid);
             } else {
                 $productInfo = SJB_ProductsManager::getProductInfoBySID($product);
                 $this->failedProducts = $this->failedProducts . $productInfo['name'] . ',';
                 $countOfProducts += 1;
             }
         }
         SJB_InvoiceManager::saveInvoice($invoice);
         $this->failedProducts = substr($this->failedProducts, 0, -1);
         SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/my-products/?subscriptionComplete=true&failedProducts=' . $this->failedProducts);
     } else {
         $invoice->setStatus(SJB_Invoice::INVOICE_STATUS_UNPAID);
         SJB_InvoiceManager::saveInvoice($invoice);
         SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/my-products/?subscriptionComplete=false');
     }
 }
Exemplo n.º 19
0
 function mayChooseProduct($productSID, &$error)
 {
     $productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
     if (isset($productInfo['trial']) && $productInfo['trial']) {
         if ($this->ifSubscribeOnceUsersProperties($productSID, $this->getID())) {
             return true;
         }
         $error = 'PRODUCT_IS_ONLY_ONCE_AVAILABLE';
         return false;
     }
     return true;
 }
Exemplo n.º 20
0
 /**
  * Можно ли?
  * @param $resource
  * @param $roleId
  */
 public function isAllowed($resource, $roleId = null, $type = 'user', $returnParams = false, $returnMessage = false)
 {
     $resource = strtolower($resource);
     $userInfo = array();
     if (null === $roleId) {
         // если не задан пользователь, то попробуем использовать текущего
         $userInfo = SJB_UserManager::getCurrentUserInfo();
         if (!empty($userInfo)) {
             $roleId = $userInfo['sid'];
         }
         if (null === $roleId) {
             if (SJB_Admin::admin_authed() && SJB_System::getSystemSettings('SYSTEM_ACCESS_TYPE') == 'admin') {
                 if ($returnParams) {
                     return '';
                 }
                 if ($returnMessage) {
                     return '';
                 }
                 return true;
             }
             $roleId = 'guest';
         }
     } else {
         $cacheId = 'SJB_Acl::SJB_UserManager::getUserInfoBySID' . $roleId;
         if (SJB_MemoryCache::has($cacheId)) {
             $userInfo = SJB_MemoryCache::get($cacheId);
         } else {
             $userInfo = SJB_UserManager::getUserInfoBySID($roleId);
             SJB_MemoryCache::set($cacheId, $userInfo);
         }
     }
     $role = $type . '_' . $roleId;
     if ($resource == 'use_screening_questionnaires' && intval($userInfo['parent_sid']) > 0) {
         if ($this->isAllowed($resource, $userInfo['parent_sid'])) {
             return $this->isAllowed('subuser_use_screening_questionnaires', $userInfo['sid']);
         }
         return false;
     }
     if (!isset($this->permissions[$role])) {
         switch ($type) {
             case 'user':
             case 'guest':
                 if ($roleId == 'guest' || $type == 'guest') {
                     $role = 'user_guest';
                     if (empty($this->permissions[$role])) {
                         $this->permissions[$role] = $this->getPermissions('guest', 'guest');
                     }
                 } else {
                     $permissions = $this->getPermissions('user', $roleId);
                     $groupPermissions = $this->getPermissions('group', $userInfo['user_group_sid']);
                     $this->permissions['group_' . $userInfo['user_group_sid']] = $groupPermissions;
                     $contracts = SJB_ContractManager::getAllContractsSIDsByUserSID($roleId);
                     if (!empty($contracts)) {
                         foreach ($contracts as $contract) {
                             $contractPermissions = $this->mergePermissionsWithGroup($this->getPermissions('contract', $contract), $groupPermissions);
                             $this->permissions['contract_' . $contract] = $contractPermissions;
                             $permissions = $this->mergePermissions($contractPermissions, $permissions);
                         }
                     } else {
                         $permissions = $this->mergePermissionsWithGroup($permissions, $groupPermissions);
                     }
                     $this->permissions[$role] = $permissions;
                 }
                 break;
             case 'group':
                 $this->permissions[$role] = $this->getPermissions($type, $roleId);
                 break;
             case 'product':
                 $productInfo = SJB_ProductsManager::getProductInfoBySID($roleId);
                 if (!empty($productInfo['user_group_sid'])) {
                     $groupRole = 'group_' . $productInfo['user_group_sid'];
                     if (empty($this->permissions[$groupRole])) {
                         $this->permissions[$groupRole] = $this->getPermissions('group', $productInfo['user_group_sid']);
                     }
                     $this->permissions[$role] = $this->mergePermissionsWithGroup($this->getPermissions('product', $roleId), $this->permissions[$groupRole]);
                 } else {
                     $this->permissions[$role] = $this->getPermissions('product', $roleId);
                 }
                 break;
             case 'contract':
                 $this->permissions[$role] = $this->getPermissions('contract', $roleId);
                 break;
         }
     }
     if (!isset($userInfo)) {
         $userInfo = SJB_UserManager::getCurrentUserInfo();
     }
     $is_display_resume = !preg_match_all("/.*\\/(?:display_resume|display_job)\\/(\\d*)/i", $_SERVER['REQUEST_URI'], $match) ? isset($_SERVER['REDIRECT_URL']) ? preg_match_all("/.*\\/(?:display_resume|display_job)\\/(\\d*)/i", $_SERVER['REDIRECT_URL'], $match) : false : true;
     // Allow access to Resume/Job Details page if an employer has an application linked to the resume
     if (isset($userInfo) && $is_display_resume) {
         $apps = SJB_DB::query("SELECT `a`.resume FROM `applications` `a`\n\t\t\t\t\t\t            INNER JOIN `listings` l ON\n\t\t\t\t\t\t                  `l`.`sid` = `a`.`listing_id`\n\t\t\t\t\t\t            WHERE `l`.`user_sid` = ?n AND `a`.`show_emp` = 1  ORDER BY a.`date` DESC", $userInfo['sid']);
         if (isset($match[1]) && in_array(array("resume" => array_pop($match[1])), $apps)) {
             $this->permissions[$role][$resource]['value'] = 'allow';
             $this->permissions[$role][$resource]['params'] = '';
         }
     }
     if ($returnParams) {
         return empty($this->permissions[$role][$resource]['params']) ? '' : $this->permissions[$role][$resource]['params'];
     } elseif ($returnMessage) {
         $message = empty($this->permissions[$role][$resource]['message']) ? '' : $this->permissions[$role][$resource]['message'];
         if (!$message) {
             if (!empty($userInfo)) {
                 $groupRole = 'group_' . $userInfo['user_group_sid'];
                 $message = empty($this->permissions[$groupRole][$resource]['message']) ? '' : $this->permissions[$groupRole][$resource]['message'];
             }
         }
         return $message;
     }
     return isset($this->permissions[$role][$resource]['value']) && $this->permissions[$role][$resource]['value'] == 'allow';
 }
Exemplo n.º 21
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $displayForm = new SJB_Form();
     $displayForm->registerTags($tp);
     $invoiceSid = SJB_Request::getVar('sid', false);
     if (SJB_Request::getVar('error', false)) {
         SJB_FlashMessages::getInstance()->addWarning('TCPDF_ERROR');
     }
     $action = SJB_Request::getVar('action', false);
     $paymentGateway = SJB_Request::getVar('payment_gateway', false);
     $template = 'print_invoice.tpl';
     $currentUserSID = SJB_UserManager::getCurrentUserSID();
     $invoiceInfo = SJB_InvoiceManager::getInvoiceInfoBySID($invoiceSid);
     if ($invoiceInfo) {
         if ($currentUserSID == $invoiceInfo['user_sid']) {
             $taxInfo = SJB_TaxesManager::getTaxInfoBySID($invoiceInfo['tax_info']['sid']);
             $invoiceInfo = array_merge($invoiceInfo, $_REQUEST);
             if (is_array($taxInfo)) {
                 $taxInfo = array_merge($invoiceInfo['tax_info'], $taxInfo);
             } else {
                 $taxInfo = $invoiceInfo['tax_info'];
             }
             $invoice = new SJB_Invoice($invoiceInfo);
             $invoice->setSID($invoiceSid);
             $userInfo = SJB_UserManager::getUserInfoBySID($currentUserSID);
             $username = $userInfo['CompanyName'] . ' ' . $userInfo['FirstName'] . ' ' . $userInfo['LastName'];
             $user = SJB_UserManager::getObjectBySID($currentUserSID);
             $productsSIDs = SJB_ProductsManager::getProductsIDsByUserGroupSID($userInfo['user_group_sid']);
             $products = array();
             foreach ($productsSIDs as $key => $productSID) {
                 $product = SJB_ProductsManager::getProductInfoBySID($productSID);
                 $products[$key] = $product;
             }
             $displayForm = new SJB_Form($invoice);
             $displayForm->registerTags($tp);
             $show = true;
             if ($action == 'download_pdf_version' || $action == 'print') {
                 $show = false;
             }
             $tp->assign('show', $show);
             $tp->assign('products', $products);
             $tp->assign('invoice_sid', $invoiceSid);
             $tp->assign('invoice_status', $invoiceInfo['status']);
             $tp->assign('username', trim($username));
             $tp->assign('user_sid', $currentUserSID);
             $tp->assign('tax', $taxInfo);
             $userStructure = SJB_UserManager::createTemplateStructureForUser($user);
             $tp->assign('user', $userStructure);
             $tp->assign('include_tax', $invoiceInfo['include_tax']);
             if ($action == 'download_pdf_version') {
                 $template = 'invoice_to_pdf.tpl';
                 $filename = 'invoice_' . $invoiceSid . '.pdf';
                 try {
                     SJB_HelperFunctions::html2pdf($tp->fetch($template), $filename);
                     exit;
                 } catch (Exception $e) {
                     SJB_Error::writeToLog($e->getMessage());
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings("SITE_URL") . '/print-invoice/?sid=' . $invoiceSid . '&action=print&error=TCPDF_ERROR');
                 }
             }
         } else {
             SJB_FlashMessages::getInstance()->addError('NOT_OWNER');
         }
     } else {
         SJB_FlashMessages::getInstance()->addError('WRONG_INVOICE_ID_SPECIFIED');
     }
     if ($paymentGateway) {
         $gatewaySID = SJB_PaymentGatewayManager::getSIDByID($paymentGateway);
         $gatewayInfo = SJB_PaymentGatewayManager::getInfoBySID($gatewaySID);
         $tp->assign('gatewayInfo', $gatewayInfo);
     }
     $tp->assign('paymentError', SJB_Request::getVar('payment_error', false));
     $tp->display($template);
 }
Exemplo n.º 22
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $template = 'edit_invoice.tpl';
     $errors = array();
     $invoiceErrors = array();
     $invoiceSID = SJB_Request::getVar('sid', false);
     $action = SJB_Request::getVar('action', false);
     $tcpdfError = SJB_Request::getVar('error', false);
     if ($tcpdfError) {
         $invoiceErrors[] = $tcpdfError;
     }
     $invoiceInfo = SJB_InvoiceManager::getInvoiceInfoBySID($invoiceSID);
     $user_structure = null;
     if ($invoiceInfo) {
         $product_info = array();
         if (array_key_exists('custom_info', $invoiceInfo['items'])) {
             $product_info = $invoiceInfo['items']['custom_info'];
         }
         $invoiceInfo = array_merge($invoiceInfo, $_REQUEST);
         $invoiceInfo['items']['custom_info'] = $product_info;
         $includeTax = $invoiceInfo['include_tax'];
         $invoice = new SJB_Invoice($invoiceInfo);
         $invoice->setSID($invoiceSID);
         $userSID = $invoice->getPropertyValue('user_sid');
         $userExists = SJB_UserManager::isUserExistsByUserSid($userSID);
         $subUserSID = $invoice->getPropertyValue('subuser_sid');
         if (!empty($subUserSID)) {
             $userInfo = SJB_UserManager::getUserInfoBySID($subUserSID);
             $username = $userInfo['username'] . '/' . $userInfo['email'];
         } else {
             $userInfo = SJB_UserManager::getUserInfoBySID($userSID);
             $username = $userInfo['FirstName'] . ' ' . $userInfo['LastName'] . ' ' . $userInfo['ContactName'] . ' ' . $userInfo['CompanyName'] . '/' . $userInfo['email'];
         }
         $taxInfo = $invoice->getPropertyValue('tax_info');
         $productsSIDs = SJB_ProductsManager::getProductsIDsByUserGroupSID($userInfo['user_group_sid']);
         $products = array();
         foreach ($productsSIDs as $key => $productSID) {
             $productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
             if (!empty($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'volume_based') {
                 $volumeBasedPricing = $productInfo['volume_based_pricing'];
                 $minListings = min($volumeBasedPricing['listings_range_from']);
                 $maxListings = max($volumeBasedPricing['listings_range_to']);
                 $countListings = array();
                 for ($i = $minListings; $i <= $maxListings; $i++) {
                     $countListings[$i]['number_of_listings'] = $i;
                     for ($j = 1; $j <= count($volumeBasedPricing['listings_range_from']); $j++) {
                         if ($i >= $volumeBasedPricing['listings_range_from'][$j] && $i <= $volumeBasedPricing['listings_range_to'][$j]) {
                             $countListings[$i]['price'] = $volumeBasedPricing['price_per_unit'][$j];
                         }
                     }
                 }
                 $productInfo['count_listings'] = $countListings;
             }
             $products[$key] = $productInfo;
         }
         $addForm = new SJB_Form($invoice);
         $addForm->registerTags($tp);
         $tp->assign('userExists', $userExists);
         $tp->assign('products', $products);
         $tp->assign('invoice_sid', $invoiceSID);
         $tp->assign('include_tax', $includeTax);
         $tp->assign('username', trim($username));
         if ($action) {
             switch ($action) {
                 case 'save':
                 case 'apply':
                     $invoiceErrors = $invoice->isValid();
                     if (empty($invoiceErrors) && $addForm->isDataValid($errors)) {
                         $invoice->setFloatNumbersIntoValidFormat();
                         SJB_InvoiceManager::saveInvoice($invoice);
                         if ($action == 'save') {
                             SJB_HelperFunctions::redirect(SJB_System::getSystemSettings("SITE_URL") . '/manage-invoices/');
                         }
                     } else {
                         $invoiceDate = SJB_I18N::getInstance()->getInput('date', $invoice->getPropertyValue('date'));
                         $invoice->setPropertyValue('date', $invoiceDate);
                     }
                     $invoice->setFloatNumbersIntoValidFormat();
                     $taxInfo['tax_amount'] = SJB_I18N::getInstance()->getInput('float', $taxInfo['tax_amount']);
                     break;
                 case 'print':
                 case 'download_pdf_version':
                     $user = SJB_UserManager::getObjectBySID($userSID);
                     $user_structure = SJB_UserManager::createTemplateStructureForUser($user);
                     $template = 'print_invoice.tpl';
                     $username = SJB_Array::get($user_structure, 'CompanyName') . ' ' . SJB_Array::get($user_structure, 'FirstName') . ' ' . SJB_Array::get($user_structure, 'LastName');
                     $tp->assign('username', trim($username));
                     $tp->assign('user', $user_structure);
                     $tp->assign('tax', $taxInfo);
                     if ($action == 'download_pdf_version') {
                         $template = 'invoice_to_pdf.tpl';
                         $filename = 'invoice_' . $invoiceSID . '.pdf';
                         try {
                             SJB_HelperFunctions::html2pdf($tp->fetch($template), $filename);
                             exit;
                         } catch (Exception $e) {
                             SJB_Error::writeToLog($e->getMessage());
                             SJB_HelperFunctions::redirect(SJB_System::getSystemSettings("SITE_URL") . '/edit-invoice/?sid=' . $invoiceSID . '&error=TCPDF_ERROR');
                         }
                     }
                     break;
                 case 'send_invoice':
                     $result = SJB_Notifications::sendInvoiceToCustomer($invoiceSID, $userSID);
                     if ($result) {
                         echo SJB_I18N::getInstance()->gettext("Backend", "Invoice successfully sent");
                     } else {
                         echo SJB_I18N::getInstance()->gettext("Backend", "Invoice not sent");
                     }
                     exit;
                     break;
             }
         }
         $transactions = SJB_TransactionManager::getTransactionsByInvoice($invoiceSID);
         $tp->assign('tax', $taxInfo);
         $tp->assign('transactions', $transactions);
     } else {
         $tp->assign('action', 'edit');
         $errors[] = 'WRONG_INVOICE_ID_SPECIFIED';
         $template = 'errors.tpl';
     }
     $tp->assign("errors", array_merge($errors, $invoiceErrors));
     $tp->display($template);
 }
Exemplo n.º 23
0
 public function execute()
 {
     $template_processor = SJB_System::getTemplateProcessor();
     $listing_id = SJB_Request::getVar('listing_sid', SJB_Request::getVar('listing_id', null));
     $listingInfo = SJB_ListingManager::getListingInfoBySID($listing_id);
     $productSID = SJB_Request::getVar('product_sid' . null);
     $errors = null;
     $field_errors = null;
     $extraInfo = array();
     if (empty($listing_id)) {
         $errors['WRONG_PARAMETERS_SPECIFIED'] = 1;
     } elseif (!empty($listing_id) && strlen($listing_id) == strlen(time())) {
         if ($productSID) {
             SJB_Session::setValue('product_sid', $productSID);
         } else {
             $productSID = SJB_Session::getValue('product_sid');
         }
         if (empty($_SESSION['tmp_file_storage'])) {
             SJB_Session::setValue('tmp_file_storage', array());
         }
         $productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
         $contract = new SJB_Contract(array('contract_id' => $productSID));
         $gallery = new SJB_ListingGallery();
         $gallery->setListingSID($listing_id);
         $template_processor->assign("contract", $contract);
         if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add') {
             if (!isset($_FILES['picture'])) {
                 $field_errors['Picture'] = 'FILE_NOT_SPECIFIED';
             } elseif ($_FILES['picture']['error']) {
                 switch ($_FILES['picture']['error']) {
                     case '1':
                         $field_errors['Picture'] = 'UPLOAD_ERR_INI_SIZE';
                         break;
                     case '2':
                         $field_errors['Picture'] = 'UPLOAD_ERR_FORM_SIZE';
                         break;
                     case '3':
                         $field_errors['Picture'] = 'UPLOAD_ERR_PARTIAL';
                         break;
                     case '4':
                         $field_errors['Picture'] = 'UPLOAD_ERR_NO_FILE';
                         break;
                     default:
                         break;
                 }
             } else {
                 $image_caption = isset($_REQUEST['caption']) ? $_REQUEST['caption'] : '';
                 $_FILES['picture']['caption'] = $image_caption;
                 if (!$gallery->uploadImage($_FILES['picture']['tmp_name'], $image_caption)) {
                     $field_errors['Picture'] = $gallery->getError();
                 }
             }
         } elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete') {
             if (isset($_REQUEST['picture_id'])) {
                 $picture_id = $_REQUEST['picture_id'];
                 $gallery->deleteImageBySID($picture_id);
             }
         }
         if ($listingInfo) {
             $extraInfo = !empty($listingInfo['product_info']) ? unserialize($listingInfo['product_info']) : array();
         } elseif ($contract && $contract->extra_info) {
             $extraInfo = $contract->extra_info;
         } elseif ($productInfo) {
             $extraInfo = !empty($productInfo['serialized_extra_info']) ? unserialize($productInfo['serialized_extra_info']) : array();
         }
         $number_of_picture_allowed = isset($extraInfo['number_of_pictures']) ? $extraInfo['number_of_pictures'] : 0;
         $number_of_picture = $gallery->getPicturesAmount();
         $pictures_info = $gallery->getPicturesInfo();
         $_SESSION['tmp_file_storage'] = $pictures_info;
         $template_processor->assign("listing", array('id' => "{$listing_id}"));
         $template_processor->assign("number_of_picture_allowed", $number_of_picture_allowed);
         $template_processor->assign("number_of_picture", $number_of_picture);
         $template_processor->assign('pictures', $_SESSION['tmp_file_storage']);
     } else {
         $listing = SJB_ListingManager::getObjectBySID($listing_id);
         if (is_null($listing)) {
             $errors['WRONG_PARAMETERS_SPECIFIED'] = 1;
         } else {
             $gallery = new SJB_ListingGallery();
             $gallery->setListingSID($listing_id);
             $contract = new SJB_Contract(array('contract_id' => $productSID));
             if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add') {
                 if (!isset($_FILES['picture'])) {
                     $field_errors['Picture'] = 'FILE_NOT_SPECIFIED';
                 } elseif ($_FILES['picture']['error']) {
                     switch ($_FILES['picture']['error']) {
                         case '1':
                             $field_errors['Picture'] = 'UPLOAD_ERR_INI_SIZE';
                             break;
                         case '2':
                             $field_errors['Picture'] = 'UPLOAD_ERR_FORM_SIZE';
                             break;
                         case '3':
                             $field_errors['Picture'] = 'UPLOAD_ERR_PARTIAL';
                             break;
                         case '4':
                             $field_errors['Picture'] = 'UPLOAD_ERR_NO_FILE';
                             break;
                         default:
                             break;
                     }
                 } else {
                     $image_caption = isset($_REQUEST['caption']) ? $_REQUEST['caption'] : '';
                     if (!$gallery->uploadImage($_FILES['picture']['tmp_name'], $image_caption)) {
                         $field_errors['Picture'] = $gallery->getError();
                     }
                 }
             } elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete') {
                 if (isset($_REQUEST['picture_id'])) {
                     $gallery->deleteImageBySID($_REQUEST['picture_id']);
                 }
             } elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'move_up') {
                 if (isset($_REQUEST['picture_id'])) {
                     $gallery->moveUpImageBySID($_REQUEST['picture_id']);
                 }
             } elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'move_down') {
                 if (isset($_REQUEST['picture_id'])) {
                     $gallery->moveDownImageBySID($_REQUEST['picture_id']);
                 }
             }
             if ($listingInfo) {
                 $extraInfo = !empty($listingInfo['product_info']) ? unserialize($listingInfo['product_info']) : array();
             } elseif ($contract && $contract->extra_info) {
                 $extraInfo = $contract->extra_info;
             }
             $number_of_picture_allowed = isset($extraInfo['number_of_pictures']) ? $extraInfo['number_of_pictures'] : 0;
             $number_of_picture = $gallery->getPicturesAmount();
             $listing_info['id'] = $listing_id;
             $template_processor->assign("listing", $listing_info);
             $pictures_info = $gallery->getPicturesInfo();
             $template_processor->assign("pictures", $pictures_info);
             $template_processor->assign("number_of_picture", $number_of_picture);
             $template_processor->assign("number_of_picture_allowed", $number_of_picture_allowed);
         }
     }
     $template_processor->assign("uploadMaxFilesize", SJB_UploadFileManager::getIniUploadMaxFilesize());
     $template_processor->assign("errors", $errors);
     $template_processor->assign("field_errors", $field_errors);
     $template_processor->display("manage_pictures.tpl");
 }
Exemplo n.º 24
0
    private function runTaskScheduler()
    {
        // Deactivate Expired Listings & Send Notifications
        $listingsExpiredID = SJB_ListingManager::getExpiredListingsSID();
        foreach ($listingsExpiredID as $listingExpiredID) {
            SJB_ListingManager::deactivateListingBySID($listingExpiredID, true);
            $listing = SJB_ListingManager::getObjectBySID($listingExpiredID);
            $listingInfo = SJB_ListingManager::createTemplateStructureForListing($listing);
            if (SJB_UserNotificationsManager::isUserNotifiedOnListingExpiration($listing->getUserSID())) {
                SJB_Notifications::sendUserListingExpiredLetter($listingInfo);
            }
            // notify admin
            SJB_AdminNotifications::sendAdminListingExpiredLetter($listingInfo);
        }
        $listingsDeactivatedID = array();
        if (SJB_Settings::getSettingByName('automatically_delete_expired_listings')) {
            $listingsDeactivatedID = SJB_ListingManager::getDeactivatedListingsSID();
            foreach ($listingsDeactivatedID as $listingID) {
                SJB_ListingManager::deleteListingBySID($listingID);
            }
        }
        SJB_ListingManager::unFeaturedListings();
        SJB_ListingManager::unPriorityListings();
        SJB_Cache::getInstance()->clean('matchingAnyTag', array(SJB_Cache::TAG_LISTINGS));
        /////////////////////////// Send remind notifications about expiration of LISTINGS
        // 1. get user sids and days count of 'remind listing notification' setting = 1 from user_notifications table
        // 2. foreach user:
        //   - get listings with that expiration remind date
        //   - check every listing sid in DB table of sended. If sended - remove from send list
        //   - send notification with listings to user
        //   - write listings sid in DB table of sended notifications
        $notificationData = SJB_UserNotificationsManager::getUsersAndDaysOnListingExpirationRemind();
        foreach ($notificationData as $elem) {
            $userSID = $elem['user_sid'];
            $days = $elem['days'];
            $listingSIDs = SJB_ListingManager::getListingsIDByDaysLeftToExpired($userSID, $days);
            if (empty($listingSIDs)) {
                continue;
            }
            $listingsInfo = array();
            // check listings remind sended
            foreach ($listingSIDs as $key => $sid) {
                if (SJB_ListingManager::isListingNotificationSended($sid)) {
                    unset($listingSIDs[$key]);
                    continue;
                }
                $info = SJB_ListingManager::getListingInfoBySID($sid);
                $listingsInfo[$sid] = $info;
            }
            if (!empty($listingsInfo)) {
                // now only unsended listings we have in array
                // send listing notification
                foreach ($listingSIDs as $sid) {
                    SJB_Notifications::sendRemindListingExpirationLetter($userSID, $sid, $days);
                }
                // write listing id in DB table of sended notifications
                SJB_ListingManager::saveListingIDAsSendedNotificationsTable($listingSIDs);
            }
        }
        // Send Notifications for Expired Contracts
        $contractsExpiredID = SJB_ContractManager::getExpiredContractsID();
        foreach ($contractsExpiredID as $contractExpiredID) {
            $contractInfo = SJB_ContractManager::getInfo($contractExpiredID);
            $productInfo = SJB_ProductsManager::getProductInfoBySID($contractInfo['product_sid']);
            $userInfo = SJB_UserManager::getUserInfoBySID($contractInfo['user_sid']);
            $serializedExtraInfo = unserialize($contractInfo['serialized_extra_info']);
            if (!empty($serializedExtraInfo['featured_profile']) && !empty($userInfo['featured'])) {
                $contracts = SJB_ContractManager::getAllContractsInfoByUserSID($userInfo['sid']);
                $isFeatured = 0;
                foreach ($contracts as $contract) {
                    if ($contract['id'] != $contractExpiredID) {
                        $serializedExtraInfo = unserialize($contract['serialized_extra_info']);
                        if (!empty($serializedExtraInfo['featured'])) {
                            $isFeatured = 1;
                        }
                    }
                }
                if (!$isFeatured) {
                    SJB_UserManager::removeFromFeaturedBySID($userInfo['sid']);
                }
            }
            if (SJB_UserNotificationsManager::isUserNotifiedOnContractExpiration($contractInfo['user_sid'])) {
                SJB_Notifications::sendUserContractExpiredLetter($userInfo, $contractInfo, $productInfo);
            }
            // notify admin
            SJB_AdminNotifications::sendAdminUserContractExpiredLetter($userInfo['sid'], $contractInfo, $productInfo);
            SJB_ContractManager::deleteContract($contractExpiredID, $contractInfo['user_sid']);
        }
        //////////////////////// Send remind notifications about expiration of contracts
        // 1. get user sids and days count of 'remind subscription notification' setting = 1 from user_notifications table
        // 2. foreach user:
        //   - get contracts with that expiration remind date
        //   - check every contract sid in DB table of sended. If sended - remove from send list
        //   - send notification with contracts to user
        //   - write contract sid in DB table of sended contract notifications
        $notificationData = SJB_UserNotificationsManager::getUsersAndDaysOnSubscriptionExpirationRemind();
        foreach ($notificationData as $elem) {
            $userSID = $elem['user_sid'];
            $days = $elem['days'];
            $contractSIDs = SJB_ContractManager::getContractsIDByDaysLeftToExpired($userSID, $days);
            if (empty($contractSIDs)) {
                continue;
            }
            $contractsInfo = array();
            // check contracts sended
            foreach ($contractSIDs as $key => $sid) {
                if (SJB_ContractManager::isContractNotificationSended($sid)) {
                    unset($contractSIDs[$key]);
                    continue;
                }
                $info = SJB_ContractManager::getInfo($sid);
                $info['extra_info'] = !empty($info['serialized_extra_info']) ? unserialize($info['serialized_extra_info']) : '';
                $contractsInfo[$sid] = $info;
            }
            if (!empty($contractsInfo)) {
                // now only unsended contracts we have in array
                // send contract notification
                foreach ($contractSIDs as $sid) {
                    SJB_Notifications::sendRemindSubscriptionExpirationLetter($userSID, $contractsInfo[$sid], $days);
                }
                // write contract id in DB table of sended contract notifications
                SJB_ContractManager::saveContractIDAsSendedNotificationsTable($contractSIDs);
            }
        }
        // delete applications with no employer and job seeker
        $emptyApplications = SJB_DB::query('SELECT `id` FROM `applications` WHERE `show_js` = 0 AND `show_emp` = 0');
        foreach ($emptyApplications as $application) {
            SJB_Applications::remove($application['id']);
        }
        // NEWS
        $expiredNews = SJB_NewsManager::getExpiredNews();
        foreach ($expiredNews as $article) {
            SJB_NewsManager::deactivateItemBySID($article['sid']);
        }
        // LISTING XML IMPORT
        SJB_XmlImport::runImport();
        // UPDATE PAGES WITH FUNCTION EQUAL BROWSE(e.g. /browse-by-city/)
        SJB_BrowseDBManager::rebuildBrowses();
        //-------------------sitemap generator--------------------//
        SJB_System::executeFunction('miscellaneous', 'sitemap_generator');
        // CLEAR `error_log` TABLE
        $errorLogLifetime = SJB_System::getSettingByName('error_log_lifetime');
        $lifeTime = strtotime("-{$errorLogLifetime} days");
        if ($lifeTime > 0) {
            SJB_DB::query('DELETE FROM `error_log` WHERE `date` < ?t', $lifeTime);
        }
        SJB_Settings::updateSetting('task_scheduler_last_executed_date', $this->currentDate);
        $this->tp->assign('expired_listings_id', $listingsExpiredID);
        $this->tp->assign('deactivated_listings_id', $listingsDeactivatedID);
        $this->tp->assign('expired_contracts_id', $contractsExpiredID);
        $this->tp->assign('notified_saved_searches_id', $this->notifiedSavedSearchesSID);
        $schedulerLog = $this->tp->fetch('task_scheduler_log.tpl');
        SJB_HelperFunctions::writeCronLogFile('task_scheduler.log', $schedulerLog);
        SJB_DB::query('INSERT INTO `task_scheduler_log`
			(`last_executed_date`, `notifieds_sent`, `expired_listings`, `expired_contracts`, `log_text`)
			VALUES ( NOW(), ?n, ?n, ?n, ?s)', count($this->notifiedSavedSearchesSID), count($listingsExpiredID), count($contractsExpiredID), $schedulerLog);
        SJB_System::getModuleManager()->executeFunction('social', 'linkedin');
        SJB_System::getModuleManager()->executeFunction('social', 'facebook');
        SJB_System::getModuleManager()->executeFunction('classifieds', 'linkedin');
        SJB_System::getModuleManager()->executeFunction('classifieds', 'facebook');
        SJB_System::getModuleManager()->executeFunction('classifieds', 'twitter');
        SJB_Event::dispatch('task_scheduler_run');
    }
Exemplo n.º 25
0
 public static function canCurrentUserAddListing(&$error, $listingTypeId = false)
 {
     $acl = SJB_Acl::getInstance();
     if (SJB_UserManager::isUserLoggedIn()) {
         $current_user = SJB_UserManager::getCurrentUser();
         if ($current_user->hasContract()) {
             $contracts_id = $current_user->getContractID();
             $contractsSIDs = $contracts_id ? implode(',', $contracts_id) : 0;
             $resultContractInfo = SJB_DB::query("SELECT `id`, `product_sid`, `expired_date`, `number_of_postings` FROM `contracts` WHERE `id` in ({$contractsSIDs}) ORDER BY `expired_date` DESC");
             $PlanAcces = count($resultContractInfo) > 0 ? true : false;
             if ($PlanAcces && $acl->isAllowed('post_' . $listingTypeId)) {
                 $productsInfo = array();
                 $is_contract = false;
                 foreach ($resultContractInfo as $contractInfo) {
                     if ($acl->isAllowed('post_' . $listingTypeId, $contractInfo['id'], 'contract')) {
                         $permissionParam = $acl->getPermissionParams('post_' . $listingTypeId, $contractInfo['id'], 'contract');
                         if (empty($permissionParam) || $acl->getPermissionParams('post_' . $listingTypeId, $contractInfo['id'], 'contract') > $contractInfo['number_of_postings']) {
                             $product = SJB_ProductsManager::getProductInfoBySID($contractInfo['product_sid']);
                             $productsInfo[$contractInfo['id']]['product_name'] = $product['name'];
                             $productsInfo[$contractInfo['id']]['expired_date'] = $contractInfo['expired_date'];
                             $productsInfo[$contractInfo['id']]['contract_id'] = $contractInfo['id'];
                         }
                     }
                     $is_contract = true;
                 }
                 if ($is_contract && count($productsInfo) > 0) {
                     return $productsInfo;
                 } else {
                     $error = 'LISTINGS_NUMBER_LIMIT_EXCEEDED';
                 }
             } else {
                 $error = 'DO_NOT_MATCH_POST_THIS_TYPE_LISTING';
             }
         } else {
             $error = 'NO_CONTRACT';
         }
     } else {
         $error = 'NOT_LOGGED_IN';
     }
     return false;
 }
Exemplo n.º 26
0
 /**
  * @param int $currentUserID
  * @param int $productSID
  * @return bool|int|mixed
  */
 public function proceedToCheckout($currentUserID, $productSID)
 {
     $errors = array();
     $productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
     if (SJB_UserManager::isUserLoggedIn()) {
         $numberOfListings = SJB_ListingDBManager::getNumberOfCheckoutedListingsByProductSID($productSID, $currentUserID);
         $extraInfo = SJB_ProductsManager::getProductExtraInfoBySID($productSID);
         $shoppingCartProducts = SJB_ShoppingCart::getProductsInfoFromCartByProductSID($productSID, $currentUserID);
         if (!empty($shoppingCartProducts)) {
             if ($productInfo['product_type'] == 'mixed_product' || isset($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'fixed') {
                 if ($numberOfListings / (count($shoppingCartProducts) * $productInfo['number_of_listings']) > 1) {
                     SJB_ShoppingCart::addToShoppingCart($productInfo, $currentUserID);
                 }
             }
             if (isset($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'volume_based') {
                 if ($numberOfListings / (count($shoppingCartProducts) * end($productInfo['volume_based_pricing']['listings_range_to'])) > 1) {
                     $productInfo['number_of_listings'] = 1;
                     $productObj = new SJB_Product($productInfo, $productInfo['product_type']);
                     $productObj->setNumberOfListings($productInfo['number_of_listings']);
                     $productInfo['price'] = $productObj->getPrice();
                     SJB_ShoppingCart::addToShoppingCart($productInfo, $currentUserID);
                 } else {
                     foreach ($shoppingCartProducts as $shoppingCartProduct) {
                         $unserializedProductInfoFromShopCart = unserialize($shoppingCartProduct['product_info']);
                         if ($unserializedProductInfoFromShopCart['number_of_listings'] < end($unserializedProductInfoFromShopCart['volume_based_pricing']['listings_range_to'])) {
                             $unserializedProductInfoFromShopCart['number_of_listings'] += 1;
                             SJB_ShoppingCart::updateItemBySID($shoppingCartProduct['sid'], $unserializedProductInfoFromShopCart);
                             break;
                         }
                     }
                 }
             }
         } else {
             if (!empty($extraInfo['pricing_type']) && $extraInfo['pricing_type'] == 'volume_based') {
                 $productInfo['number_of_listings'] = 1;
                 $productObj = new SJB_Product($productInfo, $productInfo['product_type']);
                 $productObj->setNumberOfListings($productInfo['number_of_listings']);
                 $productInfo['price'] = $productObj->getPrice();
             }
             SJB_ShoppingCart::addToShoppingCart($productInfo, $currentUserID);
         }
     } else {
         $products = SJB_Session::getValue('products');
         if (isset($products)) {
             foreach ($products as $addedProduct) {
                 $addedProductInfo = unserialize($addedProduct['product_info']);
                 if ($addedProductInfo['user_group_sid'] != $productInfo['user_group_sid']) {
                     $errors[] = 'You are trying to add products of different User Groups in your Shopping Cart. You сan add only products belonging to one User Group. If you want to add this product in the Shopping Cart please go back to the Shopping Cart and remove products of other User Groups.';
                     break;
                 }
             }
         }
         if (!$errors) {
             $id = time();
             $products[$id]['product_info'] = serialize($productInfo);
             $products[$id]['sid'] = $id;
             $products[$id]['user_sid'] = 0;
             SJB_Session::setValue('products', $products);
         }
     }
     if (!$errors) {
         SJB_HelperFunctions::redirect(SJB_System::getSystemsettings('SITE_URL') . '/shopping-cart/');
     }
 }
Exemplo n.º 27
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $current_user = SJB_UserManager::getCurrentUser();
     $action = SJB_Request::getVar('action', 'productList');
     $productSID = SJB_Request::getVar('product_sid', 0, 'default', 'int');
     $template = 'products.tpl';
     $availableProducts = array();
     $errors = array();
     switch ($action) {
         case 'productList':
             if (SJB_UserManager::isUserLoggedIn()) {
                 $postingProductsOnly = SJB_Request::getVar('postingProductsOnly', false);
                 $availableProducts = SJB_ProductsManager::getProductsByUserGroupSID($current_user->getUserGroupSID(), $current_user->getSID());
                 $trialProduncts = $current_user->getTrialProductSIDByUserSID();
                 foreach ($availableProducts as $key => $availableProduct) {
                     if (in_array($availableProduct['sid'], $trialProduncts) || $postingProductsOnly && $availableProduct['product_type'] != "post_listings" && $availableProduct['product_type'] != "mixed_product") {
                         unset($availableProducts[$key]);
                     }
                 }
                 if ($postingProductsOnly) {
                     $tp->assign('postingProductsOnly', $postingProductsOnly);
                 }
             } elseif ($userGroupID = SJB_Request::getVar('userGroupID', false)) {
                 $userGroupSID = SJB_UserGroupManager::getUserGroupSIDByID($userGroupID);
                 $availableProducts = SJB_ProductsManager::getProductsByUserGroupSID($userGroupSID, 0);
             } else {
                 $availableProducts = SJB_ProductsManager::getAllActiveProducts();
             }
             foreach ($availableProducts as $key => $availableProductInfo) {
                 if (SJB_ProductsManager::isProductTrialAndAlreadyInCart($availableProductInfo, $current_user)) {
                     unset($availableProducts[$key]);
                     continue;
                 }
                 $availableProduct = new SJB_Product($availableProductInfo, $availableProductInfo['product_type']);
                 $availableProduct->setNumberOfListings(1);
                 $availableProducts[$key]['price'] = $availableProduct->getPrice();
                 if (isset($availableProducts[$key]['listing_type_sid'])) {
                     $availableProducts[$key]['listing_type_id'] = SJB_ListingTypeDBManager::getListingTypeIDBySID($availableProducts[$key]['listing_type_sid']);
                 }
             }
             SJB_Event::dispatch('RedefineTemplateName', $template, true);
             SJB_Event::dispatch('RedefineProductsDisplayInfo', $availableProducts, true);
             $tp->assign("account_activated", SJB_Request::getVar('account_activated', ''));
             $tp->assign("availableProducts", $availableProducts);
             break;
         case 'view_product_detail':
             $template = 'view_product_detail.tpl';
             if (!SJB_UserManager::isUserLoggedIn() || $current_user->mayChooseProduct($productSID, $errors)) {
                 $productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
                 if (in_array($productInfo['product_type'], array('post_listings', 'mixed_product'))) {
                     $productInfo['listingTypeID'] = SJB_ListingTypeManager::getListingTypeIDBySID($productInfo['listing_type_sid']);
                 }
                 $event = SJB_Request::getVar('event', false);
                 if ($event) {
                     if ($productInfo) {
                         switch ($productInfo['product_type']) {
                             case 'banners':
                                 $params = $_REQUEST;
                                 if (empty($params['title'])) {
                                     $errors[] = "Banner Title is empty.";
                                 }
                                 if (empty($params['link'])) {
                                     $errors[] = "Banner link mismatched!";
                                 }
                                 if (empty($_FILES['image']['name'])) {
                                     $errors[] = "No file attached!";
                                 } elseif ($_FILES['image']['error']) {
                                     switch ($_FILES['image']['error']) {
                                         case '1':
                                             $errors[] = 'UPLOAD_ERR_INI_SIZE';
                                             break;
                                         case '2':
                                             $errors[] = 'UPLOAD_ERR_FORM_SIZE';
                                             break;
                                         case '3':
                                             $errors[] = 'UPLOAD_ERR_PARTIAL';
                                             break;
                                         case '4':
                                             $errors[] = 'UPLOAD_ERR_NO_FILE';
                                             break;
                                         default:
                                             $errors[] = 'NOT_UPLOAD_FILE';
                                             break;
                                     }
                                 } else {
                                     $imageInfo = @getimagesize($_FILES['image']['tmp_name']);
                                     if (!$imageInfo || $imageInfo['2'] < 1 && $imageInfo['2'] > 3) {
                                         $errors[] = 'Image format is not supported';
                                     } elseif (!empty($productInfo['width']) && $imageInfo[0] != $productInfo['width']) {
                                         $errors[] = "Your banner dimensions exceed the required size. Please upload an appropriate banner.";
                                     } elseif (!empty($productInfo['height']) && $imageInfo[1] != $productInfo['height']) {
                                         $errors[] = "Your banner dimensions exceed the required size. Please upload an appropriate banner.";
                                     }
                                 }
                                 if ($errors) {
                                     break;
                                 }
                                 //add banner
                                 $title = $params['title'];
                                 $link = $params['link'];
                                 $expr = preg_match("/(http:\\/\\/)/", $link, $matches);
                                 if ($expr != true) {
                                     $link = "http://" . $link;
                                 }
                                 $filesDir = SJB_System::getSystemSettings('FILES_DIR');
                                 $ext = preg_match("|\\.(\\w{3})\\b|u", $_FILES['image']['name'], $arr);
                                 $fileName = preg_replace("|\\.(\\w{3})\\b|u", "", $_FILES['image']['name']);
                                 $hashName = md5(time() * $_FILES['image']['size']) . "_" . $fileName;
                                 $bannerFilePath = $filesDir . "banners/" . $hashName . "." . $arr[1];
                                 $copy = move_uploaded_file($_FILES['image']['tmp_name'], $bannerFilePath);
                                 if (!$copy) {
                                     $errors[] = 'Cannot copy file from TMP dir to Banners Dir';
                                     break;
                                 }
                                 if ($_FILES['image']['type'] != 'application/x-shockwave-flash') {
                                     $bannerInfo = getimagesize($bannerFilePath);
                                     if ($productInfo['width'] != '' && $productInfo['height'] != '') {
                                         $sx = $productInfo['width'];
                                         $sy = $productInfo['height'];
                                     } else {
                                         $sx = $bannerInfo[0];
                                         $sy = $bannerInfo[1];
                                     }
                                     $type = $bannerInfo['mime'];
                                 } else {
                                     if ($productInfo['width'] == '' || $productInfo['height'] == '') {
                                         $errors[] = 'Your banner dimensions exceed the required size. Please upload an appropriate banner.';
                                         break;
                                     }
                                     $sx = $productInfo['width'];
                                     $sy = $productInfo['height'];
                                     $type = $_FILES['image']['type'];
                                 }
                                 $active = 0;
                                 $group = $productInfo['banner_group_sid'];
                                 $params['bannerFilePath'] = "/" . str_replace("../", "/", str_replace(SJB_BASE_DIR, '', $bannerFilePath));
                                 $params['openBannerIn'] = '';
                                 $params['bannerType'] = 'file';
                                 $params['code'] = '';
                                 $params['title'] = $title;
                                 $params['link'] = $link;
                                 $params['type'] = $type;
                                 $params['sx'] = $sx;
                                 $params['sy'] = $sy;
                                 $params['banner_group_sid'] = $group;
                                 $productInfo['banner_info'] = $params;
                                 break;
                         }
                         if (!$errors) {
                             $numberOfListings = SJB_Request::getVar('number_of_listings');
                             $extraInfo = SJB_ProductsManager::getProductExtraInfoBySID($productSID);
                             if (!empty($extraInfo['pricing_type']) && $extraInfo['pricing_type'] == 'volume_based' && $numberOfListings) {
                                 $productInfo['number_of_listings'] = $numberOfListings;
                                 $productObj = new SJB_Product($productInfo, $productInfo['product_type']);
                                 $number_of_listings = !empty($productInfo['number_of_listings']) ? $productInfo['number_of_listings'] : 1;
                                 $productObj->setNumberOfListings($number_of_listings);
                                 $productInfo['price'] = $productObj->getPrice();
                             }
                             if (SJB_UserManager::isUserLoggedIn()) {
                                 SJB_ShoppingCart::addToShoppingCart($productInfo, $current_user->getSID());
                             } else {
                                 if (isset($_SESSION['products'])) {
                                     foreach ($_SESSION['products'] as $addedProduct) {
                                         $addedProductInfo = unserialize($addedProduct['product_info']);
                                         if ($addedProductInfo['user_group_sid'] != $productInfo['user_group_sid']) {
                                             $errors[] = 'You are trying to add products of different User Groups in your Shopping Cart. You сan add only products belonging to one User Group. If you want to add this product in the Shopping Cart please go back to the Shopping Cart and remove products of other User Groups.';
                                             break;
                                         }
                                     }
                                 }
                                 if (!$errors) {
                                     $id = time();
                                     $_SESSION['products'][$id]['product_info'] = serialize($productInfo);
                                     $_SESSION['products'][$id]['sid'] = $id;
                                     $_SESSION['products'][$id]['user_sid'] = 0;
                                 }
                             }
                             if (!$errors) {
                                 SJB_HelperFunctions::redirect(SJB_System::getSystemsettings('SITE_URL') . '/shopping-cart/');
                             }
                         }
                     }
                 }
                 if (!empty($productInfo['expiration_period']) && !is_numeric($productInfo['expiration_period'])) {
                     $productInfo['period'] = ucwords($productInfo['expiration_period']);
                 } elseif (!empty($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'volume_based' && !empty($productInfo['volume_based_pricing'])) {
                     $volumeBasedPricing = $productInfo['volume_based_pricing'];
                     $price = array();
                     $firstPrice = 0;
                     if (!empty($volumeBasedPricing['listings_range_from'])) {
                         for ($i = 1; $i <= count($volumeBasedPricing['listings_range_from']); $i++) {
                             if ($volumeBasedPricing['listings_range_from'][$i] == $volumeBasedPricing['listings_range_to'][$i]) {
                                 $price[$i]['range']['from'] = $volumeBasedPricing['listings_range_from'][$i];
                             } else {
                                 $price[$i]['range']['from'] = $volumeBasedPricing['listings_range_from'][$i];
                                 $price[$i]['range']['to'] = $volumeBasedPricing['listings_range_to'][$i];
                             }
                             $price[$i]['price'] = $volumeBasedPricing['price_per_unit'][$i];
                             if ($i > 1 && $firstPrice > $volumeBasedPricing['price_per_unit'][$i]) {
                                 $price[$i]['savings'] = round(100 - 100 / $firstPrice * $volumeBasedPricing['price_per_unit'][$i]);
                             } else {
                                 $firstPrice = $volumeBasedPricing['price_per_unit'][$i];
                             }
                         }
                     }
                     $productInfo['volume_based_pricing'] = $price;
                     $minListings = min($volumeBasedPricing['listings_range_from']);
                     $maxListings = max($volumeBasedPricing['listings_range_to']);
                     $countListings = array();
                     for ($i = $minListings; $i <= $maxListings; $i++) {
                         $countListings[] = $i;
                     }
                     $productInfo['count_listings'] = $countListings;
                 } elseif (!empty($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'fixed') {
                     $productInfo['fixed_period'] = 1;
                 }
                 if ($productInfo['product_type'] == 'banners') {
                     $params = $_REQUEST;
                     $bannersObj = new SJB_Banners();
                     $banner_fields = $bannersObj->getBannersMeta();
                     foreach ($banner_fields as $key => $banner_field) {
                         $banner_fields[$banner_field['id']] = $banner_field;
                         if (!empty($params[$banner_field['id']])) {
                             $banner_fields[$banner_field['id']]['value'] = $params[$banner_field['id']];
                         }
                         unset($banner_fields[$key]);
                     }
                     if (!empty($params['errors'])) {
                         $tp->assign("errors", $params['errors']);
                     }
                     $tp->assign("banner_fields", $banner_fields);
                 }
                 $userGroupID = SJB_UserGroupDBManager::getUserGroupIDBySID($productInfo['user_group_sid']);
                 $tp->assign('productInfo', $productInfo);
                 $tp->assign('userGroupID', $userGroupID);
                 $tp->assign('productSID', $productSID);
                 $tp->assign('mayChooseProduct', true);
             }
             $tp->assign('errors', $errors);
             break;
     }
     $tp->display($template);
 }
Exemplo n.º 28
0
 function _constructorByProduct($productInfo)
 {
     $productSID = $productInfo['product_sid'];
     $numberOfListings = isset($productInfo['numberOfListings']) ? $productInfo['numberOfListings'] : false;
     $this->product_sid = $productSID;
     $productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
     $is_recurring = !empty($productInfo['recurring']) ? $productInfo['recurring'] : false;
     if ($productInfo['product_type'] == 'featured_user') {
         $this->featured_profile = true;
     }
     $this->product_type = $productInfo['product_type'];
     $product = new SJB_Product($productInfo, $productInfo['product_type']);
     if ($numberOfListings) {
         $product->setNumberOfListings($numberOfListings);
     } else {
         $numberOfListings = !empty($productInfo['number_of_listings']) ? $productInfo['number_of_listings'] : 0;
     }
     $this->setNumberOfListings($numberOfListings);
     $expirationPeriod = $product->getExpirationPeriod();
     if ($expirationPeriod) {
         if ($is_recurring) {
             // Для рекьюринг планов, делаем запас для проплаты в 1 день
             $expirationPeriod++;
         }
         $this->expired_date = date("Y-m-d", strtotime("+" . $expirationPeriod . " day"));
     }
     $this->price = $product->getPrice();
 }