/**
  * returns current active language id
  * @return mixed
  */
 function execute()
 {
     $existLanguage = $this->fetchExistLanguage();
     if ($existLanguage !== $this->context->getLang()) {
         $this->context->setLang($existLanguage);
         $theme = $this->context->getTheme();
         if (!empty($theme)) {
             $this->session->setValue('CURRENT_THEME', $theme);
         }
     }
     return $this->context->getLang();
 }
Example #2
0
 private function processingMobileVersion($tp)
 {
     if (!SJB_Session::getValue('cookiePreferencesAlreadyShown')) {
         $_COOKIE['cookiePreferences'] = 'Advertising';
         setcookie('cookiePreferences', 'Advertising', time() + 30 * 24 * 3600, '/');
     }
     $refererUri = SJB_Request::getVar('HTTP_REFERER', null, 'SERVER');
     if ($refererUri) {
         $refererUri = parse_url($refererUri);
     }
     if ($refererUri && SJB_System::getURI() != '/' . basename($refererUri['path']) . '/') {
         SJB_Session::setValue('cookiePreferencesMobileReferer', SJB_Request::getVar('HTTP_REFERER', SJB_System::getSystemSettings('SITE_URL'), 'SERVER'));
     }
     if (SJB_Request::getVar('cookiePreferencesSave', false, 'POST')) {
         if (!SJB_Request::getVar('Functional', false, 'POST')) {
             $_COOKIE['cookiePreferences'] = 'System';
             setcookie('cookiePreferences', 'System', time() + 30 * 24 * 3600, '/');
         } else {
             if (!SJB_Request::getVar('Advertising', false, 'POST')) {
                 $_COOKIE['cookiePreferences'] = 'Functional';
                 setcookie('cookiePreferences', 'Functional', time() + 30 * 24 * 3600, '/');
             } else {
                 $_COOKIE['cookiePreferences'] = 'Advertising';
                 setcookie('cookiePreferences', 'Advertising', time() + 30 * 24 * 3600, '/');
             }
         }
     }
     $tp->assign('mobileVersion', true);
 }
Example #3
0
 /**
  * logging administrator out of system
  *
  * Function logs administrator out of system
  */
 public static function admin_log_out()
 {
     SJB_Session::unsetValue('username');
     SJB_Session::unsetValue('usertype');
     SJB_Session::unsetValue('adminLoginCounter');
     setcookie("admin_mode", '', time() - 3600, '/');
 }
Example #4
0
 static function logout()
 {
     SessionStorage::destroy(SJB_Session::getSessionId());
     $forumPath = SJB_Settings::getSettingByName('forum_path');
     if (empty($forumPath)) {
         return;
     }
     $url = SJB_System::getSystemSettings('SITE_URL') . $forumPath . '/';
     $client = new Zend_Http_Client($url, array('useragent' => SJB_Request::getUserAgent()));
     $client->setCookie($_COOKIE);
     $client->setCookieJar();
     try {
         $response = $client->request();
         $matches = array();
         if (preg_match('/\\.\\/ucp.php\\?mode=logout\\&sid=([\\w\\d]+)"/', $response->getBody(), $matches)) {
             $sid = $matches[1];
             $client->setUri($url . 'ucp.php?mode=logout&sid=' . $sid);
             $response = $client->request();
             foreach ($response->getHeaders() as $key => $header) {
                 if ('set-cookie' == strtolower($key)) {
                     if (is_array($header)) {
                         foreach ($header as $val) {
                             header("Set-Cookie: " . $val, false);
                         }
                     } else {
                         header("Set-Cookie: " . $header, false);
                     }
                 }
             }
         }
     } catch (Exception $ex) {
     }
 }
Example #5
0
    public function doBackup()
    {
        $settings = SJB_Settings::getSettings();
        if ($settings['autobackup'] && !SJB_System::getSystemSettings('isDemo') && !SJB_System::getIfTrialModeIsOn()) {
            $dirSeparator = DIRECTORY_SEPARATOR;
            $scriptPath = explode(SJB_System::getSystemSettings('SYSTEM_URL_BASE'), __FILE__);
            $scriptPath = array_shift($scriptPath);
            $path = $scriptPath . 'backup' . $dirSeparator;
            $identifier = time();
            $backupsArr = $this->getAllBackups($path);
            $this->deleteBackupAfterExpired($backupsArr);
            if ($this->isAutobackup()) {
                SessionStorage::destroy('backup_' . $identifier);
                SessionStorage::write('backup_' . $identifier, serialize(array('last_time' => time())));
                SJB_Session::unsetValue('restore');
                SJB_Session::unsetValue('error');
                $backupDir = $scriptPath . 'backup' . $dirSeparator;
                if (!is_dir($backupDir)) {
                    mkdir($backupDir);
                }
                if (!file_exists($backupDir . '.htaccess')) {
                    $handle = fopen($backupDir . '.htaccess', 'a');
                    $text = '# Apache 2.4
<IfModule mod_authz_core.c>
	<FilesMatch ".*">
		Require all denied
	</FilesMatch>
</IfModule>

# Apache 2.2
<IfModule !mod_authz_core.c>
	<FilesMatch ".*">
		Order Allow,Deny
		Deny from all
	</FilesMatch>
</IfModule>';
                    fwrite($handle, $text);
                    fclose($handle);
                }
                $backupType = SJB_System::getSettingByName('backup_type');
                switch ($backupType) {
                    case 'full':
                        $this->makeFullBackup($identifier, $scriptPath, $dirSeparator);
                        break;
                    case 'database':
                        $this->makeDatabaseBackup($identifier, $dirSeparator, $scriptPath);
                        break;
                    case 'files':
                        $this->makeFilesBackup($identifier, $scriptPath, $dirSeparator);
                        break;
                }
                SJB_Settings::updateSetting('last_autobackup', date("Y-m-d H:i:s"));
            }
        }
    }
 public function execute()
 {
     if (class_exists('SJB_SocialPlugin') && in_array('linkedin', SJB_SocialPlugin::getAvailablePlugins()) && SJB_Settings::getSettingByName('li_allowPeopleSearch')) {
         $liSearch = SJB_Request::getVar('li_search', false);
         $oLinkedin = SJB_SocialPlugin::getActiveSocialPlugin();
         if ('Resume' == $_REQUEST['listing_type']['equal'] && $liSearch && $oLinkedin instanceof LinkedinSocialPlugin) {
             SJB_Session::setValue('linkedinPeopleSearch', true);
             $request =& $_REQUEST;
             /*
              * keywords=[space delimited keywords]
              * sort=[connections|recommenders|distance|relevance]
              * postal-code=[postal code]
              * start=[number]& count=[1-25]&  facet=[facet code, values]& facets=[facet
              *
              * info:
              * http://developer.linkedin.com/docs/DOC-1191
              */
             $sKeywords = '';
             $sZip = !empty($request['ZipCode']['geo']['location']) ? $request['ZipCode']['geo']['location'] : '';
             $aIndustry = !empty($request['JobCategory']['multi_like']) ? $request['JobCategory']['multi_like'] : array();
             $sIndustry = '';
             $sCount = !empty($request['count']) ? (int) $request['count'] : 10;
             if (!empty($request['keywords']) && is_array($request['keywords'])) {
                 foreach ($request['keywords'] as $keywords) {
                     $sKeywords = $keywords;
                 }
             }
             $aFields = array('keywords' => $sKeywords, 'postal-code' => $sZip, 'count' => $sCount);
             foreach ($aIndustry as $industryName) {
                 if ($industryKey = SJB_LinkedinFields::getIndustryCodeByIndustryName($industryName)) {
                     $sIndustry .= ',' . $industryKey;
                 }
             }
             if (!empty($sIndustry)) {
                 $aFields['facets'] = 'industry';
                 $aFields['facet'] = 'industry' . $sIndustry;
             }
             $liResults = $oLinkedin->peopleSearch($aFields);
             if (isset($liResults->{'num-results'}) && (int) $liResults->{'num-results'} >= 0) {
                 $tp = SJB_System::getTemplateProcessor();
                 if (empty($sKeywords)) {
                     $tp->assign('liKeywordEmpty', true);
                 }
                 $tp->assign('liResults', $oLinkedin->preparePeopleStructure($liResults));
                 $tp->assign('liNumResults', (int) $liResults->{'num-results'});
                 $tp->assign('linkedinSearchIsAllowed', true);
                 $linkedinPeopleSearch = SJB_Session::getValue('linkedinPeopleSearch');
                 $tp->assign('linkedinSearch', !empty($linkedinPeopleSearch) && 'no' === $linkedinPeopleSearch && !empty($_GET['searchId']) ? 'notChecked' : 'no');
                 $tp->display('linkedin_people_search_results.tpl');
             }
         } else {
             SJB_Session::setValue('linkedinPeopleSearch', 'no');
         }
     }
 }
Example #7
0
 public function execute()
 {
     $action = SJB_Request::getVar('action');
     $sessionUpdateData = SJB_Session::getValue(self::SESSION_UPDATE_TAG);
     if ($action == 'mark_as_closed') {
         if (is_array($sessionUpdateData)) {
             $sessionUpdateData['closed_by_user'] = true;
             SJB_Session::setValue(self::SESSION_UPDATE_TAG, $sessionUpdateData);
         }
         exit;
     }
     // check updates
     $serverUrl = SJB_System::getSystemSettings('SJB_UPDATE_SERVER_URL');
     $version = SJB_System::getSystemSettings('version');
     // CHECK FOR UPDATES
     $updateInfo = SJB_Session::getValue(self::SESSION_UPDATE_TAG);
     if (empty($updateInfo)) {
         // check URL for accessibility
         $ch = curl_init($serverUrl);
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_exec($ch);
         $urlInfo = curl_getinfo($ch);
         $availableVersion = array();
         $updateStatus = '';
         if ($urlInfo['http_code'] > 0) {
             // OK. Url is accessible - lets get update info
             try {
                 $client = new Zend_Rest_Client($serverUrl);
                 $result = $client->isUpdateAvailable($version['major'], $version['minor'], $version['build'], SJB_System::getSystemSettings('USER_SITE_URL'))->get();
                 if ($result->isSuccess()) {
                     $updateStatus = (string) $result->updateStatus;
                     switch ($updateStatus) {
                         case 'available':
                             $availableVersion = array('major' => (string) $result->version->major, 'minor' => (string) $result->version->minor, 'build' => (string) $result->version->build);
                             break;
                     }
                 }
             } catch (Exception $e) {
                 SJB_Error::writeToLog('Update Check: ' . $e->getMessage());
             }
         }
         $updateInfo = array('availableVersion' => $availableVersion, 'updateStatus' => $updateStatus);
         SJB_Session::setValue(self::SESSION_UPDATE_TAG, $updateInfo);
     } else {
         if (isset($updateInfo['availableVersion']) && !empty($updateInfo['availableVersion'])) {
             if ($updateInfo['availableVersion']['build'] <= $version['build']) {
                 $updateInfo = array('availableVersion' => $updateInfo['availableVersion'], 'updateStatus' => 'none');
             }
         }
     }
     echo json_encode($updateInfo);
     exit;
 }
