예제 #1
0
 /**
  * Изменение позиции пользователя.
  *
  * @param integer $user           uid пользователя
  * @param integer $transaction_id id транзакции
  * @param array   $bids           массив, в котором индекс элементов - id места размещения, значения - сумма для поднятия позиции
  *
  * @return integer id операции транзакции
  */
 public function BidPlaces($user, $transaction_id, $bids, &$error)
 {
     $bill_id = 0;
     if ($bids) {
         foreach ($bids as $prof => $sum) {
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/account.php';
             $account = new account();
             $error = $account->Buy($bill_id, $transaction_id, 21, $user, $prof, '', $sum, 0);
             if ($error !== 0) {
                 return 0;
             }
             global $DB;
             $sql = 'UPDATE users_first_page SET psum=psum+? WHERE id IN (SELECT id FROM users_first_page 
                 WHERE user_id = ? AND from_date+to_date >= now() AND payed=true
                 AND ordered = true AND profession=? )';
             $DB->query($sql, $sum, $user, $prof);
             $id = 1;
         }
     }
     if ($bill_id) {
         //$account->commit_transaction($transaction_id, $user, $bill_id);
         $memBuff = new memBuff();
         $memBuff->flushGroup('firstpg');
     }
     return $id;
 }
예제 #2
0
 /**
  * Создание нового предложения
  *
  * @param array $create    Переменная типа array(name=>value) где name - поле таблицы, value - значение для записи (@see Таблица freelance_offers) 
  * @return boolean|string
  */
 public function Create($create)
 {
     global $DB;
     $uid = $create['user_id'];
     if ($_SESSION['uid'] == $uid && !is_emp()) {
         $account = new account();
         $transaction_id = $account->start_transaction($uid, $tr_id);
         $error = $account->Buy($billing_id, $transaction_id, self::FM_OP_CODE, $uid, "Покупка публикации предложения фрилансера", "Покупка публикации предложения", 1, 0);
         if ($error) {
             return $error;
         }
         $account->commit_transaction($transaction_id, $uid, $billing_id);
         $create['bill_id'] = $billing_id;
         $create['moderator_status'] = is_pro() ? NULL : 0;
         $id_offer = $DB->insert('freelance_offers', $create, 'id');
         if ($id_offer > 0) {
             if (!is_pro()) {
                 require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/stop_words.php';
                 require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/user_content.php';
                 $stop_words = new stop_words();
                 $nStopWordsCnt = $stop_words->calculate($fields['descr'], $fields['title']);
                 $DB->insert('moderation', array('rec_id' => $id_offer, 'rec_type' => user_content::MODER_SDELAU, 'stop_words_cnt' => $nStopWordsCnt));
             }
             return $id_offer;
         }
         return false;
     } else {
         return false;
     }
 }
예제 #3
0
 /**
  * Изменение логина юзера. Перед вызовом необходимо проинициализировать члены класса
  * old_login, new_login, save_old.
  * 
  * @param string $error	возвращает сообщение об ошибке	
  *
  * @return 0
  *
  * @see classes/db_access#Add($error, $return_id)
  */
 public function Add(&$error)
 {
     global $DB;
     require_once ABS_PATH . '/classes/users.php';
     $user = new users();
     $this->user_id = $user->GetUid($error, $this->old_login);
     if (!$this->user_id) {
         $error = 'Пользователь не найден!';
         return 0;
     }
     $new_user = $user->GetUid($error, $this->new_login);
     if ($new_user) {
         $error = 'Логин занят!';
         return 0;
     }
     if ($this->save_old) {
         require_once ABS_PATH . '/classes/users_old.php';
         require_once ABS_PATH . '/classes/account.php';
         $account = new account();
         $tr_id = $account->start_transaction($this->user_id);
         $id = 0;
         $error = $account->Buy($id, $tr_id, self::OP_CODE, $this->user_id, 'Изменеие логина', 'Изменение логина');
         if ($error) {
             return 0;
         }
         $this->operation_id = $id;
         $users_old = new users_old();
         $users_old->Add($this->old_login);
     }
     if (!$error) {
         $aData = array('user_id' => '', 'old_login' => '', 'new_login' => '', 'save_old' => '', 'operation_id' => '');
         foreach ($aData as $key => $val) {
             $aData[$key] = $this->{$key};
         }
         $CFile = new CFile();
         if (!$CFile->MoveDir($this->new_login, $this->old_login)) {
             $error = "Директория не создана! {$this->new_login}, {$this->old_login}";
             if ($this->operation_id) {
                 $account->Del($this->user_id, $this->operation_id);
             }
         } else {
             $DB->insert('login_change', $aData);
             $user->login = $this->new_login;
             $user->Update($this->user_id, $res);
         }
     }
     return 0;
 }
