public function execute()
 {
     $template = SJB_Request::getVar('template', 'featured_listings.tpl');
     $listingType = SJB_Request::getVar('listing_type', 'Job');
     $searches['data']['listing_type']['equal'] = $listingType;
     $searches['data']['featured']['equal'] = 1;
     $searches['data']['default_listings_per_page'] = SJB_Request::getVar('items_count', 1);
     $searches['data']['sorting_field'] = 'featured_last_showed';
     $searches['data']['default_sorting_field'] = 'featured_last_showed';
     $searches['data']['default_sorting_order'] = 'ASC';
     $searches['data']['sorting_order'] = 'ASC';
     // фичерные листинги кешировать не будем
     $cache = SJB_Cache::getInstance();
     $caching = $cache->getOption('caching');
     $cache->setOption('caching', false);
     $searchResultsTP = new SJB_SearchResultsTP($searches['data'], $listingType);
     $searchResultsTP->setLimit(SJB_Request::getVar('items_count', 1));
     $tp = $searchResultsTP->getChargedTemplateProcessor();
     $featuredListingSIDs = $searchResultsTP->getListingSidCollectionForCurrentPage();
     if ($featuredListingSIDs) {
         SJB_DB::query('UPDATE `listings` SET `featured_last_showed` = NOW() WHERE `sid` in (?w)', implode(',', $featuredListingSIDs));
         SJB_Statistics::addSearchStatistics($featuredListingSIDs, $listingType);
     }
     $cache->setOption('caching', $caching);
     $tp->assign('number_of_cols', SJB_Request::getVar('number_of_cols', 1));
     $tp->display($template);
 }
Exemple #2
0
 /**
  * @param SJB_State $state
  */
 public static function saveState(SJB_State $state)
 {
     SJB_Cache::getInstance()->clean('matchingAnyTag', array(SJB_Cache::TAG_FIELDS));
     $stateSID = $state->getSID();
     SJB_ObjectDBManager::saveObject('states', $state);
     if (!$stateSID) {
         self::setLastOrder($state);
     }
 }
Exemple #3
0
 /**
  * @static
  * @return Zend_Cache_Core
  */
 public static function getInstance()
 {
     if (empty(self::$instance)) {
         $caching = SJB_Settings::getValue('enableCache');
         $caching = !empty($caching);
         $cacheHours = SJB_Settings::getValue('cacheHours');
         if (empty($cacheHours)) {
             $cacheHours = 0;
         }
         $cacheMinutes = SJB_Settings::getValue('cacheMinutes');
         if (empty($cacheMinutes)) {
             $cacheMinutes = 0;
         }
         $lifetime = intval($cacheHours) * 3600 + intval($cacheMinutes) * 60;
         $frontendOptions = array('lifetime' => $lifetime, 'automatic_serialization' => true, 'caching' => $caching);
         $backendOptions = array('cache_dir' => SJB_BASE_DIR . 'system' . DIRECTORY_SEPARATOR . 'cache');
         // получение объекта Zend_Cache_Core
         self::$instance = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
     }
     return self::$instance;
 }
Exemple #4
0
 public static function deactivateUserByUserName($username)
 {
     SJB_Event::dispatch('onBeforeUserDeactivate', $username);
     SJB_UserDBManager::deactivateUserByUserName($username);
     SJB_Cache::getInstance()->clean('matchingAnyTag', array(SJB_Cache::TAG_USERS));
 }
Exemple #5
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');
 }
Exemple #6
0
 public static function table_exists($table_name)
 {
     if (isset($GLOBALS['SJB_DB_table_exists_tables'])) {
         $tables = $GLOBALS['SJB_DB_table_exists_tables'];
     } else {
         $cache = SJB_Cache::getInstance();
         $tables = $cache->load(md5("SHOW TABLES"));
         if (empty($tables)) {
             $rows = SJB_DB::query("SHOW TABLES");
             foreach ($rows as $table) {
                 $tables[] = current($table);
             }
             $cache->save($tables, md5("SHOW TABLES"));
         }
         $GLOBALS['SJB_DB_table_exists_tables'] = $tables;
     }
     return in_array($table_name, $tables);
 }
