Example #1
0
function aSaveDocument($stage_id, $doc_id, $name, $type, $access, $session)
{
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/sbr_meta.php';
    $stage_id = __paramValue('int', $stage_id);
    $doc_id = __paramValue('int', $doc_id);
    $objResponse = new xajaxResponse();
    if (!hasPermissions('sbr')) {
        $objResponse->script('window.sended = false');
        return $objResponse;
    }
    $sbr = sbr_meta::getInstance();
    $sbr_id = $sbr->getSbrIdFromStage($stage_id);
    $sbr->initFromId($sbr_id, true, false, false);
    if ($sbr->error) {
        $objResponse->script('window.sended = false');
        return $objResponse;
    }
    $stage = $sbr->initFromStage($stage_id, false);
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/attachedfiles.php';
    $attachedfiles = new attachedfiles($session);
    $attach = current($attachedfiles->getFiles());
    if ($attach['id']) {
        $file = new CFile($attach['id']);
        $file->table = 'file_sbr';
        $file->_remoteCopy($sbr->getUploadDir() . $file->name);
    } else {
        $file = false;
    }
    if ($doc_id) {
        $old_doc = $sbr->getDoc($doc_id);
        $doc = array('name' => $name, 'type' => $type, 'access_role' => $access, 'status' => $old_doc['status'], 'stage_id' => $stage_id, 'id' => $doc_id);
        if ($file) {
            $doc['file_id'] = $file->id;
        }
        $sbr->editDoc($doc, $old_doc);
        if ($old_doc['access_role'] == 0 && $doc['access_role'] > 0) {
            $stage->removeEvent(29, true);
        } elseif ($old_doc['access_role'] > 0 && $doc['access_role'] == 0) {
            $stage->removeEvent(30, true);
        }
    } else {
        if (!$file) {
            $objResponse->script('window.sended = false');
            $objResponse->call('alert', 'Загрузите файл');
            return $objResponse;
        }
        $doc = array('stage_id' => $stage_id, 'file_id' => $file->id, 'status' => sbr::DOCS_STATUS_PUBL, 'access_role' => $access, 'owner_role' => 0, 'type' => $type);
        $add_doc = $sbr->addDocR($doc);
        if (!$add_doc) {
            $objResponse->script('window.sended = false;');
            $objResponse->call('alert', 'Ошибка запроса');
            return $objResponse;
        }
    }
    $objResponse->script('window.location.reload()');
    return $objResponse;
}
 /**
  * Перенос файлов в рабочие папки сайта
  * 
  * @param array  $files   Массив файлов
  * @param string $table   Таблица для переноса
  * @param string $dir     Директория для переноса
  * @param bool = true $newName  Генерировать новое имя файла
  * @return array 
  */
 function transferFiles($files, $table, $dir, $newName = true)
 {
     foreach ($files as $key => $file) {
         $objFile = new CFile($file['id']);
         $ext = $objFile->getext();
         if (!$newName) {
             $tmp_name = $objFile->name;
         } else {
             $tmp_name = $objFile->secure_tmpname($dir, '.' . $ext);
             $tmp_name = substr_replace($tmp_name, "", 0, strlen($dir));
         }
         $objFile->table = $table;
         $copy = $objFile->_remoteCopy($dir . $tmp_name);
         $data[] = array('fname' => $objFile->name, 'id' => $objFile->id, 'orig_name' => $objFile->original_name, 'file_id' => $objFile->id);
         unset($objFile);
     }
     return $data;
 }
Example #3
0
 /**
  * Редактирование личного сообщения.
  * 
  * @param int    $from_id            UID пользователя-отправителя 
  * @param int    $modified_id        UID пользователя изменявшего сообщение
  * @param int    $id                 ID сообщения
  * @param string $msg_text           текст сообщения
  * @param array  $attachedfiles_file приаттаченные файлы
  * @param string $modified_reason    причина редактирования
  *
  * @return bool true - успех, false - провал
  */
 public function Update($from_id = 0, $modified_id = 0, $id = 0, $msg_text = '', $attachedfiles_file = array(), $modified_reason = '')
 {
     $bRet = false;
     if ($from_id && $id && $msg_text) {
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
         $users = new users();
         $login = $users->GetName($from_id, $err);
         $files = array();
         if ($login) {
             if ($attachedfiles_file) {
                 foreach ($attachedfiles_file as $file) {
                     switch ($file['status']) {
                         case 1:
                             // добавляем файл
                             $cFile = new CFile($file['id']);
                             $cFile->table = 'file';
                             $ext = $cFile->getext();
                             $tmp_dir = 'users/' . substr($login['login'], 0, 2) . '/' . $login['login'] . '/contacts/';
                             $tmp_name = $cFile->secure_tmpname($tmp_dir, '.' . $ext);
                             $tmp_name = substr_replace($tmp_name, '', 0, strlen($tmp_dir));
                             $cFile->_remoteCopy($tmp_dir . $tmp_name, true);
                             $files[] = $cFile->id;
                             break;
                         case 3:
                             // ранее добавленный
                             $files[] = $file['id'];
                             break;
                         case 4:
                             // удаляем файл
                             $cFile = new CFile();
                             $cFile->Delete($file['id']);
                             break;
                     }
                 }
             }
             $DB = new DB();
             $DB->val('SELECT message_update(?i, ?i, ?, ?a, ?)', $id, $modified_id, $msg_text, $files, $modified_reason);
             $bRet = empty($DB->error);
         }
     }
     return $bRet;
 }