예제 #4
0
 /**
  * Функция оплаты акции.
  *  
  * @global object $DB база данных
  *
  * @param int $transaction_id ИД транзакции сделки
  * @param int $user_id        ИД пользователя
  *
  * @return int
  */
 public function setPayed($transaction_id, $user_id)
 {
     global $DB;
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/account.php';
     $account = new account();
     if (is_emp($_SESSION['role'])) {
         return 0;
     }
     $bill_id = 0;
     $error = $account->Buy($bill_id, $transaction_id, $this->getConst_OP_CODE(), $user_id, $this->title, $this->descr, $this->getConst_PAYED_SUM(), 0);
     if ($error !== 0) {
         return 0;
     }
     if ($bill_id) {
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/pay_place.php';
         $pay_place = new pay_place(1);
         $account->commit_transaction($transaction_id, $user_id, $bill_id);
         $this->setUserPro($user_id, $bill_id);
         $pay_place->addUserTop($user_id);
         return $bill_id;
     }
     return 0;
 }
/**
 * Сохранение предложения по проектам
 * 
 * @param object $objResponse xajaxResponse
 * @param string $rec_id идентификатор записи
 * @param string $rec_type тип записи
 * @param array $aForm массив данных
 * @param string $sDrawFunc имя функции для выполнения после сохранения
 */