Example #8
0
 public static function getProductsInfoAlreadyCheckedForGuest()
 {
     $serializedProductsInfo = SJB_Session::getValue('products');
     $alreadyCheckedProducts = array();
     if (is_array($serializedProductsInfo)) {
         foreach ($serializedProductsInfo as $serializedInfo) {
             array_push($alreadyCheckedProducts, unserialize($serializedInfo['product_info']));
         }
     }
     return $alreadyCheckedProducts;
 }
Example #9
0
 public static function init($url)
 {
     // get setting from config.php
     $storageType = SJB_System::getSystemSettings('SESSION_STORAGE');
     if ($storageType != 'files') {
         $sessionStorage = new SessionStorage();
         session_set_save_handler(array($sessionStorage, 'open'), array($sessionStorage, 'close'), array($sessionStorage, 'read'), array($sessionStorage, 'write'), array($sessionStorage, 'destroy'), array($sessionStorage, 'gc'));
     }
     $path = SJB_Session::getSessionCookiePath();
     SJB_WrappedFunctions::ini_set('session.cookie_path', $path);
     Zend_Session::start();
     self::identificationUserSign();
 }
Example #10
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $errors = array();
     $activated = SJB_Request::getVar('account_activated', '') == 'yes';
     if (SJB_Request::getVar('returnToShoppingCart', false)) {
         SJB_Session::setValue('fromAnonymousShoppingCart', 1);
     }
     if (!$activated) {
         if (!isset($_REQUEST['username'], $_REQUEST['activation_key'])) {
             $errors['PARAMETERS_MISSED'] = 1;
         } elseif (!($userInfo = SJB_UserManager::getUserInfoByUserName($_REQUEST['username']))) {
             $errors['USER_NOT_FOUND'] = 1;
         } elseif ($userInfo['activation_key'] != $_REQUEST['activation_key']) {
             $errors['INVALID_ACTIVATION_KEY'] = true;
         } elseif ($userInfo['approval'] == 'Rejected') {
             SJB_UserDBManager::deleteActivationKeyByUsername($_REQUEST['username']);
             SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/system/users/activate_account/?account_activated=no&approval_status=Rejected');
         } else {
             if (SJB_UserManager::activateUserByUserName($_REQUEST['username'])) {
                 SJB_UserDBManager::deleteActivationKeyByUsername($_REQUEST['username']);
                 if (!SJB_Authorization::isUserLoggedIn()) {
                     SJB_Authorization::login($_REQUEST['username'], false, false, $errors, true, true);
                     if (!SJB_SocialPlugin::getProfileSocialID($userInfo['sid'])) {
                         SJB_Notifications::sendUserWelcomeLetter($userInfo['sid']);
                     }
                     $requireApprove = SJB_UserGroupManager::isApproveByAdmin($userInfo['user_group_sid']);
                     if ($requireApprove && !empty($userInfo['approval'])) {
                         $approvalStatus = $userInfo['approval'];
                     } else {
                         $userGroupInfo = SJB_UserGroupManager::getUserGroupInfoBySID($userInfo['user_group_sid']);
                         $pageId = !empty($userGroupInfo['after_registration_redirect_to']) ? $userGroupInfo['after_registration_redirect_to'] : '';
                         $redirectUrl = SJB_UserGroupManager::getRedirectUrlByPageID($pageId);
                         SJB_HelperFunctions::redirect($redirectUrl . 'account_activated=yes');
                     }
                 }
                 $activated = 1;
             } else {
                 $errors['CANNOT_ACTIVATE'] = TRUE;
             }
         }
     }
     $tp->assign('activated', $activated);
     $tp->assign('errors', $errors);
     $tp->assign('approvalStatus', !empty($approvalStatus) ? $approvalStatus : SJB_Request::getVar('approval_status', ''));
     $tp->assign('isLoggedIn', SJB_Authorization::isUserLoggedIn());
     $tp->display('activate_account.tpl');
 }
Example #11
0
 function isValid()
 {
     $property_info = $this->property_info;
     $property_info['type'] = 'kCaptcha';
     SJB_Event::dispatch('captchaValidation', $property_info, true);
     if ($property_info['type'] == 'kCaptcha') {
         $this->captchaImg = SJB_Session::getValue('captcha_keystring');
         if ($this->captchaImg != $this->property_info['value']) {
             return 'NOT_VALID';
         }
     } else {
         if ($property_info === false) {
             return 'NOT_VALID';
         }
     }
     return true;
 }
Example #12
0
 /**
  * @param $feedSID
  * @param string $accountId
  * @return array|null
  */
 public function saveAccountInfo($feedSID, $accountId)
 {
     self::$object = new SJB_LinkedIn($this->createCallbackUrl());
     $accessToken = self::$object->_getAccessToken();
     $liveTime = isset($accessToken->_params['oauth_expires_in']) ? $accessToken->_params['oauth_expires_in'] : 60 * 24 * 60 * 60;
     $expirationDate = date('Y-m-d', time() + $liveTime);
     $accessToken = serialize($accessToken);
     if (!empty($accountId)) {
         $result = SJB_DB::query('UPDATE `linkedin_feeds` SET `access_token` = ?s, expiration_date = ?s, `account_id` = ?s WHERE `sid` = ?n OR `access_token` = ?s', $accessToken, $expirationDate, $accountId, $feedSID, $accessToken);
     } else {
         $result = SJB_DB::query('UPDATE `linkedin_feeds` SET `access_token` = ?s, expiration_date = ?s WHERE `sid` = ?n OR `access_token` = ?s', $accessToken, $expirationDate, $feedSID, $accessToken);
     }
     if ($result) {
         self::$object->setAccessToken(null);
         SJB_Session::unsetValue(self::NETWORK_ID);
     }
     return $result;
 }
Example #13
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $currentUser = SJB_UserManager::getCurrentUser();
     $products = array();
     if (!empty($_SESSION['products'])) {
         $products = $_SESSION['products'];
     }
     if (SJB_UserManager::isUserLoggedIn()) {
         foreach ($products as $product) {
             if (!empty($product['product_info'])) {
                 $productInfo = unserialize($product['product_info']);
                 if ($currentUser->getUserGroupSID() != $productInfo['user_group_sid']) {
                     SJB_Session::unsetValue('products');
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/shopping-cart/?error=user_group");
                 } else {
                     SJB_ShoppingCart::addToShoppingCart($productInfo, $currentUser->getSID());
                 }
             }
         }
         SJB_Session::unsetValue('products');
         $products = SJB_ShoppingCart::getAllProductsByUserSID($currentUser->getSID());
     }
     $total_price = 0;
     foreach ($products as $product) {
         $productInfo = unserialize($product['product_info']);
         $product = new SJB_Product($productInfo, $productInfo['product_type']);
         $number_of_listings = !empty($productInfo['number_of_listings']) ? $productInfo['number_of_listings'] : 1;
         $product->setNumberOfListings($number_of_listings);
         $productInfo['price'] = $product->getPrice();
         $total_price += $productInfo['price'];
         if ($productInfo['pricing_type'] != 'volume_based' && $productInfo['code_info']) {
             $total_price += $productInfo['code_info']['promoAmount'];
         }
     }
     $tp->assign('products_number', count($products));
     $tp->assign('total_price', $total_price);
     $tp->assign("currency", SJB_CurrencyManager::getDefaultCurrency());
     $tp->display('show_shopping_cart.tpl');
 }
Example #14
0
 public function execute()
 {
     $action = SJB_Request::getVar('action', '');
     $tp = SJB_System::getTemplateProcessor();
     $errors = array();
     $formSubmitted = !empty($action) ? true : false;
     $adminCurrentDetails = SJB_AdminPasswordManager::getCurrentAdminDetails();
     $adminDetails = array_merge($adminCurrentDetails, $_REQUEST);
     $admin = new SJB_AdminPassword($adminDetails);
     $admin->setSID($adminCurrentDetails['sid']);
     $adminPasswordForm = new SJB_Form($admin);
     $adminPasswordForm->registerTags($tp);
     $formFields = $adminPasswordForm->getFormFieldsInfo();
     if ($formSubmitted) {
         if (SJB_System::getSystemSettings("isDemo")) {
             $errors['PERMISSION_DENIED'] = "You don't have permissions for it. This is a Demo version of the software.";
         } else {
             if ($action == 'change_admin_account' && $adminPasswordForm->isDataValid($errors)) {
                 $oldPassword = $admin->getPropertyValue('password');
                 $newPassword = SJB_AdminPasswordManager::getNewPasswordValue($adminDetails);
                 if ($adminCurrentDetails['password'] != md5($oldPassword)) {
                     $errors['Password'] = '******';
                 } else {
                     if ($newPassword) {
                         $admin->setPropertyValue('password', $newPassword);
                     }
                     $admin->deleteProperty('new_password');
                     SJB_AdminPasswordManager::saveAdmin($admin);
                     SJB_Session::setValue('username', $admin->getPropertyValue('username'));
                 }
             }
         }
     }
     $tp->assign('action', $action);
     $tp->assign('errors', $errors);
     $tp->assign('adminInfo', SJB_AdminPasswordManager::getCurrentAdminDetails());
     $tp->assign("form_fields", $formFields);
     $tp->display("adminpswd.tpl");
 }