Example #4
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;
 }
Example #5
0
 /**
  * Новая СБР
  * Инициализирует этапы сделки для редактирования/создания из пользовательского запроса.
  * Загружает вложения на сервер. Учитывает удаление этапов.
  * 
  * @param array $tstages          массив этапов. Может содержать новые этапы и старые, отредактированные.
  * @param array $attached_session ид сессии автозагрузчика
  * @param int   $mode             0: создается, 1: редактируется вся сделка, 2: редактируется один этап.
  */
 private function _new_initStagesFromRequest($tstages, $tstages_attach, $mode)
 {
     //        $tstages_attach = array();
     $stages = array();
     $stages_attach = array();
     $fcnt = self::MAX_FILES;
     // Формируем массив удаленных этапов. Уменьшаем общий бюджет сделки.
     if ($this->data['delstages']) {
         foreach ($this->data['delstages'] as $id => $ds) {
             if ($dds = $this->getStageById($id)) {
                 $this->_delstages[$id] = clone $dds;
                 $this->data['cost'] -= $dds->cost;
             }
         }
     }
     // Упорядочиваем массив этапов в новой последовательности, на случай если были удаления/добавления и все перемешалось.
     // Если редактируется только один этап, то он не меняет номер ни при каких обстоятельствах.
     $num = 0;
     foreach ($tstages as $rnum => $ts) {
         if ($ts['id']) {
             if ($mode == 2 && ($tts = $this->getStageById($ts['id']))) {
                 $num = $tts->num;
             }
         }
         $stages[$num] = $ts;
         //            if($tstages_attach[$rnum])
         //                $stages_attach[$num] = $tstages_attach[$rnum];
         if ($mode == 2) {
             break;
         }
         ++$num;
     }
     unset($tstages, $tstages_attach);
     // Инициализируем $this->stages.
     $stage_cnt = count($stages);
     $new_stages = 0;
     $dnum = 0;
     foreach ($stages as $num => $stg) {
         $num = $num - $dnum;
         if ($stg['id'] && ($tts = $this->getStageById($stg['id']))) {
             $this->stages[$num] = $tts;
         } else {
             $this->stages[$num] = new sbr_stages($this);
             ++$new_stages;
         }
         $this->stages[$num]->data['num'] = $num;
         $this->data['cost'] -= $this->stages[$num]->cost;
         $data_exists = $this->stages[$num]->initFromRequest($stg) || $stages[$num]['attached'];
         $this->data['cost'] += $this->stages[$num]->cost;
         // Если передан пустой этап то решаем, что с ним делать:
         if (!$data_exists && $stage_cnt > 1 && ($mode == 0 || $mode == 1 && $this->isDraft())) {
             array_splice($this->stages, $num, 1);
             //                array_splice($stages_attach, $num, 1);
             ++$dnum;
             --$stage_cnt;
         } elseif ($this->stages[$num]->error) {
             $this->error['stages'][$num] = $this->stages[$num]->error;
         }
         // @todo файлы при редактировании
     }
     $d = $new_stages - count($this->_delstages);
     $this->data['stages_cnt'] += $d;
     while (++$d <= 0) {
         array_pop($this->stages);
     }
     // Загружаем вложения на сервер.
     if (!$this->error) {
         $dest = $this->getUploadDir();
         foreach ($stages as $num => $stage) {
             if (!$stage['attached']) {
                 continue;
             }
             foreach ($stage['attached'] as $idx => $att) {
                 $file = new CFile($att['id']);
                 $file->table = 'file_sbr';
                 $file->_remoteCopy($dest . $file->name);
                 $this->stages[$num]->uploaded_files[$idx] = $file;
             }
             if ($stage['new_del_attach']) {
                 foreach ($stage['new_del_attach'] as $idx => $att) {
                     $this->stages[$num]->data['new_del_attach'][$att['id']] = $att;
                 }
             }
         }
     }
 }
