public function saveFileAction()
 {
     //die("1ssss");
     if (!($img = $_FILES['Filedata'])) {
         print json_encode(array('success' => false, 'text' => 'Не получены данные', 'debug' => $_FILES['Filedata']));
         return false;
     }
     if (front::$_req['type'] == 'img') {
         list($width, $height, $type, $attr) = getimagesize($img['tmp_name']);
         $ext = array('gif', 'jpeg', 'png');
         $ext_format = array('gif' => 1, 'jpeg' => 2, 'png' => 3);
         if ($type < 1 || $type > 3) {
             //   print(json_encode(array ('success' => false, 'text'=>"Формат не поддерживается", 'debug' => $_FILES['Filedata'])));
             //  return false;
         }
         if (front::$_req['width'] > 0 && $width > front::$_req['width'] || front::$_req['height'] > 0 && $height > front::$_req['height']) {
             print json_encode(array('success' => false, 'text' => 'Слишком большое разрешение', 'debug' => $_FILES['Filedata']));
             return false;
         }
     }
     $b_file = new CFile($_FILES['Filedata']);
     $b_file->max_size = 1048576;
     $b_file->server_root = 1;
     $f_name = $b_file->MoveUploadedFile('temp/');
     echo json_encode(array('success' => true, 'id' => $f_name, 'path' => WDCPREFIX . '/temp/' . $f_name, 'name' => $_FILES['Filedata']['name']));
 }
 function saveFileAction()
 {
     if (!($img = $_FILES['Filedata'])) {
         print json_encode(array('success' => false, 'text' => "Не получены данные", 'debug' => $_FILES['Filedata']));
         return false;
     }
     if (front::$_req["type"] == "img") {
         list($width, $height, $type, $attr) = getimagesize($img['tmp_name']);
         $ext = array('gif', 'jpeg', 'png');
         $ext_format = array('gif' => 1, 'jpeg' => 2, 'png' => 3);
         if ($type < 1 || $type > 3) {
             print json_encode(array('success' => false, 'text' => "Формат не поддерживается", 'debug' => $_FILES['Filedata']));
             return false;
         }
         if (front::$_req["width"] > 0 && $width > front::$_req["width"] || front::$_req["height"] > 0 && $height > front::$_req["height"]) {
             print json_encode(array('success' => false, 'text' => "Слишком большое разрешение", 'debug' => $_FILES['Filedata']));
             return false;
         }
     }
     $b_file = new CFile($_FILES['Filedata']);
     $b_file->max_size = 1048576;
     $b_file->server_root = 1;
     $f_name = $b_file->MoveUploadedFile("temp/");
     echo json_encode(array("success" => true, "id" => $f_name, "path" => WDCPREFIX . "/temp/" . $f_name));
 }
 function saveFileAction()
 {
     if (!($img = $_FILES['Filedata'])) {
         print json_encode(array('success' => false, 'text' => "Не получены данные", 'debug' => $_FILES['Filedata']));
         return false;
     }
     if (front::$_req["type"] == "img") {
         list($width, $height, $type, $attr) = getimagesize($img['tmp_name']);
         $ext = array('gif', 'jpeg', 'png');
         $ext_format = array('gif' => 1, 'jpeg' => 2, 'png' => 3);
         if ($type < 1 || $type > 3) {
             print json_encode(array('success' => false, 'text' => "Формат не поддерживается", 'debug' => $_FILES['Filedata']));
             return false;
         }
         if (front::$_req["width"] > 0 && $width > front::$_req["width"] || front::$_req["height"] > 0 && $height > front::$_req["height"]) {
             print json_encode(array('success' => false, 'text' => "Слишком большое разрешение", 'debug' => $_FILES['Filedata']));
             return false;
         }
     }
     $b_file = new CFile($_FILES['Filedata']);
     $b_file->max_size = 1048576;
     $b_file->server_root = 1;
     $f_name = $b_file->MoveUploadedFile("temp/");
     echo json_encode(array("success" => true, "id" => $f_name, "path" => WDCPREFIX . "/temp/" . $f_name));
 }
Example #4
0
 if (trim($msgtext) == '') {
     $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] = 'Необходимо загрузить файл.';