function _admEditPrjOfferSaveForm(&$objResponse, $rec_id = '', $rec_type = '', $aForm = array(), $sDrawFunc = '')
{
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/messages.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/user_content.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects_offers.php';
    $obj_offer = new projects_offers();
    $payed_items = $aForm['ps_payed_items'];
    $payed_color = $aForm['ps_payed_items'][0] == '1';
    if ($aForm['is_color'] && !$payed_color) {
        $account = new account();
        $transaction_id = $account->start_transaction(get_uid());
        $error_buy = $account->Buy($billing_id, $transaction_id, $answers->color_op_code, get_uid(), "Выделение ответа на проект цветом", "Выделение <a href='" . getFriendlyURL("project", $project['id']) . "#freelancer_{$_SESSION['uid']}' target='_blank'>предложения</a> цветом", 1, 1);
        $payed_items = '1';
        if ($error_buy) {
            $aForm['is_color'] = false;
            $payed_items = '0';
        }
    }
    $sReason = _parseReason($aForm['user_id'], $aForm['adm_edit_text']);
    $error = $obj_offer->AddOffer($aForm['user_id'], $aForm['pid'], $aForm['ps_cost_from'], $aForm['ps_cost_to'], $aForm['ps_cost_type'], $aForm['ps_time_from'], $aForm['ps_time_to'], $aForm['ps_time_type'], antispam(stripslashes($aForm['ps_text'])), $aForm['ps_work_1_id'], $aForm['ps_work_2_id'], $aForm['ps_work_3_id'], $aForm['ps_work_1_link'], $aForm['ps_work_2_link'], $aForm['ps_work_3_link'], $aForm['ps_work_1_name'], $aForm['ps_work_2_name'], $aForm['ps_work_3_name'], $aForm['ps_work_1_pict'], $aForm['ps_work_2_pict'], $aForm['ps_work_3_pict'], $aForm['ps_work_1_prev_pict'], $aForm['ps_work_2_prev_pict'], $aForm['ps_work_3_prev_pict'], isset($aForm['ps_for_customer_only']), $aForm['edit'], 0, isset($aForm['prefer_sbr']), $aForm['is_color'], null, $payed_items, 0, $_SESSION['uid'], $sReason);
    if (!$error && !$error_buy && !$payed_color && $account) {
        $account->commit_transaction($transaction_id, get_uid(), $billing_id);
        $is_payed_color = true;
    }
    if ($error) {
        $objResponse->alert('Ошибка сохранения предложения' . $error);
        $sParent = $sDrawFunc == 'stream0' || $sDrawFunc == 'stream1' || $sDrawFunc == 'stream2' ? 'parent.' : '';
        $objResponse->script("{$sParent}adm_edit_content.disabled = false; {$sParent}adm_edit_content.button();");
    } else {
        messages::prjOfferModifiedNotification($aForm['user_id'], $aForm['pid'], $sReason);
        $content_id = user_content::MODER_PRJ_OFFERS;
        _admEditAfterAll($objResponse, $content_id, $rec_id, $rec_type, $sDrawFunc, $aForm);
    }
}
예제 #6
0
 /**
  * Обработка и оплата операций
  * 
  * @global type $DB
  * @param type $option
  * @return boolean 
  */
 function billingOperation($option, $transaction_id)
 {
     global $DB;
     $ok = false;
     $account = new account();
     switch ($option['op_code']) {
         // Аккаунт ПРО у фрилансера
         case 48:
         case 49:
         case 50:
         case 51:
         case 76:
             // Удаляем операции по покупке ответов - публикуем ответы
             $prof = new payed();
             $ok = $prof->SetOrderedTarif($this->uid, $transaction_id, 1, "Аккаунт PRO", $option['op_code'], $error);
             if ($ok) {
                 $_SESSION['pro_last'] = payed::ProLast($_SESSION['login']);
                 $_SESSION['pro_last'] = $_SESSION['pro_last']['freeze_to'] ? false : $_SESSION['pro_last']['cnt'];
                 $userdata = new users();
                 $_SESSION['pro_test'] = $userdata->GetField($this->uid, $error2, 'is_pro_test', false);
                 $this->clearBlockedOperations(step_freelancer::OFFERS_OP_CODE);
                 $step_frl = new step_freelancer();
                 $offers = $step_frl->getWizardOffers($this->uid, 'all', false);
                 if ($offers) {
                     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/users.php";
                     $step_frl->log = $this->log;
                     $step_frl->user = new users();
                     $step_frl->user->GetUserByUID($this->uid);
                     $step_frl->transferOffers($offers);
                 }
                 $this->showProjectsFeedbacks();
             }
             break;
             // Аккаунт ПРО у работодателя
         // Аккаунт ПРО у работодателя
         case 15:
             $prof = new payed();
             $ok = $prof->SetOrderedTarif($this->uid, $transaction_id, 1, "Аккаунт PRO", $option['op_code'], $error);
             if ($ok) {
                 $_SESSION['pro_last'] = payed::ProLast($_SESSION['login']);
                 $_SESSION['pro_last'] = $_SESSION['pro_last']['freeze_to'] ? false : $_SESSION['pro_last']['cnt'];
                 $userdata = new users();
                 $_SESSION['pro_test'] = $userdata->GetField($this->uid, $error2, 'is_pro_test', false);
             }
             // Обновляем выбор цвета для проектов тк он для ПРО бесплатный
             $colorProjects = $this->updateColorProject();
             $prj = new new_projects();
             foreach ($colorProjects as $k => $project) {
                 $delete_color[] = $project['op_id'];
                 if ($project['country'] == null) {
                     $project['country'] = 'null';
                 }
                 if ($project['city'] == null) {
                     $project['city'] = 'null';
                 }
                 $project['name'] = addslashes($project['name']);
                 $project['descr'] = addslashes($project['descr']);
                 if ($project['logo_id'] <= 0) {
                     $project['logo_id'] = 'null';
                 }
                 $project['payed_items'] = $project['payed_items'] | '010';
                 $project['is_color'] = 't';
                 $prj->editPrj($project, false);
             }
             // Удаляем данные операции
             if ($delete_color) {
                 $this->deleteDraftAccountOperation($delete_color);
             }
             break;
             // Публикация конкурса
         // Публикация конкурса
         case new_projects::OPCODE_KON:
         case new_projects::OPCODE_KON_NOPRO:
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/wizard/step_wizard_registration.php';
             $drafts = new drafts();
             $draft = $drafts->getDraft($option['parent_id'], $this->uid, 1);
             // Если еще не опубликован
             if (!$draft['prj_id']) {
                 $project_id = $draft['id'];
                 $error = $account->Buy($bill_id, $transaction_id, $option['op_code'], $this->uid, $option['descr'], $option['comment'], 1, 0);
                 $ok = $bill_id > 0;
                 if ($bill_id) {
                     $color = $DB->val("SELECT id FROM draft_account_operations WHERE parent_id = ? AND op_type = 'contest' AND option = 'color' AND uid = ?", $project_id, wizard::getUserIDReg());
                     $draft['billing_id'] = $bill_id;
                     $draft['folder_id'] = 'null';
                     $draft['payed'] = '0';
                     $draft['payed_items'] = '000';
                     if (is_pro() && $color > 0) {
                         $draft['is_color'] = 't';
                     } else {
                         $draft['is_color'] = 'f';
                     }
                     $draft['win_date'] = date('d-m-Y', strtotime($draft['win_date']));
                     $draft['end_date'] = date('d-m-Y', strtotime($draft['end_date']));
                     $draft['is_bold'] = 'f';
                     $draft['user_id'] = $this->uid;
                     if ($draft['country'] == null) {
                         $draft['country'] = 'null';
                     }
                     if ($draft['city'] == null) {
                         $draft['city'] = 'null';
                     }
                     $draft['name'] = addslashes($draft['name']);
                     $draft['descr'] = addslashes($draft['descr']);
                     if ($draft['logo_id'] <= 0) {
                         $draft['logo_id'] = 'null';
                     }
                     $prj = new new_projects();
                     $attachedfiles_tmpdraft_files = drafts::getAttachedFiles($option['parent_id'], 4);
                     if ($attachedfiles_tmpdraft_files) {
                         $attachedfiles_tmpdraft_files = array_map(create_function('$a', 'return array("id" => $a);'), $attachedfiles_tmpdraft_files);
                     }
                     if ($attachedfiles_tmpdraft_files) {
                         $month = date('Ym');
                         $dir = 'projects/upload/' . $month . '/';
                         $files = step_wizard_registration::transferFiles($attachedfiles_tmpdraft_files, 'file_projects', $dir);
                     }
                     $spec = $draft["categories"];
                     $spec = explode("|", $spec);
                     $spec = array(array('category_id' => $spec[0], 'subcategory_id' => $spec[1]));
                     $prj->addPrj($draft, $files);
                     $prj->saveSpecs($draft["id"], $spec);
                     // смотрим были ли выбраны платные опции для опубликованного конкурса
                     if ($draft['id'] != $project_id && $draft['id'] > 0) {
                         if ($this->sleep[$project_id]) {
                             foreach ($this->sleep[$project_id] as $k => $opt) {
                                 $opt['parent_id'] = $draft['id'];
                                 $this->billingOperation($opt);
                             }
                         } else {
                             //Обновляем родителя на всякий случай
                             $update = array("parent_id" => $draft['id']);
                             $DB->update("draft_account_operations", $update, "parent_id = ? AND op_type = 'contest' AND uid = ?", $project_id, wizard::getUserIDReg());
                             $this->sleep_parent[$project_id] = $draft['id'];
                         }
                         $DB->update("draft_projects", array('prj_id' => $draft['id']), "id = ? AND uid = ?", $project_id, wizard::getUserIDReg());
                     }
                 }
             }
             break;
             // Платный проект/конкурс
         // Платный проект/конкурс
         case 53:
             $prj = new new_projects();
             if ($this->sleep_parent[$option['parent_id']]) {
                 $option['parent_id'] = $this->sleep_parent[$option['parent_id']];
             }
             $project = $prj->getProject($option['parent_id']);
             if (!$project['id']) {
                 $this->sleep[$option['parent_id']][$option['id']] = $option;
                 return true;
             } else {
                 unset($this->sleep[$option['parent_id']]);
             }
             if ($project['country'] == null) {
                 $project['country'] = 'null';
             }
             if ($project['city'] == null) {
                 $project['city'] = 'null';
             }
             $project['name'] = addslashes($project['name']);
             $project['descr'] = addslashes($project['descr']);
             if ($project['logo_id'] <= 0) {
                 $project['logo_id'] = 'null';
             }
             $project['folder_id'] = 'null';
             $items = array();
             switch ($option['option']) {
                 case 'top':
                     $project['top_days'] = $option['op_count'];
                     break;
                 case 'color':
                     $is_pay = $project['payed_items'] & '010';
                     if ($is_pay != '010') {
                         $project['payed_items'] = $project['payed_items'] | '010';
                         $project['is_color'] = 't';
                         $items['color'] = true;
                         if (is_pro()) {
                             $is_payed = true;
                             $prj->SavePayedInfo($items, $project['id'], null, $project['top_days']);
                             $prj->editPrj($project, false);
                         }
                     } else {
                         $is_payed = true;
                     }
                     break;
                 case 'bold':
                     $is_pay = $project['payed_items'] & '001';
                     if ($is_pay != '001') {
                         $project['payed_items'] = $project['payed_items'] | '001';
                         $project['is_bold'] = 't';
                         $items['bold'] = true;
                     } else {
                         $is_payed = true;
                     }
                     break;
                 case 'logo':
                     $is_pay = $project['payed_items'] & '100';
                     if ($is_pay != '100') {
                         $key = md5(microtime());
                         $prj = new tmp_project($key);
                         $prj->init(1);
                         $fu = new CFile($option['src_id']);
                         $ext = $fu->getext();
                         $tmp_dir = $prj->getDstAbsDir();
                         $tmp_name = $fu->secure_tmpname($tmp_dir, '.' . $ext);
                         $tmp_name = substr_replace($tmp_name, "", 0, strlen($tmp_dir));
                         $fu->table = 'file_projects';
                         $r = $fu->_remoteCopy($tmp_dir . $tmp_name);
                         $project['payed_items'] = $project['payed_items'] | '100';
                         $project['logo_id'] = $fu->id;
                         $items['logo'] = true;
                         if ($option['extra']) {
                             $project['link'] = $option['extra'];
                         }
                     } else {
                         $is_payed = true;
                     }
                     break;
             }
             if (!$is_payed) {
                 $error = $account->Buy($bill_id, $transaction_id, $option['op_code'], $this->uid, $option['descr'], $option['comment'], $option['ammount'], 0);
                 $ok = $bill_id > 0;
                 $project['billing_id'] = $bill_id;
                 $prj->SavePayedInfo($items, $project['id'], $bill_id, $project['top_days']);
                 $prj->editPrj($project, false);
             } else {
                 $ok = true;
             }
             break;
             // Платные ответы на проекты
         // Платные ответы на проекты
         case 61:
             $answers = new projects_offers_answers();
             $error = $answers->BuyByFM($this->uid, $option['op_count'], $transaction_id, 0);
             if (!$error) {
                 $ok = true;
                 $_SESSION['answers_ammount'] = $option['op_count'];
                 // Публикуем ответы
                 $step_frl = new step_freelancer();
                 $offers = $step_frl->getWizardOffers($this->uid, $option['op_count']);
                 if ($offers) {
                     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/users.php";
                     $step_frl->log = $this->log;
                     $step_frl->user = new users();
                     $step_frl->user->GetUserByUID($this->uid);
                     $step_frl->transferOffers($offers);
                 }
             }
             break;
     }
     return $ok;
 }