Example #15
0
 public function getAccessToken($feedSID = null, $action = null, &$errors)
 {
     SJB_Session::setValue('twitterFeed', serialize($_REQUEST));
     if ($feedSID != null) {
         $feedInfo = SJB_SocialMedia::getFeedInfoByNetworkIdAndSID(self::NETWORK_ID, $feedSID);
     }
     if ($action != 'grant') {
         $feedInfo['consumerKey'] = SJB_Request::getVar('consumerKey');
         $feedInfo['consumerSecret'] = SJB_Request::getVar('consumerSecret');
         $feedInfo['account_id'] = SJB_Request::getVar('account_id');
     }
     $config = array('callbackUrl' => self::getCallBackUrl($feedSID, $action, SJB_Request::getVar('submit')), 'siteUrl' => 'http://twitter.com/oauth', 'consumerKey' => $feedInfo['consumerKey'], 'consumerSecret' => $feedInfo['consumerSecret'], 'requestTokenUrl' => 'https://api.twitter.com/oauth/request_token', 'userAuthorizationUrl' => 'https://api.twitter.com/oauth/authorize', 'accessTokenUrl' => 'https://api.twitter.com/oauth/access_token');
     $consumer = new Zend_Oauth_Consumer($config);
     $client = new Zend_Http_Client();
     $client->setConfig(array('sslcert' => 'cacert.pem'));
     $consumer->setHttpClient($client);
     $sessionTwitterRequestToken = SJB_Session::getValue('TWITTER_REQUEST_TOKEN');
     if (SJB_Request::getVar('process_token', false) && !is_null($sessionTwitterRequestToken)) {
         $accessToken = $consumer->getAccessToken($_GET, unserialize($sessionTwitterRequestToken));
         $feedInfo['access_token'] = $accessToken;
         $twitter = self::getZendServiceTwitter($feedInfo, $accessToken);
         $response = $twitter->account->accountVerifyCredentials()->toValue();
         if (!empty($response->screen_name) && strtolower($response->screen_name) == strtolower($feedInfo['account_id'])) {
             return $accessToken;
         } else {
             $errors[] = 'Twitter account verification failed';
             return false;
         }
     } else {
         if ($requestToken = $consumer->getRequestToken()) {
             SJB_Session::setValue('TWITTER_REQUEST_TOKEN', serialize($requestToken));
             $consumer->redirect();
         } else {
             $errors[] = 'Could not retrieve a valid Token. Please check "Consumer Key" and "Consumer secret"';
             return false;
         }
     }
 }
Example #16
0
 public static function copyFilesAndPicturesFromListing($srcListingSid, $dstListingSid, $tmpListingSid)
 {
     $listing = SJB_ListingManager::getObjectBySID($srcListingSid);
     if ($listing) {
         foreach ($listing->getProperties() as $listingProperty) {
             if ($listingProperty->getType() == 'complex') {
                 self::copyComplexFiles($dstListingSid, $listingProperty);
             } elseif (in_array($listingProperty->getType(), array('file', 'video'))) {
                 self::copyFiles($dstListingSid, $listingProperty);
             }
         }
     }
     if ($tmpListingSid) {
         $gallery = new SJB_ListingGallery();
         $gallery->setListingSID($tmpListingSid);
         $numberOfPictures = $gallery->getPicturesAmount();
         if ($numberOfPictures != 0) {
             $picturesInfo = $gallery->getPicturesInfo();
             $gallery->setListingSID($dstListingSid);
             $gallery->deleteImages();
             foreach ($picturesInfo as $pictureInfo) {
                 $gallery->uploadImage($pictureInfo['picture_url'], $pictureInfo['caption']);
             }
         }
     }
     SJB_Session::unsetValue('tmp_file_storage');
     SJB_ListingDBManager::setListingExpirationDateBySid($dstListingSid);
 }
Example #17
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     if (isset($_REQUEST['listing_type_id'])) {
         $listing_type_id = $_REQUEST['listing_type_id'];
         SJB_Session::setValue('listing_type_id', $listing_type_id);
     } elseif (isset($_REQUEST['restore'])) {
         $listing_type_id = SJB_Session::getValue('listing_type_id');
     } else {
         SJB_Session::setValue('listing_type_id', null);
     }
     $listing_type_sid = 0;
     if (!empty($listing_type_id)) {
         $listing_type_sid = SJB_ListingTypeManager::getListingTypeSIDByID($listing_type_id);
     }
     if (!isset($_REQUEST['listing_type']['equal']) && isset($listing_type_id)) {
         $_REQUEST['listing_type']['equal'] = $listing_type_id;
     }
     if (isset($_REQUEST['searchId'])) {
         $criteria_saver = new SJB_ListingCriteriaSaver($_REQUEST['searchId']);
         $_REQUEST = array_merge($_REQUEST, $criteria_saver->getCriteria());
     }
     $empty_listing = new SJB_Listing(array(), $listing_type_sid);
     $empty_listing->addIDProperty();
     $empty_listing->addActivationDateProperty();
     $empty_listing->addUsernameProperty();
     $empty_listing->addKeywordsProperty();
     $empty_listing->addPicturesProperty();
     $empty_listing->addListingTypeIDProperty();
     $empty_listing->addPostedWithinProperty();
     $search_form_builder = new SJB_SearchFormBuilder($empty_listing);
     $criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($_REQUEST);
     $properties = $empty_listing->getProperties();
     foreach ($properties as $propertyName => $property) {
         if ($property->getType() == 'location') {
             $propertyInfo = $property->type->property_info;
             if ($propertyInfo['enable_search_by_radius'] == 1) {
                 if (!isset($criteria['system'][$propertyName])) {
                     $value = array('value' => '', 'radius' => '10');
                     $criterion = SJB_SearchCriterion::getCriterionByType('location');
                     $criterion->setProperty($property);
                     $criterion->setPropertyName($propertyName);
                     $criterion->setValue($value);
                     $criteria['system'][$propertyName][] = $criterion;
                 }
             }
         }
     }
     $search_form_builder->setCriteria($criteria);
     $search_form_builder->registerTags($tp);
     $form_fields = $search_form_builder->getFormFieldsInfo();
     $metaDataProvider = SJB_ObjectMother::getMetaDataProvider();
     $template = SJB_Request::getVar('form_template', 'search_form.tpl');
     $formBuilder = SJB_FormBuilderManager::getFormBuilder(SJB_FormBuilderManager::FORM_BUILDER_TYPE_SEARCH, $listing_type_id);
     $formBuilder->setChargedTemplateProcessor($tp);
     if ($template == 'quick_search.tpl') {
         $fieldSID = SJB_ListingFieldManager::getListingFieldSIDByID('Location');
         if ($fieldSID) {
             $fields = SJB_ListingFieldManager::getFieldInfoBySID($fieldSID);
             if (!empty($fields['fields'])) {
                 foreach ($fields['fields'] as $field) {
                     $form_fields[$fields['id'] . '_' . $field['id']] = $field;
                 }
             }
             $tp->assign('locationFields', array($fields));
         }
     }
     $tp->assign('form_fields', $form_fields);
     $tp->assign('METADATA', array('form_fields' => $metaDataProvider->getFormFieldsMetadata($form_fields)));
     $tp->display($template);
 }
Example #18
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");
 }
