/** * Возвращает ленту проектов. * * @param int $kind тип проектов (-1=5=Все проекты; 2=Конкурсы; 4=В офис; 6=Только для про) * @param array $filter массив с фильтром проектов (тот же, что для projects::getProjects(), но разделы в таком виде: [[1,2,3], [44,55,66]], где по индексу 0 -- разделы, по 1 -- подразделы) * @param int $page_size кол-во проектов на странице. * * @return array */ protected function x____getProjects($args) { list($kind, $filter, $page_size) = $args; require_once ABS_PATH . '/classes/projects.php'; require_once ABS_PATH . '/classes/projects_filter.php'; require_once ABS_PATH . '/classes/professions.php'; $result = null; $projects = new new_projects(); $kind = $kind ? (int) $kind : $this->_mCfg['default_kind']; $page_size = (int) $page_size; $limit = $page_size > $this->_mCfg['max_page_size'] ? $this->_mCfg['max_page_size'] : ($page_size < $this->_mCfg['min_page_size'] ? $this->_mCfg['page_size'] : $page_size); if ($filter) { $filter['active'] = $this->ex2pg(EXTERNAL_TRUE, EXTERNAL_DT_BOOL); $filter['wo_cost'] = $this->ex2pg($filter['wo_cost'], EXTERNAL_DT_BOOL); $filter['only_sbr'] = $this->ex2pg($filter['prefer_sbr'], EXTERNAL_DT_BOOL); if ($filter['my_specs']) { $filter['my_specs'] = $this->ex2pg($filter['my_specs'], EXTERNAL_DT_BOOL); $filter['user_specs'] = professions::GetProfessionsByUser($this->_sess->_uid, false, true); } if (isset($filter['categories']) && is_array($filter['categories'])) { $filter['categories'] = intarrPgSql($filter['categories']); $cats = $filter['categories']; $filter['categories'] = array(); foreach ($cats as $i => $arr) { if ($i > 1) { break; } if (is_array($arr) && !isNulArray($arr)) { if ($i == 1) { $arr = professions::GetMirroredProfs(implode(',', $arr)); } $filter['categories'][$i] = array_fill_keys($arr, $i); } } } list($filter['cost_from'], $filter['cost_to']) = projects_filters::preCosts($filter['cost_from'], $filter['cost_to']); } if ($prjs = $projects->getLastProjects($kind, $filter, $limit, true)) { foreach ($prjs as $key => $p) { $row = $this->pg2exRow($this->_mCfg['fields'], $p); if ($row['logo']) { $row['logo'] = WDCPREFIX . '/' . $row['logo']; } if ($attach = $projects->getAllAttach($p['id'])) { $row['attach'] = array(); foreach ($attach as $a) { $att = $this->pg2exRow($this->_mCfg['attach-fields'], $a); $att['link'] = WDCPREFIX . '/' . $a['path'] . $a['name']; $row['attach'][] = $att; } } $result[$key] = $row; } } return $result; }
$alert[2] = 'Поле не должно быть пустым!'; } if (trim($title) == '') { $alert[0] = 'Поле не должно быть пустым!'; } $file = new CFile($_FILES['attach']); if ($file->tmp_name) { $file->max_size = articles::ARTICLE_MAX_LOGOSIZE; $file->proportional = 1; $file->max_image_size = array('width' => 100, 'height' => 100, 'less' => 1); $file->resize = 1; $file->proportional = 1; // $file->topfill = 1; $file->server_root = 1; $f_name = $file->MoveUploadedFile('about/articles/'); if (!isNulArray($file->error)) { $alert[3] = 'Файл не удовлетворяет условиям загрузки'; $error_flag = 1; } $fileid = $file->id; $filepath = $file->path; $filename = $file->name; // // if(!$file->img_to_small('sm_' . $f_name, array('width' => 100, 'height' => 100))) { // $alert[3] = "Невозможно уменьшить изображение"; // $error_flag = 1; // } } if (!$fileid) { $alert[3] = 'Необходимо загрузить файл.'; }
/** * Закачать файл * * @param mixed $attach Массив закаченных файлов * @param array $max_image_size Максимально разрешенные размеры файла [width=длинна,height=ширина] * @param string $login Логин того кто закачивает файл * @return array [файлы, ошибки(если есть), коды ошибок(если есть)] */ function uploadFile($attach, $max_image_size, $login = '') { if ($login == '') { $login = $_SESSION['login']; } if ($attach) { foreach ($attach as $file) { $file->max_size = blogs::MAX_FILE_SIZE; $file->proportional = 1; $f_name = $file->MoveUploadedFile($login . "/upload"); $ext = $file->getext(); if (in_array($ext, $GLOBALS['graf_array'])) { $is_image = TRUE; } else { $is_image = FALSE; } $p_name = ''; if (!isNulArray($file->error)) { $error_flag = 1; $alert[3] = "Один или несколько файлов не удовлетворяют условиям загрузки."; break; } else { if ($is_image && $ext != 'swf' && $ext != 'flv') { if (!$file->image_size['width'] || !$file->image_size['height']) { $error_flag = 1; $alert[3] = 'Невозможно уменьшить картинку'; break; } if (!$error_flag && ($file->image_size['width'] > $max_image_size['width'] || $file->image_size['height'] > $max_image_size['height'])) { if (!$file->img_to_small("sm_" . $f_name, $max_image_size)) { $error_flag = 1; $alert[3] = 'Невозможно уменьшить картинку.'; break; } else { $tn = 2; $p_name = "sm_{$f_name}"; } } else { $tn = 1; } } else { if ($ext == 'flv') { $tn = 2; } else { $tn = 0; } } } $files['f_name'][] = $f_name; $files['p_name'][] = $p_name; $files['tn'][] = $tn; } } return array($files, $alert, $error_flag); }
/** * Закачать файл * * @param mixed $attach Массив закаченных файлов (см. класс CFile) * @param array $max_image_size Максимально разрешенные размеры файла [width=длинна,height=ширина] * @param string $login Логин того кто закачивает файл * @return array [файлы, ошибки(если есть), коды ошибок(если есть)] */ function uploadFile($attach, $max_image_size, $login = '******') { if ($login == '') { $login = $_SESSION['login']; } if ($attach) { foreach ($attach as $file) { $file->real_name = $file->name; $file->max_size = MAX_FILE_SIZE_MANAGER; $file->proportional = 1; $file->allowed_ext = array("gif", "jpeg", "png", "swf", "zip", "rar", "xls", "doc", "rtf", "pdf", "psd", "mp3", "txt", "jpg", "docx", "xlsx", "ppt", "pptx", "pub", "tiff", "eps"); $f_name = $file->MoveUploadedFile($login . "/upload"); $p_name = ''; if (!isNulArray($file->error)) { $error_flag = 1; $alert[3] = "Файл не удовлетворяет условиям загрузки."; break; } $files[] = $file; } } return array($files, $alert, $error_flag); }
/** * Регистрирует новое личное сообщение. * * @param int $user_id id пользователя-отправителя * @param string $target_login логин пользователя-получателя * @param string $text текст сообщения * @param array $files прикрепленные файлы * @param int $force разрешение/отказ ответа на письмо (1/0) * @param bool $skip_mail Если TRUE - не отправлять уведомление о новом сообщении на емайл. * @param string $attachedfiles_session ID сессии загруженных файлов * * @return mixed сообщение об ошибке и флаг ошибки в случае ее возниконовения */ public function Add($user_id, $target_login, $text, $files, $force = 0, $skip_mail = false, $attachedfiles_session = null, &$message_id = 0) { require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php'; require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/ignor.php'; $users = new users(); $login = $users->GetName($user_id, $err); $tar_id = $users->GetUid($err, $target_login); if ((ignor::CheckIgnored($tar_id, $user_id) || in_array($target_login, array('admin', 'Anonymous'))) && !$force) { $error = 'Пользователь запретил отправлять ему сообщения'; } else { if ($files) { if (count($files) > self::MAX_FILES) { $alert[1] = 'Вы не можете прикрепить больше ' . self::MAX_FILES . ' файлов к сообщению.'; } else { $max_file_size = self::MAX_FILE_SIZE; foreach ($files as $file) { $ext = $file->getext(); $file->max_size = $max_file_size; $max_file_size -= $file->size; if (!in_array($ext, $GLOBALS['disallowed_array'])) { $f_name = $file->MoveUploadedFile($login['login'] . '/contacts'); if (!isNulArray($file->error)) { if ($max_file_size < 0) { $alert[1] = 'Вы превысили максимально допустимый размер файлов'; } else { $alert[1] = $GLOBALS['PDA'] ? 'Файл не удовлетворяет условиям загрузки' : 'Один или несколько файлов не удовлетворяют условиям загрузки.'; } break; } } else { $alert[1] = $GLOBALS['PDA'] ? 'Файл не удовлетворяет условиям загрузки' : 'Один или несколько файлов имеют неправильный формат.'; } } } } if (empty($alert) && empty($error)) { $memBuff = new memBuff(); // автоматические папки для массовых рассылок личных менеджеров global $aPmUserUids; if (in_array($tar_id, $aPmUserUids) || SERVER === 'local' || SERVER === 'beta' || SERVER === 'alpha') { $DBproxy = new DB(); $nRecId = $DBproxy->val('SELECT mess_pm_ustf_add(?i, ?i)', $tar_id, $user_id); if ($nRecId) { $memBuff->delete('pmAutoFolder' . $tar_id . '_' . $nRecId); } } //--------------------------------------------- $DB = new DB(); $f = array(); if ($files) { foreach ($files as $file) { $f[] = $file->id; } } require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/attachedfiles.php'; $attachedfiles = new attachedfiles($attachedfiles_session); $attachedfiles_files = $attachedfiles->getFiles(); if ($attachedfiles_files) { foreach ($attachedfiles_files as $attachedfiles_file) { $cFile = new CFile($attachedfiles_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); $f[] = $cFile->id; } } $attachedfiles->clear(); $aNoMod = array_merge($GLOBALS['aContactsNoMod'], $GLOBALS['aPmUserUids']); //$bNoMod = hasPermissions('streamnomod', $user_id) || hasPermissions('streamnomod', $tar_id) || is_pro(true, $user_id) || is_pro(true, $tar_id) || in_array($user_id, $aNoMod); $bNoMod = true; // #0022344: Убрать из потоков личку $message_id = $DB->val('SELECT messages_add(?i, ?i, ?, ?b, ?a, ?b)', $user_id, $tar_id, $text, $skip_mail, $f, $bNoMod); if ($user_id % 2 == $tar_id % 2) { $memBuff->delete(self::MEMBUFF_CHAT_PREFIX . $tar_id); } if ($message_id && !$skip_mail && !QChat::active($tar_id)) { $mail = new pmail(); $mail->NewMessage($user_id, $tar_id, stripslashes($text)); } if ($message_id) { require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/external/base.php'; require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/external/api/api.php'; require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/external/api/mobile.php'; externalApi_Mobile::addPushMsg($tar_id, 'message', array('from_user_id' => get_uid(false), 'text' => stripslashes($text))); } } } return array($alert, $error); }
/** * Прикрепляет файлы * * @param array $files массив файлов * @param string $dir папка назначения * @param bool $formatted true - файлы являются экземплярами CFile, иначе false * @return mixed сообщение об ошибке или 0 */ function addAttach($files, $dir, $formatted = false) { global $DB; if (!$files) { return 0; } $attach = NULL; if (!$formatted) { foreach ($files['name'] as $idx => $value) { foreach ($files as $key => $a) { $att[$key] = $files[$key][$idx]; } if ($att['size']) { $attach[] = new CFile($att); } } } else { $attach = $files; } if (!$attach) { return 0; } $i = 0; $sql = ''; foreach ($attach as $file) { if (!$file->size) { continue; } if (++$i > self::MAX_FILE_COUNT) { continue; } $ext = $file->getext(); $file->orig_name = change_q_x($file->name); if (!in_array($ext, $GLOBALS['graf_array']) || $ext == 'swf') { return "Неверный формат файла: {$file->orig_name}"; } $file->max_size = self::MAX_FILE_SIZE; if (!$file->MoveUploadedFile($dir) || !isNulArray($file->error)) { return $file->StrError(); } $sql .= "INSERT INTO account_attach (account_id, file_id, name, orig_name) VALUES ({$this->id}, {$file->id}, '{$file->name}', '{$file->orig_name}');"; } if ($sql && !$DB->query($sql)) { return 'Ошибка'; } return 0; }
/** * Подгрузка аттачей * * @param array $attach массив с элементами типа CFile * @param array $max_image_size массив с максимальными размерами картинки (см. CFile). Один для всех элементов attach * @param string $login логин юзера, которому загрузить картинку. По умолчанию - юзер из $_SESSION['login'] * @return array сообщение об ошибке */ function UploadFiles($attach, $max_image_size, $login = '') { if (!$login) { $login = $_SESSION['login']; } if (!$attach || !$login) { return NULL; } $i = 0; foreach ($attach as $file) { $file->max_size = blogs::MAX_FILE_SIZE; $file->proportional = 1; $file->table = self::FILE_TABLE; $f_name = $file->MoveUploadedFile($login . "/upload"); $i++; $ext = $file->getext(); if (in_array($ext, $GLOBALS['graf_array'])) { $is_image = TRUE; } else { $is_image = FALSE; } if (!isNulArray($file->error)) { if (count($attach) == 1) { $alert[3] = "Файл не удовлетворяет условиям загрузки"; } else { $alert[3] = "Один или несколько файлов не удовлетворяют условиям загрузки."; } break; } else { if ($is_image && $ext != 'swf' && $ext != 'flv') { if (!$file->image_size['width'] || !$file->image_size['height']) { $alert[3] = 'Невозможно уменьшить картинку'; break; } if (!$alert && ($file->image_size['width'] > $max_image_size['width'] || $file->image_size['height'] > $max_image_size['height'])) { $tmp = clone $file; if (!$tmp->img_to_small("sm_" . $f_name, $max_image_size)) { $alert[3] = 'Невозможно уменьшить картинку.'; break; } else { $file->small = 2; } } else { $file->small = 1; } } else { $file->small = $ext == 'flv' ? 2 : 0; } } } return $alert; }
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/yaping.php'; $yaping = new yaping(); //$out = $yaping->doping($gr); header('Location: /users/' . $_SESSION['login'] . (is_emp() ? '/setup' : '') . "/journal/?tr={$thread}&page={$page}"); exit; } if ($site == 'siteadmin' && hasPermissions('blogs')) { if ($alert || $error || $error_flag) { $_SESSION['user.siteadmin.change.result'] = array('alert' => $alert, 'error' => $error, 'title' => $msg_name, 'msgtext' => $msg, 'yt_link' => $yt_link); header("Location: /siteadmin/ban-razban/?mode=blogs&action=edit&tr={$thread}" . ($page ? "&p={$page}" : '') . ($sort ? "&sort={$sort}" : '') . ($search ? "&search={$search}" : '') . ($admin ? "&admin={$admin}" : '')); } else { header("Location: /siteadmin/ban-razban/?mode=blogs&tr={$thread}" . ($page ? "&p={$page}" : '') . ($sort ? "&sort={$sort}" : '') . ($search ? "&search={$search}" : '') . ($admin ? "&admin={$admin}" : '')); } exit; } if ($error || $error_flag || !isNulArray($alert)) { $action = 'edit'; } else { unset($msg_name); unset($msg); require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/yaping.php'; $yaping = new yaping(); if (!$gr) { $gr = __paramInit('int', 'gr'); } if ($ord == 'my' || $ord == 'favs') { $t_ord = isset($_SESSION["blogs_{$ord}_ord"]) ? $_SESSION["blogs_{$ord}_ord"] : ($ord == 'my' ? 'my_all' : 'favs_std'); } else { $t_ord = $ord; } if ($t_ord == 'my_comments' || $t_ord == 'my_all') {
public function saveAction() { $db = front::og('db'); $form = front::$_req['form']; $id_comm = front::$_req['comment']; $parent = front::$_req['parent']; if (!$id_comm) { $id_comm = false; } // global $session; $validate_errors = array(); $save = array(); if (($str = trim($form['title'])) && mb_strlen($str) >= 3) { $save['title'] = change_q_x_a(antispam($str), 0, 96); } else { $validate_errors['title'] = 'Заголовок короче 3 символов'; } if (($str = trim($form['msg'])) && mb_strlen($str) >= 3) { $save['msg'] = change_q_x_a(antispam($str), false, false); } else { $validate_errors['msg'] = 'Текст короче 3 символов'; } if (strlen($form['msg']) > blogs::MAX_DESC_CHARS) { $validate_errors['msg'] = 'Максимальный размер сообщения ' . blogs::MAX_DESC_CHARS . ' символов!'; } else { $save['msg'] = change_q_x_a(antispam($form['msg']), false, false); } $yt_link = substr(change_q_x(antispam(str_replace('watch?v=', 'v/', $form['yt_link'])), true), 0, 128); if ($yt_link != '') { if (strpos($yt_link, 'http://ru.youtube.com/v/') !== 0 && strpos($yt_link, 'http://youtube.com/v/') !== 0 && strpos($yt_link, 'http://www.youtube.com/v/') !== 0) { $validate_errors['yt_link'] = 'Неверная ссылка.'; } } if (sizeof($validate_errors) > 0) { echo json_encode(array('success' => 0, 'validate' => $validate_errors)); exit(1); } $save = front::toWin(array('title' => $form['title'], 'msg' => $form['msg'], 'yt_link' => $yt_link)); $id = intval($id = front::$_req['id']); if ($id_comm) { // if($parent > 0) { // // } else { $save['id_blog'] = $parent; $save['id_reply'] = $id; $save['id_user'] = get_uid(); $id = $db->insert('corporative_blog', $save); // } //if($id_comm && $id > 0) { // $save["id_blog"] = $id; // $save["id_reply"] = $id; // } } else { if ($id > 0) { $save['id_modified'] = get_uid(); $save['id_deleted'] = 0; $save['date_change'] = date('Y-m-d H:i:s'); $aff = $db->update('UPDATE corporative_blog SET ?s WHERE (id = ?n)', $save, $id); } else { $save['id_user'] = get_uid(); $id = $db->insert('corporative_blog', $save); } } if ($form['files_deleted'] != '') { $form['files_deleted'] = preg_replace('/\\\\\\"/', '"', $form['files_deleted']); $filesBefore = json_decode($form['files_deleted']); $login = $_SESSION['login']; foreach ($filesBefore as $file) { if (!$file->db_id) { continue; } front::og('db')->delete('DELETE FROM corporative_blog_attach WHERE id = ?n', $file->db_id); } } if ($form['files'] != '') { //$filesBefore = explode(";", $form["files"]); // vardump($form["files"]); $form['files'] = preg_replace('/\\\\\\"/', '"', $form['files']); $filesBefore = json_decode($form['files']); if ($group == 7) { $max_image_size = array('width' => 400, 'height' => 600, 'less' => 0); } else { $max_image_size = array('width' => 470, 'height' => 1000, 'less' => 0); } $login = $_SESSION['login']; if ($filesBefore) { foreach ($filesBefore as $file) { if (!$file->temp) { continue; } $b_file = new CFile('temp/' . $file->id); if ($b_file->id > 0) { $b_file->Rename('users/' . substr($login, 0, 2) . '/' . $login . '/upload' . '/' . $file->id); $ext = $b_file->getext(); if (in_array($ext, $GLOBALS['graf_array'])) { $is_image = true; } else { $is_image = false; } $b_file->max_size = blogs::MAX_FILE_SIZE; $b_file->proportional = 1; if (!isNulArray($file->error)) { // $error_flag = 1; //print_r($file->error); $alert[3] = 'Один или несколько файлов не удовлетворяют условиям загрузки.'; // break; } else { if ($is_image && $ext != 'swf' && $ext != 'flv') { if (!$b_file->image_size['width'] || !$b_file->image_size['height']) { // $error_flag = 1; $alert[3] = 'Невозможно уменьшить картинку'; break; } if (!$error_flag && ($b_file->image_size['width'] > $max_image_size['width'] || $b_file->image_size['height'] > $max_image_size['height'])) { if (!$b_file->img_to_small('sm_' . $file->id, $max_image_size)) { // $error_flag = 1; $alert[3] = 'Невозможно уменьшить картинку.'; break; } else { $b_file->tn = 2; $b_file->p_name = 'sm_' . $file->id; } } else { $b_file->tn = 1; } } elseif ($ext == 'flv') { $b_file->tn = 2; } else { $b_file->tn = 0; } if ($alert[3]) { $validate_errors['files'] = $alert[3]; } $files[] = $b_file; } } } } } //global $session; if (is_array($files) && sizeof($files)) { $asql = ''; foreach ($files as $file) { //currval('corporative_blog_id_seq') if ($file->name) { $asql .= ", ({$id}, '{$file->name}', '{$file->tn}')"; } } if ($asql) { $asql = substr($asql, 2); } } //echo $asql; if ($asql) { pg_query(DBConnect(), "INSERT INTO corporative_blog_attach(msg_id, \"name\", small) VALUES {$asql}"); } $htmlMode = front::$_req['htmlMode']; if ($htmlMode == 'inPostPage') { front::og('tpl')->blog = front::og('db')->select('SELECT cb.*, u.login, u.uname, u.usurname, u.role, u.is_pro, u.is_pro_test, u.boss_rate FROM corporative_blog as cb, users as u WHERE cb.id = ? AND u.uid = cb.id_user;', $id)->fetchRow(); $attach_blog = front::og('db')->select('SELECT * FROM corporative_blog_attach WHERE msg_id = ?', $id)->fetchAll(); if ($attach_blog) { front::og('tpl')->attach_blog = $attach_blog; } // front::og("tpl")->usbank = $usr; // front::og("tpl")->comment = $comm; //front::og("tpl")->blog = $blog; $html = front::og('tpl')->fetch('my_corporative_post_item.tpl'); } elseif ($htmlMode == 'normal') { $blog = front::og('db')->select('SELECT * FROM corporative_blog WHERE id_blog = 0 AND (id_deleted IS NULL OR id_deleted = 0) AND id = ?n', $id)->fetchRow(); $bids = array($id => $id); $uids = array($blog['id_user'] => $blog['id_user']); $comm = front::get_hash(front::og('db')->select('SELECT COUNT(id_blog) as count, id_blog FROM corporative_blog WHERE id_blog IN(?a) GROUP BY id_blog', $bids)->fetchAll(), 'id_blog', 'count'); $user = front::og('db')->select('SELECT uname, usurname, login, uid, role, is_pro, is_pro_test, boss_rate FROM users WHERE uid IN(?a)', $uids)->fetchAll(); //, "uid", "usname"); $cid[$blog['id']] = $blog['id']; if ($cid) { $attach = front::og('db')->select('SELECT * FROM corporative_blog_attach WHERE msg_id IN(?a)', $cid)->fetchAll(); } if ($attach) { foreach ($attach as $key => $val) { $res_attach[$val['msg_id']][] = $val; } front::og('tpl')->attach = $res_attach; } foreach ($user as $k => $v) { $usr[$v['uid']] = $v; } front::og('tpl')->usbank = $usr; front::og('tpl')->comment = $comm; front::og('tpl')->blog = $blog; $html = front::og('tpl')->fetch('my_corporative_item.tpl'); } echo json_encode(array('success' => true, 'id' => $id, 'html' => front::toUtf($html))); }
/** * Загрузить файл на сервер. * * @param CFile $file объект, инициалзированный из $_FILES. * @param integer $max_size максимально допустимый размер файла. * @return string ошибка или 0 -- все ок. */ function uploadFile($file, $max_size) { if (!$file->size && strlen($file->tmp_name) == 0) { return -1; } if ($file->size == 0) { return 'Файл ' . htmlspecialchars($file->name, ENT_QUOTES, 'cp1251') . ' имеет размер 0 байт'; } $file->server_root = 1; $file->table = 'file_sbr'; $file->max_size = $max_size; $file->orig_name = change_q_x($file->name); if (!$file->MoveUploadedFile($this->_uploadDir) || !isNulArray($file->error)) { return 'Ошибка при загрузке файла ' . htmlspecialchars($file->name, ENT_QUOTES, 'cp1251') . ': ' . $file->error; } return 0; }
/** * Закачать файл. * * @param mixed $attach Массив закаченных файлов (см. класс CFile) * @param array $max_image_size Максимально разрешенные размеры файла [width=длинна,height=ширина] * @param string $login Логин того кто закачивает файл * * @return array [файлы, ошибки(если есть), коды ошибок(если есть)] */ public function uploadFile($attach, $max_image_size, $login = '******') { if ($login == '') { $login = $_SESSION['login']; } if ($attach) { foreach ($attach as $file) { $file->real_name = $file->name; $file->max_size = MAX_FILE_SIZE_MANAGER; $file->proportional = 1; $file->allowed_ext = array('gif', 'jpeg', 'png', 'swf', 'zip', 'rar', 'xls', 'doc', 'rtf', 'pdf', 'psd', 'mp3', 'txt', 'jpg', 'docx', 'xlsx', 'ppt', 'pptx', 'pub', 'tiff', 'eps'); $f_name = $file->MoveUploadedFile($login . '/upload'); $p_name = ''; if (!isNulArray($file->error)) { $error_flag = 1; $alert[3] = 'Файл не удовлетворяет условиям загрузки.'; break; } $files[] = $file; } } return array($files, $alert, $error_flag); }
/** * Редактирование работы в портфолио. * * @see self::addPortf(); * * @param integer $fid ИД * @param string $name Название работы * @param string $pict Основное изображение * @param string $sm_pict Уменьшенное изображение * @param string $link Ссылка на работу * @param string $descr Описание работы * @param integer $prof Специализация работы * @param integer $cost Стоимость работы * @param integer $cost_type Тип стоимости * @param integer $time_type Тип времени работы * @param integer $time_value Время рабты * @param integer $prev_type Тип превью * @param mixed $file_error Ошибка файла если есть * @param mixed $preview_error Превью ошибка * @param integer $new_position Новая позиция * @param integer $in_shop Работа в магазине * @param integer $is_video Есть ли видео * @param string $video_link Ссылка на видео * @param boolean $upd_prev Нужно ли обновить превью из основного изображения * @param integer $moduser_id UID изменяющего пользователя (админа). если null - то берется $fid * @param string $pict_filename Основное изображение для новой загрузки файлов * @param string $prev_pict_filename Уменьшенное изображение для новой загрузки файлов * @param string $login логин пользователя на случай если редактирует админ * @param string $modified_reason причина редактирования * * @return string Сообщение об ошибке */ public function EditPortf($fid, $name, $pict, $sm_pict, $link, $descr, $prof, $cost, $cost_type, $time_type, $time_value, $prev_type, $prj_id, &$file_error, &$preview_error, $new_position, $in_shop = 0, $video_link = '', $upd_prev = false, $moduser_id = null, $pict_filename = '', $prev_pict_filename = '', $login = '', $modified_reason = '') { global $DB; require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/professions.php'; $prfs = new professions(); $profs = $prfs->GetAllProfessionsPortf($fid); foreach ($profs as $pf) { if ($pf['checked']) { $check_prof[] = $pf['id']; } } $check_prof[] = professions::CLIENTS_PROF_ID; $check_prof[] = professions::BEST_PROF_ID; if (!in_array($prof, $check_prof)) { return false; } $old_pict = $this->GetField($prj_id, 'pict'); $old_prev_pict = $this->GetField($prj_id, 'prev_pict'); $sp = $this->GetField($prj_id, 'show_preview'); $dir = $login ? $login : get_login($fid); $l_dir = substr($dir, 0, 2) . '/' . $dir; $mp = false; $filename = ''; $fullDir = 'users/' . $l_dir . '/upload/'; $moduser_id = $moduser_id ? $moduser_id : $fid; // если превью не загружено и требуется обновить превью на основе основного изображения if (!$sm_pict->size > 0 && $upd_prev) { $sm_pict = new CFile(); $sm_pict->GetInfo($fullDir . $old_pict); // оригинальное большое изображение if ($sm_pict->size > 0) { $sm_pict->table = 'file_template'; $sm_pict->quality = 100; if ($sm_pict->resizeImage($fullDir . 'sm_' . $sm_pict->name, 200, 200, 'auto', true)) { // уменьшаем $filename = 'sm_' . $sm_pict->name; $static_preview = $filename; $mp = true; } } } /** * Отдельно загруженное превью. */ if (($sm_pict->size > 0 || $prev_pict_filename) && !$upd_prev) { $preview_error = ''; if ($sm_pict->size > 0) { $sm_pict->max_image_size = array('width' => 200, 'height' => 200, 'less' => 0); $sm_pict->resize = 1; $sm_pict->proportional = 1; $sm_pict->prefix_file_name = 'sm_'; $sm_pict->max_size = 102400; $filename = $sm_pict->MoveUploadedFile($dir . '/upload'); $preview_error = $sm_pict->StrError(); // генерируем неанимированное gif превью для ответов в проектах (только для gif файлов) // файл будет такой: st_sm_f_имя файла.gif if ($sm_pict->image_size['type'] == 1) { $static_preview = 'st_' . $sm_pict->name; $sm_pict->resizeImage($sm_pict->path . $static_preview, 200, 200, 'auto', true); } else { $static_preview = $sm_pict->name; } } else { $filename = $prev_pict_filename; $static_preview = $prev_pict_filename; } if ($preview_error) { return $preview_error; } elseif ($old_prev_pict) { $cfile = new CFile(); $cfile->Delete(0, "users/{$l_dir}/upload/", $old_prev_pict); // удаляем ранее загруженное превью $mp = true; } else { $mp = true; } $sql = 'SELECT show_preview FROM portf_choise WHERE user_id=?i AND prof_id=?i'; $res = $DB->row($sql, $fid, $prof); $show_preview = $res['show_preview']; if ($show_preview == 't') { $sp = 't'; } } /*else $filename = $old_prev_pict;*/ if ($pict->size > 0 || $pict_filename) { $sql = 'SELECT prev_pict FROM portfolio WHERE id=?i AND user_id=?i'; $res = $DB->row($sql, $prj_id, $fid); if ($pict->size > 0) { $pict->max_size = 10485760; $pictname = $pict->MoveUploadedFile($dir . '/upload'); if (!isNulArray($pict->error)) { $file_error = true; return $pict->StrError; } } else { $pict = new CFile($fullDir . $pict_filename); $pictname = $pict_filename; } /*if (is_array($pictname)) list($pictname, $filename) = $pictname;*/ if ($upd_prev && !in_array($pict->getext(), $GLOBALS['graf_array'])) { $filename = null; $static_preview = null; $need_delete_preview = true; } if (isNulArray($pict->error) && in_array($pict->getext(), $GLOBALS['graf_array']) && !$filename && $res['prev_pict'] == '' || $upd_prev && in_array($pict->getext(), $GLOBALS['graf_array'])) { //print "2";exit; /** * Делаем превью. */ $pict->proportional = 1; //$pict->imgtosmall() /* if (!$pict->img_to_small("sm_".$pictname,array('width'=>200,'height'=>200))) { $mp = false; } else { $mp = true; $filename = "sm_".$pictname; } */ $pict->table = 'file_template'; $pict->quality = 100; if ($pict->resizeImage($fullDir . 'sm_' . $pict->name, 200, 200, 'auto', true)) { // уменьшаем $filename = 'sm_' . $pict->name; $static_preview = $filename; $mp = true; } $sql = 'SELECT show_preview FROM portf_choise WHERE user_id=?i AND prof_id=?i'; $res = $DB->row($sql, $fid, $prof); $show_preview = $res['show_preview']; if ($show_preview == 't') { $sp = 't'; if (!$mp) { $file_error .= 'Невозможно уменьшить картинку.'; $sp = 'f'; } } } if (isNulArray($pict->error) && $res['prev_pict'] == '') { if (!$cfile) { $cfile = new CFile(); if ($old_prev_pict && $sm_pict->name) { $cfile->Delete(0, "users/{$l_dir}/upload/", $old_prev_pict); // удаляем ранее загруженное превью $need_delete_preview = true; } } if ($old_pict) { $cfile->Delete(0, "users/{$l_dir}/upload/", $old_pict); } // удаляем ранее загруженное превью } } else { $pictname = $old_pict; } // для картинок: если превью загружено отдельно - делаем отдельное привью из оригинальной большой картинки $sPreview = $filename ? $filename : $old_prev_pict; if ($pictname != substr($sPreview, 3, strlen($sPreview))) { $sm_pict = new CFile(); if (($pict->size > 0 || $pict_filename) && $old_pict) { $sm_pict->Delete(0, "users/{$l_dir}/upload/", 'tn_' . $old_pict); } $sm_pict->GetInfo($fullDir . $pictname); if ($sm_pict->size > 0) { $ext = $sm_pict->getext(); if (in_array($ext, $GLOBALS['graf_array']) && $ext != 'swf') { $sm_pict->table = 'file_template'; $sm_pict->quality = 100; $sm_pict->resizeImage($fullDir . 'tn_' . $sm_pict->name, 200, 200, 'auto', true); } } } else { $sm_pict = new CFile(); $sm_pict->Delete(0, "users/{$l_dir}/upload/", 'tn_' . $pictname); } if ($in_shop == 1) { $in_shop = 't'; } else { $in_shop = 'f'; } $prof = professions::GetProfessionOrigin($prof); $sql = ''; if ($fid == $_SESSION['uid'] && !hasPermissions('users')) { // автор, не админ, не про меняет заголовок либо текст - отправить на модерирование $sModer = ' , moderator_status = ' . (!is_pro() ? '0' : '-2') . ' '; 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( $name, $descr ); $DB->insert( 'moderation', array('rec_id' => $prj_id, 'rec_type' => user_content::MODER_PORTFOLIO, 'stop_words_cnt' => $nStopWordsCnt) );*/ } } if ($mp) { $sql .= "UPDATE portfolio SET name='{$name}', link='{$link}', descr='{$descr}', cost='{$cost}', cost_type='{$cost_type}', time_type='{$time_type}', time_value='{$time_value}', prev_type='{$prev_type}', pict='{$pictname}', prev_pict='{$filename}', static_preview='{$static_preview}', prof_id='{$prof}'" . ($new_position !== NULL ? ", norder='{$new_position}'" : '') . ", edit_date = NOW(), edit_id = {$moduser_id}, modified_reason = '{$modified_reason}' {$sModer} WHERE (id='{$prj_id}' AND user_id='{$fid}') RETURNING norder"; } else { $sql .= "UPDATE portfolio SET show_preview = '{$sp}', name='{$name}', link='{$link}', descr='{$descr}', cost='{$cost}', cost_type='{$cost_type}', time_type='{$time_type}', time_value='{$time_value}', prev_type='{$prev_type}', pict='{$pictname}', " . ($need_delete_preview ? "prev_pict='',static_preview=''," : '') . " prof_id='{$prof}'" . ($new_position !== NULL ? ", norder='{$new_position}'" : '') . ", in_shop='{$in_shop}', video_link='{$video_link}', edit_date = NOW(), edit_id = {$moduser_id}, modified_reason = '{$modified_reason}' {$sModer} WHERE (id='{$prj_id}' AND user_id='{$fid}') RETURNING norder"; } $DB->squery($sql); return $error; }
/** * Добавление личного сообщения * * @param array $aParams массив входящих данных * @return array $aResult ответ */ protected function x____messages_send($aParams = array()) { $this->_validDevice($aParams); $nUid = get_uid(false); $nTo = intvalPgSql($aParams['to_id']); if (!empty($nTo)) { require_once ABS_PATH . '/classes/users.php'; $oUser = new users(); $oUser->GetUserByUID($nTo); if ($oUser->uid) { if ($oUser->uid != $nUid) { if (empty($oUser->is_banned)) { require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/ignor.php'; $bIgnor = ignor::CheckIgnored($oUser->uid, $nUid) || in_array($oUser->login, array('admin', 'Anonymous')); if (!$bIgnor) { $sMessage = __paramValue('html', antispam(iconv('utf-8', 'cp1251', $aParams['text'])), null, true); if (!$sMessage || trim($sMessage) == '') { $this->error(EXTERNAL_ERR_EMPTY_MESSAGE); } elseif ($sMessage && strlen($sMessage) > $this->_mCfg['text_limit']) { $this->error(EXTERNAL_ERR_LENGTH_MESSAGE); } require_once ABS_PATH . '/classes/messages.php'; list($alert, $error) = messages::Add($nUid, $oUser->login, $sMessage, array(), 0, false, null, $sId); if (!$error && isNulArray($alert)) { messages::updateSendLog($nUid); } else { $this->error(EXTERNAL_ERR_SERVER_ERROR); } $aResult = array("message" => array("id" => $sId, "from_id" => $nUid, "to_id" => $oUser->uid, "text" => $aParams['text'], "status" => 1, "read" => 0, "create_time" => time(), "update_time" => time())); } else { $this->error(EXTERNAL_ERR_MESSAGE_IGNOR); } } else { $this->error(EXTERNAL_ERR_USER_BANNED); } } else { $this->error(EXTERNAL_ERR_SELF_MESSAGE); } } else { $this->error(EXTERNAL_ERR_USER_NOTFOUND); } } else { $this->error(EXTERNAL_ERR_EMPTY_USER_ID); } return $aResult; }
/** * Изменить отзыв * * @param string $msg Текст отзыва * @param string $sign Подпись * @param object $file CFile файл с логотипом * @param string $link Ссылка на сайт того кто оставил отзыв * @param string $from_ip IP адрес того кто писал отзыв * @param int $msgid ID отзыва * @return array сообщения об ошибках (файл, база) */ function Edit($msg, $sign, $file, $link, $from_ip, $msgid) { if ($file) { $file->max_size = 1048576; $file->proportional = 1; $file->max_image_size = array('width' => 120, 'height' => 120, 'less' => 1); $file->resize = 1; $file->proportional = 1; $file->topfill = 1; $file->server_root = 1; $f_name = $file->MoveUploadedFile("about/opinions/"); if (!isNulArray($file->error)) { $alert[3] = "Файл не удовлетворяет условиям загрузки"; $error_flag = 1; } if (!$error_flag) { $GLOBALS['DB']->query("UPDATE sopinions SET msgtext = ?, sign = ?, logo = ?, link = ?, from_ip = ?, modified = NOW() WHERE id = ?", $msg, $sign, $f_name, $link, $from_id, $msgid); } } else { $GLOBALS['DB']->query("UPDATE sopinions SET msgtext = ?, sign = ?, link = ?, from_ip = ?, modified = NOW() WHERE id=?", $msg, $sign, $link, $from_id, $msgid); } return array($alert, $DB->error); }
/** * Редактирование фотографий * * @param integer $id Ид * @param object $attach Приложеные файлы (см. класс CFile) * @param array $photo Фотки (см. класс CFile) * @return integer */ function EditPhotos($id, $attach, $photo) { if (!$id) { return 0; } // Проверяем приложены ли файлы и обрабатываем их если они есть if ($attach->size > 0) { $fn = 0; $attach->proportional = 1; $f_name = $attach->MoveUploadedFile($_SESSION['login'] . "/upload"); if (!isNulArray($attach->error)) { $error_flag = 1; $alert[2] = "Файл не удовлетворяет условиям загрузки"; } else { $ext = $attach->getext(); if (in_array($ext, $GLOBALS['graf_array']) && $ext != "swf") { if (!$attach->image_size['width'] || !$attach->image_size['height']) { $error_flag = 1; $alert[2] = "Невозможно уменьшить картинку."; } if ($attach->image_size['width'] > 200 || $attach->image_size['height'] > 1000) { if (!$attach->img_to_small("sm_" . $f_name, array('width' => 200, 'height' => 1000, 'less' => 0))) { $error_flag = 1; $alert[2] = "Невозможно уменьшить картинку."; } else { $fn = 2; } } else { $fn = 1; } } } } // Если есть фотки if ($photo) { // Обратобка фоток foreach ($photo as $ikey => $wrk) { $tn = 0; $w_name = $wrk->MoveUploadedFile($_SESSION['login'] . "/upload"); if (!isNulArray($wrk->error)) { $error_flag = 1; $alert[2] = "Файл не удовлетворяет условиям загрузки"; } else { $ext = $wrk->getext(); $wrk->proportional = 1; if (in_array($ext, $GLOBALS['graf_array']) && $ext != "swf") { if (!$wrk->image_size['width'] || !$wrk->image_size['height']) { $error_flag = 1; $alert[2] = "Невозможно уменьшить картинку."; } if ($wrk->image_size['width'] > 200 || $wrk->image_size['height'] > 1000) { if (!$wrk->img_to_small("sm_" . $w_name, array('width' => 200, 'height' => 1000, 'less' => 0))) { $error_flag = 1; $alert[2] = "Невозможно уменьшить картинку."; } else { $tn = 2; } } else { $tn = 1; } } } if (!$error_flag) { $qstn[] = "file" . ($ikey + 1) . "='{$w_name}'"; $qstv[$ikey] = "file" . ($ikey + 1); $qsts[$ikey] = "pt" . ($ikey + 1); $qstp[] = "pt" . ($ikey + 1) . "='" . $tn . "'"; } $w_name = ""; } } // Сохранение всего обработанного добра if ($id && ($qstn || $f_name)) { global $DB; $sql = "SELECT ft, foto" . (isset($qstv) ? "," . implode(", ", $qstv) . ", " . implode(", ", $qsts) : "") . " FROM interview WHERE id=?"; $ret = $DB->row($sql, $id); if ($ret['foto'] && $f_name) { $file = new CFile(); $file->Delete(0, "users/" . substr($_SESSION['login'], 0, 2) . "/" . $_SESSION['login'] . "/upload/", $ret['foto']); if ($ret['ft'] == 2) { $file->Delete(0, "users/" . substr($_SESSION['login'], 0, 2) . "/" . $_SESSION['login'] . "/upload/", "sm_" . $ret['foto']); } } if ($f_name) { $af = "foto = '{$f_name}', ft = '{$fn}'"; } if ($qstn) { foreach ($qstv as $ikey => $value) { if ($ret[$value] && $qstn[$ikey]) { $file = new CFile(); $file->Delete(0, "users/" . substr($_SESSION['login'], 0, 2) . "/" . $_SESSION['login'] . "/upload/", $ret[$value]); if ($ret[$qsts[$ikey]] == 2) { $file->Delete(0, "users/" . substr($_SESSION['login'], 0, 2) . "/" . $_SESSION['login'] . "/upload/", "sm_" . $ret[$value]); } } } $af .= (isset($af) ? "," : "") . implode(", ", $qstn) . ", " . implode(", ", $qstp); } $sql = "UPDATE interview SET " . $af . " WHERE id=?"; $res = $DB->query($sql, $id); } return 0; }
$captchanum = $_POST['captchanum']; $captcha = new captcha($captchanum); $rnd = $_POST['rndnum']; if (!$captcha->checkNumber(trim($rnd))) { $error_flag = 1; $alert[4] = "Вы ввели неверную комбинацию символов"; } } // если запрошено обновление капчи в PDA $newCaptcha = $_POST['newcaptcha']; if ($newCaptcha) { $alert = array(); } if ($chat_with != $_SESSION['login'] && !$error_flag) { list($alert, $error) = messages::Add(get_uid(), $chat_with, $msg, $files, 0, false, $attachedfiles_session); if (!$error && isNulArray($alert)) { messages::updateSendLog(get_uid(false)); if ($draft_id) { require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/drafts.php"; drafts::DeleteDraft(intval($draft_id), get_uid(false), 2, true); } //Если сообщение фрилансеру то разрешаем отправку сообщений обратно if (!is_emp($chat_user->role)) { messages::setIsAllowed($uid, $chat_user->uid); } unset($msg); header("Location: " . $_SERVER["REQUEST_URI"]); exit; } } break;
} // загрузка файлов $files = array(); $attach = $_FILES['attach']; if (is_array($attach) && !empty($attach['name'])) { $i = 0; foreach ($attach['name'] as $key => $v) { if (!$attach['name'][$key]) { continue; } $files[$i] = new CFile(array('name' => $attach['name'][$key], 'type' => $attach['type'][$key], 'tmp_name' => $attach['tmp_name'][$key], 'error' => $attach['error'][$key], 'size' => $attach['size'][$key])); $ext = $files[$i]->getext(); if (!in_array($ext, $GLOBALS['disallowed_array'])) { if ($files[$i]->size > 0) { $name = $files[$i]->MoveUploadedFile("{$FROM}/contacts"); if (!isNulArray($files[$i]->error)) { $alert[1] = "ќдин или несколько файлов не удовлетвор¤ют услови¤м загрузки"; $error_flag = 1; } } } else { $alert[1] = "ќдин или несколько файлов имеют неправильный формат."; $error_flag = 1; } $i++; } } $error = 0; if (!$msg && !$name) { $error_flag = 1; $alert[2] = "ѕоле заполнено некорректно";
/** * Назначить логотип к проекту * * @param object file Файл логотипа (@see CFile) * @return string|integer Сообщение об ошибке. либо 0 */ function setLogo($file) { if (!$file->size) { return 0; } $file->server_root = 1; $file->table = 'file_projects'; $file->max_size = self::LOGO_SIZE; $file->disable_animate = true; $file->max_image_size = array("width" => self::LOGO_WIDTH, "height" => self::LOGO_HEIGHT, "less" => 1); if (!$file->MoveUploadedFile($this->_tmpAbsDir) || !isNulArray($file->error)) { return $file->StrError(); } if ($file->image_size['width'] != self::LOGO_WIDTH) { $file->Delete($file->id); return 'Ширина логотипа должна быть равна ' . self::LOGO_WIDTH . ' пикселям.'; } $this->delLogo(); $this->_tmpFiles[] = $file->name; $file_name = get_unanimated_gif($_SESSION['login'], $file->name, $file->path); $this->_tmpFiles[] = $file_name; $this->_logo = array('id' => $file->id, 'path' => $file->path, 'name' => $file->name, 'size' => $file->size, 'ftype' => $file->getext()); return 0; }
/** * Закачка файлов прикрепленных к сообщению. * * @param object $file Вложенные файлы @link class CFile(); * @param array $max_image_size Максимальный размер изображения [height=>1111, width=>1111] * * @return array [object CFile, предупреждение, флаги ошибок] */ public function UploadFiles($file, $max_image_size) { if ($file) { if (!$this instanceof blogs_norisk) { $file->max_size = 2097152; } $file->proportional = 1; $f_name = $file->MoveUploadedFile($_SESSION['login'] . '/upload'); $ext = $file->getext(); if (in_array($ext, $GLOBALS['graf_array'])) { $is_image = TRUE; } else { $is_image = FALSE; } $p_name = ''; if (!isNulArray($file->error)) { $error_flag = 1; $alert[3] = 'Файл не удовлетворяет условиям загрузки.'; } else { if ($is_image && $ext != 'swf' && $ext != 'flv') { if (!$file->image_size['width'] || !$file->image_size['height']) { $error_flag = 1; $alert[3] = 'Невозможно уменьшить картинку'; } if (!$error_flag && ($file->image_size['width'] > $max_image_size['width'] || $file->image_size['height'] > $max_image_size['height'])) { if (!$file->img_to_small('sm_' . $f_name, $max_image_size)) { $error_flag = 1; $alert[3] = 'Невозможно уменьшить картинку.'; } else { $tn = 2; $p_name = "sm_{$f_name}"; } } else { $tn = 1; } } else { if ($ext == 'flv') { $tn = 2; } else { $tn = 0; } } } $files['f_name'] = $f_name; $files['p_name'] = $p_name; $files['tn'] = $tn; } return array($files, $alert, $error_flag); }
/** * Перемещает загруженный файл в новое место * * @param string $dir Папка закачки * @param boolean $virusScan Если TRUE, то проверять на вирусы * @param string $destFileName Если не пусто, то сохранить файл с этим именем * @return string Название закаченного файла */ function MoveUploadedFile($dir, $virusScan = TRUE, $destFileName = '') { if (@$this->error[0]) { return NULL; } $this->path = $this->server_root ? $dir : "users/" . substr($dir, 0, 2) . "/" . $dir . "/"; $dir = $this->path; if (!$virusScan) { $this->virus = 16; } /*if (!file_exists($dir)) { mkdir($dir, 0777,1); }*/ if ($this->size > 0) { $ext = strtolower($this->getext($this->name)); if (strlen($destFileName) > 0) { $ext = strtolower($this->getext($destFileName)); } if ($this->size > $this->max_size) { $this->error = "Cлишком большой файл. "; return NULL; } if (in_array($ext, $GLOBALS['disallowed_array']) && $ext != $this->file_ext) { $this->error = "Недопустимый тип файла. "; return NULL; } if (count($this->allowed_ext) && !in_array($ext, $this->allowed_ext)) { $this->error = "Недопустимый тип файла. "; return NULL; } if (!$this->CheckPath($this->path, true)) { // проверяем директорию, если надо - создаем. $this->MakeDir($this->path); } if ($this->CheckPath($dir, true)) { $tmp = $this->secure_tmpname($dir, "." . $ext); if (!$tmp) { $this->error = "Директория задана неверно. "; return false; } if (strlen($destFileName) == 0) { $this->name = substr_replace($tmp, "", 0, strlen($dir)); } else { $this->name = $destFileName; } if (in_array($ext, $GLOBALS['graf_array']) && $this->disable_animate) { $this->getDisabledAnimateGIF(); } if (!isNulArray($this->max_image_size) && in_array($ext, $GLOBALS['graf_array'])) { $this->_getImageSize($this->tmp_name); $this->validExtensionFile($this->image_size['type']); $ext = strtolower($this->getext($this->name)); if (in_array($ext, $GLOBALS['disallowed_array']) && $ext != $this->file_ext) { $this->error = "Недопустимый тип файла. "; return NULL; } if (count($this->allowed_ext) && !in_array($ext, $this->allowed_ext)) { $this->error = "Недопустимый тип файла. "; return NULL; } $prevent_less = $this->max_image_size['prevent_less'] && ($this->image_size['width'] < $this->max_image_size['width'] || $this->image_size['height'] < $this->max_image_size['height']); if ($this->resize && ($this->image_size['width'] > $this->max_image_size['width'] || $this->image_size['height'] > $this->max_image_size['height']) && !$prevent_less) { $src = $this->tmp_name; $dest = $this->tmp_name; $format = strtolower(substr($this->image_size['mime'], strpos($this->image_size['mime'], '/') + 1)); $icfunc = "imagecreatefrom" . $format; $imfunc = "image" . $format; if (!function_exists($icfunc) || !function_exists($imfunc)) { $this->error = "Недопустимый формат файла. " . $imfunc; $this->name = ""; } else { $x_ratio = $this->max_image_size['width'] / $this->image_size['width']; $y_ratio = $this->max_image_size['height'] / $this->image_size['height']; $ratio = min($x_ratio, $y_ratio); if ($ratio == 0) { $ratio = max($x_ratio, $y_ratio); } $use_x_ratio = $x_ratio == $ratio; $new_width = $use_x_ratio ? $this->max_image_size['width'] : floor($this->image_size['width'] * $ratio); $new_height = !$use_x_ratio ? $this->max_image_size['height'] : floor($this->image_size['height'] * $ratio); $new_left = $use_x_ratio ? 0 : floor(($this->max_image_size['width'] - $new_width) / 2); $new_top = !$use_x_ratio ? 0 : floor(($this->max_image_size['height'] - $new_height) / 2); $isrc = $icfunc($src); if ($isrc) { if ($this->proportional) { if ($this->topfill) { if ($this->image_size['type'] == 3) { $idest = $this->imageResizeAlpha($isrc, $new_width, $new_height); } else { $idest = imagecreatetruecolor($this->max_image_size['width'], $this->max_image_size['height']); imagefill($idest, 0, 0, $this->background); imagecopyresampled($idest, $isrc, $new_left, $new_top, 0, 0, $new_width, $new_height, $this->image_size['width'], $this->image_size['height']); } } elseif ($this->crop) { if ($this->image_size['type'] == 3) { $idest = $this->imageResizeAlpha($isrc, $new_width, $new_height); } else { $newWidth = $this->max_image_size['width']; $newHeight = $this->max_image_size['height']; $optionArray = $this->_getImageOptimalCrop($newWidth, $newHeight); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; $imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight); imagecopyresampled($imageResized, $isrc, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->image_size['width'], $this->image_size['height']); $isrc = $imageResized; $cropStartX = $optimalWidth / 2 - $newWidth / 2; $cropStartY = $optimalHeight / 2 - $newHeight / 2; $idest = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($idest, $isrc, 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight, $newWidth, $newHeight); } } else { if ($this->image_size['type'] == 3) { $idest = $this->imageResizeAlpha($isrc, $new_width, $new_height); } else { $idest = imagecreatetruecolor($new_width, $new_height); imagefill($idest, 0, 0, $this->background); imagecopyresampled($idest, $isrc, 0, 0, 0, 0, $new_width, $new_height, $this->image_size['width'], $this->image_size['height']); } } } else { $idest = imagecreatetruecolor($this->max_image_size['width'], $this->max_image_size['height']); imagefill($idest, 0, 0, $this->background); imagecopyresampled($idest, $isrc, 0, 0, 0, 0, $this->max_image_size['width'], $this->max_image_size['height'], $this->image_size['width'], $this->image_size['height']); } if ($this->image_size['type'] == 2) { imagejpeg($idest, $dest, $this->quality); } else { if ($this->image_size['type'] != 1) { $imfunc($idest, $dest); } } $this->_getImageSize($dest); $this->size = filesize($dest); imagedestroy($isrc); imagedestroy($idest); unset($isrc); unset($idest); } else { $this->error[] = "Не смог изменить размер файла. "; $this->name = ""; } } } elseif (!$this->resize && (!$this->max_image_size['less'] && ($this->image_size['width'] != $this->max_image_size['width'] || $this->image_size['height'] != $this->max_image_size['height']) || $this->max_image_size['less'] && ($this->image_size['width'] > $this->max_image_size['width'] || $this->image_size['height'] > $this->max_image_size['height'])) || $prevent_less) { $this->error[] = "Недопустимые размеры файла. "; $this->name = ""; } } if (isNulArray($this->error)) { $this->_upload($this->tmp_name); } } else { $this->error[] = "Невозможно загрузить файл. "; } } else { $this->name = ""; } return $this->name; }
function saveAction() { $db = front::og("db"); $form = front::$_req["form"]; $id_comm = front::$_req["comment"]; $parent = front::$_req["parent"]; if (!$id_comm) { $id_comm = false; } // global $session; $validate_errors = array(); $save = array(); if (($str = trim($form['title'])) && mb_strlen($str) >= 3) { $save['title'] = change_q_x_a(antispam($str), 0, 96); } else { $validate_errors['title'] = 'Заголовок короче 3 символов'; } if (($str = trim($form['msg'])) && mb_strlen($str) >= 3) { $save['msg'] = change_q_x_a(antispam($str), false, false); } else { $validate_errors['msg'] = 'Текст короче 3 символов'; } if (strlen($form['msg']) > blogs::MAX_DESC_CHARS) { $validate_errors['msg'] = "Максимальный размер сообщения " . blogs::MAX_DESC_CHARS . " символов!"; } else { $save['msg'] = change_q_x_a(antispam($form['msg']), false, false); } $yt_link = substr(change_q_x(antispam(str_replace('watch?v=', 'v/', $form['yt_link'])), true), 0, 128); if ($yt_link != '') { if (strpos($yt_link, 'http://ru.youtube.com/v/') !== 0 && strpos($yt_link, 'http://youtube.com/v/') !== 0 && strpos($yt_link, 'http://www.youtube.com/v/') !== 0) { $validate_errors['yt_link'] = "Неверная ссылка."; } } if (sizeof($validate_errors) > 0) { echo json_encode(array("success" => 0, "validate" => $validate_errors)); exit(1); } $save = front::toWin(array("title" => $form["title"], "msg" => $form["msg"], "yt_link" => $yt_link)); $id = intval($id = front::$_req["id"]); if ($id_comm) { // if($parent > 0) { // // } else { $save["id_blog"] = $parent; $save["id_reply"] = $id; $save["id_user"] = get_uid(); $id = $db->insert("corporative_blog", $save); // } //if($id_comm && $id > 0) { // $save["id_blog"] = $id; // $save["id_reply"] = $id; // } } else { if ($id > 0) { $save["id_modified"] = get_uid(); $save["id_deleted"] = 0; $save["date_change"] = date("Y-m-d H:i:s"); $aff = $db->update("UPDATE corporative_blog SET ?s WHERE (id = ?n)", $save, $id); } else { $save["id_user"] = get_uid(); $id = $db->insert("corporative_blog", $save); } } if ($form["files_deleted"] != "") { $form["files_deleted"] = preg_replace('/\\\\\\"/', '"', $form["files_deleted"]); $filesBefore = json_decode($form["files_deleted"]); $login = $_SESSION['login']; foreach ($filesBefore as $file) { if (!$file->db_id) { continue; } front::og("db")->delete("DELETE FROM corporative_blog_attach WHERE id = ?n", $file->db_id); } } if ($form["files"] != "") { //$filesBefore = explode(";", $form["files"]); // vardump($form["files"]); $form["files"] = preg_replace('/\\\\\\"/', '"', $form["files"]); $filesBefore = json_decode($form["files"]); if ($group == 7) { $max_image_size = array('width' => 400, 'height' => 600, 'less' => 0); } else { $max_image_size = array('width' => 470, 'height' => 1000, 'less' => 0); } $login = $_SESSION["login"]; if ($filesBefore) { foreach ($filesBefore as $file) { if (!$file->temp) { continue; } $b_file = new CFile("temp/" . $file->id); if ($b_file->id > 0) { $b_file->Rename("users/" . substr($login, 0, 2) . "/" . $login . "/upload" . "/" . $file->id); $ext = $b_file->getext(); if (in_array($ext, $GLOBALS['graf_array'])) { $is_image = TRUE; } else { $is_image = FALSE; } $b_file->max_size = blogs::MAX_FILE_SIZE; $b_file->proportional = 1; if (!isNulArray($file->error)) { // $error_flag = 1; //print_r($file->error); $alert[3] = "Один или несколько файлов не удовлетворяют условиям загрузки."; // break; } else { if ($is_image && $ext != 'swf' && $ext != 'flv') { if (!$b_file->image_size['width'] || !$b_file->image_size['height']) { // $error_flag = 1; $alert[3] = 'Невозможно уменьшить картинку'; break; } if (!$error_flag && ($b_file->image_size['width'] > $max_image_size['width'] || $b_file->image_size['height'] > $max_image_size['height'])) { if (!$b_file->img_to_small("sm_" . $file->id, $max_image_size)) { // $error_flag = 1; $alert[3] = 'Невозможно уменьшить картинку.'; break; } else { $b_file->tn = 2; $b_file->p_name = "sm_" . $file->id; } } else { $b_file->tn = 1; } } else { if ($ext == 'flv') { $b_file->tn = 2; } else { $b_file->tn = 0; } } if ($alert[3]) { $validate_errors['files'] = $alert[3]; } $files[] = $b_file; } } } } } //global $session; if (is_array($files) && sizeof($files)) { $asql = ''; foreach ($files as $file) { //currval('corporative_blog_id_seq') if ($file->name) { $asql .= ", ({$id}, '{$file->name}', '{$file->tn}')"; } } if ($asql) { $asql = substr($asql, 2); } } //echo $asql; if ($asql) { pg_query(DBConnect(), "INSERT INTO corporative_blog_attach(msg_id, \"name\", small) VALUES {$asql}"); } $htmlMode = front::$_req["htmlMode"]; if ($htmlMode == "inPostPage") { front::og("tpl")->blog = front::og("db")->select("SELECT cb.*, u.login, u.uname, u.usurname, u.role, u.is_pro, u.is_pro_test, u.boss_rate FROM corporative_blog as cb, users as u WHERE cb.id = ? AND u.uid = cb.id_user;", $id)->fetchRow(); $attach_blog = front::og("db")->select("SELECT * FROM corporative_blog_attach WHERE msg_id = ?", $id)->fetchAll(); if ($attach_blog) { front::og("tpl")->attach_blog = $attach_blog; } // front::og("tpl")->usbank = $usr; // front::og("tpl")->comment = $comm; //front::og("tpl")->blog = $blog; $html = front::og("tpl")->fetch("my_corporative_post_item.tpl"); } elseif ($htmlMode == "normal") { $blog = front::og("db")->select("SELECT * FROM corporative_blog WHERE id_blog = 0 AND (id_deleted IS NULL OR id_deleted = 0) AND id = ?n", $id)->fetchRow(); $bids = array($id => $id); $uids = array($blog["id_user"] => $blog["id_user"]); $comm = front::get_hash(front::og("db")->select("SELECT COUNT(id_blog) as count, id_blog FROM corporative_blog WHERE id_blog IN(?a) GROUP BY id_blog", $bids)->fetchAll(), "id_blog", "count"); $user = front::og("db")->select("SELECT uname, usurname, login, uid, role, is_pro, is_pro_test, boss_rate FROM users WHERE uid IN(?a)", $uids)->fetchAll(); //, "uid", "usname"); $cid[$blog['id']] = $blog['id']; if ($cid) { $attach = front::og("db")->select("SELECT * FROM corporative_blog_attach WHERE msg_id IN(?a)", $cid)->fetchAll(); } if ($attach) { foreach ($attach as $key => $val) { $res_attach[$val['msg_id']][] = $val; } front::og("tpl")->attach = $res_attach; } foreach ($user as $k => $v) { $usr[$v['uid']] = $v; } front::og("tpl")->usbank = $usr; front::og("tpl")->comment = $comm; front::og("tpl")->blog = $blog; $html = front::og("tpl")->fetch("my_corporative_item.tpl"); } echo json_encode(array("success" => true, "id" => $id, "html" => front::toUtf($html))); }
if (is_array($img->error)) { $err = $img->error[0]; } else { $err = $img->error; } $error = true; $pictname = $prevname = ''; } else { if (in_array($img->getext(), $GLOBALS['disallowed_array'])) { $err = 'Недопустимый тип файла'; $error = true; } else { if (in_array($img->getext(), $GLOBALS['graf_array']) && strtolower($img->getext()) != 'swf' && strtolower($img->getext()) != 'flv') { // Делаем превью. $pict_added = $img->img_to_small('sm_' . $pictname, array('width' => 200, 'height' => 200, 'less' => 0)); if (!isNulArray($img->error)) { $error = true; $pictname = $prevname = ''; } elseif ($pict_added) { $prevname = 'sm_' . $pictname; } } else { $pict_added = true; } } } } elseif (strlen($img->tmp_name) != 0) { $err = 'Пустой файл'; $error = true; } elseif ($img->error) { $err = $img->error[0];
} else { $ontop = null; } if ($_POST['not_is_private']) { $is_private = 'n'; } if ($_POST['not_close_comments']) { $close_comments = 'n'; } $blogs->Edit($_SESSION['uid'], $reply, $msg, $msg_name, $files, getRemoteIP(), $err, $mod, '', $gr, $t, $attach_delete, $olduserlogin, $yt_link, $close_comments, $is_private, $ontop, null, $question, $answers, $answers_exists, $multiple); $attachedfiles_files = $attachedfiles->getFiles(array(1, 3, 4)); $blogs->addAttachedFiles($attachedfiles_files, $reply, $olduserlogin, $draft_id ? true : false); $attachedfiles->clear(); //$nStopWordsCnt = $stop_words->calculate( $msg, $msg_name, $question, $answers, $answers_exists ); //$blogs->insertIntoModeration( $reply, $nStopWordsCnt, (!$categ ? 1 : 0) ); // больше не модерируем if (is_array($err) && !isNulArray($err)) { $error_flag = 1; $alert[3] = $err[3]; $action = "edit"; $edit_id = $reply; } else { $last_id = $reply; if ($draft_id) { require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/drafts.php"; drafts::DeleteDraft($draft_id, get_uid(false), 3); } header("Location: " . getFriendlyURL("blog", $thread) . "?pagefrom=" . intval($_POST['pagefrom']) . '&openlevel=' . $reply . "&ord=" . $_GET["ord"]); } } } if ($error_flag) {
/** * Редактировать статью. * * @param char $title название статьи * @param char $short превью статьи * @param char $msg текст статьи * @param char $sign подпись * @param char $f_name имя файла с логотипом * @param char $link ссылка на ресурс * @param integer $msgid идентификатор стаьи * * @return char сообщение об ошибке */ public function Edit($title, $short, $msg, $sign, $file, $link, $msgid) { global $DB; validate_code_style($msg); if ($file->tmp_name) { $file->max_size = 1048576; $file->proportional = 1; $file->max_image_size = array('width' => self::MAX_IMAGE_WIDTH, 'height' => self::MAX_IMAGE_HEIGHT, 'less' => 1); $file->resize = 1; $file->proportional = 1; $file->topfill = 1; $file->server_root = 1; $f_name = $file->MoveUploadedFile('about/articles/'); if (!isNulArray($file->error)) { $alert[3] = 'Файл не удовлетворяет условиям загрузки'; $error_flag = 1; } if (!$error_flag) { $sql = "UPDATE articles SET title = '{$title}', short= '{$short}', msgtext='{$msg}', sign='{$sign}', logo='{$f_name}', link='{$link}', modified=now() WHERE (id=?i)"; } } else { $sql = "UPDATE articles SET title = '{$title}', short = '{$short}', msgtext='{$msg}', sign='{$sign}', link='{$link}', modified=now() WHERE (id=?i)"; } $DB->query($sql, $msgid); return array($alert, $DB->error); }
/** * Подгрузка аттачей. * * @param array $attach массив с элементами типа CFile * @param array $max_image_size массив с максимальными размерами картинки (см. CFile). Один для всех элементов attach * @param string $login логин юзера, которому загрузить картинку. По умолчанию - юзер из $_SESSION['login'] * * @return array массив ($files, $alert, $error_flag) */ public function UploadFiles($attach, $max_image_size, $login = '') { $alert = null; if ($login == '') { $login = $_SESSION['login']; } if ($login == '') { $login = '******'; } if ($attach) { foreach ($attach as $file) { $file->max_size = self::MAX_FILE_SIZE; $file->proportional = 1; $f_name = $file->MoveUploadedFile($login . '/upload'); $f_id = $file->id; $ext = $file->getext(); if (in_array($ext, $GLOBALS['graf_array'])) { $is_image = true; } else { $is_image = false; } $p_name = ''; $p_id = ''; if (!isNulArray($file->error)) { $error_flag = 1; $alert = 'Один или несколько файлов не удовлетворяют условиям загрузки.'; break; } else { if ($is_image && $ext != 'swf' && $ext != 'flv') { if (!$file->image_size['width'] || !$file->image_size['height']) { $error_flag = 1; $alert = 'Невозможно уменьшить картинку'; break; } if (!$error_flag && ($file->image_size['width'] > $max_image_size['width'] || $file->image_size['height'] > $max_image_size['height'])) { if (!$file->img_to_small('sm_' . $f_name, $max_image_size)) { $error_flag = 1; $alert = 'Невозможно уменьшить картинку.'; break; } else { $tn = 2; $p_name = "sm_{$f_name}"; $p_id = $file->id; } } else { $tn = 1; } } elseif ($ext == 'flv') { $tn = 2; } else { $tn = 0; } } $files['f_id'][] = $f_id; $files['f_name'][] = $f_name; $files['p_name'][] = $p_name; $files['p_id'][] = $p_id; $files['tn'][] = $tn; } } return array($files, $alert, $error_flag); }