예제 #7
0
 /**
  * Сохраняет временный проект в базу.
  *
  * @param integer $buyer_id     ид. юзера-покупателя проекта. Если указан, то проект будет куплен за его счет (например, для админов).
  * @param mixed &$proj     сюда сохранится информация о проекте после его сохранения
  * @return integer|string   0 в случае успешной покупки или текст ошибки.
  */
 function saveProject($buyer_id = NULL, &$proj, $promo_codes = array())
 {
     $price = 0;
     // Если проект новый добаляется, то надо отослать уведомление
     if (!$this->isEdit()) {
         $need_send_email = true;
     } else {
         $need_send_email = false;
     }
     $operations = array();
     if ($ammount = $this->getAmmount()) {
         $buyer_id = $buyer_id ? $buyer_id : $this->_uid;
         $account = new account();
         if (!$account->GetInfo($buyer_id, true)) {
             return 'Ошибка в получении информации по счету.';
         }
         $is_pro = is_pro(true, $this->_project["user_id"]);
         $price = $this->getPrice($items);
         if ($this->isKonkurs()) {
             if ($items['contest']) {
                 $operations['contest'] = array('op_code' => $is_pro ? self::OPCODE_KON : self::OPCODE_KON_NOPRO, 'op_code_bns' => $is_pro ? self::OPCODE_KON_BNS : self::OPCODE_KON_BNS_NOPRO, 'ammount' => 1, 'comment' => $this->getOperationComment('contest'));
             }
         }
         if ($this->isVacancy()) {
             if ($items['office']) {
                 $operations['office'] = array('op_code' => $this->getVacancyOpCode(), 'op_code_bns' => self::OPCODE_PAYED_BNS, 'ammount' => 1, 'comment' => $this->getOperationComment('office'));
             }
         }
         $services = array('top', 'logo', 'urgent', 'hide');
         foreach ($services as $service) {
             if ($items[$service]) {
                 $operations[$service] = array('op_code' => self::getOpCodeByService($service), 'ammount' => $items[$service], 'comment' => $this->getOperationComment($service));
             }
         }
         foreach ($operations as $service => $operation) {
             $bill_id = 0;
             $this->_transactionId = $account->start_transaction($buyer_id, $this->_transactionId);
             if (!isset($operation['op_code_bns'])) {
                 $operation['op_code_bns'] = $operation['op_code'];
             }
             $descr = trim($operation['comment'], '&');
             if ($this->_project['billing_id']) {
                 $descr .= ' - дополнение к операции #' . $this->_project['billing_id'];
             }
             if ($account->bonus_sum >= $price) {
                 $error = $account->BuyFromBonus($bill_id, $this->_transactionId, $operation['op_code_bns'], $buyer_id, "{$descr} за счет подарка", "{$operation['comment']} за счет подарка", $operation['ammount'], true);
                 if ($error) {
                     return $error;
                 }
             } else {
                 $error = $account->Buy($bill_id, $this->_transactionId, $operation['op_code'], $buyer_id, $descr, $operation['comment'], $operation['ammount'], 0, isset($promo_codes[$service]) ? $promo_codes[$service] : 0);
                 if ($error) {
                     return $error;
                 }
             }
             if (!$bill_id) {
                 return 'Не хватает денег. ' . $account->sum . ' из ' . $price;
             }
             $this->account_operation_id = $bill_id;
             $operations[$service]['bill_id'] = $bill_id;
         }
     }
     $prePrj = $this->_preDb($price, $bill_id);
     $success = $this->isEdit() ? $this->editPrj($this->_project, $this->_attach, array_reverse($this->getCategories())) : $this->addPrj($this->_project, $this->_attach, array_reverse($this->_categories));
     if (!$this->isEdit()) {
         foreach ($operations as $service => $operation) {
             $account->updateComment($this->getOperationComment($service), $operation['bill_id'], array($operation['op_code'], $operation['op_code_bns']));
         }
     }
     $proj = $this->_project;
     if (!$success) {
         $this->_postDbFailed($prePrj, $bill_id, $buyer_id);
         return $error ? $error : 'Error';
     }
     $this->SavePayedInfo($items, $this->_project['id'], $bill_id, $topDays ? $topDays : 1);
     $this->_postDbSuccess();
     if (!$_SESSION['quickprjbuy_ok_id']) {
         $_SESSION['quickprjbuy_ok_id'] = $this->_project['id'];
     }
     return 0;
 }
