Ejemplo n.º 1
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $user_group_sid = SJB_Request::getVar('sid', null);
     $errors = array();
     if (!is_null($user_group_sid)) {
         $action = SJB_Request::getVar("action", false);
         $product_sid = SJB_Request::getVar("product_sid", false);
         if ($action && $product_sid !== false) {
             switch ($action) {
                 case 'move_up':
                     SJB_ProductsManager::moveUpProductBySID($product_sid, $user_group_sid);
                     break;
                 case 'move_down':
                     SJB_ProductsManager::moveDownProductBySID($product_sid, $user_group_sid);
                     break;
                 case 'set_default_product':
                     SJB_UserGroupManager::setDefaultProduct($user_group_sid, $product_sid);
                     break;
             }
         }
         $user_group_info = SJB_UserGroupManager::getUserGroupInfoBySID($user_group_sid);
         $user_group_info = array_merge($user_group_info, $_REQUEST);
         $userGroup = new SJB_UserGroup($user_group_info);
         $userGroup->setSID($user_group_sid);
         $edit_user_group_form = new SJB_Form($userGroup);
         $form_is_submitted = SJB_Request::getVar('submit');
         if ($form_is_submitted && $edit_user_group_form->isDataValid($errors)) {
             SJB_UserGroupManager::saveUserGroup($userGroup);
             if ($form_is_submitted == 'save_info') {
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/user-groups/');
             }
         }
         $productSIDs = SJB_ProductsManager::getProductsInfoByUserGroupSID($user_group_sid);
         $productsInfo = array();
         $user_sids_in_group = SJB_UserManager::getUserSIDsByUserGroupSID($user_group_sid);
         $user_group_product_user_number = array();
         foreach ($productSIDs as $product) {
             $productsInfo[] = $product;
             $user_sids_in_product = SJB_UserManager::getUserSIDsByProductSID($product['sid']);
             $user_number = count(array_intersect($user_sids_in_group, $user_sids_in_product));
             $user_group_product_user_number[$product['sid']] = $user_number;
         }
         $edit_user_group_form->registerTags($tp);
         $tp->assign('object_sid', $userGroup->getSID());
         $tp->assign('notifications', $userGroup->getNotifications());
         $tp->assign('notificationGroups', $userGroup->getNotificationsGroups());
         $tp->assign('user_group_sid', $user_group_sid);
         $tp->assign('user_group_products_info', $productsInfo);
         $tp->assign('user_group_product_user_number', $user_group_product_user_number);
         $tp->assign('form_fields', $edit_user_group_form->getFormFieldsInfo());
     } else {
         $errors['USER_GROUP_SID_NOT_SET'] = 1;
     }
     $tp->assign('user_group_info', isset($user_group_info) ? $user_group_info : null);
     $tp->assign('errors', $errors);
     $tp->assign('object_sid', $user_group_sid);
     $tp->display('edit_user_group.tpl');
 }
Ejemplo n.º 2
0
 public static function createInfoForCustomProduct($userSid, $productSid, $listingSid, $price, $name, $type)
 {
     $productName = SJB_ProductsManager::getProductNameBySid($productSid);
     $userGroupSid = SJB_UserManager::getUserGroupByUserSid($userSid);
     $productInfo = array('custom_item' => "{$name} ({$productName})", 'custom_info' => array('listing_id' => (int) $listingSid, 'type' => $type, 'extraDescription' => "({$productName})", 'productSid' => (int) $productSid), 'name' => $name, 'number_of_listings' => 1, 'QtyPeriod' => 1, 'price' => $price, 'pricing_type' => 'fixed', 'sid' => -1, 'product_type' => 'post_listings', 'user_group_sid' => $userGroupSid);
     $productInfo['serialized_extra_info'] = serialize($productInfo);
     return $productInfo;
 }
Ejemplo n.º 3
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);
 }
Ejemplo n.º 4
0
 public static function getProductList()
 {
     $products = SJB_ProductsManager::getAllProductsInfo(true);
     $productList = array();
     foreach ($products as $key => $product) {
         $productList[$key]['id'] = $product['sid'];
         $productList[$key]['caption'] = $product['name'];
     }
     return $productList;
 }
Ejemplo n.º 5
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");
 }