Example #5
0
     }
     $link = WDCPREFIX . '/' . $dir . (!$prevname ? $pictname : $prevname);
     $js_callback_func = "parent.addIMGLogo('{$link}', '{$img->id}')";
     $js_callback_err_func = "parent.UploadLogoFileError('{$err}')";
     break;
 case 'upload':
     if (is_array($_FILES['upload_file'])) {
         $img = new CFile($_FILES['upload_file']);
         $img->table = 'file_wizard';
         $img->disable_animate = true;
         if ($img->size > 0) {
             $dir = 'wizard/';
             $img->max_size = 5242880;
             $img->proportional = 1;
             $img->server_root = 1;
             $pictname = $img->MoveUploadedFile($dir);
             $id_upload = $img->id;
             if (!isNulArray($img->error)) {
                 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') {
Example #6
0
 /**
  * Сохраняет файл с резюме
  * @param    integer   $fid           uid фрилансера
  * @param    CFile     $resume        объект CFile с данными о файле с резюме. Если резюме уже существует, то оно будет перезаписано
  * @param    boolean   $del_resume    удалить резюме? В случае удаления новое резюме загужено не будет, в независимости от переменной $resume
  * @param    integer   $file_error    1 - если произошла ошибка при загрузке файла
  * @return   string                   возможная ошибка
  */
 function UpdateInform($fid, $resume, $del_resume, &$file_error)
 {
     // если юзер меняет файл резюме пока предыдущий еще не отмодерирован - будет история изменений
     $aChange = $GLOBALS['DB']->row("SELECT id, old_val, new_val FROM users_change WHERE user_id = ?i AND ucolumn = 'resume_file'", $fid);
     $aDelFile = array();
     // файлы которые нужно будет удалять сразу
     while (strlen($this->blocks) < $GLOBALS['blockssize']) {
         $this->blocks .= '1';
     }
     $dir = get_login($fid);
     $err = '';
     $old = $this->GetField($fid, $err, "resume_file");
     $error .= $err;
     if ($del_resume) {
         $this->resume_file = '';
     } elseif ($resume->name) {
         $resume->max_size = 5242880;
         $this->resume_file = $resume->MoveUploadedFile($dir . "/resume");
         $error .= $resume->StrError('<br />');
         if ($error) {
             $file_error = 1;
         }
     }
     if (!$error) {
         $error .= $this->Update($fid, $res);
         // определяемся какие файлы нужно удалить
         if ($del_resume == 1) {
             // удаляем файл резюме
             if ($aChange) {
                 // если хранили версии файла резюме на случай возврата - то грохаем обе
                 if ($aChange['old_val']) {
                     $aDelFile[] = $aChange['old_val'];
                 }
                 $aDelFile[] = $aChange['new_val'];
             } else {
                 // иначе просто грохаем файл резюме
                 $aDelFile[] = $old;
             }
         } elseif ($resume->name) {
             // меняем файл резюме
             if ($aChange && $aChange['new_val']) {
                 // грохаем только промежуточную версию, если была
                 $aDelFile[] = $aChange['new_val'];
             }
         }
     }
     // удаление не нужных файлов (если нет ошибок при сохранении разумеется)
     if ($aDelFile && !$error) {
         foreach ($aDelFile as $file) {
             $resume->Delete(0, "users/" . substr($dir, 0, 2) . "/" . $dir . "/resume/", $file);
         }
     }
     return $error;
 }
Example #7
0
 /**
  * Создает csv файл для AdWords
  * 
  * @param   $filename   string  полный путь к файлу куда webdav должен сохранить получившийся csv
  * @return  boolean  успех
  */
 function adWords($filename)
 {
     global $DB;
     $profs = array();
     $groups = array();
     $rows = $DB->rows("SELECT * FROM professions");
     foreach ($rows as $row) {
         $profs[$row['id']] = $row;
     }
     $rows = $DB->rows("SELECT * FROM prof_group");
     foreach ($rows as $row) {
         $groups[$row['id']] = $row;
     }
     $sql = "\n            SELECT\n                p.id, e.compname, country.country_name, city.city_name,\n                date_trunc('seconds', p.create_date) c_date, p.name, p.descr, p.cost, p.currency, p.priceby,\n                array_agg(pts.category_id) cats, array_agg(pts.subcategory_id) subcats\n            FROM\n                projects p\n            INNER JOIN\n                employer e ON e.uid = p.user_id AND e.is_banned = B'0'\n            LEFT JOIN\n                country ON country.id = p.country\n            LEFT JOIN\n                city ON city.id = p.city\n            LEFT JOIN\n                project_to_spec pts ON pts.project_id = p.id\n            LEFT JOIN\n                projects_blocked pb ON pb.project_id = p.id\n            WHERE\n                /*( p.moderator_status <> 0 OR p.moderator_status IS NULL ) AND*/ \n                pb.project_id IS NULL \n                AND p.post_date > DATE_TRUNC('day', now() - interval '2 weeks')\n            GROUP BY\n                p.id, e.compname, country.country_name, city.city_name, c_date, p.name, p.descr, p.cost, p.currency, p.priceby\n            ORDER BY\n                id DESC\n        ";
     $tmpfile = "/var/tmp/adwords.csv";
     $fp = fopen($tmpfile, "a");
     $res = $DB->query($sql);
     $c = 0;
     while ($row = pg_fetch_assoc($res)) {
         $data = array();
         // ссылка
         $data['url'] = $GLOBALS['host'] . '/projects/' . $row['id'] . '/' . translit(strtolower(htmlspecialchars_decode($row['name'], ENT_QUOTES))) . '.html';
         // цена
         if (!empty($row['cost'])) {
             switch ($row['currency']) {
                 case 0:
                     $cost = "{$row['cost']}\$";
                     break;
                 case 1:
                     $cost = "€{$row['cost']}";
                     break;
                 case 2:
                     $cost = "{$row['cost']} руб.";
                     break;
                 case 4:
                     $cost = "{$row['cost']} FM";
                     break;
             }
             switch ($row['priceby']) {
                 case 1:
                     $priceby = 'за час';
                     break;
                 case 2:
                     $priceby = 'за день';
                     break;
                 case 3:
                     $priceby = 'за месяц';
                     break;
                 case 4:
                     $priceby = 'за проект';
                     break;
             }
             $data['Wage'] = "{$cost} {$priceby}";
         } else {
             $data['Wage'] = 'По договоренности';
         }
         // специализация (если несколько, берем только первую)
         $cats = $DB->array_to_php($row['cats']);
         $subcats = $DB->array_to_php($row['subcats']);
         $data['Vacancy'] = '';
         $data['Vacancy_title'] = '';
         $data['Category 1'] = '';
         $data['Category 2'] = '';
         if ($cats[0]) {
             $data['Vacancy'] = $groups[(int) $cats[0]]['name_case'];
             $data['Category 1'] = $groups[(int) $cats[0]]['name'];
             $data['Category 1'] = preg_replace("/[\\.\\,\\_\\\\\\/\\*\\;\\:\\?]+/", " ", $data['Category 1']);
             $data['Category 1'] = preg_replace("/\\s{2,}/", " ", $data['Category 1']);
             $data['Category 1'] = preg_replace("/[^-A-Za-zА-Яа-яЁё0-9\\s]+/", "", $data['Category 1']);
         } else {
             $data['Category 1'] = 'Прочее';
         }
         if ($subcats[0]) {
             $data['Vacancy'] = $profs[(int) $subcats[0]]['name_case'];
             $data['Category 2'] = $profs[(int) $subcats[0]]['name'];
             $data['Category 2'] = preg_replace("/[\\.\\,\\_\\\\\\/\\*\\;\\:\\?]+/", " ", $data['Category 2']);
             $data['Category 2'] = preg_replace("/\\s{2,}/", " ", $data['Category 2']);
             $data['Category 2'] = preg_replace("/[^-A-Za-zА-Яа-яЁё0-9\\s]+/", "", $data['Category 2']);
         } else {
             $data['Category 2'] = $data['Category 1'];
         }
         if (empty($data['Vacancy'])) {
             $data['Vacancy'] = 'Прочее';
         } else {
             $data['Vacancy'] = preg_replace("/[\\.\\,\\_\\\\\\/\\*\\;\\:\\?]+/", " ", $data['Vacancy']);
             $data['Vacancy'] = preg_replace("/\\s{2,}/", " ", $data['Vacancy']);
             $data['Vacancy'] = preg_replace("/[^-A-Za-zА-Яа-яЁё0-9\\s]+/", "", $data['Vacancy']);
         }
         $data['Vacancy_title'] = LenghtFormatEx($data['Vacancy'], 30, '');
         $data['vacancy_id'] = $row['id'];
         // сохраняем
         if (!$c) {
             $rowsNames = array_keys($data);
             $dataStr = implode(',', $rowsNames) . "\r\n";
             fwrite($fp, chr(255) . chr(254) . iconv('CP1251', 'UTF-16LE//TRANSLIT', $dataStr));
         }
         $dataStr = implode(',', $data) . "\r\n";
         fwrite($fp, iconv('CP1251', 'UTF-16LE//TRANSLIT', $dataStr));
         $c++;
     }
     fclose($fp);
     $path = pathinfo($filename);
     $oldFile = new CFile();
     $newFile = new CFile(array('tmp_name' => $tmpfile, 'name' => NULL, 'size' => filesize($tmpfile)));
     $oldFile->server_root = 1;
     $newFile->server_root = 1;
     $oldFile->Delete(0, $path['dirname'] . '/', $path['basename']);
     $newFile->max_size = 1024 * 1048576;
     $newFile->MoveUploadedFile($path['dirname'] . '/');
     $newFile->Rename($filename);
     unlink($tmpfile);
     return true;
 }
Example #8
0
 if (trim($msgtext) == '') {
     $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] = 'Необходимо загрузить файл.';
Example #9
0
}
if (empty($_SESSION['masssending']['files'])) {
    $_SESSION['masssending']['files'] = array();
}
if (count($_SESSION['masssending']['files']) >= masssending::MAX_FILES) {
    $error = 'Максимальное кол-во прикрепленных файлов - ' . masssending::MAX_FILES;
} else {
    if ($_SESSION['masssending_total_filesize'] + $_FILES['attach']['size'] > masssending::MAX_FILE_SIZE) {
        $error = 'Максимальный объем прикрепленных файлов - ' . masssending::MAX_FILE_SIZE / (1024 * 1024) . ' Mб';
    } else {
        if ($uid = get_uid(false)) {
            $login = get_login($uid);
            $file = new CFile($_FILES['attach']);
            $file->table = 'file';
            $file->max_size = masssending::MAX_FILE_SIZE;
            $filename = $file->MoveUploadedFile("{$login}/contacts");
            $filetype = $file->getext();
            $error = $file->error;
        } else {
            $error = 'Вы не авторизованы';
        }
        if (!$file->id && !$error) {
            $error = 'Ошибка при загрузке файла. Пожалуйста, попробуйте еще раз.';
        }
        $masssending->AddFile($file->id, session_id());
    }
}
if ($error || ($error = $masssending->error)) {
    echo "\n\t\t-- IBox --\n\t\t<uploaded>\n\t\t\t<nothing>opera</nothing>\n\t\t\t<status>error</status>\n\t\t\t<message>{$error}</message>\n\t\t</uploaded>\n\t\t-- IBox --\n\t";
    exit(1);
}
Example #10
0
 /**
  * Перемещает загруженный файл изображения на dav сервер если высота файла менее 30 px
  * @param $id           - ключ массива информации о файле в $_FILES
  * @param &$err         - текстовое сообщение об ошибке    
  * @return string       - путь к файлу от корня dav сервера без WDCSERVER или пустая строка
  * */
 private function _moveUploadedFile($id, &$err)
 {
     if (count($_FILES[$id])) {
         $data = $_FILES[$id];
         $name = strtolower($data["name"]);
         $mime = $data["type"];
         if (strpos($mime, "png") || strpos($mime, "jpg") || strpos($mime, "gif") || strpos($mime, "jpeg")) {
             $sz = getimagesize($data["tmp_name"]);
             if ($sz[1] > 30) {
                 $err = "Размер файла превышает 30 пикселей";
                 return '';
             }
             $cfile = new CFile($data);
             $name = $cfile->MoveUploadedFile("images");
             return "/" . $cfile->path . $name;
         } else {
             $err = "Недопустимый тип файла";
             return '';
         }
     }
 }
 /**
  * Создание архива документов 
  * по последней задаче
  * 
  * Рекомендуется запускать 
  * в кроне с интервалом 1-2 минуты
  * 
  * @return boolean
  * @throws Exception
  */
 public function generateArchive()
 {
     //Получаем последнюю задачу на создания архива
     $last = $this->db()->row("\n            SELECT \n                rda.*,\n                u.email\n            FROM " . self::$_TABLE_ARCHIVE . " AS rda\n            LEFT JOIN users AS u ON u.uid = rda.uid\n            WHERE \n                rda.status IN(0,-1) \n                AND rda.try_count < ?i\n            ORDER BY rda.id DESC, rda.status DESC\n            LIMIT 1\n        ", self::TRY_COUNT);
     if (!$last) {
         return false;
     }
     $archObj = new ReservesArchiveItemModel($last);
     //Ставим статус в работе
     $this->updateArchive($archObj->id, array('status' => self::STATUS_INPROGRESS));
     try {
         //Получаем файлы документов
         require_once ABS_PATH . '/classes/reserves/ReservesTServiceOrderModel.php';
         $bs_ids = $archObj->getFields();
         $files = CFile::selectFilesBySrc(ReservesTServiceOrderModel::$_TABLE_RESERVES_FILES, $bs_ids, NULL, $this->db()->parse('doc_type IN(?l)', $this->doc_req));
         if (!$files) {
             throw new Exception('Нет файлов документов');
         }
         $_archive_dir = uniqid();
         $_archive_path = self::TMP_PATH . $_archive_dir . DIRECTORY_SEPARATOR;
         $_dav_temp_path = self::DAV_TMP_PATH . $_archive_dir . DIRECTORY_SEPARATOR;
         $filelist = array();
         $cfile = new CFile();
         if (!$cfile->MakeDir(trim($_dav_temp_path, '/'))) {
             throw new Exception('Не удалось создать временную директорию в хранилище');
         }
         //Формируем массив файлов для архива
         foreach ($files as $file) {
             $cfile->name = $file['fname'];
             $cfile->path = $file['path'];
             $info = new SplFileInfo($file['fname']);
             $_ext = $info->getExtension();
             $name = $info->getBasename(".{$_ext}");
             //Создаем временную директорию для файлов на локальной файловой системе
             $_local_tmp_path = "{$_archive_path}{$file['src_id']}/";
             if (!file_exists($_local_tmp_path)) {
                 if (!mkdir($_local_tmp_path, 0777, true)) {
                     throw new Exception("Нет прав на создание: {$_local_tmp_path}");
                 }
             }
             //Сколько копий документа сделать в зависимости от его типа
             $doc_cnt = isset($this->doc_type_cnt[$file['doc_type']]) && $this->doc_type_cnt[$file['doc_type']] > 1 ? $this->doc_type_cnt[$file['doc_type']] : 1;
             $_prefix = sprintf('%07d-', $file['src_id']);
             while ($doc_cnt > 0) {
                 $_suffix = $doc_cnt > 1 ? "-{$doc_cnt}" : '';
                 $_dav_tmp_filename = "{$_dav_temp_path}{$name}{$_suffix}.{$_ext}";
                 if (!$cfile->copyFileTo($_dav_tmp_filename)) {
                     throw new Exception("Не удалось скопировать: {$_dav_tmp_filename}");
                 }
                 $_tmp_name = empty($file['original_name']) ? $name : $file['original_name'];
                 $_local_tmp_filename = "{$_local_tmp_path}{$_prefix}{$_tmp_name}{$_suffix}.{$_ext}";
                 //Кодировка имен файлов для Windows
                 $_local_tmp_filename = iconv('WINDOWS-1251', 'CP866', $_local_tmp_filename);
                 //$_local_tmp_filename = iconv('WINDOWS-1251', 'UTF-8', $_local_tmp_filename);
                 $filelist[$_dav_tmp_filename] = $_local_tmp_filename;
                 //Перемещаем нужные документы из хранища во временную папку
                 if (!$cfile->copyToLocalPathFromDav($_dav_tmp_filename, $_local_tmp_filename)) {
                     throw new Exception("Не удалось переместить файл из хранища {$_dav_tmp_filename} \n                                             в локальную файловую систему {$_local_tmp_filename}");
                 }
                 $doc_cnt--;
             }
         }
         if (empty($filelist)) {
             throw new Exception("Не удалось сформировать массив документов");
         }
         /*
          * @todo: пока используем CFile::copyToLocalPathFromDav
          *             
         //Перемещаем нужные документы из хранища во временную папку
         $cfile = new CFile();
         $res = $cfile->copyFilesToLocalPath($filelist);
         
         if (!$res) {
             throw new Exception("Не удалось переместить файлы из хранища");
         }
         */
         //Создаем архив документов
         $_zip_filename = self::TMP_PATH . "{$_archive_dir}.zip";
         $zip = new ZipArchive();
         if ($zip->open($_zip_filename, ZipArchive::CREATE)) {
             foreach ($filelist as $filename) {
                 $localname = basename($filename);
                 $zip->addFile($filename, $localname);
             }
             $zip->close();
         }
         if (!file_exists($_zip_filename)) {
             throw new Exception("Не удалось создать архив.");
         }
         //Загружаем архив документов
         $cfile = new CFile(array('tmp_name' => $_zip_filename, 'size' => filesize($_zip_filename), 'name' => basename($_zip_filename)), self::$_TABLE_FILE);
         $cfile->server_root = true;
         $cfile->original_name = $archObj->getName();
         $cfile->src_id = $archObj->id;
         $cfile->max_size = 104857600;
         //100Mb
         $cfile->MoveUploadedFile(self::DAV_PATH);
         if (!$cfile->id) {
             $_error = is_array($cfile->error) ? implode(', ', $cfile->error) : $cfile->error;
             throw new Exception("Не удалось загрузить архив в хранилище: {$_error}");
         }
         $this->updateArchive($archObj->id, array('file_id' => $cfile->id, 'try_count' => $archObj->try_count + 1, 'status' => self::STATUS_SUCCESS));
         //@todo: send mail here!
         //Удаляем
         $cfile->deleteFromTempDir($_dav_temp_path);
         delete_files($_archive_path, true, 1);
         unlink($_zip_filename);
         //------------------------------------------------------------------
         $this->addArchiveToLetters($bs_ids, $cfile);
     } catch (Exception $e) {
         $this->updateArchive($archObj->id, array('status' => self::STATUS_ERROR, 'try_count' => $archObj->try_count + 1, 'techmessage' => $e->getMessage()));
         return false;
     }
     return true;
 }
Example #12
0
 /**
  * Редактирование работы в портфолио.
  *
  * @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;
 }
Example #13
0
 if (!$commune_id) {
     $commune_id = __paramInit('int', 'communeid', 'communeid');
 }
 if (!$commune_id) {
     $commune_id = __paramInit('int', 'commune_id', 'commune_id');
 }
 if (!intval($commune_id)) {
     $comm_info = commune::getCommuneInfoByMsgID($top_id);
     $commune_id = $comm_info['commune_id'];
 }
 $commune_member = commune::GetUserCommuneRel($commune_id, $uid);
 if ($permissions > 0 || $commune_member['is_accepted'] || $commune_member['is_author']) {
     $info = getimagesize($_FILES['wysiwyg_uploadimage']['tmp_name']);
     if ($info['mime'] && strpos($info['mime'], 'shockwave-flash') === false) {
         $cfile = new CFile($_FILES['wysiwyg_uploadimage'], 'file_commune');
         $fname = $cfile->MoveUploadedFile($_SESSION['login'] . '/upload');
         if ($cfile->image_size['width'] > commune::IMAGE_MAX_WIDTH || $cfile->image_size['height'] > commune::IMAGE_MAX_HEIGHT) {
             $cfile->Delete($cfile->id);
             echo 'status=fileTooBig&msg=Размер изображения превышает максимально допустимый: ' . commune::IMAGE_MAX_WIDTH . ' x ' . commune::IMAGE_MAX_HEIGHT;
             exit;
         }
         if ($fname) {
             //добавить данные о файле
             commune::addWysiwygFile($cfile);
             //запомнить идентификатор временного файла
             $_SESSION['wysiwyg_inline_files'][$cfile->id] = $cfile->id;
             $link = WDCPREFIX . '/users/' . substr($_SESSION['login'], 0, 2) . '/' . $_SESSION['login'] . '/upload/' . $fname;
             $imgWidth = $cfile->image_size['width'];
             $imgHeight = $cfile->image_size['height'];
             echo "status=uploadSuccess&url={$link}&width={$imgWidth}&height={$imgHeight}";
         } else {
Example #14
0
 $error = false;
 $error_add_file = false;
 if ($request['is_post']) {
     // загрузка файлов, сначала грузим файлы
     if ($_FILES['attach']) {
         $attach = $_FILES['attach'];
         $files = array();
         if (is_array($attach) && !empty($attach['name'])) {
             foreach ($attach['name'] as $key => $v) {
                 if (!$attach['name'][$key]) {
                     continue;
                 }
                 $tmp = 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]));
                 $tmp->max_size = 10485760;
                 $tmp->server_root = true;
                 $tmp->MoveUploadedFile('/docs/');
                 $files_attache[] = $tmp;
                 if ($tmp->error && !$tmp->id) {
                     $error_add_file = $tmp->error;
                     $error = true;
                 }
             }
         }
     }
     if (count($_POST['attach_files_id']) > 0) {
         foreach ($_POST['attach_files_id'] as $key => $value) {
             $tmp = new CFile();
             $tmp->max_size = 10485760;
             $tmp->server_root = true;
             $tmp->GetInfoById($value);
             $files_attache[] = $tmp;
Example #15
0
 $cfile->max_size = $_config['max_file_size'];
 $cfile->server_root = $_config['server_root'];
 $cfile->max_image_size = $_config['max_image_size'];
 $cfile->resize = $_config['resize'];
 $cfile->proportional = $_config['proportional'];
 $cfile->crop = $_config['crop'];
 $cfile->topfill = $_config['topfill'];
 $cfile->allowed_ext = $_config['allowed_ext'];
 $dir = sprintf($_config['dir'], $user_obj->login);
 $cfile->_getImageSize($cfile->tmp_name);
 if ($cfile->image_size && in_array($cfile->image_size['type'], $_config['image_types'])) {
     if ($_config['minImageHeight'] && $cfile->image_size['height'] < $_config['minImageHeight'] || $_config['minImageWidth'] && $cfile->image_size['width'] < $_config['minImageWidth']) {
         $result['error'] = sprintf(STR_FTOSMAL, $_config['minImageWidth'], $_config['minImageHeight']);
         //sprintf('Изображение слишком маленькое. Минимальные размеры %d на %d точек.',$_config['minImageWidth'],$_config['minImageHeight']);
     } else {
         $filename = $cfile->MoveUploadedFile($dir);
         $error = $cfile->error;
         $error = is_array($error) ? $error : array($error);
         $cnt = count($error);
         if (!$filename || $cnt > 0) {
             $result['error'] = STR_FERR . ' ' . implode(' ', $error);
             //'Ошибка загрузки файла. '
         } else {
             $fileinfo = $uploader->createFile($cfile);
             if (count($_config['params'])) {
                 $err = $cfile->updateFileParams($_config['params']);
             }
             if (count($_config['thumbs'])) {
                 foreach ($_config['thumbs'] as $thumb) {
                     $thumb_cfile = $cfile->resizeImage($cfile->path . $thumb['prefix'] . $cfile->name, $thumb['width'], $thumb['height'], $thumb['option'], true);
                     if (!$thumb_cfile) {
Example #16
0
 /**
  * Сохраняет загруженный файл.
  *
  * @return bool
  */
 public function saveUploadedFile($input = 'reestr3', $allowed_ext = array())
 {
     if (!isset($_FILES[$input])) {
         return false;
     }
     $cf = new CFile($_FILES[$input], $this->TABLE);
     if ($cf) {
         $cf->allowed_ext = is_array($allowed_ext) ? $allowed_ext : array($allowed_ext);
         $cf->server_root = true;
         $cf->max_size = 104857600;
         //100Mb
         if ($filename = $cf->MoveUploadedFile($this->path)) {
             return $filename;
         }
     }
     return false;
 }
 if (is_array($_FILES['attachedfiles_file']) && !$_FILES['attachedfiles_file']['error']) {
     $dir = wizard::FILE_DIR;
     $cFile = new CFile($_FILES['attachedfiles_file']);
     $cFile->table = 'file';
     switch ($type) {
         case 'wizard':
             $max_files = wizard::MAX_FILE_COUNT;
             $max_files_size = wizard::MAX_FILE_SIZE;
             break;
         default:
             $file['error'] = 'Ошибка загрузки файла';
             break;
     }
     $cFile->max_size = $max_files_size;
     $cFile->server_root = 1;
     $cFile->MoveUploadedFile($dir);
     if ($cFile->id) {
         $attachedfiles = new attachedfiles($sess);
         $files_info = $attachedfiles->calcFiles();
         $files_count = $files_info['count'];
         $files_size = $files_info['size'];
         if ($files_count + 1 > $max_files) {
             $file['error'] = "Максимальное количество файлов: {$max_files}";
         }
         if ($files_size + $cFile->size > $max_files_size) {
             $file['error'] = 'Максимальный объем файлов: ' . ConvertBtoMB($max_files_size);
         }
         if (in_array($cFile->getext(), $GLOBALS['disallowed_array'])) {
             $file['error'] = 'Недопустимый формат файла';
         }
         if ($file['error']) {
Example #18
0
 $is_main = isset($_FILES['main_foto']);
 $farr = isset($_FILES['main_foto']) ? $_FILES['main_foto'] : (isset($_FILES['attach']) ? $_FILES['attach'] : null);
 $file = new CFile($farr);
 $file->allowed_ext = array('gif', 'jpg', 'jpeg', 'png');
 $file->resize = 1;
 $file->proportional = 1;
 $file->server_root = 1;
 if (isset($_FILES['main_foto'])) {
     $file->max_image_size = array('width' => 800, 'height' => 1000, 'less' => 1);
 } elseif (isset($_FILES['attach'])) {
     $file->max_image_size = array('width' => 720, 'height' => 1000, 'less' => 1);
 }
 if ($file->name && $file->error) {
     $alert = $file->error[0];
 } else {
     $file->MoveUploadedFile('about/interview/');
     if (!isNulArray($file->error)) {
         $alert = 'Файл не удовлетворяет условиям загрузки';
     }
 }
 $fileid = $file->id;
 $filepath = $file->path;
 $filename = $file->name;
 if (isset($_FILES['main_foto']) && !isset($alert)) {
     $resf = $file->img_to_small('sm_' . $file->name, array('width' => 180, 'height' => 180), true);
     if (!$resf) {
         $alert = $file->error[0];
     }
 }
 if (isset($alert)) {
     $result['errorMessage'] = iconv('CP1251', 'UTF-8', $alert);
Example #19
0
//die ("DUMP: " . var_export($_FILES, true));
if (isset($_POST['action']) && $_POST['action'] == 'add_pic' && is_array($_FILES['ps_attach'])) {
    $prj_id = isset($_POST['pid']) ? intval($_POST['pid']) : 0;
    $img = new CFile($_FILES['ps_attach']);
    if ($img->size > 0) {
        $dir = get_login($uid);
        // чтобы админ мог редактировать предложения по проектам
        if ($is_adm) {
            require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
            $user = new users();
            $user->GetUserByUID($uid);
            $dir = $user->login;
        }
        $img->max_size = 2097152;
        $img->proportional = 1;
        $pictname = $img->MoveUploadedFile($dir . "/upload");
        $mid = $img->id;
        if (!isNulArray($img->error)) {
            if ($img->size > $img->max_size) {
                $err = 'Недопустимый размер файла';
            }
            $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") {
                    /**
                     * Делаем превью.
Example #20
0
 /**
  * Загрузить файл на сервер.
  * 
  * @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;
 }
 **/
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/stdf.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/CFile.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/dav_file_upload.php';
if (!hasPermissions('admin')) {
    header('Location: /404.php');
    exit;
}
$srcdir = $_SERVER['DOCUMENT_ROOT'] . '/about';
$ls = scandir($srcdir);
foreach ($ls as $item) {
    if ($item != '.' && $item !== '..' && !is_dir("{$srcdir}/{$item}")) {
        $filedata = array('name' => $item, 'tmp_name' => "{$srcdir}/{$item}", 'size' => filesize("{$srcdir}/{$item}"));
        $srcfile = new CFile($filedata);
        $srcfile->unlinkOff = true;
        $path = 'about/documents';
        $destfile = new CFile("{$path}/{$item}", dav_file_upload::FILE_TABLE);
        $rename_name = '';
        if ($destfile->id) {
            $ext = $destfile->getext($destfile->name);
            $tmp = $destfile->secure_tmpname($path . '/', '.' . $ext);
            $rename_name = substr_replace($tmp, '', 0, strlen($path) + 1);
            $destfile->Rename("{$path}/{$rename_name}");
        }
        $srcfile->server_root = 1;
        $srcfile->max_size = dav_file_upload::MAX_FILE_SIZE;
        $r = $srcfile->MoveUploadedFile($path . '/', true, $item);
        dav_file_upload::addRecord($srcfile->id, $srcfile->name, $rename_name);
        echo "Copy {$srcdir}/{$item} " . WDCPREFIX . '/' . $path . '/' . $item . '<br><br>';
    }
}
Example #22
0
 /**
  * Перемещает загруженный файл изображения на dav сервер если высота файла менее 30 px.
  *
  * @param $id           - ключ массива информации о файле в $_FILES
  * @param &$err         - текстовое сообщение об ошибке    
  *
  * @return string - путь к файлу от корня dav сервера без WDCSERVER или пустая строка
  * */
 private function _moveUploadedFile($id, &$err)
 {
     if (count($_FILES[$id])) {
         $data = $_FILES[$id];
         $name = strtolower($data['name']);
         $mime = $data['type'];
         if (strpos($mime, 'png') || strpos($mime, 'jpg') || strpos($mime, 'gif') || strpos($mime, 'jpeg')) {
             $sz = getimagesize($data['tmp_name']);
             if ($sz[1] > 30) {
                 $err = 'Размер файла превышает 30 пикселей';
                 return '';
             }
             $cfile = new CFile($data);
             $name = $cfile->MoveUploadedFile('images');
             return '/' . $cfile->path . $name;
         } else {
             $err = 'Недопустимый тип файла';
             return '';
         }
     }
 }
 /**
  * Обновить файл счет-фактуры.
  *
  * @param type $invoice_id
  * @param type $file
  */
 public function updateFactura($invoice_id, $uploaded_file)
 {
     if (!$uploaded_file || !is_array($uploaded_file) || !$uploaded_file['size']) {
         return false;
     }
     $data = $this->getInvoice($invoice_id);
     if (!$data) {
         return false;
     }
     $old_file = new CFile();
     $old_file->table = self::$_TABLE_FILE;
     $old_file->GetInfoById($data['file_factura_id']);
     $file = new CFile($uploaded_file);
     $file->table = self::$_TABLE_FILE;
     $file->src_id = $old_file->src_id;
     $file->original_name = $old_file->original_name;
     $file->server_root = 1;
     $file->MoveUploadedFile($old_file->path);
     $old_file->Delete($data['file_factura_id']);
     $this->update($invoice_id, array('file_factura_id' => $file->id));
     return true;
 }
Example #24
0
 /**
  * Загружает файл списка и возвращает его имя
  * 
  * @return type
  */
 public function uploadExtra($old_file = '')
 {
     $cf = new CFile($_FILES['extra_recievers_file'], 'file');
     if ($cf) {
         $cf->server_root = true;
         $cf->max_size = 104857600;
         //100Mb
         if ($filename = $cf->MoveUploadedFile("/mailer/")) {
             return $filename;
         }
     }
     return $old_file;
 }
 /**
  * Сохраняет файл в базу и постоянную директорию.
  *
  * @param type $filename
  *
  * @return bool
  */
 private function uploadFile($filename)
 {
     $file = array('tmp_name' => $this->temp_file_dir . $filename, 'size' => filesize($this->temp_file_dir . $filename), 'name' => $filename);
     $cf = new CFile($file, $this->TABLE);
     if ($cf) {
         $cf->server_root = true;
         $cf->max_size = 104857600;
         //100Mb
         if ($filename = $cf->MoveUploadedFile($this->path_payout, true, $filename)) {
             return $filename;
         }
     }
     return false;
 }
Example #26
0
    header_location_exit('/404.php');
}
define('BANNER_PATH', 'banners/newsletter/');
define('MAX_SIZE', 5 * 1024 * 1024);
//5Mb
$action = __paramInit('string', 'action', 'action');
$type = __paramInit('bool', 'type', 'type');
$type_prefix = $type == 1 ? 'emp_' : '';
$settings = new settings();
switch ($action) {
    case 'save':
        $uploaded_file = new CFile($_FILES['file']);
        $uploaded_file->server_root = 1;
        $uploaded_file->max_size = MAX_SIZE;
        $uploaded_file->allowed_ext = array('jpg', 'jpeg', 'gif', 'png');
        $filename = $uploaded_file->MoveUploadedFile(BANNER_PATH);
        if (!count($uploaded_file->error) && $filename) {
            $settings->AddVariable('newsletter', $type_prefix . 'banner_file', WDCPREFIX . '/' . $uploaded_file->path . $uploaded_file->name);
            $settings->AddVariable('newsletter', $type_prefix . 'banner_link', __paramInit('string', null, 'link'));
        }
        header_location_exit('./#' . ($type == 1 ? 'emp' : 'frl'));
        break;
    case 'delete':
        $settings->SetVariable('newsletter', $type_prefix . 'banner_file', null);
        $settings->SetVariable('newsletter', $type_prefix . 'banner_link', null);
        break;
}
$newsletter_banner_file = $settings->GetVariable('newsletter', 'banner_file');
$newsletter_banner_link = $settings->GetVariable('newsletter', 'banner_link');
$newsletter_emp_banner_file = $settings->GetVariable('newsletter', 'emp_banner_file');
$newsletter_emp_banner_link = $settings->GetVariable('newsletter', 'emp_banner_link');
Example #27
0
 /**
  * Добавить новую рассылку
  *
  * @param    string  $subject        тема email
  * @param    string  $message        текст email
  * @param    array   $attaches       прикрепленные файлы
  * @param    string  $contact_ids    идентификаторы получателей
  */
 function AddMail($subject, $message, $attaches, $contact_ids)
 {
     global $DB;
     $files = '';
     $fs = array();
     if ($attaches['file']) {
         $f = new CFile($attaches['file']);
         $f->max_size = 2097152;
         $dir = get_login(get_uid(false));
         $f_name = $f->MoveUploadedFile($dir . "/upload");
         array_push($fs, $f_name);
     }
     for ($i = 1; $i <= 5; $i++) {
         if ($attaches['file_' . $i]) {
             $f = new CFile($attaches['file_' . $i]);
             $f->max_size = 2097152;
             $dir = get_login(get_uid(false));
             $f_name = $f->MoveUploadedFile($dir . "/upload");
             array_push($fs, $f_name);
         }
     }
     if ($fs) {
         foreach ($fs as $v) {
             $files .= $v . ',';
         }
         $files = preg_replace("/,\$/", "", $files);
     }
     $sql = "INSERT INTO contacts_mails(subject,message,attaches,contact_ids,user_id) VALUES(?, ?, ?,? , ?i)";
     $DB->query($sql, pg_escape_string($subject), pg_escape_string(nl2br($message)), $files, $contact_ids, get_uid(false));
 }
Example #28
0
         $file->max_image_size = array('width' => 200, 'height' => 200, 'less' => 0);
         $file->resize = 1;
         $file->proportional = 1;
         $file->prefix_file_name = 'sm_';
         $file->max_size = 102400;
     }
     // если заданы типы графических файлов
     if ($imageTypes) {
         // то файл должен быть графическим
         $file->_getImageSize($file->tmp_name);
         if (!$file->image_size['type'] || !in_array($file->image_size['type'], $imageTypes)) {
             $err = 'Недопустимый формат файла';
         }
     }
     if (!$err) {
         $filename = $file->MoveUploadedFile($sFullDir);
         $fileid = $file->id;
         $err = $file->StrError();
         if (!$err && $type == 'work_prev' && (!in_array($file->getext(), $GLOBALS['graf_array']) || strtolower($file->getext()) == 'swf' || strtolower($file->getext()) == 'flv')) {
             $err = 'Недопустимый тип файла';
         }
         if ($type == 'photo' || $type == 'logo') {
             if (!$err && !$file->img_to_small('sm_' . $filename, array('width' => 50, 'height' => 50))) {
                 $err .= 'Невозможно уменьшить картинку.';
             }
         }
     }
 } elseif (!$err) {
     // логотип проекта
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects.php';
     $tmpPrj = new tmp_project($pkey);
Example #29
0
                    }
                }
            }
            if (!$save) {
                break;
            }
        }
        //}
        if ($save && $count_docs) {
            $sql = "INSERT INTO letters(\n                                            title,\n                                            user_add,\n                                            user_1,\n                                            user_2,\n                                            user_status_2,\n                                            date_add,\n                                            date_change_status,\n                                            is_user_1_company,\n                                            delivery\n                                        ) VALUES (\n                                            ?,\n                                            ?i,\n                                            ?i,\n                                            ?i,\n                                            ?i,\n                                            NOW(),\n                                            NOW(),\n                                            't',\n                                            1\n                                        ) RETURNING id";
            $letter['id'] = $DB->val($sql, $letter['title'], $letter['user_add'], $letter['user_1'], $letter['user_2'], $letter['user_status_2']);
            $pdf->Output($pdf_name, 'F');
            $cfile = new CFile(array('tmp_name' => $pdf_name, 'name' => $pdf_name, 'size' => filesize($pdf_name)));
            $cfile->server_root = 1;
            $cfile->max_size = 5000000;
            $cfile->MoveUploadedFile('letters/');
            $sql = 'UPDATE letters SET file_id = ?i WHERE id = ?i';
            $DB->query($sql, $cfile->id, $letter['id']);
            ++$res['s'];
            echo "{$row['sbr_id']} - OK\n";
        } else {
            $res['e'][] = $row['sbr_id'];
            echo "{$row['sbr_id']} - PDF Convert Error!\n";
        }
    }
}
echo "-- Haven't address -------------------------------------\n";
foreach ($res['a'] as $r) {
    echo $r . "\n";
}
echo "-- PDF Conver Error ------------------------------------\n";
Example #30
0
 /**
  * Слушатель который обрабатывает на серверной стороне поступление файла
  * 
  * @param string $resource  Сессия загрузчика
  * @return boolean
  */
 static function listener($resource)
 {
     $browser = '';
     $version = array();
     browserCompat($browser, $version);
     // Скрипт посылает в той кодировке в которой страница в IE, в остальных браузерах в UTF-8
     if ($browser != 'msie' && ((int) $version[1] != 8 || (int) $version[1] != 10)) {
         $_FILES = self::encodeCharset($_FILES, array('utf-8', 'cp1251'));
     }
     $validate = self::getValidationInfo(self::sgetTypeUpload($resource));
     if ($validate['is_auth'] && !get_uid(false)) {
         return array('success' => false, 'error' => 'Ошибка загрузки файлов');
     }
     if ($validate['is_admin'] && !hasPermissions('adm')) {
         return array('success' => false, 'error' => 'Ошибка загрузки файлов');
     }
     if ($validate['max_files'] == 1 && $validate['is_replace']) {
         // Удаляем старые файлы для замены на новые
         self::sclear($resource);
     }
     $_FILES['qqfile']['name'] = stripslashes(__paramValue('string', $_FILES['qqfile']['name']));
     $CFile = new CFile($_FILES['qqfile']);
     $CFile->table = 'file';
     $CFile->server_root = $validate['server_root'] === true ? true : false;
     $CFile->max_size = $validate['max_file_size'];
     $uploader = new uploader($resource);
     $resourceInfo = $uploader->getCountResource();
     if ($validate['imageOnly'] && strpos($_FILES['qqfile']['type'], 'image') === false) {
         $file['error'] = "Недопустимый формат файла";
     }
     if ($resourceInfo['count'] + 1 > $validate['max_files']) {
         $file['error'] = "Максимальное количество файлов: {$validate['max_files']}";
     }
     if ($resourceInfo['size'] + $CFile->size > $validate['max_file_size'] && $validate['is_total_size']) {
         $file['error'] = "Максимальный объем файлов: " . ConvertBtoMB($validate['max_file_size']);
     }
     if (in_array($CFile->getext(), $GLOBALS['disallowed_array'])) {
         $file['error'] = "Недопустимый формат файла";
     }
     if ($file['error']) {
         $file['success'] = false;
         return $file;
     } else {
         $CFile->MoveUploadedFile($validate['dir']);
         if ($validate['resize'] && ($CFile->image_size['height'] > $validate['imageHeight'] || $CFile->image_size['width'] > $validate['imageWidth'])) {
             $CFile = $CFile->resizeImage($CFile->path . $CFile->name, $validate['imageWidth'], $validate['imageHeight'], 'auto', true);
         }
     }
     $skipEncoding = false;
     if ($CFile->id) {
         // если заданы типы графических файлов
         if ($validate['imageTypes'] && (!$CFile->image_size['type'] || !in_array($CFile->image_size['type'], $validate['imageTypes']))) {
             $file['error'] = "Недопустимый формат файла";
         }
         // если задана максимальная высота
         if ($validate['maxImageHeight'] && $CFile->image_size['height'] > $validate['maxImageHeight']) {
             $file['error'] = "Превышена максимальная высота изображения";
         }
         // если задана максимальная ширина
         if ($validate['maxImageWidth'] && $CFile->imae_size['width'] > $validate['maxImageWidth']) {
             $file['error'] = "Превышена максимальная ширина изображения";
         }
         if ($file['error']) {
             $CFile->Delete($CFile->id);
             $file['success'] = false;
         } else {
             $file = $uploader->createFile($CFile);
             if ($validate['copy_table'] != '') {
                 $cremotefile = self::remoteCopy($CFile->id, $validate['copy_table'], mailer::FILE_DIR);
                 $file['path'] = $cremotefile->path;
                 $file['fname'] = $cremotefile->name;
             }
             $file['success'] = true;
         }
     } else {
         $file['success'] = false;
         $file['error'] = $CFile->error;
         if (is_array($file['error']) && count($file['error']) == 0 && $CFile->size == 0) {
             $file['error'] = "Пустой файл";
             $skipEncoding = true;
         }
     }
     $file['onComplete'] = self::getCallback(self::sgetTypeUpload($resource), $CFile, $_FILES['qqfile']['type']);
     $file['orig_name'] = self::cutNameFile($file['orig_name'], $validate['fname_length']);
     if (!$skipEncoding) {
         $file = self::encodeCharset($file);
     }
     return $file;
 }