Exemple #7
0
    private function runTaskScheduler()
    {
        // Deactivate Expired Listings & Send Notifications
        $listingsExpiredID = SJB_ListingManager::getExpiredListingsSID();
        foreach ($listingsExpiredID as $listingExpiredID) {
            SJB_ListingManager::deactivateListingBySID($listingExpiredID, true);
            $listing = SJB_ListingManager::getObjectBySID($listingExpiredID);
            $listingInfo = SJB_ListingManager::createTemplateStructureForListing($listing);
            if (SJB_UserNotificationsManager::isUserNotifiedOnListingExpiration($listing->getUserSID())) {
                SJB_Notifications::sendUserListingExpiredLetter($listingInfo);
            }
            // notify admin
            SJB_AdminNotifications::sendAdminListingExpiredLetter($listingInfo);
        }
        $listingsDeactivatedID = array();
        if (SJB_Settings::getSettingByName('automatically_delete_expired_listings')) {
            $listingsDeactivatedID = SJB_ListingManager::getDeactivatedListingsSID();
            foreach ($listingsDeactivatedID as $listingID) {
                SJB_ListingManager::deleteListingBySID($listingID);
            }
        }
        SJB_ListingManager::unFeaturedListings();
        SJB_ListingManager::unPriorityListings();
        SJB_Cache::getInstance()->clean('matchingAnyTag', array(SJB_Cache::TAG_LISTINGS));
        /////////////////////////// Send remind notifications about expiration of LISTINGS
        // 1. get user sids and days count of 'remind listing notification' setting = 1 from user_notifications table
        // 2. foreach user:
        //   - get listings with that expiration remind date
        //   - check every listing sid in DB table of sended. If sended - remove from send list
        //   - send notification with listings to user
        //   - write listings sid in DB table of sended notifications
        $notificationData = SJB_UserNotificationsManager::getUsersAndDaysOnListingExpirationRemind();
        foreach ($notificationData as $elem) {
            $userSID = $elem['user_sid'];
            $days = $elem['days'];
            $listingSIDs = SJB_ListingManager::getListingsIDByDaysLeftToExpired($userSID, $days);
            if (empty($listingSIDs)) {
                continue;
            }
            $listingsInfo = array();
            // check listings remind sended
            foreach ($listingSIDs as $key => $sid) {
                if (SJB_ListingManager::isListingNotificationSended($sid)) {
                    unset($listingSIDs[$key]);
                    continue;
                }
                $info = SJB_ListingManager::getListingInfoBySID($sid);
                $listingsInfo[$sid] = $info;
            }
            if (!empty($listingsInfo)) {
                // now only unsended listings we have in array
                // send listing notification
                foreach ($listingSIDs as $sid) {
                    SJB_Notifications::sendRemindListingExpirationLetter($userSID, $sid, $days);
                }
                // write listing id in DB table of sended notifications
                SJB_ListingManager::saveListingIDAsSendedNotificationsTable($listingSIDs);
            }
        }
        // Send Notifications for Expired Contracts
        $contractsExpiredID = SJB_ContractManager::getExpiredContractsID();
        foreach ($contractsExpiredID as $contractExpiredID) {
            $contractInfo = SJB_ContractManager::getInfo($contractExpiredID);
            $productInfo = SJB_ProductsManager::getProductInfoBySID($contractInfo['product_sid']);
            $userInfo = SJB_UserManager::getUserInfoBySID($contractInfo['user_sid']);
            $serializedExtraInfo = unserialize($contractInfo['serialized_extra_info']);
            if (!empty($serializedExtraInfo['featured_profile']) && !empty($userInfo['featured'])) {
                $contracts = SJB_ContractManager::getAllContractsInfoByUserSID($userInfo['sid']);
                $isFeatured = 0;
                foreach ($contracts as $contract) {
                    if ($contract['id'] != $contractExpiredID) {
                        $serializedExtraInfo = unserialize($contract['serialized_extra_info']);
                        if (!empty($serializedExtraInfo['featured'])) {
                            $isFeatured = 1;
                        }
                    }
                }
                if (!$isFeatured) {
                    SJB_UserManager::removeFromFeaturedBySID($userInfo['sid']);
                }
            }
            if (SJB_UserNotificationsManager::isUserNotifiedOnContractExpiration($contractInfo['user_sid'])) {
                SJB_Notifications::sendUserContractExpiredLetter($userInfo, $contractInfo, $productInfo);
            }
            // notify admin
            SJB_AdminNotifications::sendAdminUserContractExpiredLetter($userInfo['sid'], $contractInfo, $productInfo);
            SJB_ContractManager::deleteContract($contractExpiredID, $contractInfo['user_sid']);
        }
        //////////////////////// Send remind notifications about expiration of contracts
        // 1. get user sids and days count of 'remind subscription notification' setting = 1 from user_notifications table
        // 2. foreach user:
        //   - get contracts with that expiration remind date
        //   - check every contract sid in DB table of sended. If sended - remove from send list
        //   - send notification with contracts to user
        //   - write contract sid in DB table of sended contract notifications
        $notificationData = SJB_UserNotificationsManager::getUsersAndDaysOnSubscriptionExpirationRemind();
        foreach ($notificationData as $elem) {
            $userSID = $elem['user_sid'];
            $days = $elem['days'];
            $contractSIDs = SJB_ContractManager::getContractsIDByDaysLeftToExpired($userSID, $days);
            if (empty($contractSIDs)) {
                continue;
            }
            $contractsInfo = array();
            // check contracts sended
            foreach ($contractSIDs as $key => $sid) {
                if (SJB_ContractManager::isContractNotificationSended($sid)) {
                    unset($contractSIDs[$key]);
                    continue;
                }
                $info = SJB_ContractManager::getInfo($sid);
                $info['extra_info'] = !empty($info['serialized_extra_info']) ? unserialize($info['serialized_extra_info']) : '';
                $contractsInfo[$sid] = $info;
            }
            if (!empty($contractsInfo)) {
                // now only unsended contracts we have in array
                // send contract notification
                foreach ($contractSIDs as $sid) {
                    SJB_Notifications::sendRemindSubscriptionExpirationLetter($userSID, $contractsInfo[$sid], $days);
                }
                // write contract id in DB table of sended contract notifications
                SJB_ContractManager::saveContractIDAsSendedNotificationsTable($contractSIDs);
            }
        }
        // delete applications with no employer and job seeker
        $emptyApplications = SJB_DB::query('SELECT `id` FROM `applications` WHERE `show_js` = 0 AND `show_emp` = 0');
        foreach ($emptyApplications as $application) {
            SJB_Applications::remove($application['id']);
        }
        // NEWS
        $expiredNews = SJB_NewsManager::getExpiredNews();
        foreach ($expiredNews as $article) {
            SJB_NewsManager::deactivateItemBySID($article['sid']);
        }
        // LISTING XML IMPORT
        SJB_XmlImport::runImport();
        // UPDATE PAGES WITH FUNCTION EQUAL BROWSE(e.g. /browse-by-city/)
        SJB_BrowseDBManager::rebuildBrowses();
        //-------------------sitemap generator--------------------//
        SJB_System::executeFunction('miscellaneous', 'sitemap_generator');
        // CLEAR `error_log` TABLE
        $errorLogLifetime = SJB_System::getSettingByName('error_log_lifetime');
        $lifeTime = strtotime("-{$errorLogLifetime} days");
        if ($lifeTime > 0) {
            SJB_DB::query('DELETE FROM `error_log` WHERE `date` < ?t', $lifeTime);
        }
        SJB_Settings::updateSetting('task_scheduler_last_executed_date', $this->currentDate);
        $this->tp->assign('expired_listings_id', $listingsExpiredID);
        $this->tp->assign('deactivated_listings_id', $listingsDeactivatedID);
        $this->tp->assign('expired_contracts_id', $contractsExpiredID);
        $this->tp->assign('notified_saved_searches_id', $this->notifiedSavedSearchesSID);
        $schedulerLog = $this->tp->fetch('task_scheduler_log.tpl');
        SJB_HelperFunctions::writeCronLogFile('task_scheduler.log', $schedulerLog);
        SJB_DB::query('INSERT INTO `task_scheduler_log`
			(`last_executed_date`, `notifieds_sent`, `expired_listings`, `expired_contracts`, `log_text`)
			VALUES ( NOW(), ?n, ?n, ?n, ?s)', count($this->notifiedSavedSearchesSID), count($listingsExpiredID), count($contractsExpiredID), $schedulerLog);
        SJB_System::getModuleManager()->executeFunction('social', 'linkedin');
        SJB_System::getModuleManager()->executeFunction('social', 'facebook');
        SJB_System::getModuleManager()->executeFunction('classifieds', 'linkedin');
        SJB_System::getModuleManager()->executeFunction('classifieds', 'facebook');
        SJB_System::getModuleManager()->executeFunction('classifieds', 'twitter');
        SJB_Event::dispatch('task_scheduler_run');
    }
Exemple #8
0
 public static function getListingsSIDByUserSID($userSid, $subuser = false, $limit = false)
 {
     $subuserFilter = $subuser !== false ? " AND `subuser_sid` = '" . SJB_DB::quote($subuser) . "'" : '';
     $limit = $limit ? ' LIMIT ' . $limit : '';
     $query = "SELECT `sid` FROM `listings` WHERE `user_sid` = {$userSid}" . $subuserFilter . $limit;
     $cache = SJB_Cache::getInstance();
     if ($cache->test(md5($query))) {
         $listings_info = $cache->load(md5($query));
     } else {
         $listings_info = SJB_DB::query('SELECT `sid` FROM `listings` WHERE `user_sid` = ?n ' . $subuserFilter . $limit, $userSid);
         $cache->save($listings_info, md5($query), array(SJB_Cache::TAG_LISTINGS));
     }
     $listings_sid = array();
     foreach ($listings_info as $listing_info) {
         $listings_sid[] = $listing_info['sid'];
     }
     return $listings_sid;
 }
Exemple #9
0
 public function current()
 {
     $listing_structure = array();
     $info = current($this->array);
     if (is_numeric($info)) {
         $sid = $info;
         $cache = SJB_Cache::getInstance();
         $cacheID = md5('ListingIterator::SJB_ListingManager::getObjectBySID' . $sid);
         if ($cache->test($cacheID)) {
             $listing = $cache->load($cacheID);
         } else {
             $listing = SJB_ListingManager::getObjectBySID($sid);
             $cache->save($listing, $cacheID, array(SJB_Cache::TAG_LISTINGS));
         }
         $listing->addPicturesProperty();
         $cacheId = md5('SJB_ListingTypeManager::getListingTypeIDBySID' . $listing->getListingTypeSID());
         if (SJB_MemoryCache::has($cacheId)) {
             $listing_type = SJB_MemoryCache::get($cacheId);
         } else {
             $listing_type = SJB_ListingTypeManager::getListingTypeIDBySID($listing->getListingTypeSID());
             SJB_MemoryCache::set($cacheId, $listing_type);
         }
         $listing_structure = SJB_ListingManager::createTemplateStructureForListing($listing);
         $listing_structure = SJB_ListingManager::newValueFromSearchCriteria($listing_structure, $this->criteria);
         if ($this->user_logged_in) {
             $listing_structure['saved_listing'] = SJB_SavedListings::getSavedListingsByUserAndListingSid($this->current_user_sid, $listing->getID());
         }
         $listing_structure['activation_date'] = date('Y-m-d H:i:s', strtotime($listing_structure['activation_date']));
         $listing_structure['expiration_date'] = date('Y-m-d H:i:s', strtotime($listing_structure['expiration_date']));
         $listing_structure['listing_url'] = SJB_System::getSystemSettings('SITE_URL') . "/display-" . strtolower($listing_type) . "/" . $listing->getSID() . "/";
         if (isset($listing->details->properties['EmploymentType'])) {
             $employmentInfo = $listing->details->properties['EmploymentType']->type->property_info;
             $employmentTypes = array();
             $employment = explode(",", $employmentInfo['value']);
             foreach ($employmentInfo['list_values'] as $type) {
                 $empType = str_replace(" ", "", $type['caption']);
                 $employmentTypes[$empType] = 0;
                 if (in_array($type['id'], $employment)) {
                     $employmentTypes[$empType] = 1;
                 }
             }
             $listing_structure['myEmploymentType'] = $employmentTypes;
         }
         // GOOGLE MAP SEARCH RESULTS CUSTOMIZATION
         if ($this->view == 'map') {
             $zipCode = $listing_structure['Location']['ZipCode'];
             // get 'latitude' and 'longitude' from zipCode field, if it not set
             $latitude = isset($listing_structure['latitude']) ? $listing_structure['latitude'] : '';
             $longitude = isset($listing_structure['longitude']) ? $listing_structure['longitude'] : '';
             if (!empty($zipCode) && empty($latitude) && empty($longitude)) {
                 $result = SJB_DB::query("SELECT * FROM `locations` WHERE `name` = ?s LIMIT 1", $zipCode);
                 if ($result) {
                     $current_coordinates = array($result[0]['latitude'], $result[0]['longitude']);
                     if (in_array($current_coordinates, self::$coordinates)) {
                         self::$index += 0.0001;
                     }
                     $listing_structure['latitude'] = $result[0]['latitude'] + self::$index;
                     $listing_structure['longitude'] = $result[0]['longitude'] + self::$index;
                     self::$coordinates = array_merge(self::$coordinates, array($current_coordinates));
                 }
             } elseif (!empty($listing_structure['Location']['City']) && !empty($listing_structure['Location']['State']) && !empty($listing_structure['Location']['Country'])) {
                 $address = $listing_structure['Location']['City'] . ', ' . $listing_structure['Location']['State'] . ', ' . $listing_structure['Location']['Country'];
                 $address = urlencode($address);
                 $cache = SJB_Cache::getInstance();
                 $parameters = array('City' => $listing_structure['Location']['City'], 'State' => $listing_structure['Location']['State'], 'Country' => $listing_structure['Location']['Country']);
                 $hash = md5('google_map' . serialize($parameters));
                 $data = $cache->load($hash);
                 if (!$data) {
                     try {
                         $geoCod = SJB_HelperFunctions::getUrlContentByCurl("http://maps.googleapis.com/maps/api/geocode/json?address={$address}&sensor=false");
                         $geoCod = json_decode($geoCod);
                         if ($geoCod->status == 'OK') {
                             $cache->save($geoCod, $hash);
                         }
                     } catch (Exception $e) {
                         $backtrace = SJB_Logger::getBackTrace();
                         SJB_Error::writeToLog(array(array('level' => 'E_USER_WARNING', 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'backtrace' => sprintf("BACKTRACE:\n [%s]", join("<br/>\n", $backtrace)))));
                     }
                 } else {
                     $geoCod = $data;
                 }
                 try {
                     if (!is_object($geoCod)) {
                         throw new Exception("Map object nave not been Created");
                     }
                     if ($geoCod->status != 'OK') {
                         throw new Exception("Status is not OK");
                     }
                     $location = $geoCod->results[0]->geometry->location;
                     $current_coordinates = array($location->lat, $location->lng);
                     if (in_array($current_coordinates, self::$coordinates)) {
                         self::$index += 0.0001;
                     }
                     $listing_structure['latitude'] = $location->lat + self::$index;
                     $listing_structure['longitude'] = $location->lng + self::$index;
                     self::$coordinates = array_merge(self::$coordinates, array($current_coordinates));
                 } catch (Exception $e) {
                     $backtrace = SJB_Logger::getBackTrace();
                     SJB_Error::writeToLog(array(array('level' => 'E_USER_WARNING', 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'backtrace' => sprintf("BACKTRACE:\n [%s]", join("<br/>\n", $backtrace)))));
                 }
             }
         }
     } elseif ($info) {
         $listing_structure = $info;
     }
     return $listing_structure;
 }
 public static function deleteListingTypeBySID($listing_type_sid)
 {
     SJB_ListingFieldManager::deleteListingFieldsByListingTypeSID($listing_type_sid);
     SJB_Cache::getInstance()->clean('matchingAnyTag', array(SJB_Cache::TAG_LISTING_TYPES));
     return SJB_ListingTypeDBManager::deleteListingTypeBySID($listing_type_sid);
 }
 public static function saveListingField($listing_field)
 {
     $result = SJB_ListingFieldDBManager::saveListingComplexField($listing_field);
     SJB_Cache::getInstance()->clean('matchingAnyTag', array(SJB_Cache::TAG_FIELDS));
     return $result;
 }
 public static function getListingFieldInfoByID($listing_field_id)
 {
     $cache = SJB_Cache::getInstance();
     $cacheId = md5('SJB_ListingFieldDBManager::getListingFieldInfoByID' . $listing_field_id);
     if ($cache->test($cacheId)) {
         return $cache->load($cacheId);
     }
     $result = null;
     $sid = SJB_ListingFieldDBManager::getListingFieldsValue($listing_field_id, 'id');
     if (!empty($sid)) {
         $listing_field_sid = $sid[0]['sid'];
         $result = parent::getObjectInfo('listing_fields', $listing_field_sid);
     }
     $cache->save($result, $cacheId, array(SJB_Cache::TAG_FIELDS));
     return $result;
 }
Exemple #13
0
 public function execute()
 {
     $tp = SJB_System::getTemplateProcessor();
     $display_form = new SJB_Form();
     $display_form->registerTags($tp);
     $current_user = SJB_UserManager::getCurrentUser();
     $errors = array();
     $template = SJB_Request::getVar('display_template', 'display_listing.tpl');
     $tcpdfError = SJB_Request::getVar('error', false);
     $action = substr($template, 0, -4);
     $listing_id = SJB_Request::getVar("listing_id");
     if (isset($_REQUEST['passed_parameters_via_uri'])) {
         $passed_parameters_via_uri = SJB_UrlParamProvider::getParams();
         $listing_id = isset($passed_parameters_via_uri[0]) ? $passed_parameters_via_uri[0] : null;
     }
     if (is_null($listing_id) && SJB_FormBuilderManager::getIfBuilderModeIsSet()) {
         $listing_type_id = SJB_Request::getVar('listing_type_id');
         $listing_id = SJB_ListingManager::getListingIDByListingTypeID($listing_type_id);
     }
     if (is_null($listing_id)) {
         $errors['UNDEFINED_LISTING_ID'] = true;
     } elseif (is_null($listing = SJB_ListingManager::getObjectBySID($listing_id)) || !SJB_ListingManager::isListingAccessableByUser($listing_id, SJB_UserManager::getCurrentUserSID())) {
         $errors['WRONG_LISTING_ID_SPECIFIED'] = true;
     } elseif (!$listing->isActive() && $listing->getUserSID() != SJB_UserManager::getCurrentUserSID()) {
         $errors['LISTING_IS_NOT_ACTIVE'] = true;
     } elseif (($listingStatus = SJB_ListingManager::getListingApprovalStatusBySID($listing_id)) != 'approved' && SJB_ListingTypeManager::getWaitApproveSettingByListingType($listing->listing_type_sid) == 1 && $listing->getUserSID() != SJB_UserManager::getCurrentUserSID()) {
         $errors['LISTING_IS_NOT_APPROVED'] = true;
     } elseif (SJB_ListingTypeManager::getListingTypeIDBySID($listing->listing_type_sid) == 'Resume' && ($template == 'display_job.tpl' or SJB_System::getURI() == '/print-job/') || SJB_ListingTypeManager::getListingTypeIDBySID($listing->listing_type_sid) == 'Job' && ($template == 'display_resume.tpl' or SJB_System::getURI() == '/print-resume/')) {
         $errors['WRONG_DISPLAY_TEMPLATE'] = true;
     } else {
         $listing_type_id = SJB_ListingTypeManager::getListingTypeIDBySID($listing->listing_type_sid);
         if (SJB_System::getURI() == '/print-listing/') {
             SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/print-' . strtolower($listing_type_id) . '/?listing_id=' . $listing_id);
             exit;
         }
         $listing->addPicturesProperty();
         $display_form = new SJB_Form($listing);
         $display_form->registerTags($tp);
         $form_fields = $display_form->getFormFieldsInfo();
         $listingOwner = SJB_UserManager::getObjectBySID($listing->user_sid);
         if ($action !== 'print_listing') {
             SJB_ListingManager::incrementViewsCounterForListing($listing_id, $listing);
         }
         $listing_structure = SJB_ListingManager::createTemplateStructureForListing($listing, array('comments', 'ratings'));
         $filename = SJB_Request::getVar('filename', false);
         if ($filename) {
             $file = SJB_UploadFileManager::openFile($filename, $listing_id);
             $errors['NO_SUCH_FILE'] = true;
         }
         $metaDataProvider = SJB_ObjectMother::getMetaDataProvider();
         $tp->assign("METADATA", array("listing" => $metaDataProvider->getMetaData($listing_structure['METADATA']), "form_fields" => $metaDataProvider->getFormFieldsMetadata($form_fields)));
         $comments = array();
         $comments_total = '';
         if (SJB_Settings::getSettingByName('show_comments') == '1') {
             $comments = SJB_CommentManager::getEnabledCommentsToListing($listing_id);
             $comments_total = count($comments);
         }
         $searchId = SJB_Request::getVar("searchId", "");
         $page = SJB_Request::getVar("page", "");
         $criteria_saver = new SJB_ListingCriteriaSaver($searchId);
         $searchCriteria = $criteria_saver->getCriteria();
         $keywordsHighlight = '';
         if (isset($searchCriteria['keywords']) && SJB_System::getSettingByName('use_highlight_for_keywords')) {
             foreach ($searchCriteria['keywords'] as $type => $keywords) {
                 switch ($type) {
                     case 'like':
                     case 'exact_phrase':
                         $keywordsHighlight = json_encode($keywords);
                         break;
                     case 'all_words':
                     case 'any_words':
                         $keywordsHighlight = json_encode(explode(' ', $keywords));
                         break;
                     case 'boolean':
                         $keywordsHighlight = json_encode(SJB_BooleanEvaluator::parse($keywords, true));
                         break;
                 }
             }
         }
         $prevNextIds = $criteria_saver->getPreviousAndNextObjectID($listing_id);
         $search_criteria_structure = $criteria_saver->createTemplateStructureForCriteria();
         //permissions contact info
         $acl = SJB_Acl::getInstance();
         $permission = 'view_' . $listing_type_id . '_contact_info';
         $allowViewContactInfo = false;
         if (SJB_UserManager::isUserLoggedIn()) {
             if (SJB_ContractManager::isPageViewed($current_user->getSID(), $permission, $listing_id) || $acl->isAllowed($permission) && in_array($acl->getPermissionParams($permission), array('', '0'))) {
                 $allowViewContactInfo = true;
             } elseif ($acl->isAllowed($permission)) {
                 $viewContactInfo['count_views'] = 0;
                 $contractIDs = $current_user->getContractID();
                 $numberOfContactViewed = SJB_ContractManager::getNumbeOfPagesViewed($current_user->getSID(), $contractIDs, $permission);
                 foreach ($contractIDs as $contractID) {
                     if ($acl->getPermissionParams($permission, $contractID, 'contract')) {
                         $params = $acl->getPermissionParams($permission, $contractID, 'contract');
                         $viewsLeft = SJB_ContractManager::getNumbeOfPagesViewed($current_user->getSID(), array($contractID), $permission);
                         if (isset($viewContactInfo['count_views']) && is_numeric($params)) {
                             $viewContactInfo['count_views'] += $params;
                             if ($params > $viewsLeft) {
                                 $viewContactInfo['contract_id'] = $contractID;
                             }
                         }
                     }
                 }
                 if ($viewContactInfo && $viewContactInfo['count_views'] > $numberOfContactViewed) {
                     $allowViewContactInfo = true;
                     SJB_ContractManager::addViewPage($current_user->getSID(), $permission, $listing_id, $viewContactInfo['contract_id'], $listing->getListingTypeSID());
                 }
             }
             $user_group_id = SJB_UserGroupManager::getUserGroupIDBySID($current_user->getUserGroupSID());
             if ($allowViewContactInfo && $user_group_id == 'JobSeeker' && $listing_type_id == 'Job') {
                 SJB_UserManager::saveRecentlyViewedListings($current_user->getSID(), $listing_id);
             }
         } elseif ($acl->isAllowed($permission)) {
             $allowViewContactInfo = true;
         }
         $tp->assign("keywordsHighlight", $keywordsHighlight);
         $tp->assign('allowViewContactInfo', $allowViewContactInfo);
         $tp->assign('show_rates', SJB_Settings::getSettingByName('show_rates'));
         $tp->assign("isApplied", SJB_Applications::isApplied($listing_id, SJB_UserManager::getCurrentUserSID()));
         $tp->assign('show_rates', SJB_Settings::getSettingByName('show_rates'));
         $tp->assign('show_comments', SJB_Settings::getSettingByName('show_comments'));
         $tp->assign('comments', $comments);
         $tp->assign('comments_total', $comments_total);
         $tp->assign('listing_id', $listing_id);
         $tp->assign("form_fields", $form_fields);
         $tp->assign('video_fields', SJB_HelperFunctions::takeMediaFields($form_fields));
         $tp->assign('uri', base64_encode(SJB_Navigator::getURIThis()));
         $tp->assign('listingOwner', $listingOwner);
         $listing_structure = SJB_ListingManager::newValueFromSearchCriteria($listing_structure, $criteria_saver->criteria);
         // SJB-1197: ajax autoupload.
         // Fix to view video from temporary uploaded storage.
         $sessionFilesStorage = SJB_Session::getValue('tmp_uploads_storage');
         // NEED TO CHECK FOR COMPLEX PARENT AND COMPLEX STEP PARAMETERS!
         $complexParent = SJB_Request::getVar('complexParent');
         $complexStep = SJB_Request::getVar('complexEnum');
         $fieldId = SJB_Request::getVar('field_id');
         $isComplex = false;
         if ($complexParent && $complexStep) {
             $fieldId = $complexParent . ":" . $fieldId . ":" . $complexStep;
             $isComplex = true;
         }
         $tempFileValue = SJB_Array::getPath($sessionFilesStorage, "listings/{$listing_id}/{$fieldId}");
         if ($isComplex) {
             $uploadFileManager = new SJB_UploadFileManager();
             $fileLink = $uploadFileManager->getUploadedFileLink($tempFileValue['file_id']);
             $tp->assign('videoFileLink', $fileLink);
         } else {
             if (!empty($tempFileValue)) {
                 $fileUniqueId = isset($tempFileValue['file_id']) ? $tempFileValue['file_id'] : '';
                 if (!empty($fileUniqueId)) {
                     $upload_manager = new SJB_UploadFileManager();
                     // file structure for videoplayer
                     $fileInfo = array('file_url' => $upload_manager->getUploadedFileLink($fileUniqueId), 'file_name' => $upload_manager->getUploadedFileName($fileUniqueId), 'saved_file_name' => $upload_manager->getUploadedSavedFileName($fileUniqueId), 'file_id' => $fileUniqueId);
                     $listing_structure[$fieldId] = $fileInfo;
                 }
             }
         }
         // SJB-1197
         // GOOGLE MAP SEARCH RESULTS CUSTOMIZATION
         $zipCode = '';
         if (!empty($listing_structure['Location']['ZipCode'])) {
             $zipCode = $listing_structure['Location']['ZipCode'];
         }
         // get 'latitude' and 'longitude' from zipCode field, if it not set
         $latitude = isset($listing_structure['latitude']) ? $listing_structure['latitude'] : '';
         $longitude = isset($listing_structure['longitude']) ? $listing_structure['longitude'] : '';
         if (!empty($zipCode) && empty($latitude) && empty($longitude)) {
             $result = SJB_DB::query("SELECT * FROM `locations` WHERE `name` = ?s LIMIT 1", $zipCode);
             if ($result) {
                 $listing_structure['latitude'] = $result[0]['latitude'];
                 $listing_structure['longitude'] = $result[0]['longitude'];
             }
         } elseif (!empty($listing_structure['Location']['City']) && !empty($listing_structure['Location']['State']) && !empty($listing_structure['Location']['Country'])) {
             $address = $listing_structure['Location']['City'] . ', ' . $listing_structure['Location']['State'] . ', ' . $listing_structure['Location']['Country'];
             $address = urlencode($address);
             $cache = SJB_Cache::getInstance();
             $parameters = array('City' => $listing_structure['Location']['City'], 'State' => $listing_structure['Location']['State'], 'Country' => $listing_structure['Location']['Country']);
             $hash = md5('google_map' . serialize($parameters));
             $data = $cache->load($hash);
             $geoCod = '';
             if (!$data) {
                 try {
                     $geoCod = SJB_HelperFunctions::getUrlContentByCurl("http://maps.googleapis.com/maps/api/geocode/json?address={$address}&sensor=false");
                     $geoCod = json_decode($geoCod);
                     if ($geoCod->status == 'OK') {
                         $cache->save($geoCod, $hash);
                     }
                 } catch (Exception $e) {
                     $backtrace = SJB_Logger::getBackTrace();
                     SJB_Error::writeToLog(array(array('level' => 'E_USER_WARNING', 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'backtrace' => sprintf("BACKTRACE:\n [%s]", join("<br/>\n", $backtrace)))));
                 }
             } else {
                 $geoCod = $data;
             }
             try {
                 if (!is_object($geoCod)) {
                     throw new Exception("Map object nave not been Created");
                 }
                 if ($geoCod->status !== 'OK') {
                     throw new Exception("Status is not OK");
                 }
                 $location = $geoCod->results[0]->geometry->location;
                 $listing_structure['latitude'] = $location->lat;
                 $listing_structure['longitude'] = $location->lng;
             } catch (Exception $e) {
                 $backtrace = SJB_Logger::getBackTrace();
                 SJB_Error::writeToLog(array(array('level' => 'E_USER_WARNING', 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'backtrace' => sprintf("BACKTRACE:\n [%s]", join("<br/>\n", $backtrace)))));
             }
         }
         if (SJB_Request::getVar('view')) {
             $tp->assign('listings', array($listing_structure));
         }
         $tp->filterThenAssign("listing", $listing_structure);
         $tp->assign("prev_next_ids", $prevNextIds);
         $tp->assign("searchId", $searchId);
         $tp->assign("page", $page);
         $tp->filterThenAssign("search_criteria", $search_criteria_structure);
         $tp->filterThenAssign("search_uri", $criteria_saver->getUri());
         if ($field_id = SJB_Request::getVar('field_id')) {
             // SJB-825
             $complexEnum = SJB_Request::getVar('complexEnum', null, 'GET');
             $complexFieldID = SJB_Request::getVar('complexParent', null, 'GET');
             if (!is_null($complexEnum) && !is_null($complexFieldID)) {
                 $videoFileID = $complexFieldID . ':' . $field_id . ':' . $complexEnum . '_' . $listing_id;
                 $videoFileLink = SJB_UploadFileManager::getUploadedFileLink($videoFileID);
                 if ($videoFileLink) {
                     $tp->assign('videoFileLink', $videoFileLink);
                 }
             }
             // SJB-825
             $tp->assign('field_id', $field_id);
         } else {
             if (SJB_Request::getVar('action', false) == 'download_pdf_version') {
                 $formBuilder = SJB_FormBuilderManager::getFormBuilder(SJB_FormBuilderManager::FORM_BUILDER_TYPE_PDF, $listing_type_id);
                 $formBuilder->setChargedTemplateProcessor($tp);
                 $tpl = 'resume_to_pdf.tpl';
                 if ($listing_structure['anonymous'] == '1') {
                     $filename = 'Anonymous User_' . $listing_structure['Title'] . '.pdf';
                 } else {
                     $filename = $listing_structure['user']['FirstName'] . ' ' . $listing_structure['user']['LastName'] . '_' . $listing_structure['Title'] . '.pdf';
                 }
                 try {
                     $html = $tp->fetch($tpl);
                     $html = preg_replace('/<div[^>]*>/', '', $html);
                     $html = str_replace('</div>', '', $html);
                     SJB_HelperFunctions::html2pdf($html, $filename, str_replace('http://', '', SJB_HelperFunctions::getSiteUrl()));
                     exit;
                 } catch (Exception $e) {
                     SJB_Error::writeToLog($e->getMessage());
                     SJB_HelperFunctions::redirect(SJB_System::getSystemSettings("SITE_URL") . '/display-resume/' . $listing_id . '/?error=TCPDF_ERROR');
                 }
             } else {
                 $formBuilder = SJB_FormBuilderManager::getFormBuilder(SJB_FormBuilderManager::FORM_BUILDER_TYPE_DISPLAY, $listing_type_id);
                 $formBuilder->setChargedTemplateProcessor($tp);
             }
         }
     }
     if ($errors) {
         foreach ($errors as $k => $v) {
             switch ($k) {
                 case 'TCPDF_ERROR':
                 case 'UNDEFINED_LISTING_ID':
                 case 'WRONG_LISTING_ID_SPECIFIED':
                 case 'LISTING_IS_NOT_ACTIVE':
                 case 'LISTING_IS_NOT_APPROVED':
                     $header = $_SERVER['SERVER_PROTOCOL'] . ' 404  Not Found';
                     $header_status = "Status: 404  Not Found";
                     header($header_status);
                     header($header);
                     SJB_System::setGlobalTemplateVariable('page_not_found', true);
                     break;
             }
         }
     }
     $tp->assign('errors', $errors);
     $tp->assign('tcpdfError', $tcpdfError);
     $tp->display($template);
 }
 public static function addLevelField($level)
 {
     SJB_Cache::getInstance()->clean('matchingAnyTag', array(SJB_Cache::TAG_FIELDS));
     if (!SJB_DB::query("SHOW COLUMNS FROM `listing_fields` WHERE `Field` = ?s", 'level_' . $level)) {
         $fieldLevel = 'level_' . $level;
         if ($level > 1) {
             $prevLevel = 'level_' . ($level - 1);
             SJB_DB::query("ALTER TABLE `listing_fields` ADD `{$fieldLevel}` VARCHAR( 255 ) NULL AFTER `{$prevLevel}`");
         } else {
             SJB_DB::query("ALTER TABLE `listing_fields` ADD `{$fieldLevel}` VARCHAR( 255 ) NULL");
         }
     }
 }
Exemple #15
0
 public static function setDefaultProduct($groupSID, $productSID)
 {
     SJB_Cache::getInstance()->clean('matchingAnyTag', array(SJB_Cache::TAG_FIELDS, SJB_Cache::TAG_USERS));
     SJB_DB::query('UPDATE `user_groups`	SET `default_product` = ?n WHERE `sid` = ?n', $productSID, $groupSID);
     return true;
 }
Exemple #16
0
 public static function setListingApprovalStatus($listingSids, $status, $updateBrowsePages = true)
 {
     $statusValues = array('pending', 'approved', 'rejected');
     if (in_array($status, $statusValues)) {
         if (!is_array($listingSids)) {
             $listingSids = array($listingSids);
         }
         if ($updateBrowsePages) {
             SJB_BrowseDBManager::deleteListings($listingSids);
         }
         switch ($status) {
             case 'pending':
                 // set status to 'pending' and clear reject reason
                 SJB_DB::queryExec("UPDATE `listings` SET `status`=?s, `reject_reason` = '' WHERE `sid` IN (?l)", $status, $listingSids);
                 break;
             case 'approved':
                 SJB_DB::queryExec("UPDATE `listings` SET `status`=?s WHERE `sid` IN (?l)", $status, $listingSids);
                 break;
             case 'rejected':
                 $rejectReason = $_REQUEST['rejectReason'] != '' ? $_REQUEST['rejectReason'] : 'rejected with no reason';
                 SJB_DB::queryExec("UPDATE `listings` SET `status`=?s, `reject_reason` = ?s WHERE `sid` IN (?l)", $status, $rejectReason, $listingSids);
                 break;
         }
         SJB_Cache::getInstance()->clean('matchingAnyTag', array(SJB_Cache::TAG_LISTINGS));
         if ($updateBrowsePages && $status == 'approved') {
             SJB_BrowseDBManager::addListings($listingSids);
         }
     }
 }
Exemple #17
0
 public static function deleteCountryBySID($sid)
 {
     SJB_Cache::getInstance()->clean('matchingAnyTag', array(SJB_Cache::TAG_FIELDS));
     SJB_StatesManager::deleteStatesByCountrySID($sid);
     return SJB_DB::query("DELETE FROM `countries` WHERE `sid` = ?n", $sid);
 }
 public static function getUserProfileFieldInfoByID($user_field_id)
 {
     $cache = SJB_Cache::getInstance();
     $cacheId = md5('SJB_UserProfileFieldManager::getUserProfileFieldInfoByID' . $user_field_id);
     if ($cache->test($cacheId)) {
         return $cache->load($cacheId);
     }
     $result = null;
     $sid = self::getUserProfileFieldsValue($user_field_id, 'id');
     if (!empty($sid)) {
         $user_field_sid = $sid[0]['sid'];
         $result = SJB_ObjectDBManager::getObjectInfo('user_profile_fields', $user_field_sid);
     }
     $cache->save($result, $cacheId, array(SJB_Cache::TAG_FIELDS));
     return $result;
 }
Exemple #19
0
 /**
  * @param $fieldName
  * @param $fieldID
  * @param SJB_SearchResultsTP $stp
  * @param $userField
  * @return mixed
  */
 public static function countListingsByFieldName($fieldName, $fieldID, $stp, $userField)
 {
     $refineSearchLimit = SJB_Settings::getSettingByName('refine_search_items_limit');
     $limit = $refineSearchLimit ? ' LIMIT 0, ' . $refineSearchLimit : '';
     $listing = new SJB_Listing(array(), $stp->listing_type_sid);
     $id_alias_info = $listing->addIDProperty();
     $listing->addActivationDateProperty();
     $listing->addFeaturedProperty();
     $username_alias_info = $listing->addUsernameProperty();
     $listing_type_id_info = $listing->addListingTypeIDProperty();
     $listing->addCompanyNameProperty();
     $requestedCriteria = $stp->criteria_saver->getCriteria();
     if (isset($requestedCriteria['PostedWithin']) && $requestedCriteria['PostedWithin']['multi_like'][0] != '') {
         $within_period = $requestedCriteria['PostedWithin']['multi_like'][0];
         $i18n = SJB_I18N::getInstance();
         $requestedCriteria['activation_date']['not_less'] = $i18n->getDate(date('Y-m-d', strtotime("- {$within_period} days")));
         unset($requestedCriteria['PostedWithin']);
     }
     if (isset($requestedCriteria['CompanyName']['multi_like_and'][0])) {
         $userName = SJB_UserManager::getUserNameByCompanyName($requestedCriteria['CompanyName']['multi_like_and'][0]);
         unset($requestedCriteria['CompanyName']);
         if ($userName) {
             $requestedCriteria['username']['equal'] = $userName;
         }
     }
     $criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($requestedCriteria, $listing);
     $aliases = new SJB_PropertyAliases();
     $aliases->addAlias($id_alias_info);
     $aliases->addAlias($username_alias_info);
     $aliases->addAlias($listing_type_id_info);
     $aliases->changeAliasValuesInCriteria($criteria);
     $sqlTranslator = new SJB_SearchSqlTranslator('listings');
     $whereStatement = $sqlTranslator->_getWhereStatement($criteria);
     $objectSids = implode(',', $stp->found_listings_sids);
     if ($userField == 1) {
         $field = SJB_UserProfileFieldManager::getFieldInfoBySID($fieldID);
     } else {
         $field = SJB_ListingFieldDBManager::getListingFieldInfoBySID($fieldID);
     }
     $result = array();
     $cache = SJB_Cache::getInstance();
     if (!empty($field['parent_sid'])) {
         $parentInfo = SJB_ListingFieldManager::getFieldInfoBySID($field['parent_sid']);
         $fieldName = $parentInfo['id'] . "_" . $fieldName;
         $field['id'] = $fieldName;
         $field['parentID'] = $parentInfo['id'];
     }
     switch ($field['type']) {
         case 'list':
         case 'multilist':
             if ($userField == 1) {
                 $query = "SELECT up.`{$fieldName}` as caption, count(`listings`.`sid`) as count\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t FROM `listings`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t INNER JOIN `users` `up` ON `listings`.`user_sid` = `up`.`sid`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {$whereStatement}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t AND up.`{$fieldName}` != ''\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t GROUP BY `up`.`{$fieldName}` ORDER BY count DESC";
                 if (!($result = $cache->load(md5($query)))) {
                     $result = SJB_DB::query($query);
                     $cache->save($result, md5($query), array(SJB_Cache::TAG_LISTINGS, SJB_Cache::TAG_USERS));
                 }
             } else {
                 $query = "SELECT `{$fieldName}` as caption, count(`{$fieldName}`) as count FROM `listings` {$whereStatement} AND `{$fieldName}` != '' GROUP BY `{$fieldName}` ORDER BY count DESC";
                 if (!($result = $cache->load(md5($query)))) {
                     $result = SJB_DB::query($query);
                     $cache->save($result, md5($query), array(SJB_Cache::TAG_LISTINGS));
                 }
             }
             self::breakMultiCategory($result);
             $newResult = array();
             $listItem = new SJB_ListingFieldListItemManager();
             foreach ($result as $key => $val) {
                 if (!empty($field['parent_sid'])) {
                     $caption = '';
                     if ($field['id'] == $field['parentID'] . '_State') {
                         $listValues = SJB_StatesManager::getStatesNamesByCountry(false, true, $field['display_as']);
                     } else {
                         $listValues = $field['list_values'];
                     }
                     foreach ($listValues as $listValue) {
                         if ($listValue['id'] == $val['caption']) {
                             $caption = $listValue['caption'];
                             break;
                         }
                     }
                 } else {
                     $itemInfo = $listItem->getListItemBySID($val['caption']);
                     $caption = $itemInfo ? $itemInfo->getValue() : null;
                 }
                 if ($caption != null) {
                     $newResult[$key]['count'] = $val['count'];
                     $newResult[$key]['value'] = $caption;
                     $newResult[$key]['sid'] = $val['caption'];
                 }
             }
             arsort($newResult);
             $result = $newResult;
             if (count($result) > $refineSearchLimit) {
                 $result = array_slice($result, 0, $refineSearchLimit);
             }
             break;
         case 'tree':
             $query = "SELECT `lt`.`sid` as `sid`, `lt`.`caption` as `value`, count(`listings`.`sid`) as `count`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM `listings`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN `listing_field_tree` `lt` ON `lt`.`field_sid` = {$field['sid']} AND find_in_set(`lt`.`sid`, `listings`.`{$fieldName}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{$whereStatement} GROUP BY `lt`.`sid` having `lt`.`sid` IS NOT NULL ORDER BY `count` DESC {$limit}";
             if (!($propertyValue = $cache->load(md5($query)))) {
                 $propertyValue = SJB_DB::query($query);
                 $cache->save($propertyValue, md5($query), array(SJB_Cache::TAG_LISTINGS, SJB_Cache::TAG_FIELDS));
             }
             foreach ($propertyValue as $value) {
                 $result[$value['sid']] = $value;
             }
             break;
         default:
             if ($userField == 1) {
                 $companyColumn = "up.`{$fieldName}`";
                 $query = "SELECT {$companyColumn} as `value`, count(listings.`sid`) as `count`\n\t\t\t\t\t\t\t\t\t\t\t FROM `listings`\n\t\t\t\t\t\t\t\t\t\t\t INNER JOIN `users` `up` ON `listings`.`user_sid` = `up`.`sid`\n\t\t\t\t\t\t\t\t\t\t\t {$whereStatement}\n\t\t\t\t\t\t\t\t\t\t\t GROUP BY {$companyColumn} ORDER BY `count` DESC {$limit}";
                 if (!($result = $cache->load(md5($query)))) {
                     $result = SJB_DB::query($query);
                     $cache->save($result, md5($query), array(SJB_Cache::TAG_LISTINGS, SJB_Cache::TAG_USERS));
                 }
             } else {
                 if ($field['type'] == 'complex') {
                     $query = "SELECT `value`, count(`value`) as count FROM `listings_properties` WHERE `id`='{$fieldName}' AND `value` != '' AND `object_sid` in ({$objectSids}) GROUP BY `value` ORDER BY count DESC {$limit}";
                 } else {
                     $query = "SELECT `{$fieldName}` as value, count(`{$fieldName}`) as count FROM `listings` {$whereStatement} AND `{$fieldName}` != '' GROUP BY `{$fieldName}` ORDER BY count DESC {$limit}";
                 }
                 if (!($result = $cache->load(md5($query)))) {
                     $result = SJB_DB::query($query);
                     $cache->save($result, md5($query), array(SJB_Cache::TAG_LISTINGS));
                 }
             }
             break;
     }
     $returnArr['caption'] = $field['caption'];
     $returnArr['values'] = $result;
     return $returnArr;
 }