예제 #8
0
파일: payed.php 프로젝트: amage/fl-ru-damp
 /**
  * Поднимаем рейтиинг
  *
  * @param integer $fid                ИД Кому поднимаем
  * @param integer $transaction_id     ИД Транзакции     
  * @param integer $time               Время
  * @param string  $comments           Дополнительный комментарий
  * @param integer $tarif              Тариф
  * @param integer $ammount            Kоличество товара
  * @param integer $commit             Завершать ли транзакцию после этой операции.
  * @return unknown
  */
 function getUpRating($fid, $sum, $transaction_id, $time, $comments = "Поднятие рейтинга за FM", $tarif = 75, $ammount = 1, $commit = 1)
 {
     require_once ABS_PATH . "/classes/account.php";
     $account = new account();
     $error = $account->Buy($bill_id, $transaction_id, $tarif, $fid, $comments, $comments, $ammount, $commit);
     if ($error !== 0) {
         return 1;
     }
     return 0;
 }
예제 #9
0
 /**
  * Обновляет дату объявления, поднимая на первое место
  * @param type $uid
  * @param type $prof_id
  * @param type $from_buffer
  */
 public static function moveTop($uid, $prof_id, $is_group, $transaction_id, $from_buffer = false, $psum = 0, $op_code, $promo = 0)
 {
     $success = false;
     $prof_name = self::getOperationDescr($is_group ? 0 : $prof_id, $is_group ? $prof_id : 0);
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/account.php";
     $account = new account();
     $ok = $account->Buy($id, $transaction_id, $op_code, $uid, "Перемещение наверх размещения в {$prof_name} каталога фрилансеров и услуг", $from_buffer ? 'оплата из буфера' : '', 1, 1, $promo);
     if ($ok === 0) {
         global $DB;
         $data = array('first_post' => 'NOW()', 'skip_psum' => true, 'sent_up' => false);
         if ($from_buffer) {
             $data['psum'] = $psum;
         }
         $tarif_case = $is_group ? 'AND tarif = 19' : '';
         $success = $DB->update('users_first_page', $data, "user_id = ?i AND profession = ?i {$tarif_case}", $uid, $prof_id);
     }
     $memBuff = new memBuff();
     $memBuff->flushGroup("firstpg");
     unset($_SESSION['payed_frl']);
     return $success;
 }