Example #6
0
 /**
  * Связывает файлы загруженные ассинхронно с проектом и добавляет информацию о них в массив $this->_attach
  *
  * @param   array     $files         Список добавляемых файлов
  * @param   boolean   $from_draft    Файлы из черновика
  */
 function addAttachedFiles($files, $from_draft = false)
 {
     global $DB;
     $old_files = array();
     if ($this->_attach) {
         foreach ($this->_attach as $f) {
             array_push($old_files, $f['file_id']);
         }
     }
     if ($from_draft) {
         if ($this->_attach) {
             foreach ($this->_attach as $attach_id => $attach) {
                 if (!in_array($attach['file_id'], $old_files)) {
                     $this->delAttach($attach_id, true);
                 }
             }
         }
     }
     if ($files) {
         foreach ($files as $file) {
             switch ($file['status']) {
                 case 4:
                     // Удаляем файл
                     if ($this->_attach) {
                         foreach ($this->_attach as $attach_id => $attach) {
                             if ($attach['file_id'] == $file['id']) {
                                 $this->delAttach($attach_id, true);
                             }
                         }
                     }
                     break;
                 case 1:
                 case 3:
                     // Добавляем файл
                     if (!in_array($file['id'], $old_files)) {
                         if (in_array($file['id'], $old_files)) {
                             $need_copy = false;
                         } else {
                             $need_copy = true;
                         }
                         $cFile = new CFile($file['id']);
                         $cFile->table = 'file_projects';
                         $ext = $cFile->getext();
                         if ($need_copy) {
                             $tmp_dir = $this->_tmpAbsDir;
                             $tmp_name = $cFile->secure_tmpname($tmp_dir, '.' . $ext);
                             $tmp_name = substr_replace($tmp_name, "", 0, strlen($tmp_dir));
                             $cFile->_remoteCopy($tmp_dir . $tmp_name, true);
                         }
                         $this->_attach[] = array('file_id' => $cFile->id, 'path' => $cFile->path, 'name' => $cFile->name, 'size' => $cFile->size, 'ftype' => $cFile->getext(), 'is_new' => true);
                         $this->_tmpFiles[] = $cFile->name;
                     }
                     break;
             }
         }
     }
 }
Example #7
0
 /**
  *  Добавление/удаление файлов к рассылке
  * @param array   $files   Список файлов
  * @param integer $id      Ид рассылки
  */
 public function addAttachedFiles($files, $id)
 {
     if ($files) {
         foreach ($files as $file) {
             switch ($file['status']) {
                 case 4:
                     // Удаляем файл
                     $this->delAttach($file['id']);
                     break;
                 case 1:
                     // Добавляем файл
                     $cFile = new CFile($file['id']);
                     $cFile->table = 'file_mailer';
                     $ext = $cFile->getext();
                     $tmp_name = $cFile->secure_tmpname(self::FILE_DIR, '.' . $ext);
                     $tmp_name = substr_replace($tmp_name, "", 0, strlen(self::FILE_DIR));
                     $cFile->_remoteCopy(self::FILE_DIR . $tmp_name, true);
                     $this->insertAttachedFile($cFile->id, $id);
                     break;
             }
         }
     }
 }
Example #8
0
 /**
  * Принимает заявку в Арбитраж.
  *
  * @param string $descr   причина обращения.
  * @param array $files   массив файлов ($_FILES).
  * @return boolean   успешно?
  */
 function arbitrage($descr, $files)
 {
     // проверим не послал ли паралельно ктото в арбитраж
     $this->getArbitrage();
     if ($this->arbitrage['id'] != null) {
         $this->error['arbitrage']['descr'] = 'Сделка уже находится в арбитраже';
         return false;
     }
     if (!($descr = pg_escape_string(change_q_x($descr, true, false)))) {
         $this->error['arbitrage']['descr'] = 'Поле не должно быть пустым';
         return false;
     }
     $fcnt = sbr::MAX_FILES;
     if ($files) {
         foreach ($files as $file) {
             $cfile = new CFile($file['id']);
             $cfile->table = 'file_sbr';
             $cfile->_remoteCopy($this->sbr->getUploadDir() . $cfile->name);
             $this->uploaded_files[] = $cfile;
         }
         /*$this->sbr->getUploadDir(); // !!! если админ редактирует, то нужно в папку автора коммента загружать.
           foreach($files['name'] as $idx=>$aname) {
               foreach($files as $prop=>$a)
                   $att[$idx][$prop] = $a[$idx];
               if(--$fcnt < 0) break;
               $file = new CFile($att[$idx]);
               // проверка файла
               if($file->size > self::ARB_FILE_MAX_SIZE) {
                   $this->error['arbitrage']['err_attach'] = "Максимальный объем файлов: ".ConvertBtoMB(self::ARB_FILE_MAX_SIZE);
                   return false;
               }
               if( in_array($file->getext(), $GLOBALS['disallowed_array'])) {
                   $this->error['arbitrage']['err_attach'] = "Недопустимый формат файла";
                   return false;
               }
               if($err = $this->sbr->uploadFile($file, self::ARB_FILE_MAX_SIZE)) {
                   if($err == -1) continue;
                   else {
                       $this->error['arbitrage']['err_attach'] = $err;
                       break;
                   }
               }
               $this->uploaded_files[] = $file;
           }*/
     }
     if ($this->error) {
         return false;
     }
     if (!$this->_openXact(TRUE)) {
         return false;
     }
     $sql = "INSERT INTO sbr_stages_arbitrage (stage_id, user_id, descr) VALUES ({$this->id}, {$this->sbr->uid}, '{$descr}') RETURNING id";
     if (!($res = pg_query(self::connect(false), $sql)) || !pg_num_rows($res)) {
         $this->_abortXact();
         return false;
     }
     $id = pg_fetch_result($res, 0, 0);
     $sql_attach = '';
     if ($this->uploaded_files) {
         foreach ($this->uploaded_files as $file) {
             if (!$file->id) {
                 continue;
             }
             $file->orig_name = pg_escape_string($file->original_name);
             $file->orig_name = $file->shortenName($file->orig_name, 128);
             if (!$file->orig_name) {
                 continue;
             }
             $sql_attach .= "INSERT INTO sbr_stages_arbitrage_attach(arbitrage_id, file_id, orig_name) VALUES({$id}, {$file->id}, '{$file->orig_name}');";
         }
     }
     if ($sql_attach && !pg_query(self::connect(false), $sql_attach)) {
         $this->_abortXact();
         return false;
     }
     $this->_commitXact();
     return true;
 }