Ejemplo n.º 6
0
 public static function updateAllContractsExtraInfoByProductSID($contractsSIDs, $productSID)
 {
     $productExtraInfo = SJB_ProductsManager::getProductExtraInfoBySID($productSID);
     $currentPermissions = array();
     SJB_DB::query("delete from `permissions` where `type` = 'contract' and `role` in ({$contractsSIDs})");
     foreach (explode(',', $contractsSIDs) as $contractSID) {
         $contractInfo = self::selectInfoByID($contractSID);
         if ($contractInfo['status'] == 'active') {
             SJB_DB::query("INSERT INTO `permissions` (`type`, `role`, `name`, `value`, `params`, `message`)\n\t\t\t\t\t\t\t\tSELECT 'contract', ?s, `name`, `value`, `params`, `message`\n\t\t\t\t\t\t\t\tFROM `permissions`\n\t\t\t\t\t\t\t\tWHERE `type` = 'product' AND `role` = ?s", $contractSID, $productSID);
         }
         $extraInfo = !empty($contractInfo['serialized_extra_info']) ? unserialize($contractInfo['serialized_extra_info']) : array();
         $contractExtraInfo = $productExtraInfo;
         if (!empty($extraInfo['pricing_type']) && $extraInfo['pricing_type'] == 'volume_based') {
             $numberOfListings = $extraInfo['number_of_listings'];
             $numberOfPostings[$contractSID] = $numberOfListings;
             $volumeBasedPricing = !empty($productExtraInfo['volume_based_pricing']) ? $productExtraInfo['volume_based_pricing'] : array();
             if (!empty($volumeBasedPricing['listings_range_from'])) {
                 for ($i = 1; $i <= count($volumeBasedPricing['listings_range_from']); $i++) {
                     if ($numberOfListings >= $volumeBasedPricing['listings_range_from'][$i] && $numberOfListings <= $volumeBasedPricing['listings_range_to'][$i]) {
                         $contractExtraInfo['listings_range_from'] = $volumeBasedPricing['listings_range_from'][$i];
                         $contractExtraInfo['listings_range_to'] = $volumeBasedPricing['listings_range_to'][$i];
                         $contractExtraInfo['price_per_unit'] = $volumeBasedPricing['price_per_unit'][$i];
                         $contractExtraInfo['renewal_price'] = $volumeBasedPricing['renewal_price_per_listing'][$i];
                         $contractExtraInfo['number_of_listings'] = $numberOfListings;
                         break;
                     }
                 }
                 unset($contractExtraInfo['volume_based_pricing']);
             }
         }
         SJB_DB::query("UPDATE `contracts` SET `serialized_extra_info` = ?s WHERE `id` = ?n", serialize($contractExtraInfo), $contractSID);
     }
     if (isset($productExtraInfo['pricing_type'])) {
         $currentPermissions = SJB_DB::query("SELECT * FROM `permissions` WHERE `type` = 'contract' AND `role` in ({$contractsSIDs})");
     }
     foreach ($currentPermissions as $key => $permission) {
         $currentPermissions[$permission['name']] = $permission;
         unset($currentPermissions[$key]);
     }
     if ($currentPermissions && !empty($numberOfPostings) || isset($productExtraInfo['number_of_listings'])) {
         foreach (explode(',', $contractsSIDs) as $contractSID) {
             $listingTypes = SJB_ListingTypeManager::getAllListingTypesInfo();
             foreach ($listingTypes as $listingType) {
                 if (isset($currentPermissions['post_' . strtolower($listingType['id'])])) {
                     $permission = $currentPermissions['post_' . strtolower($listingType['id'])];
                     if ($permission['value'] == 'allow') {
                         SJB_DB::query("UPDATE `permissions` SET `params` = ?n WHERE `type` = 'contract' AND  `role` = ?s AND `name` = ?s", !empty($numberOfPostings) ? $numberOfPostings[$contractSID] : $productExtraInfo['number_of_listings'], $contractSID, 'post_' . strtolower($listingType['id']));
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 7
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $action = SJB_Request::getVar('action', false);
     $sid = SJB_Request::getVar('sid', 0);
     $errors = array();
     switch ($action) {
         case 'activate':
             SJB_ProductsManager::activateProductBySID($sid);
             break;
         case 'deactivate':
             SJB_ProductsManager::deactivateProductBySID($sid);
             break;
         case 'delete':
             if (SJB_ContractManager::getContractQuantityByProductSID($sid) || SJB_InvoiceManager::getInvoiceQuantityByProductSID($sid)) {
                 $errors['PRODUCT_IS_IN_USE'] = 1;
             } else {
                 SJB_ProductsManager::deleteProductBySID($sid);
             }
             break;
     }
     $products = SJB_ProductsManager::getAllProductsInfo();
     foreach ($products as $key => $productInfo) {
         $product = new SJB_Product($productInfo, $productInfo['product_type']);
         $product->setNumberOfListings(1);
         if ($productInfo['product_type'] != 'post_listings' && $productInfo['product_type'] != 'mixed_product') {
             $products[$key]['number_of_postings'] = '-';
         }
         $products[$key]['price'] = $product->getPrice();
         $products[$key]['user_group'] = SJB_UserGroupManager::getUserGroupInfoBySID($productInfo['user_group_sid']);
         $products[$key]['product_type'] = SJB_ProductsManager::getProductTypeByID($productInfo['product_type']);
         $products[$key]['subscribed_users'] = SJB_ContractManager::getContractQuantityByProductSID($productInfo['sid']);
         $products[$key]['invoices'] = SJB_InvoiceManager::getInvoiceQuantityByProductSID($productInfo['sid']);
         if (!empty($productInfo['availability_to']) && $productInfo['availability_to'] <= date('Y-m-d')) {
             $products[$key]['expired'] = 1;
         }
     }
     $tp->assign('errors', $errors);
     $tp->assign('products', $products);
     $tp->display('products.tpl');
 }
Ejemplo n.º 8
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];
 }
Ejemplo n.º 9
0
 public function createUser()
 {
     $user_group_id = SJB_Request::getVar('user_group_id');
     if (!is_null($user_group_id)) {
         $user_group_sid = SJB_UserGroupManager::getUserGroupSIDByID($user_group_id);
         $user = SJB_ObjectMother::createUser($_REQUEST, $user_group_sid);
         $user->deleteProperty('active');
         $user->deleteProperty('featured');
         $this->fillRegistrationDataWithUser($user);
         self::addReferenceDetails($user);
         $user->deleteProperty('captcha');
         SJB_UserManager::saveUser($user);
         // subscribe user on default product
         $defaultProduct = SJB_UserGroupManager::getDefaultProduct($user_group_sid);
         $available_products_ids = SJB_ProductsManager::getProductsByUserGroupSID($user_group_sid, $user->getSID());
         if ($defaultProduct && in_array($defaultProduct, $available_products_ids)) {
             $contract = new SJB_Contract(array('product_sid' => $defaultProduct));
             $contract->setUserSID($user->getSID());
             $contract->saveInDB();
         }
         $this->sendUserSocialRegistrationLetter($user);
         // notifying administrator
         SJB_AdminNotifications::sendAdminUserRegistrationLetter($user);
         SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/my-account/');
     }
 }
Ejemplo n.º 10
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $tp->assign('terms_of_use_check', SJB_System::getSettingByName('terms_of_use_check'));
     $user_group_id = SJB_Request::getVar('user_group_id', null);
     $form_submitted = isset($_REQUEST['action']) && $_REQUEST['action'] == 'register';
     if (!is_null($user_group_id)) {
         $user_group_sid = SJB_UserGroupManager::getUserGroupSIDByID($user_group_id);
         /**
          * check if registration is allowed for this UserGroup
          */
         if (!SJB_SocialPlugin::ifRegistrationIsAllowedByUserGroupSID($user_group_sid)) {
             return null;
         }
         $user_group_info = SJB_UserGroupManager::getUserGroupInfoBySID($user_group_sid);
         $user = SJB_ObjectMother::createUser($_REQUEST, $user_group_sid);
         $user->deleteProperty('active');
         $user->deleteProperty('featured');
         $errors = array();
         // social plugin
         if ($form_submitted) {
             SJB_Event::dispatch('SocialPlugin_AddListingFieldsIntoRegistration', $user, true);
             SJB_Event::dispatch('MakeRegistrationFieldsNotRequired_SocialPlugin', $user, true);
         } else {
             SJB_Event::dispatch('PrepareRegistrationFields_SocialPlugin', $user, true);
             SJB_Event::dispatch('SocialPlugin_AddListingFieldsIntoRegistration', $user, true);
             SJB_Event::dispatch('FillRegistrationData_Plugin', $user, true);
         }
         $registration_form = SJB_ObjectMother::createForm($user);
         $registration_form->registerTags($tp);
         if ($form_submitted && $registration_form->isDataValid($errors)) {
             SJB_Event::dispatch('FillRegistrationData_Plugin', $user, true);
             SJB_Event::dispatch('AddReferencePluginDetails', $user, true);
             $user->deleteProperty('captcha');
             $user->deleteProperty('active');
             $user->deleteProperty('featured');
             SJB_UserManager::saveUser($user);
             SJB_Statistics::addStatistics('addUser', $user->getUserGroupSID(), $user->getSID(), false, 0, 0, false, 0, SJB_SocialPlugin::getNetwork());
             SJB_Statistics::addStatistics('addUser' . SJB_SocialPlugin::getNetwork(), $user->getUserGroupSID(), $user->getSID(), false, 0, 0, false, 0, SJB_SocialPlugin::getNetwork());
             // subscribe user on default product
             $defaultProduct = SJB_UserGroupManager::getDefaultProduct($user_group_sid);
             $availableProductIDs = SJB_ProductsManager::getProductsIDsByUserGroupSID($user_group_sid);
             if ($defaultProduct && in_array($defaultProduct, $availableProductIDs)) {
                 $contract = new SJB_Contract(array('product_sid' => $defaultProduct));
                 $contract->setUserSID($user->getSID());
                 $contract->saveInDB();
             }
             SJB_SocialPlugin::sendUserSocialRegistrationLetter($user);
             // notify administrator
             SJB_AdminNotifications::sendAdminUserRegistrationLetter($user);
             // Activation
             $isSendActivationEmail = SJB_UserGroupManager::isSendActivationEmail($user_group_sid);
             $isApproveByAdmin = SJB_UserGroupManager::isApproveByAdmin($user_group_sid);
             if ($isApproveByAdmin) {
                 SJB_UserManager::setApprovalStatusByUserName($user->getUserName(), 'Pending');
             }
             if ($isSendActivationEmail) {
                 $isSent = SJB_Notifications::sendUserActivationLetter($user->getSID());
                 if ($isSent) {
                     $tp->display('../users/registration_confirm.tpl');
                 } else {
                     $tp->display('../users/registration_failed_to_send_activation_email.tpl');
                 }
             } else {
                 if (!$isSendActivationEmail && $isApproveByAdmin) {
                     SJB_UserManager::setApprovalStatusByUserName($user->getUserName(), 'Pending');
                     $tp->display('../users/registration_pending.tpl');
                 } else {
                     SJB_UserManager::activateUserByUserName($user->getUserName());
                     $errors = array();
                     SJB_Authorization::login($user->getUserName(), $user->getPropertyValue('password'), false, $errors, false);
                     // save access token, profile info for synchronization
                     SJB_SocialPlugin::postRegistration();
                     $tp->assign('socialNetwork', SJB_SocialPlugin::getNetwork());
                     $pageId = !empty($user_group_info['after_registration_redirect_to']) ? $user_group_info['after_registration_redirect_to'] : '';
                     $redirectUrl = SJB_UserGroupManager::getRedirectUrlByPageID($pageId);
                     SJB_HelperFunctions::redirect($redirectUrl);
                 }
             }
         } else {
             // social plugin
             SJB_Event::dispatch('PrepareRegistrationFields_SocialPlugin', $user, true);
             if (SJB_UserGroupManager::isUserEmailAsUsernameInUserGroup($user_group_sid)) {
                 $user->deleteProperty('username');
             }
             $registration_form = SJB_ObjectMother::createForm($user);
             if ($form_submitted) {
                 $registration_form->isDataValid($errors);
             }
             $registration_form->registerTags($tp);
             $registration_form_template = '../users/registration_form.tpl';
             if (isset($_REQUEST['reg_form_template'])) {
                 $registration_form_template = $_REQUEST['reg_form_template'];
             } elseif (!empty($user_group_info['reg_form_template'])) {
                 $registration_form_template = $user_group_info['reg_form_template'];
             }
             $form_fields = $registration_form->getFormFieldsInfo();
             $user_group_info = SJB_UserGroupManager::getUserGroupInfoBySID($user_group_sid);
             $tp->assign('user_group_info', $user_group_info);
             $tp->assign('errors', $errors);
             $tp->assign('user_group_id', $user_group_id);
             $tp->assign('form_fields', $form_fields);
             $metaDataProvider = SJB_ObjectMother::getMetaDataProvider();
             $tp->assign('METADATA', array('form_fields' => $metaDataProvider->getFormFieldsMetadata($form_fields)));
             $tp->assign('socialRegistration', true);
             $tp->assign('userTree', true);
             $tp->display($registration_form_template);
         }
     } else {
         $userGroupsSIDs = SJB_SocialPlugin::getResolvedUserGroupsByNetwork();
         $user_groups_info = array();
         foreach ($userGroupsSIDs as $groupSID) {
             array_push($user_groups_info, SJB_UserGroupManager::getUserGroupInfoBySID($groupSID));
         }
         /*
          * if there is only one group available for registration
          * redirect user directly on Registration Fields page
          */
         if (count($user_groups_info) === 1 && !empty($user_groups_info[0]['id'])) {
             SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/registration-social/?user_group_id=' . $user_groups_info[0]['id']);
         }
         $tp->assign('user_groups_info', $user_groups_info);
         $tp->display('registration_choose_user_group_social.tpl');
     }
 }
Ejemplo n.º 11
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/');
     }
 }
