CVE-2023-4652 (published 2023-08-31T01:15Z)

Cross-site Scripting (XSS) - Stored in GitHub repository instantsoft/icms2 prior to 2.16.1-git.

CVSS v3 base score: 5.4, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/instantsoft/icms2
commit_details: repo_url: https://github.com/instantsoft/icms2
author: fuzegit
author_date: 2023-08-11 19:02:19+03:00
msg: Fixed upload XSS with wrong extension
repository: repo_url: https://github.com/instantsoft/icms2
repo_name: instantsoft/icms2
description: Self-hosted Site Management System
repo_language: PHP
owner: instantsoft
file_changes: filename: install.php
change_type: ModificationType.MODIFY
diff: @@ -285,7 +285,9 @@ class actionAdminInstall extends cmsAction {
 
         files_clear_directory(cmsConfig::get('upload_path') . $this->installer_upload_path);
 
-        $result = $this->cms_uploader->upload($this->upload_name, $this->upload_exts, 0, $this->installer_upload_path);
+        $result = $this->cms_uploader->setAllowedMime([
+            'application/zip'
+        ])->upload($this->upload_name, $this->upload_exts, 0, $this->installer_upload_path);
 
         if (!$result['success']){
             cmsUser::addSessionMessage($result['error'], 'error');
@@ -293,7 +295,6 @@ class actionAdminInstall extends cmsAction {
         }
 
         return $result['name'];
-
     }
 
 }