Example #9
0
 /**
  * Связывает файлы загруженные ассинхронно с сообщением
  *
  * @param   array     $files              Список загруженных файлов
  * @param   string    $login              Логин пользователя
  * @param   integer   $msg_id             ID сообщения
  * @param   boolean   $from_draft         Файлы из черновика
  */
 function addAttachedFiles($files, $msg_id, $login = NULL, $from_draft = false)
 {
     global $DB;
     if (!$login) {
         $login = $_SESSION['login'];
     }
     $bModeration = false;
     $old_files = $this->getAttachedFiles($msg_id);
     if ($from_draft) {
         $notdeleted_files = array();
         if ($files) {
             foreach ($files as $f) {
                 if ($f['status'] == 3 || in_array($f['id'], $old_files)) {
                     array_push($notdeleted_files, $f['id']);
                 }
             }
         }
         $attaches = CFile::selectFilesBySrc(self::FILE_TABLE, $msg_id);
         if ($attaches) {
             foreach ($attaches as $attach) {
                 if (in_array($attach['id'], $notdeleted_files)) {
                     continue;
                 }
                 $cFile = new CFile($attach['id']);
                 $cFile->table = self::FILE_TABLE;
                 if ($cFile->id) {
                     $cFile->Delete($cFile->id);
                 }
             }
         }
     }
     $max_image_size = array('width' => blogs::MAX_IMAGE_WIDTH, 'height' => blogs::MAX_IMAGE_HEIGHT, 'less' => 0);
     if ($files) {
         foreach ($files as $file) {
             switch ($file['status']) {
                 case 4:
                     // Удаляем файл
                     $cFile = new CFile($file['id']);
                     $cFile->table = self::FILE_TABLE;
                     if ($cFile->id) {
                         $cFile->Delete($cFile->id);
                     }
                     break;
                 case 1:
                     if (in_array($file['id'], $old_files)) {
                         $need_copy = false;
                     } else {
                         $bModeration = true;
                         $need_copy = true;
                     }
                     // Добавляем файл
                     $cFile = new CFile($file['id']);
                     $cFile->proportional = 1;
                     $cFile->table = self::FILE_TABLE;
                     $ext = $cFile->getext();
                     if ($need_copy) {
                         $tmp_dir = "users/" . substr($login, 0, 2) . "/" . $login . "/upload/";
                         $tmp_name = $cFile->secure_tmpname($tmp_dir, '.' . $ext);
                         $tmp_name = substr_replace($tmp_name, "", 0, strlen($tmp_dir));
                         $cFile->_remoteCopy($tmp_dir . $tmp_name, true);
                     }
                     if (in_array($ext, $GLOBALS['graf_array'])) {
                         $is_image = TRUE;
                     } else {
                         $is_image = FALSE;
                     }
                     if ($is_image && $ext != 'swf' && $ext != 'flv') {
                         if ($cFile->image_size['width'] > $max_image_size['width'] || $cFile->image_size['height'] > $max_image_size['height']) {
                             if ($need_copy) {
                                 if ($cFile->resizeImage($cFile->path . 'sm_' . $cFile->name, $max_image_size['width'], $cFile->image_size['height'], 'landscape')) {
                                     $cFile->small = 2;
                                 }
                             } else {
                                 $cFile->small = 2;
                             }
                         } else {
                             $cFile->small = 1;
                         }
                     } else {
                         $cFile->small = $ext == 'flv' ? 2 : 0;
                     }
                     $cFile->updateFileParams(array('src_id' => $msg_id, 'small' => $cFile->small), false);
                     break;
             }
         }
     }
     if ($bModeration && $login == $_SESSION['login'] && !hasPermissions('blogs')) {
         // отравляем сообщение на модерирование сразу по факту создания или редактирования
         // появились новые файлы и это правит автор, и он не админ и не ПРО - отправить на модерирование
         /*require_once( $_SERVER['DOCUMENT_ROOT'] . '/classes/user_content.php' );
           $DB->query( 'UPDATE blogs_msgs SET moderator_status = 0 WHERE id = ?i', $msg_id );
           $DB->insert( 'moderation', array('rec_id' => $msg_id, 'rec_type' => user_content::MODER_BLOGS) );*/
     }
 }