Ejemplo n.º 12
0
 /**
  * @param int $userSID
  * @param int $productSID
  * @param int $contractID
  * @param int $listingNumber
  */
 public static function activateListingsAfterPaid($userSID, $productSID, $contractID, $listingNumber)
 {
     $limit = '';
     if ($listingNumber != null) {
         $limit = 'LIMIT 0,' . $listingNumber;
     }
     $serializedProductSID = SJB_ProductsManager::generateQueryBySID($productSID);
     $listingsSIDsToProceed = SJB_DB::query("SELECT `sid` FROM `listings` WHERE `checkouted` = 0 AND `complete` = 1 AND `contract_id` = 0 AND `user_sid` = ?n AND `product_info` REGEXP '({$serializedProductSID})' ORDER BY `sid` DESC {$limit}", $userSID);
     if (!empty($listingsSIDsToProceed)) {
         foreach ($listingsSIDsToProceed as $listingSIDToProceed) {
             SJB_DB::query('UPDATE `listings` SET `contract_id` = ?n, `checkouted` = 1 WHERE `sid` = ?n', $contractID, $listingSIDToProceed['sid']);
             self::activateListingBySID($listingSIDToProceed['sid']);
         }
         SJB_ProductsManager::incrementPostingsNumber($productSID, count($listingsSIDsToProceed));
         SJB_ContractSql::updatePostingsNumber($contractID, count($listingsSIDsToProceed));
     }
 }
Ejemplo n.º 13
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);
 }
Ejemplo n.º 14
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');
     }
 }