programming_language: PHP
filename: uploader.php
change_type: ModificationType.MODIFY
diff: @@ -5,16 +5,20 @@ class cmsUploader {
     private $allow_remote = false;
     private $file_name = '';
     private $user_id = 0;
-    private $site_cfg = array();
+    private $site_cfg = null;
 
-    private $last_error = false;
-    private $upload_errors = array();
+    private $last_error = null;
+    private $upload_errors = [];
 
     private $allowed_mime = false;
     private $allowed_mime_ext = [];
+    private $mime_types = [];
 
-    public function __construct() {
-        $this->upload_errors = array(
+    public function __construct($user_id = null) {
+
+        $this->mime_types = (new cmsConfigs('mimetypes.php'))->getAll();
+
+        $this->upload_errors = [
             UPLOAD_ERR_OK         => LANG_UPLOAD_ERR_OK,
             UPLOAD_ERR_INI_SIZE   => sprintf(LANG_UPLOAD_ERR_INI_SIZE, $this->getMaxUploadSize()),
             UPLOAD_ERR_FORM_SIZE  => LANG_UPLOAD_ERR_FORM_SIZE,
@@ -23,204 +27,251 @@ class cmsUploader {
             UPLOAD_ERR_NO_TMP_DIR => LANG_UPLOAD_ERR_NO_TMP_DIR,
             UPLOAD_ERR_CANT_WRITE => LANG_UPLOAD_ERR_CANT_WRITE,
             UPLOAD_ERR_EXTENSION  => LANG_UPLOAD_ERR_EXTENSION
-        );
-        $this->user_id = cmsUser::getInstance()->id;
+        ];
+
+        $this->user_id  = $user_id ?? cmsUser::getInstance()->id;
         $this->site_cfg = cmsConfig::getInstance();
     }
 
+    /**
+     * Устанавливает разрешённые типы файлов
+     *
+     * @param array $types
+     * @return $this
+     */
     public function setAllowedMime($types) {
 
         $this->allowed_mime = $types;
 
-        $mime_types = (new cmsConfigs('mimetypes.php'))->getAll();
-
         foreach ($this->allowed_mime as $mime) {
-            if(isset($mime_types[$mime])){
-                $this->allowed_mime_ext[] = $mime_types[$mime];
+            if (isset($this->mime_types[$mime])) {
+                $this->allowed_mime_ext[] = $this->mime_types[$mime];
             }
         }
 
         return $this;
     }
 
+    /**
+     * Устанавливает разрешённые типы файлов по их расширению
+     *
+     * @param array|string $allowed_ext
+     * @return $this
+     */
+    private function setAllowedMimeByExt($allowed_ext) {
+
+        // Если установлено ранее, то ничего не делаем
+        if ($this->allowed_mime) {
+            return $this;
+        }
+
+        $this->allowed_mime = [];
+
+        if (!is_array($allowed_ext)) {
+            $allowed_ext = explode(',', (string) $allowed_ext);
+        }
+
+        foreach ($allowed_ext as $aext) {
+
+            $aext = mb_strtolower(trim(trim((string) $aext, '., ')));
+
+            if (empty($aext)) {
+                continue;
+            }
+
+            $mime_key = array_search($aext, $this->mime_types, true);
+
+            if(!$mime_key){
+                continue;
+            }
+
+            $this->allowed_mime[] = $mime_key;
+
+            $this->allowed_mime_ext[] = $aext;
+        }
+
+    }
+
+    /**
+     * Устанавливает имя файла
+     *
+     * @param string $name
+     * @return $this
+     */
     public function setFileName($name) {
-        $this->file_name = mb_substr(trim($name), 0, 64); return $this;
+
+        $this->file_name = mb_substr(trim($name), 0, 64);
+
+        return $this;
     }
 
+    /**
+     * Устанавливает id пользователя
+     *
+     * @param int $id
+     * @return $this
+     */
     public function setUserId($id) {
-        $this->user_id = $id; return $this;
+
+        $this->user_id = $id;
+
+        return $this;
     }
 
+    /**
+     * Возвращает последнюю ошибку
+     *
+     * @return ?string
+     */
     public function getLastError() {
         return $this->last_error;
     }
 
-//============================================================================//
     /**
      * Возвращает строку с максимальным размером загружаемых файлов,
      * установленным в php.ini
+     *
      * @return string
      */
-    public function getMaxUploadSize(){
+    public function getMaxUploadSize() {
 
         // вычисляем по тому, что меньше, т.к. если post_max_size меньше upload_max_filesize,
         // то максимум можно будет загрузить post_max_size
         $max_size = min(files_convert_bytes(@ini_get('upload_max_filesize')), files_convert_bytes(@ini_get('post_max_size')));
 
         return files_format_bytes($max_size);
-
     }
 
-    public function isUploaded($name){
+    /**
+     * Проверяет, загружен ли файл наличием его в $_FILES
+     *
+     * @param string $name Имя в массиве $_FILES
+     * @return boolean
+     */
+    public function isUploaded($name) {
 
-        if (!isset($_FILES[$name])) { return false; }
+        if (!isset($_FILES[$name])) {
+            return false;
+        }
 
         if (empty($_FILES[$name]['size'])) {
 
-            if(isset($_FILES[$name]['error'])){
-                if(isset($this->upload_errors[$_FILES[$name]['error']]) && $this->upload_errors[$_FILES[$name]['error']] !== UPLOAD_ERR_OK){
+            if (isset($_FILES[$name]['error'])) {
+                if (isset($this->upload_errors[$_FILES[$name]['error']]) && $this->upload_errors[$_FILES[$name]['error']] !== UPLOAD_ERR_OK) {
                     $this->last_error = $this->upload_errors[$_FILES[$name]['error']];
                 }
             }
 
             return false;
-
         }
 
         return true;
-
     }
 
-    public function isUploadedXHR($name){
+    /**
+     * Проверяет, загружен ли файл через XHR
+     *
+     * @param string $name Имя в массиве $_GET
+     * @return boolean
+     */
+    public function isUploadedXHR($name) {
         return !empty($_GET['qqfile']);
     }
 
-    public function isUploadedFromLink($name){
+    /**
+     * Проверяет, надо ли загрузить файл по ссылке
+     *
+     * @param string $name Имя в массиве $_POST
+     * @return boolean
+     */
+    public function isUploadedFromLink($name) {
         return $this->allow_remote && !empty($_POST[$name]);
     }
 
+    /**
+     * Разрешает загрузку по ссылке
+     *
+     * @return $this
+     */
     public function enableRemoteUpload() {
-        $this->allow_remote = true; return $this;
-    }
-    public function disableRemoteUpload() {
-        $this->allow_remote = false; return $this;
-    }
-
-    private function getFileName($path, $file_ext, $file_name = false) {
-
-        if(!$file_name){
-            if($this->file_name){
-                $file_name = str_replace('.'.$file_ext, '', files_sanitize_name($this->file_name.'.'.$file_ext));
-            } else {
-                $file_name = substr(md5(microtime(true)), 0, 8);
-            }
-        }
-
-        if (file_exists($path.$file_name.'.'.$file_ext)) {
-            return $this->getFileName($path, $file_ext, $file_name.'_'.md5(microtime(true)));
-        }
 
-        return $file_name.'.'.$file_ext;
+        $this->allow_remote = true;
 
+        return $this;
     }
 
-//============================================================================//
-//============================================================================//
-
     /**
-     * Этот метод устаревший, используйте класс cmsImages
+     * Запрещает загрузку по ссылке
+     *
+     * @return $this
      */
-    public function resizeImage($source_file, $size){
-
-        $dest_dir  = $this->getUploadDestinationDirectory();
-        $dest_ext  = pathinfo($source_file, PATHINFO_EXTENSION);
-        $dest_name = $this->getFileName($dest_dir, $dest_ext);
-
-        $dest_file = $dest_dir . $dest_name;
-
-        if (!isset($size['height'])) { $size['height'] = 0; }
-        if (!isset($size['quality'])) { $size['quality'] = 90; }
-
-        if (img_resize($source_file, $dest_file, $size['width'], $size['height'], $size['is_square'], $size['quality'])) {
-
-            return str_replace($this->site_cfg->upload_path, '', $dest_file);
-
-        }
+    public function disableRemoteUpload() {
 
-        return false;
+        $this->allow_remote = false;
 
+        return $this;
     }
 
-    private function checkExt($ext, $allowed_ext) {
-
-        if($allowed_ext === false){
-            return true;
-        }
-
-        if(empty($ext)){ return false; }
-
-        if(!is_array($allowed_ext)){
-            $allowed_ext = explode(',', (string)$allowed_ext);
-        }
-
-        $allowed = array();
+    /**
+     * Возвращает имя файла с расширением
+     * проверяя наличии одноимённого
+     *
+     * @param string $path Путь к директории хранения файла
+     * @param string $file_ext Расширение файла
+     * @param ?string $file_name Имя файла
+     * @return string
+     */
+    private function getFileName($path, $file_ext, $file_name = null) {
 
-        foreach($allowed_ext as $aext){
-            $aext = mb_strtolower(trim(trim((string)$aext, '., ')));
-            if(empty($aext)){
-                continue;
+        if (!$file_name) {
+            if ($this->file_name) {
+                $file_name = str_replace('.' . $file_ext, '', files_sanitize_name($this->file_name . '.' . $file_ext));
+            } else {
+                $file_name = substr(md5(microtime(true)), 0, 8);
             }
-            $allowed[] = $aext;
         }
 
-        return in_array(mb_strtolower($ext), $allowed, true);
-
-    }
-
-    private function isMimeTypeAllowed($file_path) {
-
-        $finfo = finfo_open(FILEINFO_MIME_TYPE);
-
-        $file_mime = finfo_file($finfo, $file_path);
-
-        if($file_mime === false){ return false; }
-
-        return in_array($file_mime, $this->allowed_mime);
+        if (file_exists($path . $file_name . '.' . $file_ext)) {
+            return $this->getFileName($path, $file_ext, $file_name . '_' . md5(microtime(true)));
+        }
 
+        return $file_name . '.' . $file_ext;
     }
 
-//============================================================================//
-//============================================================================//
-
     /**
      * Загружает файл на сервер
-     * @param string $post_filename Название поля с файлом в массиве $_FILES
+     *
+     * @param string $filename Название поля с файлом
      * @param string $allowed_ext Список допустимых расширений (через запятую)
      * @param string $allowed_size Максимальный размер файла (в байтах)
-     * @param string $destination Папка назначения (внутри пути upload)
+     * @param string $destination Директория назначения (внутри пути upload)
      * @return array
      */
-    public function upload($post_filename, $allowed_ext = false, $allowed_size = 0, $destination = false){
+    public function upload($filename, $allowed_ext = false, $allowed_size = 0, $destination = false) {
 
-        if ($this->isUploadedFromLink($post_filename)){
-            return $this->uploadFromLink($post_filename, $allowed_ext, $allowed_size, $destination);
+        // Если переданы расширения
+        if ($allowed_ext) {
+            $this->setAllowedMimeByExt($allowed_ext);
         }
 
-        if ($this->isUploadedXHR($post_filename)){
-            return $this->uploadXHR($post_filename, $allowed_ext, $allowed_size, $destination);
+        if ($this->isUploadedFromLink($filename)) {
+            return $this->uploadFromLink($filename, $allowed_size, $destination);
         }
 
-        if ($this->isUploaded($post_filename)){
-            return $this->uploadForm($post_filename, $allowed_ext, $allowed_size, $destination);
+        if ($this->isUploadedXHR($filename)) {
+            return $this->uploadXHR($filename, $allowed_size, $destination);
+        }
+
+        if ($this->isUploaded($filename)) {
+            return $this->uploadForm($filename, $allowed_size, $destination);
         }
 
         $last_error = $this->getLastError();
 
-        return array(
+        return [
             'success' => false,
             'error'   => ($last_error ? $last_error : LANG_UPLOAD_ERR_NO_FILE)
-        );
-
+        ];
     }
 
 //============================================================================//
@@ -228,49 +279,42 @@ class cmsUploader {
 
     /**
      * Загружает файл на сервер переданный через input типа file
-     * @param string $post_filename Название поля с файлом в массиве $_FILES
-     * @param string $allowed_ext Список допустимых расширений (через запятую)
-     * @param string $allowed_size Максимальный размер файла (в байтах)
-     * @param string $destination Папка назначения (внутри пути upload)
+     *
+     * @param string $filename Название поля с файлом в массиве $_FILES
+     * @param int $allowed_size Максимальный размер файла (в байтах)
+     * @param string $destination Директория назначения (внутри пути upload)
      * @return array
      */
-    public function uploadForm($post_filename, $allowed_ext = false, $allowed_size = 0, $destination = false){
+    public function uploadForm($filename, $allowed_size = 0, $destination = false) {
 
-        $source     = $_FILES[$post_filename]['tmp_name'];
-        $error_code = $_FILES[$post_filename]['error'];
-        $dest_size  = (int)$_FILES[$post_filename]['size'];
-        $dest_name  = files_sanitize_name($_FILES[$post_filename]['name']);
-        $dest_ext   = pathinfo($dest_name, PATHINFO_EXTENSION);
+        $source     = $_FILES[$filename]['tmp_name'];
+        $error_code = $_FILES[$filename]['error'];
+        $dest_size  = (int) $_FILES[$filename]['size'];
+        $dest_name  = files_sanitize_name($_FILES[$filename]['name']);
 
-        if(!$this->checkExt($dest_ext, $allowed_ext)){
-            return array(
-                'error'   => LANG_UPLOAD_ERR_MIME,
+        $file = new cmsUploadfile($source, $this->allowed_mime);
+
+        if (!$file->isAllowed()) {
+            return [
+                'error'   => LANG_UPLOAD_ERR_MIME . '. ' . sprintf(LANG_PARSER_FILE_EXTS_FIELD_HINT, implode(', ', $this->allowed_mime_ext)),
                 'success' => false,
                 'name'    => $dest_name
-            );
-        }
-
-        if($this->allowed_mime !== false){
-            if(!$this->isMimeTypeAllowed($source)){
-                return array(
-                    'error'   => LANG_UPLOAD_ERR_MIME.'. '.sprintf(LANG_PARSER_FILE_EXTS_FIELD_HINT, implode(', ', $this->allowed_mime_ext)),
-                    'success' => false,
-                    'name'    => $dest_name
-                );
-            }
+            ];
         }
 
-        if ($allowed_size){
-            if ($dest_size > $allowed_size){
-                return array(
+        if ($allowed_size) {
+            if ($dest_size > $allowed_size) {
+                return [
                     'error'   => sprintf(LANG_UPLOAD_ERR_INI_SIZE, files_format_bytes($allowed_size)),
                     'success' => false,
                     'name'    => $dest_name
-                );
+                ];
             }
         }
 
-        if (!$destination){
+        $dest_ext = $file->getExt();
+
+        if (!$destination) {
             $destination = $this->getUploadDestinationDirectory();
         } else {
             $destination = $this->site_cfg->upload_path . $destination . '/';
@@ -283,143 +327,129 @@ class cmsUploader {
         $destination .= $this->getFileName($destination, $dest_ext);
 
         return $this->moveUploadedFile($source, $destination, $error_code, $dest_name, $dest_size);
-
     }
 
-//============================================================================//
-//============================================================================//
-
-    public function uploadFromLink($post_filename, $allowed_ext = false, $allowed_size = 0, $destination = false) {
+    /**
+     * Загружает файл по ссылке
+     *
+     * @param string $post_filename Название поля с файлом в массиве $_POST
+     * @param int $allowed_size Максимальный размер файла (в байтах)
+     * @param string $destination Директория назначения (внутри пути upload)
+     * @return array
+     */
+    public function uploadFromLink($post_filename, $allowed_size = 0, $destination = false) {
 
         $link = $file_name = trim($_POST[$post_filename]);
 
         // проверяем редирект и имя файла
-        if (function_exists('curl_init')){
-            $curl = curl_init();
-            curl_setopt($curl, CURLOPT_URL, $link);
-            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
-            curl_setopt($curl, CURLOPT_HEADER, true);
-            curl_setopt($curl, CURLOPT_NOBODY, true);
-            curl_setopt($curl, CURLOPT_TIMEOUT, 5);
-            $headers = curl_exec($curl);
-            curl_close($curl);
-            $matches = array();
-            if(preg_match("/(?:Location:|URI:)([^\n]+)*/is", $headers, $matches)){
-                $url = trim($matches[1]);
-                if(strpos($url, 'http') !== 0){
-                    $url_data = parse_url($link);
-                    $link = $url_data['scheme'].'://'.$url_data['host'].$url;
-                } else {
-                    $link = $url;
-                }
-                $_POST[$post_filename] = $link;
-                return $this->uploadFromLink($post_filename, $allowed_ext, $allowed_size, $destination);
-            }
-            if(preg_match('#filename="([^"]+)#uis', $headers, $matches)){
-                $file_name = trim($matches[1]);
+        $curl = curl_init();
+        curl_setopt($curl, CURLOPT_URL, $link);
+        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($curl, CURLOPT_HEADER, true);
+        curl_setopt($curl, CURLOPT_NOBODY, true);
+        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
+        $headers = curl_exec($curl);
+        curl_close($curl);
+
+        $matches = [];
+        if (preg_match("/(?:Location:|URI:)([^\n]+)*/is", $headers, $matches)) {
+
+            $url = trim($matches[1]);
+
+            if (strpos($url, 'http') !== 0) {
+                $url_data = parse_url($link);
+                $link     = $url_data['scheme'] . '://' . $url_data['host'] . $url;
+            } else {
+                $link = $url;
             }
-        }
 
-        $dest_ext  = strtolower(pathinfo(parse_url($file_name, PHP_URL_PATH), PATHINFO_EXTENSION));
-        $dest_name = files_sanitize_name($file_name);
+            $_POST[$post_filename] = $link;
 
-        if(!$this->checkExt($dest_ext, $allowed_ext)){
-            return array(
-                'error'   => LANG_UPLOAD_ERR_MIME,
-                'success' => false,
-                'name'    => $dest_name
-            );
+            return $this->uploadFromLink($post_filename, $allowed_size, $destination);
+        }
+
+        if (preg_match('#filename="([^"]+)#uis', $headers, $matches)) {
+            $file_name = trim($matches[1]);
         }
 
+        $dest_name = files_sanitize_name($file_name);
+
         $file_bin = file_get_contents_from_url($link);
 
-        if(!$file_bin){
-            return array(
+        if (!$file_bin) {
+            return [
                 'success' => false,
-                'error'   => LANG_UPLOAD_ERR_PARTIAL,
+                'error'   => LANG_UPLOAD_ERR_NO_FILE,
                 'name'    => $dest_name,
                 'path'    => ''
-            );
+            ];
         }
 
-        $image_size = strlen($file_bin);
-
-        if ($allowed_size){
-            if ($image_size > $allowed_size){
-                return array(
-                    'error'   => sprintf(LANG_UPLOAD_ERR_INI_SIZE, files_format_bytes($allowed_size)),
-                    'success' => false,
-                    'name'    => $dest_name
-                );
-            }
-        }
-
-        if (!$destination){
-            $destination = $this->getUploadDestinationDirectory();
-        } else {
-            $destination = $this->site_cfg->upload_path . $destination.'/';
-        }
+        return $this->saveFileFromString($file_bin, $allowed_size, $destination, $dest_name);
+    }
 
-        $destination .= $this->getFileName($destination, $dest_ext);
+    /**
+     * Сохраняет файл из php://input в целевую директорию  и отслеживает ошибки
+     *
+     * @param string $filename Название поля с файлом в массиве $_GET
+     * @param int $allowed_size Максимальный размер файла (в байтах)
+     * @param string $destination Директория назначения (внутри пути upload)
+     * @return array
+     */
+    public function uploadXHR($filename, $allowed_size = 0, $destination = false) {
 
-		$f = fopen($destination, 'w+');
-		fwrite($f, $file_bin);
-        fclose($f);
+        $dest_name = files_sanitize_name($_GET['qqfile']);
 
+        $file_bin = file_get_contents('php://input');
 
-        if($this->allowed_mime !== false){
-            if(!$this->isMimeTypeAllowed($destination)){
-                @unlink($destination);
-                return array(
-                    'error'   => LANG_UPLOAD_ERR_MIME.'. '.sprintf(LANG_PARSER_FILE_EXTS_FIELD_HINT, implode(', ', $this->allowed_mime_ext)),
-                    'success' => false,
-                    'name'    => $dest_name
-                );
-            }
+        if (!$file_bin) {
+            return [
+                'success' => false,
+                'error'   => LANG_UPLOAD_ERR_NO_FILE,
+                'name'    => $dest_name,
+                'path'    => ''
+            ];
         }
 
-        return array(
-            'success' => true,
-            'path'    => $destination,
-            'url'     => str_replace($this->site_cfg->upload_path, '', $destination),
-            'name'    => basename($destination),
-            'size'    => $image_size
-        );
-
+        return $this->saveFileFromString($file_bin, $allowed_size, $destination, $dest_name);
     }
 
     /**
-     * Загружает файл на сервер переданный через XHR
-     * @param string $post_filename Название поля с файлом в массиве $_GET
-     * @param string $allowed_ext Список допустимых расширений (через запятую)
-     * @param string $allowed_size Максимальный размер файла (в байтах)
-     * @param string $destination Папка назначения (внутри пути upload)
+     * Сохраняет файл из строки данных
+     *
+     * @param string $file_bin
+     * @param int $allowed_size Максимальный размер файла (в байтах)
+     * @param string $destination Директория назначения (внутри пути upload)
+     * @param string $dest_name Имя файла
      * @return array
      */
-    public function uploadXHR($post_filename, $allowed_ext = false, $allowed_size = 0, $destination = false){
+    private function saveFileFromString($file_bin, $allowed_size, $destination, $dest_name) {
 
-        $dest_name = files_sanitize_name($_GET['qqfile'], false);
-        $dest_ext  = pathinfo($dest_name, PATHINFO_EXTENSION);
+        $file = new cmsUploadfile($file_bin, $this->allowed_mime);
 
-        if(!$this->checkExt($dest_ext, $allowed_ext)){
-            return array(
-                'error'   => LANG_UPLOAD_ERR_MIME,
+        if (!$file->isAllowed()) {
+            return [
+                'error'   => LANG_UPLOAD_ERR_MIME . '. ' . sprintf(LANG_PARSER_FILE_EXTS_FIELD_HINT, implode(', ', $this->allowed_mime_ext)),
                 'success' => false,
                 'name'    => $dest_name
-            );
+            ];
         }
 
-        if ($allowed_size){
-            if ($this->getXHRFileSize() > $allowed_size){
-                return array(
+        $dest_ext = $file->getExt();
+
+        $file_size = strlen($file_bin);
+
+        if ($allowed_size) {
+            if ($file_size > $allowed_size) {
+                return [
                     'error'   => sprintf(LANG_UPLOAD_ERR_INI_SIZE, files_format_bytes($allowed_size)),
                     'success' => false,
                     'name'    => $dest_name
-                );
+                ];
             }
         }
 
-        if (!$destination){
+        if (!$destination) {
             $destination = $this->getUploadDestinationDirectory();
         } else {
             $destination = $this->site_cfg->upload_path . $destination . '/';
@@ -427,126 +457,76 @@ class cmsUploader {
 
         $destination .= $this->getFileName($destination, $dest_ext);
 
-        return $this->saveXHRFile($destination, $dest_name);
-
-    }
-
-    public function getXHRFileSize(){
-        if (isset($_SERVER["CONTENT_LENGTH"])){
-            return (int)$_SERVER["CONTENT_LENGTH"];
-        } else {
-            return false;
-        }
-    }
-
-//============================================================================//
-//============================================================================//
-
-    public function saveXHRFile($destination, $orig_name=''){
-
-        $target = @fopen($destination, 'wb');
-        $input  = @fopen("php://input", 'rb');
-
-        if (!$target){
-            return array(
+        if (!is_writable(dirname($destination))) {
+            return [
                 'success' => false,
                 'error'   => LANG_UPLOAD_ERR_CANT_WRITE,
-                'name'    => $orig_name,
-                'path'    => ''
-            );
-        }
-        if (!$input){
-            return array(
-                'success' => false,
-                'error'   => LANG_UPLOAD_ERR_NO_FILE,
-                'name'    => $orig_name,
+                'name'    => $dest_name,
                 'path'    => ''
-            );
+            ];
         }
 
-        while ($buff = fread($input, 4096)) {
-            fwrite($target, $buff);
-        }
-
-        @fclose($target);
-        @fclose($input);
-
-        $real_size = filesize($destination);
-
-        if (!$real_size || $real_size != $this->getXHRFileSize()){
-            @unlink($destination);
-            return array(
+        if(file_put_contents($destination, $file_bin) === false){
+            return [
                 'success' => false,
-                'error'   => LANG_UPLOAD_ERR_PARTIAL,
-                'name'    => $orig_name,
+                'error'   => LANG_UPLOAD_ERR_CANT_WRITE,
+                'name'    => $dest_name,
                 'path'    => ''
-            );
+            ];
         }
 
-        if($this->allowed_mime !== false){
-            if(!$this->isMimeTypeAllowed($destination)){
-                @unlink($destination);
-                return array(
-                    'error'   => LANG_UPLOAD_ERR_MIME.'. '.sprintf(LANG_PARSER_FILE_EXTS_FIELD_HINT, implode(', ', $this->allowed_mime_ext)),
-                    'success' => false,
-                    'name'    => $orig_name,
-                    'path'    => ''
-                );
-            }
-        }
-
-        return array(
+        return [
             'success' => true,
             'path'    => $destination,
             'url'     => str_replace($this->site_cfg->upload_path, '', $destination),
-            'name'    => $orig_name,
-            'size'    => $real_size
-        );
-
+            'name'    => basename($destination),
+            'size'    => $file_size
+        ];
     }
 
-//============================================================================//
     /**
-     * Копирует файл из временной папки в целевую и отслеживает ошибки
+     * Копирует файл из временной директории в целевую и отслеживает ошибки
+     *
      * @param string $source
      * @param string $destination
      * @param int $errorCode
-     * @return bool
+     * @return array
      */
-    private function moveUploadedFile($source, $destination, $errorCode, $orig_name='', $orig_size=0){
+    private function moveUploadedFile($source, $destination, $errorCode, $orig_name = '', $orig_size = 0) {
 
-        if($errorCode !== UPLOAD_ERR_OK && isset($this->upload_errors[$errorCode])){
+        if ($errorCode !== UPLOAD_ERR_OK && isset($this->upload_errors[$errorCode])) {
 
-            return array(
+            return [
                 'success' => false,
                 'error'   => $this->upload_errors[$errorCode],
                 'name'    => $orig_name,
                 'path'    => ''
-            );
-
+            ];
         }
 
         $upload_dir = dirname($destination);
-        if (!is_writable($upload_dir)){	@chmod($upload_dir, 0777); }
+        if (!is_writable($upload_dir)) {
+            @chmod($upload_dir, 0777);
+        }
+
+        if (!is_writable($upload_dir)) {
 
-        if (!is_writable($upload_dir)){
-            return array(
+            return [
                 'success' => false,
                 'error'   => LANG_UPLOAD_ERR_CANT_WRITE,
                 'name'    => $orig_name,
                 'path'    => ''
-            );
+            ];
         }
 
-        return array(
+        return [
             'success' => @move_uploaded_file($source, $destination),
             'path'    => $destination,
             'url'     => str_replace($this->site_cfg->upload_path, '', $destination),
             'name'    => basename($destination),
             'size'    => $orig_size,
             'error'   => $this->upload_errors[$errorCode]
-        );
-
+        ];
     }
 
     /**
@@ -554,29 +534,16 @@ class cmsUploader {
      * @param string $file_path
      * @return boolean
      */
-    public function remove($file_path){
-        return @unlink($file_path);
+    public function remove($file_path) {
+        return files_delete_file($file_path, 2);
     }
 
     /**
      * Создаёт дерево директорий для загрузки файла
      * @return string
      */
-    public function getUploadDestinationDirectory(){
+    public function getUploadDestinationDirectory() {
         return files_get_upload_dir($this->user_id);
     }
 
-    /**
-     * Проверяет файл, является ли он изображением
-     * @param string $src
-     * @return boolean
-     */
-    public function isImage($src){
-
-        $size = getimagesize($src);
-
-        return $size !== false;
-
-    }
-
 }

programming_language: PHP
filename: uploadfile.php
change_type: ModificationType.ADD
diff: @@ -0,0 +1,57 @@
+<?php
+
+class cmsUploadfile {
+
+    private $file_mime;
+    private $mime_types;
+    private $allowed_mime;
+
+    public function __construct($file_path, $allowed_mime = null) {
+
+        $this->allowed_mime = $allowed_mime;
+
+        $this->mime_types = (new cmsConfigs('mimetypes.php'))->getAll();
+
+        $finfo = finfo_open(FILEINFO_MIME_TYPE);
+
+        if(strpos($file_path, DIRECTORY_SEPARATOR) === 0){
+
+            $this->file_mime = finfo_file($finfo, $file_path);
+
+        } else {
+
+            $this->file_mime = finfo_buffer($finfo, $file_path);
+        }
+
+        finfo_close($finfo);
+    }
+
+    public function getMime() {
+        return $this->file_mime;
+    }
+
+    public function getExt() {
+
+        if ($this->file_mime && isset($this->mime_types[$this->file_mime])) {
+
+            return $this->mime_types[$this->file_mime];
+        }
+
+        return 'bin';
+    }
+
+    public function isAllowed() {
+
+        // Пускаем любые, если не указано
+        if ($this->allowed_mime === null) {
+            return true;
+        }
+
+        if ($this->file_mime === false) {
+            return false;
+        }
+
+        return in_array($this->file_mime, $this->allowed_mime, true);
+    }
+
+}

programming_language: PHP