Example #10
0
 /**
  * Изменение документа
  *
  * @param    integer  $id      ID документа
  * @param    array    $data    Данные документа
  */
 function updateDocument($id, $data)
 {
     global $DB;
     if (!$data['letters_doc_frm_user_3_db_id'] || $data['letters_doc_frm_user_3_db_id'] == 'null') {
         $data['letters_doc_frm_user_3_db_id'] = null;
         $data['letters_doc_frm_user3_status_data'] = null;
         $data['letters_doc_frm_user3_status_date_data'] = null;
     }
     if (!$data['letters_doc_frm_user3_status_date_data']) {
         $data['letters_doc_frm_user3_status_date_data'] = null;
     }
     if (!$data['letters_doc_frm_user2_status_date_data']) {
         $data['letters_doc_frm_user2_status_date_data'] = null;
     }
     if (!$data['letters_doc_frm_user1_status_date_data']) {
         $data['letters_doc_frm_user1_status_date_data'] = null;
     }
     if (!$data['letters_doc_frm_user3_status_data']) {
         $data['letters_doc_frm_user3_status_data'] = null;
     }
     if (!$data['letters_doc_frm_user2_status_data']) {
         $data['letters_doc_frm_user2_status_data'] = null;
     }
     if (!$data['letters_doc_frm_user1_status_data']) {
         $data['letters_doc_frm_user1_status_data'] = null;
     }
     if (!$data['letters_doc_frm_parent_db_id'] || $data['letters_doc_frm_parent_db_id'] == 'null') {
         $data['letters_doc_frm_parent_db_id'] = null;
     }
     if (!$data['letters_doc_frm_group'] || $data['letters_doc_frm_group'] == 'null') {
         $data['letters_doc_frm_group'] = null;
     }
     if (!$data['letters_doc_frm_group_db_id'] || $data['letters_doc_frm_group_db_id'] == 'null') {
         $data['letters_doc_frm_group_db_id'] = null;
     }
     if (!$data['letters_doc_frm_group_db_id'] && !empty($data['letters_doc_frm_group'])) {
         $data['letters_doc_frm_group_db_id'] = letters::checkCreateGroup($data['letters_doc_frm_group']);
     }
     if ($data['letters_doc_frm_user_1_section'] == '1') {
         $data['letters_doc_frm_user_1_section'] = true;
     } else {
         $data['letters_doc_frm_user_1_section'] = false;
     }
     if ($data['letters_doc_frm_user_2_section'] == '1') {
         $data['letters_doc_frm_user_2_section'] = true;
     } else {
         $data['letters_doc_frm_user_2_section'] = false;
     }
     if ($data['letters_doc_frm_user_3_section'] == '1') {
         $data['letters_doc_frm_user_3_section'] = true;
     } else {
         $data['letters_doc_frm_user_3_section'] = false;
     }
     if ($data['letters_doc_frm_withoutourdoc'] == '1') {
         $data['letters_doc_frm_withoutourdoc'] = true;
     } else {
         $data['letters_doc_frm_withoutourdoc'] = false;
     }
     $doc = self::getDocument($id);
     $doc_data['title'] = $data['letters_doc_frm_title'];
     $doc_data['user_1'] = $data['letters_doc_frm_user_1_db_id'];
     $doc_data['user_2'] = $data['letters_doc_frm_user_2_db_id'];
     $doc_data['user_3'] = $data['letters_doc_frm_user_3_db_id'];
     $doc_data['group_id'] = $data['letters_doc_frm_group_db_id'];
     $doc_data['parent'] = $data['letters_doc_frm_parent_db_id'];
     $doc_data['user_status_1'] = $data['letters_doc_frm_user1_status_data'];
     $doc_data['user_status_2'] = $data['letters_doc_frm_user2_status_data'];
     $doc_data['user_status_3'] = $data['letters_doc_frm_user3_status_data'];
     $doc_data['user_status_date_1'] = $data['letters_doc_frm_user1_status_date_data'];
     $doc_data['user_status_date_2'] = $data['letters_doc_frm_user2_status_date_data'];
     $doc_data['user_status_date_3'] = $data['letters_doc_frm_user3_status_date_data'];
     $doc_data['is_user_1_company'] = $data['letters_doc_frm_user_1_section'] ? 't' : 'f';
     $doc_data['is_user_2_company'] = $data['letters_doc_frm_user_2_section'] ? 't' : 'f';
     $doc_data['is_user_3_company'] = $data['letters_doc_frm_user_3_section'] ? 't' : 'f';
     $doc_data['withoutourdoc'] = $data['withoutourdoc'] ? 't' : 'f';
     if (isset($data['letters_doc_frm_comment']) && $data['letters_doc_frm_comment']) {
         $doc_data['comment'] = $data['letters_doc_frm_comment'];
     } else {
         $data['letters_doc_frm_comment'] = $doc['comment'];
     }
     if ($doc_data['user_status_1'] != $doc['user_status_1'] || $doc_data['user_status_2'] != $doc['user_status_2'] || $doc_data['user_status_3'] != $doc['user_status_3']) {
         letters::updateDateStatusChange($id);
     }
     letters::saveHistory($id, $doc_data);
     $sql = "UPDATE letters SET\n                                     date_add = " . ($data['letters_doc_frm_dateadd_eng_format'] ? "'{$data['letters_doc_frm_dateadd_eng_format']}'" : "NOW()") . ",\n                                     title = ?,\n                                     user_1 = ?,\n                                     user_2 = ?,\n                                     user_3 = ?,\n                                     group_id = ?,\n                                     parent = ?,\n                                     user_status_1 = ?, \n                                     user_status_2 = ?, \n                                     user_status_3 = ?, \n                                     user_status_date_1 = ?, \n                                     user_status_date_2 = ?, \n                                     user_status_date_3 = ?,\n                                     is_user_1_company = ?,  \n                                     is_user_2_company = ?, \n                                     is_user_3_company = ?, \n                                     withoutourdoc = ?,\n                                     comment = ?\n                WHERE id = ?i;";
     $DB->query($sql, $data['letters_doc_frm_title'], $data['letters_doc_frm_user_1_db_id'], $data['letters_doc_frm_user_2_db_id'], $data['letters_doc_frm_user_3_db_id'], $data['letters_doc_frm_group_db_id'], $data['letters_doc_frm_parent_db_id'], $data['letters_doc_frm_user1_status_data'], $data['letters_doc_frm_user2_status_data'], $data['letters_doc_frm_user3_status_data'], $data['letters_doc_frm_user1_status_date_data'], $data['letters_doc_frm_user2_status_date_data'], $data['letters_doc_frm_user3_status_date_data'], $data['letters_doc_frm_user_1_section'], $data['letters_doc_frm_user_2_section'], $data['letters_doc_frm_user_3_section'], $data['letters_doc_frm_withoutourdoc'], $data['letters_doc_frm_comment'], $id);
     $sql = "UPDATE letters SET is_out=false WHERE (user_status_1 IS DISTINCT FROM 1 AND user_status_2 IS DISTINCT FROM 1 AND user_status_3 IS DISTINCT FROM 1) AND id=?i";
     $DB->query($sql, $id);
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/attachedfiles.php";
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/CFile.php";
     $attachedfiles = new attachedfiles($data['attachedfiles_session']);
     $attachedfiles_files = $attachedfiles->getFiles();
     if ($attachedfiles_files) {
         foreach ($attachedfiles_files as $attachedfiles_file) {
             $cFile = new CFile();
             $cFile->table = 'file';
             $cFile->GetInfoById($attachedfiles_file['id']);
             if ($cFile->id != $doc['file_id']) {
                 $ext = $cFile->getext();
                 $tmp_dir = "letters/";
                 $tmp_name = $cFile->secure_tmpname($tmp_dir, '.' . $ext);
                 $tmp_name = substr_replace($tmp_name, "", 0, strlen($tmp_dir));
                 $cFile->_remoteCopy($tmp_dir . $tmp_name, true);
                 $sql = "UPDATE letters SET file_id = ?i WHERE id = ?i";
                 $DB->query($sql, $cFile->id, intval($id));
                 $cFile->delete($doc['file_id']);
             }
         }
     }
     $attachedfiles->clear();
     return $id;
 }