Ejemplo n.º 15
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $template = SJB_Request::getVar('template', 'manage_invoices.tpl');
     $searchTemplate = SJB_Request::getVar('search_template', 'invoice_search_form.tpl');
     $action = SJB_Request::getVar('action_name');
     if (!empty($action)) {
         $invoicesSIDs = SJB_Request::getVar('invoices', array());
         $_REQUEST['restore'] = 1;
         switch ($action) {
             case 'paid':
                 foreach (array_keys($invoicesSIDs) as $invoiceSID) {
                     $invoice = SJB_InvoiceManager::getObjectBySID($invoiceSID);
                     $userSID = $invoice->getPropertyValue('user_sid');
                     if (SJB_UserManager::isUserExistsByUserSid($userSID)) {
                         $items = $invoice->getPropertyValue('items');
                         $productSIDs = $items['products'];
                         foreach ($productSIDs as $key => $productSID) {
                             if ($productSID != -1) {
                                 if (SJB_ProductsManager::isProductExists($productSID)) {
                                     $productInfo = $invoice->getItemValue($key);
                                     $listingNumber = $productInfo['qty'];
                                     $contract = new SJB_Contract(array('product_sid' => $productSID, 'numberOfListings' => $listingNumber, 'is_recurring' => $invoice->isRecurring()));
                                     $contract->setUserSID($userSID);
                                     $contract->setPrice($items['amount'][$key]);
                                     if ($contract->saveInDB()) {
                                         SJB_ListingManager::activateListingsAfterPaid($userSID, $productSID, $contract->getID(), $listingNumber);
                                         SJB_ShoppingCart::deleteItemFromCartBySID($productInfo['shoppingCartRecord'], $userSID);
                                         $bannerInfo = $productInfo['banner_info'];
                                         if ($productInfo['product_type'] == 'banners' && !empty($bannerInfo)) {
                                             $bannersObj = new SJB_Banners();
                                             $bannersObj->addBanner($bannerInfo['title'], $bannerInfo['link'], $bannerInfo['bannerFilePath'], $bannerInfo['sx'], $bannerInfo['sy'], $bannerInfo['type'], 0, $bannerInfo['banner_group_sid'], $bannerInfo, $userSID, $contract->getID());
                                             $bannerGroup = $bannersObj->getBannerGroupBySID($bannerInfo['banner_group_sid']);
                                             SJB_AdminNotifications::sendAdminBannerAddedLetter($userSID, $bannerGroup);
                                         }
                                         if ($contract->isFeaturedProfile()) {
                                             SJB_UserManager::makeFeaturedBySID($userSID);
                                         }
                                         if (SJB_UserNotificationsManager::isUserNotifiedOnSubscriptionActivation($userSID)) {
                                             SJB_Notifications::sendSubscriptionActivationLetter($userSID, $productInfo);
                                         }
                                     }
                                 }
                             } else {
                                 $type = SJB_Array::getPath($items, 'custom_info/' . $key . '/type');
                                 switch ($type) {
                                     case 'featuredListing':
                                         $listingId = SJB_Array::getPath($items, 'custom_info/' . $key . '/listing_id');
                                         SJB_ListingManager::makeFeaturedBySID($listingId);
                                         break;
                                     case 'priorityListing':
                                         $listingId = SJB_Array::getPath($items, 'custom_info/' . $key . '/listing_id');
                                         SJB_ListingManager::makePriorityBySID($listingId);
                                         break;
                                     case 'activateListing':
                                         $listingsIds = explode(",", SJB_Array::getPath($items, 'custom_info/' . $key . '/listings_ids'));
                                         foreach ($listingsIds as $listingId) {
                                             SJB_ListingManager::activateListingBySID($listingId);
                                         }
                                         break;
                                 }
                             }
                         }
                         SJB_Statistics::addStatisticsFromInvoice($invoice);
                     }
                     $total = $invoice->getPropertyValue('total');
                     if ($total > 0) {
                         $gatewayID = $invoice->getPropertyValue('payment_method');
                         $gatewayID = isset($gatewayID) ? $gatewayID : 'cash_payment';
                         $transactionId = md5($invoiceSID . $gatewayID);
                         $transactionInfo = array('transaction_id' => $transactionId, 'invoice_sid' => $invoiceSID, 'amount' => $total, 'payment_method' => $gatewayID, 'user_sid' => $invoice->getPropertyValue('user_sid'));
                         $transaction = new SJB_Transaction($transactionInfo);
                         SJB_TransactionManager::saveTransaction($transaction);
                     }
                     SJB_InvoiceManager::markPaidInvoiceBySID($invoiceSID);
                     SJB_PromotionsManager::markPromotionAsPaidByInvoiceSID($invoiceSID);
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/manage-invoices/");
                 break;
             case 'unpaid':
                 foreach (array_keys($invoicesSIDs) as $invoiceSID) {
                     SJB_InvoiceManager::markUnPaidInvoiceBySID($invoiceSID);
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/manage-invoices/');
                 break;
             case 'delete':
                 foreach (array_keys($invoicesSIDs) as $invoiceSID) {
                     SJB_InvoiceManager::deleteInvoiceBySID($invoiceSID);
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/manage-invoices/');
                 break;
             default:
                 unset($_REQUEST['restore']);
                 break;
         }
     }
     /***************************************************************/
     $_REQUEST['action'] = 'search';
     $invoice = new SJB_Invoice(array());
     $invoice->addProperty(array('id' => 'username', 'type' => 'string', 'value' => '', 'is_system' => true));
     $aliases = new SJB_PropertyAliases();
     $aliases->addAlias(array('id' => 'username', 'real_id' => 'user_sid', 'transform_function' => 'SJB_UserDBManager::getUserSIDsLikeSearchString'));
     $searchFormBuilder = new SJB_SearchFormBuilder($invoice);
     $criteriaSaver = new SJB_InvoiceCriteriaSaver();
     if (isset($_REQUEST['restore'])) {
         $_REQUEST = array_merge($_REQUEST, $criteriaSaver->getCriteria());
     }
     $criteria = $searchFormBuilder->extractCriteriaFromRequestData($_REQUEST, $invoice);
     $searchFormBuilder->setCriteria($criteria);
     $searchFormBuilder->registerTags($tp);
     $tp->display($searchTemplate);
     /********************** S O R T I N G *********************/
     $paginator = new SJB_InvoicePagination();
     $innerJoin = false;
     if ($paginator->sortingField == 'username') {
         $innerJoin = array('users' => array('sort_field' => array(36 => array('FirstName', 'LastName'), 41 => 'CompanyName'), 'join_field' => 'sid', 'join_field2' => 'user_sid', 'main_table' => 'invoices', 'join' => 'LEFT JOIN'));
     }
     $searcher = new SJB_InvoiceSearcher(array('limit' => ($paginator->currentPage - 1) * $paginator->itemsPerPage, 'num_rows' => $paginator->itemsPerPage), $paginator->sortingField, $paginator->sortingOrder, $innerJoin);
     $foundInvoices = array();
     $foundInvoicesInfo = array();
     if (SJB_Request::getVar('action', '') == 'search') {
         $foundInvoices = $searcher->getObjectsByCriteria($criteria, $aliases);
         if (empty($foundInvoices) && $paginator->currentPage != 1) {
             SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/manage-invoices/?page=1');
         }
         $criteriaSaver->setSession($_REQUEST, $searcher->getFoundObjectSIDs());
     } elseif (isset($_REQUEST['restore'])) {
         $foundInvoices = $criteriaSaver->getObjectsFromSession();
     }
     foreach ($foundInvoices as $id => $invoice) {
         $subUserSID = $invoice->getPropertyValue('subuser_sid');
         if ($subUserSID) {
             $subUserInfo = SJB_UserManager::getUserInfoBySID($subUserSID);
             $parentInfo = SJB_UserManager::getUserInfoBySID($subUserInfo['parent_sid']);
             $username = $parentInfo['CompanyName'];
         } else {
             $userSID = $invoice->getPropertyValue('user_sid');
             $userInfo = SJB_UserManager::getUserInfoBySID($userSID);
             if (SJB_UserGroupManager::getUserGroupIDBySID($userInfo['user_group_sid']) == 'Employer') {
                 $username = $userInfo['CompanyName'];
             } else {
                 if (SJB_UserGroupManager::getUserGroupIDBySID($userInfo['user_group_sid']) == 'JobSeeker') {
                     $username = $userInfo['FirstName'] . ' ' . $userInfo['LastName'];
                 } else {
                     $username = $userInfo['username'];
                 }
             }
         }
         $invoice->addProperty(array('id' => 'sid', 'type' => 'string', 'value' => $invoice->getSID()));
         $invoice->addProperty(array('id' => 'username', 'type' => 'string', 'value' => $username));
         $foundInvoices[$id] = $invoice;
         $foundInvoicesInfo[$invoice->getSID()] = SJB_InvoiceManager::getInvoiceInfoBySID($invoice->getSID());
         $foundInvoicesInfo[$invoice->getSID()]['userExists'] = !empty($username) ? 1 : 0;
     }
     /****************************************************************/
     $paginator->setItemsCount($searcher->getAffectedRows());
     $form_collection = new SJB_FormCollection($foundInvoices);
     $form_collection->registerTags($tp);
     $tp->assign('paginationInfo', $paginator->getPaginationInfo());
     $tp->assign("found_invoices", $foundInvoicesInfo);
     $tp->display($template);
 }
Ejemplo n.º 16
0
    public function execute()
    {
        set_time_limit(0);
        ini_set('memory_limit', -1);
        $tp = SJB_System::getTemplateProcessor();
        $user_groups_info = SJB_UserGroupManager::getAllUserGroupsInfo();
        $user_group_info = reset($user_groups_info);
        $user_group_sid = $user_group_info['sid'];
        $fields_info = SJB_UserProfileFieldManager::getFieldsInfoByUserGroupSID($user_group_sid);
        $fields = array();
        $tp->assign('test_message', SJB_Request::getVar('test_message', false));
        $tp->assign('undeliveredMailingsForTest', SJB_Request::getVar('undeliveredMailingsForTest', false));
        foreach ($fields_info as $key => $val) {
            if ($val['id'] == 'Location') {
                foreach ($val['fields'] as $field) {
                    if ($field['id'] == 'Country') {
                        $fields['country'] = SJB_CountriesManager::getAllCountriesCodesAndNames();
                    } elseif ($field['id'] == 'State') {
                        $fields['state'] = SJB_StatesManager::getStatesNamesByCountry();
                    }
                }
            }
        }
        $tp->assign('fields', $fields);
        $errors = array();
        $errorId = SJB_Request::getVar('error', null, 'GET');
        if ($errorId) {
            $errors[$errorId] = 1;
        }
        if (isset($_REQUEST['submit']) && $_FILES['file_mail']['name'] && $_FILES['file_mail']['error']) {
            $errorId = SJB_UploadFileManager::getErrorId($_FILES['file_mail']['error']);
            if ($_REQUEST['submit'] != 'save') {
                $mailID = SJB_Request::getVar('mail_id', 0);
                $parameter = $mailID ? '?edit=' . $mailID : '';
                SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/mailing/' . $parameter . '&error=' . $errorId);
            }
            $errors[$errorId] = 1;
        } else {
            if (isset($_REQUEST['submit'])) {
                SJB_DB::query("DELETE FROM uploaded_files WHERE id = 'file_mail'");
                $upload_manager = new SJB_UploadFileManager();
                $upload_manager->setFileGroup('files');
                $upload_manager->setUploadedFileID('file_mail');
                $upload_manager->uploadFile('file_mail');
                $file_name = '';
                if (!isset($_REQUEST['delete_file']) && isset($_REQUEST['old_file']) && !$upload_manager->getUploadedFileName('file_mail')) {
                    $file_name = $_REQUEST['old_file'];
                } elseif ($upload_manager->getUploadedFileName('file_mail')) {
                    $file_name = "files/files/" . $upload_manager->getUploadedSavedFileName('file_mail');
                }
                $language = SJB_Request::getVar('language', 'any');
                $users = SJB_Request::getVar('users', 'any');
                $without_cv = SJB_Request::getVar('without_cv', false);
                $country = SJB_Request::getVar('country', '');
                $state = SJB_Request::getVar('state', '');
                $city = SJB_Request::getVar('city', '');
                $products = SJB_Request::getVar('products', array());
                $user_status = SJB_Request::getVar('user_status', '');
                $registration_date = SJB_Request::getVar('registration_date', array());
                $param = serialize(array('language' => $language, 'users' => $users, 'without_cv' => $without_cv, 'products' => $products, 'country' => $country, 'state' => $state, 'city' => $city, 'status' => $user_status, 'registration' => $registration_date));
                $email = '';
                $mailSubject = SJB_Request::getVar('subject', '');
                $mailText = stripcslashes(SJB_Request::getVar('text', ''));
                $mailID = SJB_Request::getVar('mail_id', 0);
                if ($mailID) {
                    SJB_DB::query('UPDATE `mailing` SET
					`subject` 	= ?s,
					`text` 		= ?s,
					`email` 	= ?s,
					`file` 		= ?s,
					`param` 	= ?s
				WHERE `id` 	= ?s', $mailSubject, $mailText, $email, $file_name, $param, $mailID);
                } else {
                    $query = "INSERT INTO mailing ( email , subject , text , file, param) VALUES ( ?s, ?s, ?s, ?s, ?s)";
                    SJB_DB::query($query, $email, $mailSubject, $mailText, $file_name, $param);
                }
                if ($_REQUEST['submit'] == 'save') {
                    SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/mailing/');
                } else {
                    $parameter = $mailID ? '?edit=' . $mailID : '';
                    SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/mailing/' . $parameter);
                }
            }
        }
        if (SJB_Request::getVar('delete')) {
            $mailings = SJB_Request::getVar('mailing');
            if (is_array($mailings)) {
                foreach ($mailings as $id => $value) {
                    SJB_DB::query('DELETE FROM `mailing` WHERE `id` = ?n', $id);
                    SJB_DB::query('DELETE FROM `mailing_info` WHERE `mailing_id` = ?n', $id);
                }
            } else {
                $idToDelete = SJB_Request::getInt('delete', 0);
                SJB_DB::query('DELETE FROM `mailing` WHERE `id` = ?n', $idToDelete);
                SJB_DB::query('DELETE FROM `mailing_info` WHERE `mailing_id` = ?n', $idToDelete);
            }
            SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/mailing/');
        }
        if (isset($_REQUEST['edit'])) {
            $idToEdit = SJB_Request::getInt('edit', 0);
            $mail_arr = SJB_DB::query('SELECT * FROM mailing WHERE id = ?n', $idToEdit);
            $tp->assign("mail_id", $mail_arr[0]['id']);
            $tp->assign("subject", $mail_arr[0]['subject']);
            $tp->assign("text", $mail_arr[0]['text']);
            $tp->assign("file", $mail_arr[0]['file']);
            $tp->assign("file_url", $mail_arr[0]['file']);
            $tp->assign("param", unserialize($mail_arr[0]['param']));
        }
        // get products by UserGroup ID
        if (SJB_Request::isAjax()) {
            $userGroupID = SJB_Request::getVar('usergr', 0);
            if ($userGroupID > 0) {
                $products = SJB_ProductsManager::getProductsInfoByUserGroupSID($userGroupID);
            } else {
                $products = SJB_ProductsManager::getAllProductsInfo();
            }
            $tp->assign("products", $products);
            $tp->display("mailing_products.tpl");
            exit;
        }
        $mail_list = SJB_DB::query('SELECT * FROM mailing');
        foreach ($mail_list as $key => $var) {
            $param = unserialize($mail_list[$key]['param']);
            $where = '';
            $join = '';
            $numSentEmails = SJB_DB::queryValue('SELECT count(*) FROM `mailing_info` WHERE `mailing_id` = ?n AND `status`=0', $var['id']);
            if ($param["language"] != 'any') {
                $where .= " and language='{$param['language']}'";
            }
            if ($param["users"] != '0') {
                $where .= ' and u.user_group_sid=' . $param['users'];
            }
            if ($param["without_cv"]) {
                $join = "left join listings l on l.user_sid = u.sid";
                $where .= " and l.sid is null";
            }
            // user status
            if (!empty($param['status'])) {
                $where .= ' and `u`.`active`=' . (int) $param['status'];
            }
            // registration date
            if (!empty($param['registration']) && is_array($param['registration'])) {
                $i18n = SJB_I18N::getInstance();
                if (!empty($param['registration']['not_less'])) {
                    $where .= ' AND `u`.`registration_date` > \'' . $i18n->getInput('date', $param['registration']['not_less']) . '\'';
                }
                if (!empty($param['registration']['not_more'])) {
                    $where .= ' AND `u`.`registration_date` < \'' . $i18n->getInput('date', $param['registration']['not_more']) . '\'';
                }
            }
            // products
            if (!empty($param['products'])) {
                $join .= "\n            LEFT JOIN contracts ON u.sid = contracts.user_sid\n            LEFT JOIN products ON products.sid = contracts.product_sid\n        ";
                $whereProduct = array();
                foreach ($param['products'] as $theProduct) {
                    $theProduct = (int) $theProduct;
                    if (!empty($theProduct)) {
                        $whereProduct[] .= "products.sid = '{$theProduct}'";
                    } else {
                        $whereProduct[] .= 'products.sid IS NULL';
                    }
                }
                if (!empty($whereProduct)) {
                    $where .= ' AND (' . implode(' OR ', $whereProduct) . ')';
                }
            }
            /// products
            if (!empty($param['country']) || !empty($param['state'])) {
                if (!empty($param['country'])) {
                    $where_country = array();
                    foreach ($param['country'] as $the_country) {
                        if (!empty($the_country)) {
                            $where_country[] .= "`u`.`Location_Country` = '{$the_country}'";
                        } else {
                            $where_country[] .= "`u`.`Location_Country` IS NULL";
                        }
                    }
                    if (!empty($where_country)) {
                        $where .= ' AND (' . implode(' OR ', $where_country) . ')';
                    }
                }
                if (!empty($param['state'])) {
                    $where_state = array();
                    foreach ($param['state'] as $the_state) {
                        if (!empty($the_state)) {
                            $where_state[] .= "`u`.`Location_State` = '{$the_state}'";
                        } else {
                            $where_state[] .= "`u`.`Location_State` IS NULL";
                        }
                    }
                }
                if (!empty($where_state)) {
                    $where .= ' AND (' . implode(' OR ', $where_state) . ')';
                }
                if (!empty($param['city'])) {
                    $where .= " AND `u`.`Location_City` = '{$param['city']}'";
                }
            }
            $mail_list[$key]['not_send'] = $numSentEmails;
            $mail_list[$key]['mail_arr'] = SJB_DB::query("\n        SELECT u.sid as sid, u.username, u.user_group_sid, u.language\n        FROM users u\n            {$join}\n            WHERE u.sendmail = 0\n            {$where}\n            GROUP BY `u`.`sid`");
            $mail_list[$key]['count'] = count($mail_list[$key]['mail_arr']);
        }
        /*
         * test sending
         */
        $testMailingID = SJB_Request::getVar('test_send', 0);
        if ($testMailingID) {
            if ($this->isTestEmailValid()) {
                $testSendResult = false;
                $oMailing = new SJB_Mailing($testMailingID);
                $mailings = SJB_Request::getVar('mailing');
                if (is_array($mailings)) {
                    foreach ($mailings as $id => $value) {
                        $oMailing->setMailingID($id);
                        $oMailing->setMailingList($mail_list);
                        if ($oMailing->testSend()) {
                            $testSendResult = true;
                        }
                    }
                } else {
                    $oMailing->setMailingList($mail_list);
                    $testSendResult = $oMailing->testSend();
                }
                if ($testSendResult) {
                    SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/mailing/?test_message=1');
                } else {
                    $email = urlencode(SJB_Request::getString('email', false));
                    SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/mailing/?undeliveredMailingsForTest={$email}");
                }
            } else {
                $tp->assign('testEmailNotValid', true);
            }
        }
        // general sending
        $sendToMailingID = SJB_Request::getVar('sending', 0);
        $sendResult = false;
        if ($sendToMailingID) {
            $oMailing = new SJB_Mailing($sendToMailingID);
            $mailings = SJB_Request::getVar('mailing');
            $undeliveredMailingsInfo = array();
            if (is_array($mailings)) {
                foreach ($mailings as $id => $value) {
                    $oMailing->setMailingID($id);
                    $oMailing->setMailingList($mail_list);
                    $countOfSendMailings = $oMailing->send();
                    if ($countOfSendMailings != 0) {
                        $sendResult = true;
                    }
                    $undeliveredMailingsInfo = array_merge($oMailing->getUndeliveredMailingsInfo(), $undeliveredMailingsInfo);
                }
            } else {
                $oMailing->setMailingList($mail_list);
                $countOfSendMailings = $oMailing->send();
                if ($countOfSendMailings != 0) {
                    $sendResult = true;
                }
                $undeliveredMailingsInfo = $oMailing->getUndeliveredMailingsInfo();
            }
            if ($sendResult) {
                $tp->assign('send_result', $sendResult);
            }
            if (count($undeliveredMailingsInfo)) {
                $tp->assign("UndeliveredMailings", $oMailing->getUndeliveredMailingsInfo());
            }
        }
        // send mailing to undelivered
        $sendToUndeliveredMailingID = SJB_Request::getVar('sendToUndeliveredEmails', 0);
        if (!empty($sendToUndeliveredMailingID)) {
            $oMailing = new SJB_Mailing($sendToUndeliveredMailingID);
            $oMailing->setMailingList($mail_list);
            $oMailing->sendToUndelivered();
            if ($oMailing->getUndeliveredMailingsInfo()) {
                $tp->assign("UndeliveredMailings", $oMailing->getUndeliveredMailingsInfo());
            }
        }
        $groups = SJB_DB::query("SELECT * FROM `user_groups`");
        $products = SJB_ProductsManager::getAllProductsInfo();
        $testEmail = SJB_Settings::getSettingByName('test_email');
        $tp->assign('test_email', $testEmail);
        $tp->assign("products", $products);
        $tp->assign("groups", $groups);
        $tp->assign("mail_list", $mail_list);
        $tp->assign('errors', $errors);
        $tp->assign("uploadMaxFilesize", SJB_UploadFileManager::getIniUploadMaxFilesize());
        $tp->display("mailing.tpl");
    }
Ejemplo n.º 17
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);
 }
Ejemplo n.º 18
0
 public static function sendAdminUserContractExpiredLetter($userSID, $contractInfo, $productInfo)
 {
     $emailTplSID = SJB_Settings::getSettingByName('notify_on_user_contract_expiration');
     if ($emailTplSID) {
         $user = SJB_UserManager::getObjectBySID($userSID);
         $user = SJB_UserManager::createTemplateStructureForUser($user);
         $productInfo = array_merge($productInfo, SJB_ProductsManager::createTemplateStructureForProductForEmailTpl($productInfo));
         $params = array('user' => $user, 'contract' => $contractInfo, 'product' => $productInfo);
         $admin_email = SJB_Settings::getSettingByName('notification_email');
         $email = SJB_EmailTemplateEditor::getEmail($admin_email, $emailTplSID, $params);
         if ($email) {
             // notify subadmins
             $subAdminsToNotify = self::isSubAdminNotifiedOnUserContractExpiration($user['group']['id']);
             if (is_array($subAdminsToNotify)) {
                 foreach ($subAdminsToNotify as $subAdminEmail) {
                     $email->addCC($subAdminEmail);
                 }
             }
             return $email->send();
         }
     }
     return null;
 }
Ejemplo n.º 19
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);
 }