Example #19
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $listingTypeID = SJB_Request::getVar('listing_type_id');
     $listingTypeSID = SJB_Request::getVar('listing_type');
     if ($listingTypeID !== null) {
         $listingTypeSID = SJB_ListingTypeManager::getListingTypeSIDByID($listingTypeID);
     }
     // SET PAGINATION AND SORTING VALUES
     $restore = SJB_Request::getVar('restore', false);
     $paginator = new SJB_FlaggedListingsPagination();
     // FILTERS
     $filters = array();
     $filters['title'] = SJB_Request::getVar('filter_title');
     $filters['username'] = SJB_Request::getVar('filter_user');
     $filters['flag'] = SJB_Request::getVar('filter_flag');
     // check session for pagination settings
     $sessionFlaggedSettings = !is_null(SJB_Session::getValue('flagged_settings')) ? SJB_Session::getValue('flagged_settings') : false;
     if ($sessionFlaggedSettings !== false) {
         if (!$restore) {
             SJB_Session::setValue('flagged_settings', array('filters' => $filters));
         } else {
             if (!$listingTypeSID && !empty($sessionFlaggedSettings['listing_type_sid'])) {
                 $listingTypeSID = $sessionFlaggedSettings['listing_type_sid'];
             }
             $filters = $sessionFlaggedSettings['filters'];
         }
     } else {
         SJB_Session::setValue('flagged_settings', array('filters' => $filters));
     }
     // DEFAULT SORTING
     // resolve flag to it text value for search
     $filterFlag = $filters['flag'];
     if (!empty($filterFlag) && is_numeric($filterFlag)) {
         $result = SJB_DB::query('SELECT * FROM `flag_listing_settings` WHERE `sid` = ?n LIMIT 1', $filterFlag);
         if (!empty($result)) {
             $filters['flag_reason'] = $result[0]['value'];
         }
     }
     //////////////////////  ACTIONS
     $action = SJB_Request::getVar('action_name');
     $flagSIDs = SJB_Request::getVar('flagged');
     if (!empty($flagSIDs)) {
         switch ($action) {
             case 'remove':
                 foreach ($flagSIDs as $sid => $val) {
                     SJB_ListingManager::removeFlagBySID($sid);
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/flagged-listings/?page=1');
                 break;
             case 'deactivate':
                 foreach ($flagSIDs as $sid => $val) {
                     SJB_ListingManager::deactivateListingByFlagSID($sid);
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/flagged-listings/?page=1');
                 break;
             case 'delete':
                 foreach ($flagSIDs as $sid => $val) {
                     SJB_ListingManager::deleteListingByFlagSID($sid);
                 }
                 SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/flagged-listings/?page=1');
                 break;
         }
     }
     //////////////////////// OUTPUT
     $allListingTypes = SJB_ListingTypeManager::getAllListingTypesInfo();
     $allFlags = SJB_ListingManager::getAllFlags();
     $countFlaggedListings = SJB_ListingManager::getFlagsNumberByListingTypeSID($listingTypeSID, $filters);
     $paginator->setItemsCount($countFlaggedListings);
     $flaggedListings = SJB_ListingManager::getFlaggedListings($listingTypeSID, $paginator->currentPage, $paginator->itemsPerPage, $paginator->sortingField, $paginator->sortingOrder, $filters);
     if (empty($flaggedListings) && $paginator->currentPage != 1) {
         SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/flagged-listings/?page=1');
     }
     foreach ($flaggedListings as $key => $val) {
         $listingInfo = SJB_ListingManager::getListingInfoBySID($val['listing_sid']);
         $listingUser = SJB_UserManager::getUserInfoBySID($listingInfo['user_sid']);
         $flaggedUser = SJB_UserManager::getUserInfoBySID($val['user_sid']);
         $flaggedListings[$key]['listing_info'] = $listingInfo;
         $flaggedListings[$key]['user_info'] = $listingUser;
         $flaggedListings[$key]['flagged_user'] = $flaggedUser;
     }
     $tp->assign('paginationInfo', $paginator->getPaginationInfo());
     $tp->assign('listing_types', $allListingTypes);
     $tp->assign('listings', $flaggedListings);
     $tp->assign('listing_type_sid', $listingTypeSID);
     $tp->assign('all_flags', $allFlags);
     $tp->assign('filters', $filters);
     $tp->display('flagged_listings.tpl');
 }
Example #20
0
 public function execute()
 {
     $logged_in = false;
     $tp = SJB_System::getTemplateProcessor();
     $shoppingCart = SJB_Request::getVar('shopping_cart', false);
     $proceedToPosting = SJB_Request::getVar('proceed_to_posting', false);
     $productSID = SJB_Request::getVar('productSID', false);
     $listingTypeID = SJB_Request::getVar('listing_type_id', false);
     $errors = array();
     if (SJB_Authorization::isUserLoggedIn() && !isset($_REQUEST['as_user'])) {
         $tp->display('already_logged_in.tpl');
     } else {
         $template = SJB_Request::getVar('template', 'login.tpl');
         $page_config = SJB_System::getPageConfig(SJB_System::getURI());
         if (SJB_Request::getVar('action', false) == 'login') {
             $username = SJB_Request::getVar('username');
             $password = SJB_Request::getVar('password');
             $keep_signed = SJB_Request::getVar('keep', false);
             $login_as_user = false;
             if (isset($_REQUEST['as_user'])) {
                 $login_as_user = true;
                 if (SJB_UserManager::getCurrentUserSID()) {
                     SJB_Authorization::logout();
                 }
             }
             // redirect user to the home page if it's login page or to the same page otherwise
             if (SJB_Request::getVar('return_url', false) != false) {
                 $redirect_url = base64_decode(SJB_Request::getVar('return_url'));
                 if (!empty($proceedToPosting)) {
                     $redirect_url .= '&proceed_to_posting=1&productSID=' . $productSID;
                 }
             } else {
                 if ($page_config->module == 'users' && $page_config->function == 'login') {
                     $redirect_url = SJB_System::getSystemSettings("SITE_URL") . "/my-account/";
                 } else {
                     $redirect_url = SJB_System::getSystemSettings("SITE_URL") . SJB_System::getURI();
                 }
             }
             if (SJB_UserManager::getCurrentUserSID()) {
                 $logged_in = true;
             } else {
                 SJB_UserManager::login($username, $password, $errors, false, $login_as_user);
                 if ($errors) {
                     if (is_null(SJB_Session::getValue('userLoginCounter'))) {
                         SJB_Session::setValue('userLoginCounter', 1);
                     } else {
                         SJB_Session::setValue('userLoginCounter', SJB_Session::getValue('userLoginCounter') + 1);
                     }
                 }
                 if (SJB_Captcha::getInstance($tp, $_REQUEST)->isValid($errors) && empty($errors)) {
                     $logged_in = SJB_Authorization::login($username, $password, $keep_signed, $errors, $login_as_user);
                 }
             }
             if ($logged_in && !$shoppingCart) {
                 SJB_HelperFunctions::redirect($redirect_url);
             }
             $tp->assign('logged_in', $logged_in);
         }
         $return_url = SJB_Request::getVar('return_url', $page_config->function != 'login' && $page_config->function != 'search_form' ? base64_encode(SJB_Navigator::getURIThis()) : false);
         if (!filter_var(SJB_System::getSystemSettings("SITE_URL") . base64_decode($return_url), FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) {
             $return_url = '';
         }
         $tp->assign('shopping_cart', $shoppingCart);
         $tp->assign('proceedToPosting', $proceedToPosting);
         $tp->assign('productSID', $productSID);
         $tp->assign('listingTypeID', $listingTypeID);
         $tp->assign('return_url', $return_url);
         $tp->assign('ajaxRelocate', SJB_Request::getVar('ajaxRelocate', false));
         $tp->assign('errors', $errors);
         $tp->assign('adminEmail', SJB_System::getSettingByName('system_email'));
         $tp->display($template);
     }
 }
Example #21
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');
     }
 }