Example #11
0
 /**
  * Связывает файлы загруженные ассинхронно с сообщением
  *
  * @param   array     $files              Список загруженных файлов
  * @param   string    $login              Логин пользователя
  * @param   integer   $msg_id             ID сообщения
  * @param   boolean   $from_draft         Файлы из черновика
  */
 function addAttachedFiles($files, $msg_id, $login, $from_draft = false)
 {
     global $DB;
     if (!$login) {
         $login = $_SESSION['login'];
     }
     $bModeration = false;
     $where = " inline != TRUE";
     $attaches = CFile::selectFilesBySrc(self::FILE_TABLE, $msg_id, NULL, $where);
     //$DB->rows($sql, $msg_id);
     $old_files = array();
     if ($attaches) {
         foreach ($attaches as $f) {
             array_push($old_files, $f['fid']);
         }
     }
     if ($from_draft) {
         $notdeleted_files = array();
         if ($files) {
             foreach ($files as $f) {
                 if ($f['status'] == 3) {
                     array_push($notdeleted_files, $f['id']);
                 }
             }
         }
         if ($attaches) {
             $cfile = new CFile();
             foreach ($attaches as $attach) {
                 if (in_array($attach['id'], $notdeleted_files)) {
                     continue;
                 }
                 $cfile->Delete(0, "users/" . substr($login, 0, 2) . "/" . $login . "/upload/", $attach['fname']);
                 //if ($attach['small'] == 't') {
                 //    $cfile->Delete(0, "users/" . substr($login, 0, 2) . "/" . $login . "/upload/", "sm_" . $attach['fname']);
                 //}
             }
         }
     }
     $max_image_size = array('width' => 470, 'height' => 1000, 'less' => 0);
     if ($files) {
         $cfile = new CFile();
         $num = 0;
         foreach ($files as $file) {
             switch ($file['status']) {
                 case 3:
                     $num++;
                     break;
                 case 4:
                     // Удаляем файл
                     $cFile = new CFile($file['id']);
                     $cFile->table = self::FILE_TABLE;
                     if ($cFile->id) {
                         $cFile->updateFileParams(array('src_id' => null), false);
                         // Удаляем связь
                         $cFile->Delete($cFile->id);
                     }
                     break;
                 case 1:
                     $num++;
                     if (in_array($file['id'], $old_files)) {
                         $need_copy = false;
                     } else {
                         $bModeration = true;
                         $need_copy = true;
                     }
                     // Добавляем файл
                     $cFile = new CFile($file['id']);
                     $cFile->proportional = 1;
                     $cFile->table = self::FILE_TABLE;
                     $ext = $cFile->getext();
                     if ($need_copy) {
                         $tmp_dir = "users/" . substr($login, 0, 2) . "/" . $login . "/upload/";
                         $tmp_name = $cFile->secure_tmpname($tmp_dir, '.' . $ext);
                         $tmp_name = substr_replace($tmp_name, "", 0, strlen($tmp_dir));
                         $cFile->_remoteCopy($tmp_dir . $tmp_name, true);
                     }
                     if (in_array($ext, $GLOBALS['graf_array'])) {
                         $is_image = TRUE;
                     } else {
                         $is_image = FALSE;
                     }
                     if ($is_image && $ext != 'swf' && $ext != 'flv') {
                         if ($cFile->image_size['width'] > $max_image_size['width'] || $cFile->image_size['height'] > $max_image_size['height']) {
                             if ($need_copy) {
                                 if ($cFile->resizeImage($cFile->path . 'sm_' . $cFile->name, $max_image_size['width'], $cFile->image_size['height'], 'landscape')) {
                                     $cFile->small = true;
                                 }
                             } else {
                                 $cFile->small = true;
                             }
                         } else {
                             $cFile->small = false;
                         }
                     } else {
                         $cFile->small = false;
                     }
                     $cFile->updateFileParams(array('src_id' => $msg_id, 'small' => $cFile->small, 'sort' => $num), false);
                     //$sql = "INSERT INTO commune_attach(cid, fid, small, sort) VALUES(?i, ?i, ?b, ?i)";
                     //$DB->query($sql, $msg_id, $cFile->id, $cFile->small, $num);
                     break;
             }
         }
     }
     if ($bModeration && $login == $_SESSION['login'] && !hasPermissions('communes') && !is_pro()) {
         // отравляет сообщение на модерирование сразу по факту создания или редактирования
         // появились новые файлы и это правит автор - отправить на модерирование
         /*$sId = $DB->query( 'UPDATE commune_messages SET moderator_status = 0 WHERE id = ?i AND user_id = ?i  RETURNING id', $msg_id, $_SESSION['uid'] );
           
           if ( $sId ) {
               require_once( $_SERVER['DOCUMENT_ROOT'] . '/classes/user_content.php' );
               $DB->insert( 'moderation', array('rec_id' => $msg_id, 'rec_type' => user_content::MODER_COMMUNITY) );
           }*/
     }
 }