Ejemplo n.º 20
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');
     }
 }
Ejemplo n.º 21
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');
     }
 }
Ejemplo n.º 22
0
 private function canCurrentUserAddListing(&$error)
 {
     if (SJB_UserManager::isUserLoggedIn()) {
         $current_user = SJB_UserManager::getCurrentUser();
         if ($current_user->hasContract()) {
             $listing_type_id = SJB_Request::getVar('listing_type_id', false);
             $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 && $this->acl->isAllowed('post_' . $listing_type_id)) {
                 $productsInfo = array();
                 $is_contract = false;
                 foreach ($resultContractInfo as $contractInfo) {
                     if ($this->acl->isAllowed('post_' . $listing_type_id, $contractInfo['id'], 'contract')) {
                         $permissionParam = $this->acl->getPermissionParams('post_' . $listing_type_id, $contractInfo['id'], 'contract');
                         if (empty($permissionParam) || $this->acl->getPermissionParams('post_' . $listing_type_id, $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;
 }
Ejemplo 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");
 }
Ejemplo n.º 24
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $action = SJB_Request::getVar('action', 'search');
     $template = SJB_Request::getVar('template', 'listings_statistics.tpl');
     $errors = array();
     $userGroups = SJB_UserGroupManager::getAllUserGroupsIDsAndCaptions();
     foreach ($userGroups as $key => $userGroup) {
         unset($userGroups[$key]);
         $userGroups[$userGroup['id']] = $userGroup;
     }
     switch ($action) {
         case 'export':
             $period = SJB_Request::getVar('period', array());
             $filter = SJB_Request::getVar('filter', false);
             $listingTypeSID = SJB_Request::getVar('listingTypeSID', false);
             $listingTypeID = SJB_ListingTypeManager::getListingTypeIDBySID($listingTypeSID);
             $sorting_field = SJB_Request::getVar('sorting_field', 'total');
             $sorting_order = SJB_Request::getVar('sorting_order', 'DESC');
             $statistics = array();
             if ($filter) {
                 $statistics = SJB_Statistics::getListingsStatistics($period, $listingTypeSID, $filter, $sorting_field, $sorting_order);
                 if (!empty($statistics['errors'])) {
                     $errors = $statistics['errors'];
                 }
             } else {
                 $errors[] = 'EMPTY_PARAMETER';
             }
             $columnTitle = '';
             if (strstr($filter, 'userGroup_')) {
                 $userGroupSID = str_replace('userGroup_', '', $filter);
                 if ($userGroups[$userGroupSID]['key'] == 'Employer') {
                     $columnTitle = 'Company Name';
                 } else {
                     $columnTitle = $userGroups[$userGroupSID]['caption'] . ' Name';
                 }
             } else {
                 $fieldInfo = SJB_ListingFieldDBManager::getListingFieldInfoByID($filter);
                 $columnTitle = $fieldInfo['caption'];
             }
             if (!$errors && $statistics) {
                 $type = SJB_Request::getVar('type', 'csv');
                 $listingTypes = SJB_ListingTypeManager::getListingAllTypesForListType();
                 SJB_StatisticsExportController::createExportDirectory();
                 $exportProperties['title'] = $columnTitle;
                 $exportProperties['regular'] = '';
                 if ($listingTypeID == 'Job') {
                     $exportProperties['featured'] = '';
                 }
                 $exportProperties['priority'] = '';
                 $exportProperties['total'] = 'Total';
                 $exportProperties['percent'] = '%';
                 foreach ($listingTypes as $listingType) {
                     if ($listingType['id'] == $listingTypeSID) {
                         switch ($listingType['key']) {
                             case 'Job':
                                 $featuredTitle = "Number of Featured {$listingType['key']}s Posted";
                                 $exportProperties['featured'] = $featuredTitle;
                             case 'Resume':
                                 $regularTitle = "Number of Regular {$listingType['key']}s Posted";
                                 $exportProperties['regular'] = $regularTitle;
                                 $priorityTitle = "Number of Priority {$listingType['key']}s Posted";
                                 $exportProperties['priority'] = $priorityTitle;
                                 break;
                             default:
                                 $regularTitle = 'Number of Regular "' . $listingType['caption'] . '" Listings Posted';
                                 $exportProperties['regular'] = $regularTitle;
                                 $priorityTitle = 'Number of Priority "' . $listingType['caption'] . '" Listings Posted';
                                 $exportProperties['priority'] = $priorityTitle;
                                 break;
                         }
                     }
                 }
                 switch ($type) {
                     case 'csv':
                         $exportData = SJB_StatisticsExportController::getListingExportData($statistics, $listingTypeID);
                         $fileName = strtolower($listingTypeID) . '_statistics.csv';
                         SJB_StatisticsExportController::makeCSVExportFile($exportData, $fileName, "{$listingTypeID} Statistics");
                         SJB_StatisticsExportController::archiveAndSendExportFile(strtolower($listingTypeID) . '_statistics', 'csv');
                         break;
                     case 'xls':
                         $exportData = SJB_StatisticsExportController::getListingExportData($statistics, $listingTypeID);
                         $fileName = strtolower($listingTypeID) . '_statistics.xls';
                         SJB_StatisticsExportController::makeXLSExportFile($exportData, $fileName, "{$listingTypeID} Statistics");
                         SJB_StatisticsExportController::archiveAndSendExportFile(strtolower($listingTypeID) . '_statistics', 'xls');
                         break;
                 }
                 break;
             }
         case 'search':
             $search = SJB_Request::getVar('search', false);
             $period = SJB_Request::getVar('period', array());
             $filter = SJB_Request::getVar('filter', false);
             $listingTypeSID = SJB_Request::getVar('listingTypeSID', false);
             $sorting_field = SJB_Request::getVar('sorting_field', 'total');
             $sorting_order = SJB_Request::getVar('sorting_order', 'DESC');
             $statistics = array();
             if ($search) {
                 $i18n = SJB_I18N::getInstance();
                 $from = $i18n->getInput('date', $period['from']);
                 $to = $i18n->getInput('date', $period['to']);
                 if (!empty($period['from']) && !empty($period['to']) && strtotime($from) > strtotime($to)) {
                     $errors[] = 'SELECTED_PERIOD_IS_INCORRECT';
                 } else {
                     if ($filter) {
                         $statistics = SJB_Statistics::getListingsStatistics($period, $listingTypeSID, $filter, $sorting_field, $sorting_order);
                         if (!empty($statistics['errors'])) {
                             $errors = $statistics['errors'];
                         }
                     } else {
                         $errors[] = 'EMPTY_PARAMETER';
                     }
                 }
             }
             $columnTitle = '';
             if (strstr($filter, 'userGroup_')) {
                 $userGroupSID = str_replace('userGroup_', '', $filter);
                 if ($userGroups[$userGroupSID]['key'] == 'Employer') {
                     $columnTitle = 'Company Name';
                 } else {
                     $columnTitle = $userGroups[$userGroupSID]['caption'] . ' Name';
                 }
                 $tp->assign('link', 'user');
             } else {
                 if (in_array($filter, array('Location_Country', 'Location_State', 'Location_City'))) {
                     $fieldInfo = SJB_ListingFieldDBManager::getLocationFieldsInfoById($filter);
                 } else {
                     $fieldInfo = SJB_ListingFieldDBManager::getListingFieldInfoByID($filter);
                 }
                 $columnTitle = $fieldInfo['caption'];
             }
             $i18n = SJB_I18N::getInstance();
             $periodView = array();
             foreach ($period as $key => $value) {
                 $periodView[$key] = $i18n->getInput('date', $period[$key]);
             }
             $tp->assign('filter', $filter);
             $tp->assign('search', $search);
             $tp->assign('columnTitle', $columnTitle);
             $tp->assign('listingTypeSID', $listingTypeSID);
             $tp->assign('period', $period);
             $tp->assign('periodView', $periodView);
             $tp->assign('statistics', $statistics);
             $tp->assign('countResult', count($statistics));
             $tp->assign('sorting_field', $sorting_field);
             $tp->assign('sorting_order', $sorting_order);
             break;
     }
     $listingTypes = SJB_ListingTypeManager::getListingAllTypesForListType();
     $products = SJB_ProductsManager::getAllProductsInfo();
     $acl = SJB_Acl::getInstance();
     foreach ($listingTypes as $key => $listingType) {
         $userGroup = array();
         foreach ($products as $productInfo) {
             if ($acl->isAllowed('post_' . strtolower($listingType['key']), $productInfo['sid'], 'product') && !in_array($productInfo['user_group_sid'], $userGroup)) {
                 $userGroup[] = $productInfo['user_group_sid'];
             }
         }
         $listingTypes[$listingType['id']] = $listingType;
         $listingTypes[$listingType['id']]['userGroups'] = $userGroup;
         unset($listingTypes[$key]);
     }
     $tp->assign('userGroups', $userGroups);
     $tp->assign('listingTypes', $listingTypes);
     $tp->assign('errors', $errors);
     $tp->assign('action', $action);
     $tp->display($template);
 }
Ejemplo n.º 25
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);
 }
Ejemplo n.º 26
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;
 }
Ejemplo n.º 27
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');
 }