Example #22
0
 public function execute()
 {
     ini_set('max_execution_time', 0);
     $errors = array();
     $tp = SJB_System::getTemplateProcessor();
     $action = SJB_Request::getVar('action', false);
     $dir_separator = DIRECTORY_SEPARATOR;
     $script_path = explode(SJB_System::getSystemSettings('SYSTEM_URL_BASE'), __FILE__);
     $script_path = array_shift($script_path);
     $identifier = SJB_Request::getVar('identifier', time());
     $filename = SJB_Request::getVar('filename', false);
     $settings = array();
     if ($filename) {
         SJB_Backup::sendArchiveFile($filename, $script_path . 'backup' . $dir_separator . $filename);
     }
     if (SJB_Request::getVar('action') == "save") {
         $expPeriod = SJB_Request::getVar('backup_expired_period');
         if (!empty($expPeriod) && (!is_numeric($expPeriod) || $expPeriod < 0)) {
             $errors[] = 'EXP_PERIOD_NOT_VALID';
         }
         $ftpValid = $this->isFTPDataValid();
         if (SJB_Request::getVar('autobackup', false) && SJB_Request::getVar('ftp_backup', false) && !$ftpValid) {
             $errors[] = 'FTP_DETAILS_NOT_VALID';
         }
         if (empty($errors)) {
             $backupSettings = $_REQUEST;
             foreach ($backupSettings as $setting => $value) {
                 if (!SJB_Settings::saveSetting($setting, $value)) {
                     $errors['SETTINGS_SAVED_WITH_PROBLEMS'] = "SETTINGS_SAVED_WITH_PROBLEMS";
                 }
             }
             if (empty($errors)) {
                 $tp->assign('successSaveMessage', true);
             }
         } else {
             $settings = $_REQUEST;
         }
     }
     switch ($action) {
         case 'backup':
             if (SJB_System::getSystemSettings('isDemo')) {
                 $i18N = SJB_I18N::getInstance();
                 $str = $i18N->gettext('Backend', 'Error: You don\'t have permissions for it. This is a Demo version of the software.');
                 SJB_Session::setValue('error', $str);
                 break;
             }
             if (SJB_System::getIfTrialModeIsOn() && $_SERVER['REMOTE_ADDR'] != "91.205.51.231") {
                 $i18N = SJB_I18N::getInstance();
                 $str = $i18N->gettext('Backend', 'Error: You don\'t have permissions for it. This is a Trial version of the software.');
                 SJB_Session::setValue('error', $str);
                 break;
             }
             SessionStorage::destroy('backup_' . $identifier);
             SessionStorage::write('backup_' . $identifier, serialize(array('last_time' => time())));
             SJB_Session::unsetValue('restore');
             SJB_Session::unsetValue('error');
             $backup_type = SJB_Request::getVar('backup_type');
             $backupDir = $script_path . 'backup' . $dir_separator;
             try {
                 $this->prepareBackupDir($backupDir);
             } catch (Exception $e) {
                 SJB_Session::setValue('error', $e->getMessage());
                 exit;
             }
             switch ($backup_type) {
                 case 'full':
                     SessionStorage::write('backup_' . $identifier, serialize(array('last_time' => time())));
                     $backupDir = $script_path;
                     $name = 'db.sql';
                     SJB_Backup::dump($name, $script_path, $identifier);
                     $d = dir($script_path);
                     $contentDir = array();
                     $folders = array('.', '..', 'backup', '.svn', '.settings', '.cache', 'restore', $name);
                     while (false !== ($entry = $d->read())) {
                         if (!in_array($entry, $folders)) {
                             $contentDir[] = $entry;
                         }
                     }
                     $listFilesAndFolders = !empty($contentDir) ? $contentDir : false;
                     $backupName = 'full_backup_' . date('Y_m_d__H_i') . '.tar.gz';
                     $export_files_dir_name = '..' . $dir_separator;
                     if (SJB_Backup::archive($name, $listFilesAndFolders, $backupDir, $export_files_dir_name, $backupName, true, $identifier, 'full')) {
                         SessionStorage::write('backup_' . $identifier, serialize(array('name' => $backupName)));
                     }
                     exit;
                     break;
                 case 'database':
                     SessionStorage::write('backup_' . $identifier, serialize(array('last_time' => time())));
                     $name = 'db.sql';
                     $backupName = 'mysqldump_' . date('Y_m_d__H_i') . '.tar.gz';
                     $export_files_dir_name = '../backup' . $dir_separator;
                     SJB_Backup::dump($name, $script_path, $identifier);
                     if (SJB_Backup::archive(false, $name, $script_path, $export_files_dir_name, $backupName, false, $identifier, 'database')) {
                         SessionStorage::write('backup_' . $identifier, serialize(array('name' => $backupName)));
                     }
                     exit;
                     break;
                 case 'files':
                     SessionStorage::write('backup_' . $identifier, serialize(array('last_time' => time())));
                     $backupDir = $script_path;
                     $d = dir($script_path);
                     $contentDir = array();
                     $folders = array('.', '..', 'backup', '.svn', '.settings', '.cache', 'restore');
                     while (false !== ($entry = $d->read())) {
                         if (!in_array($entry, $folders)) {
                             $contentDir[] = $entry;
                         }
                     }
                     $listFilesAndFolders = !empty($contentDir) ? $contentDir : false;
                     $backupName = 'backup_' . date('Y_m_d__H_i') . '.tar.gz';
                     $export_files_dir_name = '..' . $dir_separator;
                     if (SJB_Backup::archive(false, $listFilesAndFolders, $backupDir, $export_files_dir_name, $backupName, true, $identifier, 'files')) {
                         SessionStorage::write('backup_' . $identifier, serialize(array('name' => $backupName)));
                     }
                     exit;
                     break;
             }
             break;
         case 'restore':
             if (SJB_System::getSystemSettings('isDemo')) {
                 SJB_Session::setValue('error', 'Error: You don\'t have permissions for it. This is a Demo version of the software.');
                 exit;
             }
             if (SJB_System::getIfTrialModeIsOn()) {
                 SJB_Session::setValue('error', 'Error: You don\'t have permissions for it. This is a Trial version of the software.');
                 exit;
             }
             SJB_Session::unsetValue('restore');
             SJB_Session::unsetValue('error');
             $error = false;
             $restoreDir = $script_path . 'restore' . $dir_separator;
             try {
                 $fileName = $this->moveUploadedFile($restoreDir);
                 $tar = new Archive_Tar($restoreDir . $fileName, 'gz');
                 $tar->_error_class = 'SJB_PEAR_Exception';
                 $tar->extractList('db.sql', $restoreDir);
                 $tar->extract($script_path);
                 if (is_file($restoreDir . 'db.sql')) {
                     SJB_Backup::restore_base_tables($restoreDir . 'db.sql');
                 }
                 SJB_Cache::getInstance()->clean();
             } catch (Exception $ex) {
                 $error = $ex->getMessage();
             }
             SJB_Filesystem::delete($restoreDir);
             if (is_file($script_path . 'install.php')) {
                 SJB_Filesystem::delete($script_path . 'install.php');
             }
             if ($error) {
                 SJB_Session::setValue('error', $error);
             } else {
                 SJB_Session::setValue('restore', 1);
             }
             exit;
             break;
         case 'send_archive':
             $name = SJB_Request::getVar('name', false);
             $archive_file_path = SJB_Path::combine(SJB_BASE_DIR . 'backup' . $dir_separator, $name);
             if ($name) {
                 SJB_Backup::sendArchiveFile($name, $archive_file_path);
             }
             break;
         case 'check':
             $sessionBackup = SessionStorage::read('backup_' . $identifier);
             $sessionBackup = $sessionBackup ? unserialize($sessionBackup) : array();
             $sessionRestore = SJB_Session::getValue('restore');
             $sessionError = SJB_Session::getValue('error');
             if (!empty($sessionBackup['name'])) {
                 $name = $sessionBackup['name'];
                 SessionStorage::destroy('backup_' . $identifier);
                 echo SJB_System::getSystemSettings('SITE_URL') . "/backup/?action=send_archive&name={$name}";
                 exit;
             } elseif (!empty($sessionRestore)) {
                 SJB_Session::unsetValue('restore');
                 echo SJB_System::getSystemSettings('SITE_URL') . '/backup/#restore';
                 exit;
             } elseif (!empty($sessionError)) {
                 echo 'Error';
                 if (SJB_System::getSystemSettings('isDemo')) {
                     echo ': You don\'t have permissions for it. This is a Demo version of the software.';
                 }
                 if (SJB_System::getIfTrialModeIsOn()) {
                     echo ': You don\'t have permissions for it. This is a Trial version of the software.';
                 }
                 exit;
             } elseif (!empty($sessionBackup['last_time'])) {
                 $period = (time() - $sessionBackup['last_time']) / 60;
                 if ($period < 5) {
                     echo 1;
                 } else {
                     SJB_Session::setValue('error', 'The backup generation process was unexpectedly interrupted. Please try again.');
                     echo 'error';
                 }
                 exit;
             } else {
                 echo 1;
             }
             exit;
             break;
         case 'delete_backup':
             $name = SJB_Request::getVar('name', false);
             if ($name) {
                 $backup = $script_path . 'backup' . $dir_separator . $name;
                 if (is_file($backup)) {
                     SJB_Filesystem::delete($backup);
                     SJB_Autobackup::deleteFileFromFtp($name);
                 } else {
                     $errors['FILE_NOT_FOUND'] = 1;
                 }
             }
             $tp->assign('errors', $errors);
             $tp->assign('delBackup', 1);
         case 'created_backups':
             $path = $script_path . 'backup' . $dir_separator;
             if (is_dir($path)) {
                 $di = new DirectoryIterator($path);
                 $backupsArr = array();
                 foreach ($di as $file) {
                     $fileName = $file->getFilename();
                     if (!$file->isDir() && !$file->isLink() && $fileName != '.htaccess') {
                         $cTime = $file->getCTime();
                         $backupsArr[$cTime]['name'] = $fileName;
                         if (preg_match('/mysqldump/', $fileName)) {
                             $backupsArr[$cTime]['type'] = 'Site database only';
                         } elseif (preg_match('/full_backup/', $fileName)) {
                             $backupsArr[$cTime]['type'] = 'Full site backup';
                         } elseif (preg_match('/backup/', $fileName)) {
                             $backupsArr[$cTime]['type'] = 'Site files only';
                         } else {
                             $backupsArr[$cTime]['type'] = 'Unknown';
                         }
                         $pattern = '/(\\w+)_(\\d+)_(\\d+)_(\\d+)__(\\d+)_(\\d+).tar.gz/i';
                         $replacement = '$2-$3-$4 $5:$6';
                         $backupsArr[$cTime]['date'] = preg_replace($pattern, $replacement, $fileName);
                     }
                 }
                 krsort($backupsArr);
                 $tp->assign('created_backups', $backupsArr);
             }
             $tp->display('created_backups.tpl');
             exit;
             break;
         case 'error':
             $sessionError = SJB_Session::getValue('error');
             if (!is_null($sessionError)) {
                 echo '<p class="error">' . $sessionError . '</p>';
                 exit;
             }
             break;
     }
     if (empty($settings)) {
         $settings = SJB_Settings::getSettings();
     }
     $tp->assign('errors', $errors);
     $tp->assign('settings', $settings);
     $tp->assign('identifier', $identifier);
     $tp->assign("uploadMaxFilesize", SJB_UploadFileManager::getIniUploadMaxFilesize());
     $tp->display('backup.tpl');
 }
Example #23
0
 public static function getRefineSearchBlock()
 {
     $tp = SJB_System::getTemplateProcessor();
     $listingTypeId = SJB_Request::getVar('listing_type');
     if (!isset($listingTypeId['equal'])) {
         $_REQUEST['listing_type']['equal'] = SJB_Session::getValue('listing_type_id');
     }
     $searchResultsTP = new SJB_SearchResultsTP($_REQUEST, $listingTypeId['equal']);
     $searchCriteria = $searchResultsTP->getCriteriaSaver()->getCriteria();
     if (SJB_Request::getVar('showRefineFields', false)) {
         $refineFields = SJB_RefineSearch::getRefineFieldsByCriteria($searchResultsTP, $searchCriteria);
         $tp->assign('refineFields', $refineFields);
     }
     $currentSearch = SJB_RefineSearch::getCurrentSearchByCriteria($searchCriteria);
     $tp->assign('currentSearch', $currentSearch);
     $tp->assign('searchId', SJB_Request::getVar('searchId'));
     $tp->assign('view', SJB_Request::getVar('view'));
     $tp->display('../classifieds/search_results_refine_block.tpl');
 }
 public static function logout()
 {
     SJB_Session::unsetValue('sn');
     if (self::$oProfile) {
         SJB_HelperFunctions::redirect(self::getFacebookLogoutUrl());
         exit;
     }
 }
Example #25
0
 public static function getCurrentUserInfo()
 {
     $currentUser = SJB_Session::getValue('current_user');
     if (!empty($currentUser)) {
         return $currentUser;
     }
     if (isset($_COOKIE['session_key'])) {
         $user_sid = SJB_UserManager::getUserSIDBySessionKey($_COOKIE['session_key']);
         if (!empty($user_sid)) {
             $userInfo = SJB_UserManager::getUserInfoBySID($user_sid);
             if (!empty($userInfo['parent_sid'])) {
                 $subuserInfo = $userInfo;
                 $userInfo = SJB_UserManager::getUserInfoBySID($userInfo['parent_sid']);
                 $userInfo['subuser'] = $subuserInfo;
             }
             SJB_Session::setValue('current_user', $userInfo);
             SJB_Authorization::setKeepCookieForUser($_COOKIE['session_key']);
             return $userInfo;
         }
     }
     return null;
 }
Example #26
0
 /**
  * @return bool
  */
 private function isCaptchaEnable()
 {
     $isCaptcha = false;
     if (SJB_PluginManager::isPluginActive('CaptchaPlugin') && SJB_Session::getValue('CURRENT_THEME') != 'mobile') {
         $userType = SJB_System::getSystemSettings('SYSTEM_ACCESS_TYPE') != SJB_System::getSystemSettings('ADMIN_ACCESS_TYPE') ? 'user' : 'admin';
         $captchaSettingName = '';
         if (!($currentFunction = SJB_Request::getVar('currentFunction'))) {
             $currentFunction = SJB_Array::get(SJB_System::getModuleManager()->getCurrentFunction(), 1);
         }
         switch ($currentFunction) {
             case 'apply_now':
                 $captchaSettingName = 'contactUserCaptcha';
                 break;
             case 'flag_listing':
                 $captchaSettingName = 'flagListingCaptcha';
                 break;
             case 'tell_friend':
                 $captchaSettingName = 'tellFriendCaptcha';
                 break;
             case 'contact_form':
                 $captchaSettingName = 'contactUsCaptcha';
                 break;
             default:
                 if (SJB_System::getSettingByName('captcha_max_allowed_auth_attempts') != 0) {
                     if (SJB_Session::getValue($userType . 'LoginCounter') >= SJB_System::getSettingByName('captcha_max_allowed_auth_attempts')) {
                         $isCaptcha = true;
                         if (SJB_Session::getValue($userType . 'LoginCounter') == SJB_System::getSettingByName('captcha_max_allowed_auth_attempts')) {
                             SJB_Session::setValue($userType . 'LoginCounter', SJB_Session::getValue($userType . 'LoginCounter') + 1);
                             $this->isNotValidate = true;
                         }
                     }
                 }
         }
         if (!$isCaptcha) {
             $isCaptcha = SJB_System::getSettingByName($captchaSettingName) == 1;
         }
     }
     return $isCaptcha;
 }
Example #27
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/');
     }
 }