Example #12
0
 /**
  * Связывает файлы загруженные ассинхронно с комментарием
  *
  * @param  array $files Список загруженных файлов @see attachedfiles::getFiles
  * @param  string $login Логин пользователя
  * @param  integer $msg_id ID комментария
  * @return bool
  */
 function addAttachedFiles($files = array(), $msg_id = 0, $login = '')
 {
     global $DB;
     $model = $this->model();
     if (!isset($model['attaches'])) {
         return false;
     }
     if (!$login) {
         $login = $_SESSION['login'];
     }
     $sql = 'SELECT ' . $model['attaches']['fields']['file'] . ' AS fid FROM ' . $model['attaches']['table'] . ' WHERE ' . $model['attaches']['fields']['comment'] . ' = ?i AND ' . $model['attaches']['fields']['inline'] . ' != TRUE';
     $attaches = $DB->rows($sql, $msg_id);
     $old_files = array();
     if ($attaches) {
         foreach ($attaches as $f) {
             array_push($old_files, $f['fid']);
         }
     }
     $max_image_size = array('width' => 390, 'height' => 1000, 'less' => 0);
     if ($files) {
         $num = 0;
         foreach ($files as $file) {
             switch ($file['status']) {
                 case 4:
                     // Удаляем файл
                     $cFile = new CFile($file['id']);
                     $cFile->table = $model['attaches']['file_table'];
                     if ($cFile->id) {
                         $sql = 'DELETE FROM ' . $model['attaches']['table'] . ' WHERE ' . $model['attaches']['fields']['file'] . ' = ?i';
                         $DB->query($sql, $cFile->id);
                         $cFile->Delete($cFile->id);
                     }
                     break;
                 case 1:
                     $num++;
                     if (in_array($file['id'], $old_files)) {
                         $need_copy = false;
                     } else {
                         $need_copy = true;
                     }
                     // Добавляем файл
                     $cFile = new CFile($file['id']);
                     $cFile->proportional = 1;
                     $cFile->table = $model['attaches']['file_table'];
                     $ext = $cFile->getext();
                     if ($need_copy) {
                         $tmp_dir = 'users/' . substr($login, 0, 2) . '/' . $login . '/upload/';
                         $tmp_name = $cFile->secure_tmpname($tmp_dir, '.' . $ext);
                         $tmp_name = substr_replace($tmp_name, '', 0, strlen($tmp_dir));
                         $cFile->_remoteCopy($tmp_dir . $tmp_name, true);
                     }
                     if (in_array($ext, $GLOBALS['graf_array'])) {
                         $is_image = TRUE;
                     } else {
                         $is_image = FALSE;
                     }
                     if ($is_image && $ext != 'swf' && $ext != 'flv') {
                         if ($cFile->image_size['width'] > $max_image_size['width'] || $cFile->image_size['height'] > $max_image_size['height']) {
                             if ($need_copy) {
                                 if ($cFile->resizeImage($cFile->path . 'sm_' . $cFile->name, $max_image_size['width'], $cFile->image_size['height'], 'landscape')) {
                                     $cFile->small = true;
                                 }
                             } else {
                                 $cFile->small = true;
                             }
                         } else {
                             $cFile->small = false;
                         }
                     } else {
                         $cFile->small = false;
                     }
                     $aData = array($model['attaches']['fields']['comment'] => $msg_id, $model['attaches']['fields']['file'] => $cFile->id);
                     if (isset($model['attaches']['fields']['small'])) {
                         $aData[$model['attaches']['fields']['small']] = $cFile->small;
                     }
                     if (isset($model['attaches']['fields']['sort'])) {
                         $aData[$model['attaches']['fields']['sort']] = $num;
                     }
                     $DB->insert($model['attaches']['table'], $aData);
                     break;
             }
         }
     }
     return true;
 }
Example #13
0
 /**
  * Перемещаем файл куда надо
  * 
  * @param integer $id_file     ИД файла который нужно переместить
  * @param string  $copy_table  Таблица в которую перемещаем
  * @param string  $dir         Директория в которую копируем
  * @return \CFile
  */
 function remoteCopy($id_file, $copy_table, $dir, $new_name = true, $prefix = 'f_')
 {
     $CFile = new CFile($id_file);
     $CFile->table = $copy_table;
     if ($new_name) {
         $tmp_name = $CFile->secure_tmpname($dir, '.' . $CFile->getext(), $prefix);
         $tmp_name = substr_replace($tmp_name, "", 0, strlen($dir));
     } else {
         $tmp_name = $prefix . str_replace(array("f_", "sm_"), "", $CFile->name);
     }
     $CFile->_remoteCopy($dir . $tmp_name);
     return $CFile;
 }