예제 #10
0
 /**
  * Продляет специализации по ID пользователя
  *
  * @param integer $uid ID пользователя
  * @param boolean $is_autopaid Учитывать только отмеченные для автопродления
  * @param string $period Период продления
  * @param boolean $prolong_only
  * @return string Сообщение об ошибке если есть
  */
 function prolongSpecs($uid, $is_autopaid = false, $period = '1 mon', $prolong_only = false)
 {
     global $DB;
     return;
     // #0022795
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/account.php";
     $account = new account();
     $specs = self::getPaidSpecs($uid, true, $is_autopaid, $prolong_only);
     if (!$specs) {
         return 'Нет специализаций';
     }
     $transaction_id = $account->start_transaction($uid);
     $billing_id = NULL;
     $sum = 0;
     foreach ($specs as $i => $spec) {
         $DB->start();
         $sql = "UPDATE spec_paid_choise SET paid_to = paid_to + '{$period}'::interval\n                    WHERE id = {$spec['id']} AND user_id = {$uid} RETURNING paid_to, (paid_to - '{$period}'::interval) as paid_from";
         if ($res = $DB->query($sql)) {
             $paid_to = pg_fetch_result($res, 0, 0);
             $paid_from = pg_fetch_result($res, 0, 1);
             $descr = 'Продление "' . $spec['name'] . '" до ' . date('d.m.Y', strtotime($paid_to));
             if ($error = $account->Buy($bill_id, $transaction_id, self::OP_PAID_SPEC, $uid, $descr, $descr, 1, 0)) {
                 $DB->rollback();
                 break;
             }
             if ($DB->commit()) {
                 $billing_id = $bill_id;
                 $sum++;
                 $sql = "INSERT INTO spec_paid_acc_operations (billing_id, paid_from, paid_to)\n                            VALUES ({$bill_id}, '{$paid_from}'::timestamp, '{$paid_to}'::timestamp)";
                 $rs = $DB->query($sql);
             }
         }
     }
     if ($billing_id) {
         $account->commit_transaction($transaction_id, $uid, $billing_id);
         require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/smail.php";
         require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/op_codes.php";
         $mail = new smail();
         $ops = new op_codes();
         $price = $ops->getCodes(self::OP_PAID_SPEC);
         if ($price) {
             $price = $price[self::OP_PAID_SPEC];
             $mail->PaidSpecsAutopayed($uid, $sum * $price['sum']);
         }
     }
     return $error;
 }