Example #28
0
 public function execute()
 {
     $formToken = SJB_Request::getVar('form_token');
     $tp = SJB_System::getTemplateProcessor();
     $tp->assign('form_token', $formToken);
     $post_max_size_orig = ini_get('post_max_size');
     $server_content_length = isset($_SERVER['CONTENT_LENGTH']) ? $_SERVER['CONTENT_LENGTH'] : null;
     // get post_max_size in bytes
     $val = trim($post_max_size_orig);
     $tmp = substr($val, strlen($val) - 1);
     $tmp = strtolower($tmp);
     switch ($tmp) {
         case 'g':
             $val *= 1024;
             break;
         case 'm':
             $val *= 1024;
             break;
         case 'k':
             $val *= 1024;
             break;
     }
     $post_max_size = $val;
     $errors = array();
     if (SJB_Request::getVar('from-preview', false, 'POST') && !SJB_Request::getVar('action_add', false, 'POST')) {
         $listingId = SJB_Request::getVar('listing_id', null, 'GET', 'int');
         $previewListingId = SJB_Session::getValue('preview_listing_sid');
         if ($previewListingId && SJB_ListingManager::isListingExists($previewListingId)) {
             $listingId = $previewListingId;
         }
     } else {
         $listingId = SJB_Request::getVar('listing_id', null, 'default', 'int');
     }
     $template = SJB_Request::getVar('edit_template', 'edit_listing.tpl');
     $filename = SJB_Request::getVar('filename', false);
     if ($filename) {
         SJB_UploadFileManager::openFile($filename, $listingId);
         // if file not found - set error here
         $errors['NO_SUCH_FILE'] = true;
     }
     if (empty($_POST) && $server_content_length > $post_max_size) {
         $errors['MAX_FILE_SIZE_EXCEEDED'] = 1;
         $listingId = SJB_Request::getVar('listing_id', null, 'GET', 'int');
         $tp->assign('post_max_size', $post_max_size_orig);
     }
     $current_user = SJB_UserManager::getCurrentUser();
     $listingInfo = SJB_ListingManager::getListingInfoBySID($listingId);
     // for listing preview
     $formSubmittedFromPreview = false;
     if (empty($listingInfo)) {
         $listingId = SJB_Session::getValue('preview_listing_sid');
         $listingInfo = SJB_ListingManager::getListingInfoBySID($listingId);
         if (!empty($listingInfo)) {
             // if on preview page 'POST' button was pressed
             $formSubmittedFromPreview = SJB_Request::getVar('action_add', false, 'POST') && SJB_Request::getVar('from-preview', false, 'POST');
             if ($formSubmittedFromPreview) {
                 $listing = new SJB_Listing($listingInfo, $listingInfo['listing_type_sid']);
                 $properties = $listing->getProperties();
                 foreach ($properties as $fieldID => $property) {
                     switch ($property->getType()) {
                         case 'date':
                             if (!empty($listingInfo[$fieldID])) {
                                 $listingInfo[$fieldID] = SJB_I18N::getInstance()->getDate($listingInfo[$fieldID]);
                             }
                             break;
                         case 'complex':
                             $complex = $property->type->complex;
                             $complexProperties = $complex->getProperties();
                             foreach ($complexProperties as $complexfieldID => $complexProperty) {
                                 if ($complexProperty->getType() == 'date') {
                                     $values = $complexProperty->getValue();
                                     foreach ($values as $index => $value) {
                                         if (!empty($listingInfo[$fieldID][$complexfieldID][$index])) {
                                             $listingInfo[$fieldID][$complexfieldID][$index] = SJB_I18N::getInstance()->getDate($listingInfo[$fieldID][$complexfieldID][$index]);
                                         }
                                     }
                                 }
                             }
                             break;
                     }
                 }
             }
         } else {
             $listingId = null;
             SJB_Session::unsetValue('preview_listing_sid');
         }
     }
     // if preview button was pressed
     $isPreviewListingRequested = SJB_Request::getVar('preview_listing', false, 'POST');
     if (SJB_UserManager::isUserLoggedIn()) {
         if ($listingInfo['user_sid'] != $current_user->getID()) {
             $errors['NOT_OWNER_OF_LISTING'] = $listingId;
         } elseif (!is_null($listingInfo)) {
             $pages = SJB_PostingPagesManager::getPagesByListingTypeSID($listingInfo['listing_type_sid']);
             $form_is_submitted = SJB_Request::getVar('action', '') == 'save_info' || SJB_Request::getVar('action', '') == 'add' || $isPreviewListingRequested || $formSubmittedFromPreview;
             if (!$form_is_submitted && !SJB_Request::getVar('from-preview', false, 'POST')) {
                 SJB_Session::unsetValue('previewListingId');
                 SJB_Session::unsetValue('preview_listing_sid_or');
             }
             // fill listing from an array of social data if allowed
             $listing_type_info = SJB_ListingTypeManager::getListingTypeInfoBySID($listingInfo['listing_type_sid']);
             $listingTypeID = $listing_type_info['id'];
             $aAutoFillData = array('formSubmitted' => $form_is_submitted, 'listingTypeID' => $listingTypeID);
             SJB_Event::dispatch('SocialSynchronization', $aAutoFillData);
             $listingInfo = array_merge($listingInfo, $_REQUEST);
             $listing = new SJB_Listing($listingInfo, $listingInfo['listing_type_sid']);
             $listing->deleteProperty('ListingLogo');
             $listing->deleteProperty('featured');
             $listing->deleteProperty('priority');
             $listing->deleteProperty('reject_reason');
             $listing->deleteProperty('status');
             $list_emp_ids = SJB_Request::getVar('list_emp_ids');
             $listing->setSID($listingId);
             $screening_questionnaires = SJB_ScreeningQuestionnaires::getList($current_user->getSID());
             if (SJB_Acl::getInstance()->isAllowed('use_screening_questionnaires') && $screening_questionnaires) {
                 $value = SJB_Request::getVar('screening_questionnaire');
                 $value = $value ? $value : isset($listingInfo['screening_questionnaire']) ? $listingInfo['screening_questionnaire'] : '';
                 $listing->addProperty(array('id' => 'screening_questionnaire', 'type' => 'list', 'caption' => 'Screening Questionnaire', 'value' => $value, 'list_values' => SJB_ScreeningQuestionnaires::getListSIDsAndCaptions($current_user->getSID()), 'is_system' => true));
             } else {
                 $listing->deleteProperty('screening_questionnaire');
             }
             //--->CLT-2637
             $properties = $listing->getProperties();
             $listing_fields_by_page = array();
             foreach ($pages as $page) {
                 $listing_fields_by_page = array_merge(SJB_PostingPagesManager::getAllFieldsByPageSIDForForm($page['sid']), $listing_fields_by_page);
             }
             foreach ($properties as $property) {
                 if (!in_array($property->getID(), array_keys($listing_fields_by_page))) {
                     $listing->deleteProperty($property->getID());
                 }
             }
             //--->CLT-2637
             // if user is not registered using linkedin , delete linkedin sync property, also if sync is turned off in admin part
             $aAutoFillData = array('oListing' => &$listing, 'userSID' => $current_user->getSID(), 'listingTypeID' => $listingTypeID, 'listing_info' => $listingInfo);
             SJB_Event::dispatch('SocialSynchronizationFields', $aAutoFillData);
             $listing_edit_form = new SJB_Form($listing);
             $listing_edit_form->registerTags($tp);
             $extraInfo = $listingInfo['product_info'];
             if ($extraInfo) {
                 $extraInfo = unserialize($extraInfo);
                 $numberOfPictures = isset($extraInfo['number_of_pictures']) ? $extraInfo['number_of_pictures'] : 0;
                 $listingSidForPictures = SJB_Session::getValue('preview_listing_sid_or') ? SJB_Session::getValue('preview_listing_sid_or') : $listingId;
                 $tp->assign('pic_limit', $numberOfPictures);
                 $tp->assign('listingSidForPictures', $listingSidForPictures);
             }
             if ($form_is_submitted) {
                 $listing->addProperty(array('id' => 'access_list', 'type' => 'multilist', 'value' => SJB_Request::getVar('list_emp_ids'), 'is_system' => true));
             }
             $field_errors = array();
             if ($form_is_submitted && ($formSubmittedFromPreview || $listing_edit_form->isDataValid($field_errors))) {
                 $or_listing_id = SJB_Session::getValue('preview_listing_sid_or');
                 /* preview listing */
                 if ($isPreviewListingRequested && SJB_Session::getValue('preview_listing_sid') != $listing->getSID()) {
                     SJB_Session::setValue('preview_listing_sid_or', $listing->getSID());
                     $listing->setSID(null);
                 } elseif (!$isPreviewListingRequested && SJB_Session::getValue('preview_listing_sid') == $listing->getSID() && $or_listing_id && $or_listing_id != $listingId) {
                     $listing->setSID($or_listing_id);
                 }
                 if ($isPreviewListingRequested) {
                     $listing->addProperty(array('id' => 'preview', 'type' => 'integer', 'value' => 1, 'is_system' => true));
                 } else {
                     $listing->addProperty(array('id' => 'complete', 'type' => 'integer', 'value' => 1, 'is_system' => true));
                 }
                 if ($isPreviewListingRequested) {
                     $listing->product_info = $extraInfo;
                     if (SJB_Session::getValue('previewListingId')) {
                         $listing->setSID(SJB_Session::getValue('previewListingId'));
                     }
                 } else {
                     SJB_BrowseDBManager::deleteListings($listing->getID());
                 }
                 $listingSidsForCopy = array('filesFrom' => $listingId, 'picturesFrom' => $isPreviewListingRequested && (!$or_listing_id || $or_listing_id === $listingId) ? $listingId : null);
                 SJB_ListingManager::saveListing($listing, $listingSidsForCopy);
                 if (!$isPreviewListingRequested && SJB_Session::getValue('preview_listing_sid') == $listingId && $or_listing_id && $or_listing_id != $listingId) {
                     SJB_Session::unsetValue('preview_listing_sid');
                     SJB_ListingManager::deleteListingBySID($listingId);
                 }
                 $listingInfo = SJB_ListingManager::getListingInfoBySID($listing->getSID());
                 if ($listingInfo['active']) {
                     SJB_ListingManager::activateListingKeywordsBySID($listing->getSID());
                     SJB_BrowseDBManager::addListings($listing->getID());
                 }
                 // >>> SJB-1197
                 // SET VALUES FROM TEMPORARY SESSION STORAGE
                 $formToken = SJB_Request::getVar('form_token');
                 $sessionFileStorage = SJB_Session::getValue('tmp_uploads_storage');
                 $tempFieldsData = SJB_Array::getPath($sessionFileStorage, $formToken);
                 if (is_array($tempFieldsData)) {
                     foreach ($tempFieldsData as $fieldId => $fieldData) {
                         $isComplex = false;
                         if (strpos($fieldId, ':') !== false) {
                             $isComplex = true;
                         }
                         $tmpUploadedFileId = $fieldData['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);
                         }
                     }
                     SJB_ListingManager::saveListing($listing);
                     // recreate form object for saved listing
                     // it fix display of complex file fields
                     $listing = SJB_ListingManager::getObjectBySID($listing->getSID());
                     $listing->deleteProperty('featured');
                     $listing->deleteProperty('priority');
                     $listing->deleteProperty('reject_reason');
                     $listing->deleteProperty('status');
                     $listing_edit_form = new SJB_Form($listing);
                     $listing_edit_form->registerTags($tp);
                 }
                 // <<< SJB-1197
                 if ($isPreviewListingRequested) {
                     SJB_Session::setValue('previewListingId', $listing->getSID());
                 }
                 /* preview listing */
                 if ($isPreviewListingRequested) {
                     $listing->setUserSID($current_user->getSID());
                     SJB_Session::setValue('preview_listing_sid', $listing->getSID());
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/' . strtolower($listingTypeID) . '-preview/' . $listing->getSID() . '/');
                 } else {
                     /* normal */
                     $listingSid = $listing->getSID();
                     SJB_Event::dispatch('listingEdited', $listingSid);
                     $tp->assign('display_preview', 1);
                     SJB_Session::unsetValue('preview_listing_sid');
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/my-' . strtolower($listingTypeID) . '-details/' . $listing->getSID() . '/');
                 }
             }
             $listing->deleteProperty('access_list');
             $tp->assign('form_is_submitted', $form_is_submitted);
             $listing_structure = SJB_ListingManager::createTemplateStructureForListing($listing);
             $form_fields = $listing_edit_form->getFormFieldsInfo();
             $listing_fields_by_page = array();
             foreach ($pages as $page) {
                 $listing_fields_by_page[$page['page_name']] = SJB_PostingPagesManager::getAllFieldsByPageSIDForForm($page['sid']);
                 foreach (array_keys($listing_fields_by_page[$page['page_name']]) as $field) {
                     if (!$listing->propertyIsSet($field)) {
                         unset($listing_fields_by_page[$page['page_name']][$field]);
                     }
                 }
             }
             // delete sync fields from posting pages that are not in array $form_fields
             $aAutoFillData = array('listing_fields_by_page' => &$listing_fields_by_page, 'pages' => &$pages, 'form_fields' => $form_fields);
             SJB_Event::dispatch('SocialSynchronizationFieldsOnPostingPages', $aAutoFillData);
             $metaDataProvider = SJB_ObjectMother::getMetaDataProvider();
             $tp->assign('METADATA', array('listing' => $metaDataProvider->getMetaData($listing_structure['METADATA']), 'form_fields' => $metaDataProvider->getFormFieldsMetadata($form_fields)));
             if (!isset($listing_structure['access_type'])) {
                 $listing_structure['access_type'] = 'everyone';
             }
             $listing_access_list = SJB_ListingManager::getListingAccessList($listingId, $listing->getPropertyValue('access_type'));
             $tp->assign('contract_id', $listingInfo['contract_id']);
             $tp->assign('extraInfo', $extraInfo);
             $tp->assign('listing', $listing_structure);
             $tp->assign('pages', $listing_fields_by_page);
             $tp->assign('countPages', count($listing_fields_by_page));
             $tp->assign('field_errors', $field_errors);
             $tp->assign('listing_access_list', $listing_access_list);
             $tp->assign('listingTypeID', $listingTypeID);
             $tp->assign('expired', SJB_ListingManager::getIfListingHasExpiredBySID($listing->getSID()));
             // only for Resume listing types
             $aAutoFillData = array('tp' => &$tp, 'listingTypeID' => $listingTypeID, 'userSID' => $current_user->getSID());
             SJB_Event::dispatch('SocialSynchronizationForm', $aAutoFillData);
         }
     } else {
         $errors['NOT_LOGGED_IN'] = 1;
     }
     $tp->assign('errors', $errors);
     $tp->display($template);
 }