Ejemplo n.º 28
0
 public function saveProduct($product, $request = array())
 {
     $price = trim($product->getPropertyValue('price'));
     if (empty($price)) {
         $product->setPropertyValue('price', 0);
     }
     $product = $this->details->saveProduct($product, $request);
     SJB_ProductsManager::saveProduct($product);
     return $product;
 }
Ejemplo n.º 29
0
 /**
  * @param $userSID
  * @param $productSID
  * @param $limitCheckoutedListingsToDelete
  */
 public function deleteCheckoutedListingsByProduct($userSID, $productSID, $limitCheckoutedListingsToDelete)
 {
     $serializedProductSID = SJB_ProductsManager::generateQueryBySID($productSID);
     $listingsToDelete = SJB_DB::query("SELECT `sid` FROM `listings` WHERE `checkouted` = 0 AND `complete` = 1 AND `contract_id` = 0 AND `user_sid` = ?n AND `product_info` REGEXP '({$serializedProductSID})' ORDER BY `sid` DESC LIMIT ?n", $userSID, $limitCheckoutedListingsToDelete);
     $criteriaSaver = new SJB_ListingCriteriaSaver('MyListings');
     $foundListingsSIDs = $criteriaSaver->getObjectSIDs();
     foreach ($listingsToDelete as $listing) {
         SJB_ListingManager::deleteListingBySID($listing['sid']);
         if ($foundListingsSIDs != null) {
             $key = array_search($listing['sid'], $foundListingsSIDs);
             unset($foundListingsSIDs[$key]);
         }
     }
     if ($foundListingsSIDs != null) {
         $criteriaSaver->setSessionForObjectSIDs($foundListingsSIDs);
     }
 }
Ejemplo n.º 30
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');
    }