예제 #11
0
 public function paidOperation($id)
 {
     global $DB;
     if (!$id) {
         return false;
     }
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects.php';
     $operation = $DB->row('SELECT * FROM draft_account_operations WHERE id = ? AND status IS NULL', $id);
     $account = new account();
     $this->_transactionId = $account->start_transaction($_SESSION['uid'], $this->_transactionId);
     switch ($operation['op_type']) {
         case 'project':
             $project = $DB->row('SELECT id, payed_info FROM projects WHERE id = ?i', $operation['parent']);
             if (!$project['id']) {
                 return 'Ошибка обработки операции.';
             }
             if ($account->sum >= $operation['ammount']) {
                 if ($error = $account->Buy($bill_id, $this->_transactionId, $operation['op_code'], $_SESSION['uid'], trim($operations['descr'], '/'), trim($operations['comments'], '/'), 1, true)) {
                     return $error;
                 }
             }
             if (!$bill_id) {
                 return 'Не хватает денег.';
             }
             $update = array();
             switch ($operation['option']) {
                 case 'color':
                     $update['is_color'] = true;
                     $update['payed_items'] = $project['payed_info'] | '010';
                     break;
                 case 'bold':
                     $update['is_bold'] = true;
                     $update['payed_items'] = $project['payed_info'] | '001';
                     break;
                 case 'top':
                     $update['top_from'] = date('d.m.Y H:i', strtotime('now'));
                     $update['top_to'] = date('d.m.Y H:i', strtotime("now +{$operation['op_count']} day"));
                     break;
                 case 'logo':
                     $update['logo_id'] = $operation['src_id'];
                     $update['payed_items'] = $project['payed_info'] | '100';
                     break;
             }
             $update['billing_id'] = $bill_id;
             $DB->update('projects', $update, 'id = ?', $operation['parent']);
             header('Location: /bill/success/');
             exit;
             break;
         case 'contest':
             // Публикация конкурса
             if ($account->sum >= $operation['ammount']) {
                 if ($error = $account->Buy($bill_id, $this->_transactionId, $operation['op_code'], $_SESSION['uid'], trim($operations['descr'], '/'), trim($operations['comments'], '/'), 1, true)) {
                     return $error;
                 }
             }
             if (!$bill_id) {
                 return 'Не хватает денег.';
             }
             $key = md5(microtime());
             $prj = new tmp_project($key);
             if (get_uid()) {
                 $prj->init(1);
             }
             $draft = new drafts();
             $project = $drafts->getDraft($operation['parent'], $_SESSION['uid'], 1);
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/attachedfiles.php';
             $attachedfiles = new attachedfiles();
             $attachedfiles_tmpdraft_files = drafts::getAttachedFiles($operation['parent'], 4);
             if ($attachedfiles_tmpdraft_files) {
                 $attachedfiles_prj_files = array();
                 foreach ($attachedfiles_tmpdraft_files as $attachedfiles_draft_file) {
                     $attachedfiles_draft_files[] = $attachedfiles_draft_file;
                 }
                 $attachedfiles->setFiles($attachedfiles_draft_files, 1);
             }
             $insert = array('user_id' => $_SESSION['uid'], 'name' => $project['name'], 'descr' => $project['descr'], 'kind' => $project['kind'], 'cost' => $project['cost'], 'currency' => $project['currency'], 'country' => $project['country'] > 0 ? $project['country'] : 'NULL', 'city' => $project['city'] > 0 ? $project['city'] : 'NULL', 'payed' => '0', 'pro_only' => $project['pro_only'], 'logo_id' => 'NULL', 'link' => $project['logo_link'], 'is_color' => 'f', 'is_bold' => 'f', 'billing_id' => 0, 'payed_items' => '000', 'folder_id' => 0, 'budget_type' => $project['budget_type'], 'priceby' => $project['priceby'], 'prefer_sbr' => $project['prefer_sbr'], 'end_date' => $project['p_end_date'], 'win_date' => $project['p_win_date']);
             if (!empty($project['categories'])) {
                 $cat = explode('|', $project['categories']);
                 $categories[0] = array('category_id' => intval($cat[0]), 'subcategory_id' => intval($cat[1]));
             }
             $create = $prj->addPrj($insert, $attachedfiles_draft_files, $categories);
             // Добавляем проект
             if ($create) {
                 $drafts->DeleteDraft($draft_id, $uid, 1);
                 header('Location: /bill/success/');
                 exit;
             }
             break;
         case 'account':
             // Покупка ПРО
             break;
     }
 }
예제 #12
0
 /**
  * Возврат ответов в случае блокировки проекта.
  *
  * @param int $project_id - ID проекта
  *
  * @return mixed - сообщение об ошибке или 0 в случае успеха
  */
 public function ReturnAnswers($project_id)
 {
     global $DB;
     $descr = 'Возврат ответа на проект в связи с блокировкой проекта';
     $op_code = $this->return_op_code;
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects_offers.php';
     $of = new projects_offers();
     $offers = $of->GetPrjOffers($count, $project_id, 'ALL', 0, 0, true);
     if (!$count) {
         return;
     }
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/account.php';
     $account = new account();
     foreach ($offers as $offer) {
         $uid = $offer['user_id'];
         if ($offer['type'] == 0) {
             continue;
         }
         $transaction_id = $account->start_transaction($uid);
         $error = $account->Buy($billing_id, $transaction_id, $op_code, $uid, $descr, $descr, 0, 0);
         if ($error) {
             return $error;
         }
         if ($offer['type'] == 2) {
             $DB->query('UPDATE projects_offers_answers SET pay_offers = pay_offers + 1 WHERE uid = ?', $uid);
         } else {
             $free_cnt = self::FREE_ANSWERS_CNT;
             $DB->query("UPDATE projects_offers_answers \n                    SET free_offers = free_offers + (CASE WHEN free_offers < {$free_cnt} THEN 1 ELSE 0 END) WHERE uid = ?", $uid);
         }
         $account->commit_transaction($transaction_id, $uid, $billing_id);
     }
 }