Example #29
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $currentUser = SJB_UserManager::getCurrentUser();
     $action = SJB_Request::getVar('action', false);
     $error = SJB_Request::getVar('error', false);
     $applyPromoCode = SJB_Request::getVar('applyPromoCode', false);
     $action = $applyPromoCode ? 'applyPromoCode' : $action;
     $numberOfListings = SJB_Request::getVar('number_of_listings');
     $productInfo = null;
     $errors = array();
     switch ($action) {
         case 'delete':
             $itemSID = SJB_Request::getVar('item_sid', 0, false, 'int');
             if (SJB_UserManager::isUserLoggedIn()) {
                 if (SJB_Settings::getSettingByName('allow_to_post_before_checkout') == true) {
                     $this->findCheckoutedListingsByProduct($itemSID, $currentUser->getSID());
                 }
                 SJB_ShoppingCart::deleteItemFromCartBySID($itemSID, $currentUser->getSID());
             } else {
                 $products = SJB_Session::getValue('products');
                 if (!empty($products[$itemSID])) {
                     unset($products[$itemSID]);
                     SJB_Session::setValue('products', $products);
                 }
             }
             break;
         case 'checkout':
             if (SJB_UserManager::isUserLoggedIn()) {
                 $products = SJB_Session::getValue('products');
                 $products = $products ? $products : array();
                 $trialProduct = false;
                 foreach ($products as $product) {
                     if (!empty($product['product_info'])) {
                         $productInfo = unserialize($product['product_info']);
                         if ($currentUser->getUserGroupSID() != $productInfo['user_group_sid']) {
                             SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/shopping-cart/?error=user_group");
                         } elseif (in_array($productInfo['sid'], $currentUser->getTrialProductSIDByUserSID())) {
                             $trialProduct = true;
                         } else {
                             $product = new SJB_Product($productInfo, $productInfo['product_type']);
                             $number_of_listings = !empty($productInfo['number_of_listings']) ? $productInfo['number_of_listings'] : 1;
                             $product->setNumberOfListings($number_of_listings);
                             $productInfo['price'] = $product->getPrice();
                             SJB_ShoppingCart::addToShoppingCart($productInfo, $currentUser->getSID());
                         }
                     }
                 }
                 SJB_Session::unsetValue('products');
                 if ($trialProduct) {
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/shopping-cart/?error=trial_product");
                 } elseif ($products) {
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/shopping-cart/");
                 }
                 $products = SJB_ShoppingCart::getAllProductsByUserSID($currentUser->getSID());
                 if (empty($products)) {
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/my-account/");
                 }
                 $isRecurring = false;
                 $subTotal = 0;
                 foreach ($products as $key => $product) {
                     $productInfo = unserialize($product['product_info']);
                     if (!empty($productInfo['recurring'])) {
                         $isRecurring = true;
                     }
                     if (!empty($productInfo['pricing_type']) == 'volume_based' && isset($numberOfListings[$productInfo['sid']][$product['sid']])) {
                         $productInfo['number_of_listings'] = $numberOfListings[$productInfo['sid']][$product['sid']];
                         $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 (!empty($productInfo['code_info'])) {
                             SJB_PromotionsManager::applyPromoCodeToProduct($productInfo, $productInfo['code_info']);
                         }
                         SJB_ShoppingCart::updateItemBySID($product['sid'], $productInfo);
                     }
                     $subTotal += $productInfo['price'];
                     $products[$key] = $productInfo;
                     $products[$key]['item_sid'] = $product['sid'];
                     $products[$key]['product_info'] = serialize($productInfo);
                 }
                 $index = 1;
                 $items = array();
                 $codeInfo = array();
                 if ($isRecurring) {
                     $tp->assign('confirmation', 1);
                     $tp->assign('sub_total_price', $subTotal);
                 } else {
                     foreach ($products as $product) {
                         $product_info = unserialize($product['product_info']);
                         SJB_PromotionsManager::preparePromoCodeInfoByProductPromoCodeInfo($product, $product['code_info']);
                         $qty = !empty($product_info['number_of_listings']) ? $product_info['number_of_listings'] : null;
                         $items['products'][$index] = $product_info['sid'];
                         if ($qty > 0) {
                             $items['price'][$index] = round($product['price'] / $qty, 2);
                         } else {
                             $items['price'][$index] = round($product['price'], 2);
                         }
                         $items['amount'][$index] = $product['price'];
                         $items['qty'][$index] = $qty;
                         if (isset($product['custom_item'])) {
                             $items['custom_item'][$index] = $product['custom_item'];
                         } else {
                             $items['custom_item'][$index] = "";
                         }
                         if (isset($product['custom_info'])) {
                             $items['custom_info'][$index] = $product['custom_info'];
                         } else {
                             $items['custom_info'][$index]['shoppingCartRecord'] = $product['item_sid'];
                         }
                         if ($product_info['product_type'] == 'banners' && !empty($product_info['banner_info'])) {
                             $items['custom_info'][$index]['banner_info'] = $product_info['banner_info'];
                         }
                         $index++;
                         SJB_PromotionsManager::preparePromoCodeInfoByProductPromoCodeInfo($product_info, $codeInfo);
                     }
                     $subUserInfo = $currentUser->getSubuserInfo();
                     $userSID = isset($subUserInfo['sid']) ? $subUserInfo['sid'] : $currentUser->getSID();
                     $invoiceSID = SJB_InvoiceManager::generateInvoice($items, $userSID, $subTotal, SJB_System::getSystemSettings('SITE_URL') . "/create-contract/");
                     SJB_PromotionsManager::addCodeToHistory($codeInfo, $invoiceSID, $userSID);
                     if ($subTotal <= 0) {
                         SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/create-contract/?invoice_sid=' . $invoiceSID);
                     } else {
                         SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/payment-page/?invoice_sid=" . $invoiceSID);
                     }
                 }
             }
             break;
         case 'applyPromoCode':
             $promotionCode = SJB_Request::getVar('promotion_code', false);
             if ($promotionCode) {
                 if (SJB_UserManager::isUserLoggedIn()) {
                     $products = SJB_ShoppingCart::getAllProductsByUserSID($currentUser->getSID());
                 } else {
                     $products = SJB_Session::getValue('products');
                     $products = $products ? $products : array();
                     krsort($products);
                 }
                 $allowShoppingItems = array();
                 $productSIDs = array();
                 foreach ($products as $product) {
                     $productInfo = unserialize($product['product_info']);
                     if (!isset($productInfo['code_info'])) {
                         if (isset($productInfo['custom_info'])) {
                             $allowShoppingItems[] = $product['sid'];
                             $productSIDs[] = $productInfo['custom_info']['productSid'];
                         } else {
                             $allowShoppingItems[] = $product['sid'];
                             $productSIDs[] = $productInfo['sid'];
                         }
                     } else {
                         $appliedPromoCode = $productInfo['code_info'];
                     }
                 }
                 if ($codeInfo = SJB_PromotionsManager::checkCode($promotionCode, $productSIDs)) {
                     $productSIDs = $codeInfo['product_sid'] ? explode(',', $codeInfo['product_sid']) : false;
                     $appliedProducts = array();
                     $codeValid = false;
                     foreach ($products as $key => $product) {
                         $productInfo = unserialize($product['product_info']);
                         if ($productInfo['sid'] != '-1') {
                             $productSid = $productInfo['sid'];
                         } else {
                             $productSid = $productInfo['custom_info']['productSid'];
                         }
                         if ($productSIDs && in_array($productSid, $productSIDs) && $allowShoppingItems && in_array($product['sid'], $allowShoppingItems)) {
                             $currentUsesCount = SJB_PromotionsManager::getUsesCodeBySID($codeInfo['sid']);
                             if ($codeInfo['maximum_uses'] != 0 && $codeInfo['maximum_uses'] > $currentUsesCount || $codeInfo['maximum_uses'] == 0) {
                                 $codeValid = true;
                                 SJB_PromotionsManager::applyPromoCodeToProduct($productInfo, $codeInfo);
                                 $appliedProducts[] = $productInfo;
                                 if (SJB_UserManager::isUserLoggedIn()) {
                                     SJB_ShoppingCart::updateItemBySID($product['sid'], $productInfo);
                                 } else {
                                     $products[$key]['product_info'] = serialize($productInfo);
                                     SJB_Session::setValue('products', $products);
                                 }
                             }
                         }
                     }
                     if (!$codeValid) {
                         $errors['NOT_VALID'] = 'Invalid promotion code';
                         unset($promotionCode);
                     }
                     $tp->assign('applied_products', $appliedProducts);
                     $tp->assign('code_info', $codeInfo);
                 } else {
                     $errors['NOT_VALID'] = 'Invalid promotion code';
                 }
                 if (isset($promotionCode) && isset($appliedPromoCode)) {
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/shopping-cart/');
                 }
             } else {
                 $errors['EMPTY_VALUE'] = 'Promotion code';
             }
             break;
         case 'deletePromoCode':
             if (SJB_UserManager::isUserLoggedIn()) {
                 $products = SJB_ShoppingCart::getAllProductsByUserSID($currentUser->getSID());
             } else {
                 $products = SJB_Session::getValue('products');
                 $products = $products ? $products : array();
                 krsort($products);
             }
             foreach ($products as $key => $product) {
                 $productInfo = unserialize($product['product_info']);
                 SJB_PromotionsManager::removePromoCodeFromProduct($productInfo);
                 if (SJB_UserManager::isUserLoggedIn()) {
                     $numberOfListings = is_array($numberOfListings) ? array_pop($numberOfListings) : false;
                     if (is_array($numberOfListings)) {
                         foreach ($numberOfListings as $listingSid => $listingsCount) {
                             if ($listingSid == $product['sid']) {
                                 $productInfo['number_of_listings'] = $listingsCount;
                             }
                         }
                     }
                     SJB_ShoppingCart::updateItemBySID($product['sid'], $productInfo);
                 } else {
                     $products[$key]['product_info'] = serialize($productInfo);
                     SJB_Session::setValue('products', $products);
                 }
             }
             break;
     }
     if (SJB_UserManager::isUserLoggedIn()) {
         $products = SJB_ShoppingCart::getAllProductsByUserSID($currentUser->getSID());
         // To display products in shopping cart after user has been registered from shopping cart page
         if (empty($products)) {
             $products = SJB_Session::getValue('products');
             $products = $products ? $products : array();
         }
     } else {
         $products = SJB_Session::getValue('products');
         $products = $products ? $products : array();
         krsort($products);
     }
     $allowShoppingItems = array();
     foreach ($products as $product) {
         $productInfo = unserialize($product['product_info']);
         if (!empty($productInfo['code_info'])) {
             $promotionCode = $productInfo['code_info']['code'];
             $promotionCodeInfo = $productInfo['code_info'];
         } else {
             $allowShoppingItems[] = $product['sid'];
         }
     }
     $promotionCode = isset($promotionCode) ? $promotionCode : '';
     $totalPrice = 0;
     $discountTotalAmount = 0;
     $numberOfListings = SJB_Request::getVar('number_of_listings', false);
     foreach ($products as $key => $product) {
         $productInfo = unserialize($product['product_info']);
         if ($allowShoppingItems && in_array($product['sid'], $allowShoppingItems)) {
             $this->applyPromoCodesToProduct($promotionCode, $productInfo);
             if (SJB_UserManager::isUserLoggedIn()) {
                 SJB_ShoppingCart::updateItemBySID($product['sid'], $productInfo);
             } else {
                 $products[$key]['product_info'] = serialize($productInfo);
             }
         }
         if ($numberOfListings && array_key_exists('number_of_listings', $productInfo) && array_key_exists($productInfo['sid'], $numberOfListings)) {
             $productInfo['number_of_listings'] = $numberOfListings[$productInfo['sid']][$product['sid']];
         }
         $productObj = new SJB_Product($productInfo, $productInfo['product_type']);
         $productExtraInfo = unserialize($productInfo['serialized_extra_info']);
         if (!empty($productInfo['expiration_period']) && !is_numeric($productInfo['expiration_period'])) {
             $productInfo['primaryPrice'] = $productExtraInfo['price'];
             $productInfo['period'] = ucwords($productInfo['expiration_period']);
         } elseif (!empty($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'volume_based') {
             $volumeBasedPricing = $productInfo['volume_based_pricing'];
             $number_of_listings = !empty($productInfo['number_of_listings']) ? $productInfo['number_of_listings'] : 1;
             $productObj->setNumberOfListings($number_of_listings);
             $productInfo['price'] = $productObj->getPrice();
             $productInfo['primaryPrice'] = $productObj->getPrice();
             $this->applyPromoCodesToProduct($promotionCode, $productInfo);
             $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] * $i;
                         $countListings[$i]['primaryPrice'] = $volumeBasedPricing['price_per_unit'][$j] * $i;
                         if (!empty($productInfo['code_info']['type'])) {
                             switch ($productInfo['code_info']['type']) {
                                 case 'percentage':
                                     $countListings[$i]['price'] = round($countListings[$i]['price'] - $countListings[$i]['primaryPrice'] / 100 * $productInfo['code_info']['discount'], 2);
                                     $countListings[$i]['percentPromoAmount'] = round($countListings[$i]['primaryPrice'] - $countListings[$i]['price'], 2);
                                     $countListings[$i]['percentPromoCode'] = $productInfo['code_info']['code'];
                                     break;
                                 case 'fixed':
                                     $countListings[$i]['price'] = round($countListings[$i]['price'] - $productInfo['code_info']['discount'], 2);
                                     break;
                             }
                         }
                     }
                 }
             }
             $productInfo['count_listings'] = $countListings;
         } elseif (!empty($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'fixed') {
             $productInfo['primaryPrice'] = $productObj->getPrice();
             $this->applyPromoCodesToProduct($promotionCode, $productInfo);
             unset($productInfo['volume_based_pricing']);
         }
         if (isset($productInfo['code_info'])) {
             if ($productInfo['code_info']['type'] != 'fixed' && isset($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'volume_based') {
                 $discountTotalAmount += (double) $productInfo['count_listings'][$productInfo['number_of_listings']]['percentPromoAmount'];
             } else {
                 $discountTotalAmount += (double) $productInfo['code_info']['promoAmount'];
             }
         }
         if (empty($productInfo['volume_based_pricing'])) {
             $productInfo['primaryPrice'] = $productExtraInfo['price'];
             $this->applyPromoCodesToProduct($promotionCode, $productInfo);
             $totalPrice += (double) $productInfo['price'];
         }
         $products[$key] = $productInfo;
         $products[$key]['item_sid'] = $product['sid'];
     }
     if ($currentUser) {
         $taxInfo = SJB_TaxesManager::getTaxInfoByUserSidAndPrice($currentUser->getSID(), $totalPrice);
         $tp->assign('tax', $taxInfo);
     }
     $userGroupID = $productInfo ? SJB_UserGroupDBManager::getUserGroupIDBySID($productInfo['user_group_sid']) : false;
     $tp->assign('promotionCodeAlreadyUsed', $promotionCode && empty($errors));
     if (isset($promotionCodeInfo)) {
         $tp->assign('promotionCodeInfo', $promotionCodeInfo);
     }
     $tp->assign('error', $error);
     $tp->assign('errors', $errors);
     $tp->assign('total_price', $totalPrice);
     $tp->assign('discountTotalAmount', $discountTotalAmount);
     $tp->assign('products', $products);
     $tp->assign('userGroupID', $userGroupID);
     $tp->assign('account_activated', SJB_Request::getVar('account_activated', ''));
     $tp->display('shopping_cart.tpl');
 }
Example #30
0
 public static function init($url)
 {
     $sessionStorage = new PHPBBSessionStorage();
     session_set_save_handler(array($sessionStorage, 'open'), array($sessionStorage, 'close'), array($sessionStorage, 'read'), array($sessionStorage, 'write'), array($sessionStorage, 'destroy'), array($sessionStorage, 'gc'));
     $path = SJB_Session::getSessionCookiePath($url);
     SJB_WrappedFunctions::ini_set("session.cookie_path", $path);
     SJB_WrappedFunctions::session_start();
 }