예제 #13
0
             header('Location: ' . getFriendlyURL('project', $project['id']) . '?' . intval($project['id']) . $from_prm_s);
         }
     }
     break;
 case 'buy':
     if (!($error = $answers->BuyByFM($_SESSION['uid'], $_POST['ammount']))) {
         header('Location: ' . getFriendlyURL('project', $project['id']));
         exit;
     }
     break;
 case 'payed_is_color':
     $offer_id = __paramInit('int', null, 'id_offers');
     $account = new account();
     $transaction_id = $account->start_transaction(get_uid());
     $project_id = $obj_offer->getProjectIDByOfferID($offer_id);
     $error_buy = $account->Buy($billing_id, $transaction_id, $answers->color_op_code, get_uid(), 'Выделение ответа на проект цветом', "Выделение <a href='" . getFriendlyURL('project', $project_id) . "#freelancer_{$_SESSION['uid']}' target='_blank'>ответа на проект</a> цветом", 1, 1);
     $is_color = 't';
     $payed_items = '1';
     if ($error_buy) {
         $is_color = 'f';
         $payed_items = '0';
     }
     $fields = array('is_color' => "'{$is_color}'", 'payed_items' => "B'{$payed_items}'");
     $error = $obj_offer->setFieldsOffers($offer_id, $fields);
     if (!$error) {
         header('Location: /bill/success/');
         exit;
     } else {
         $error_is_color = 'Ошибка обработки запроса';
     }
     break;
예제 #14
0
 public function payedAdvice($id_advice, $uid, $transaction_id, $tarif, $trs_sum)
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/account.php';
     $tarif = floatval($tarif);
     $account = new account();
     $link = "<a href='{$GLOBALS['host']}/users/{$_SESSION['login']}/opinions/#p_" . $id_advice * 2 . "' target='_blank'>Рекомендация</a>";
     $error = $account->Buy($bill_id, $transaction_id, self::OP_CODE, $uid, 'Оплата рекомендации', $link, $tarif, 0, 0, $trs_sum);
     if ($error !== 0) {
         return 0;
     }
     if ($bill_id) {
         $account->commit_transaction($transaction_id, $uid, $bill_id);
         $this->setPayed($id_advice, $bill_id);
         return $bill_id;
     }
     return 0;
 }
 /**
  * Покупка места в карусели на главной и странице каталога.
  * */
 private function setCatalogOrMainPageRoundabout()
 {
     global $DB;
     $uid = (int) $_POST['uid'];
     $row = $DB->row("SELECT role, uname, usurname, login, sum  FROM users LEFT JOIN account ON account.uid = users.uid \n                          WHERE users.uid = {$uid}");
     $role = $row['role'][0];
     $user = $row['uname'] . ' ' . $row['usurname'] . ' [' . $row['login'] . ']';
     $sum = $row['sum'];
     if ($role !== '0') {
         $this->jsonError('Пользователь не найден или является работодателем');
     }
     $date = $_POST['date'];
     $f = preg_match("#[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}#", $date, $m);
     if (!$f) {
         $date = false;
     }
     if ($uid) {
         $catalog = $_POST['type'] == 'catalog';
         if ($_POST['type'] == 'catalog') {
             $tarif = 73;
         } elseif ($_POST['type'] == 'main') {
             $tarif = 65;
         }
         $payPlace = new pay_place($catalog ? 1 : 0);
         $account = new account();
         $transaction_id = $account->start_transaction($uid, $tr_id);
         if (($buy = $account->Buy($id, $transaction_id, $tarif, $uid, 'Оплата новых платных мест за FM', 'Оплачено', 1)) === 0) {
             $payPlace->addUser($uid);
             $t = intval($payPlace->getTimeShow());
             $msg = "{$user} будет размещен " . ($catalog ? 'в <a href="/freelancers/">каталоге</a> ' : 'на <a href="/">главной странице</a> ') . ($t == 0 ? 'сейчас' : "через {$t} минут" . ($t == 1 ? 'у' : ($t > 1 && $t < 5 ? 'ы' : ''))) . '.';
             $this->jsonOk('msg', $msg);
         } else {
             $msg = "В данный момент на счету у {$user} {$sum} FM. <a href=\"/bill\" target=\"_blank\">Пополнить счет</a><br/><br/>";
             $this->jsonError($msg);
         }
     }
 }