<?php

if (!defined('ABSPATH'))
    die('Restricted Access');

class JSSTuploads {

    private $ticketid;
    private $articleid;
    private $downloadid;
    private $categoryid;
    private $staffid;
    private $uploadfor;

    function jssupportticket_upload_dir( $dir ) {
        $form_request = JSSTrequest::getVar('form_request');
        if($form_request == 'jssupportticket' OR $this->uploadfor == 'agent'){
            $datadirectory = jssupportticket::$_config['data_directory'];
            $path = $datadirectory . '/attachmentdata';

            $foldername = '';

            if($this->uploadfor == 'ticket'){
                if(!is_numeric($this->ticketid)) return false;
                $path = $path . '/ticket';
                $query = "SELECT attachmentdir FROM `".jssupportticket::$_db->prefix."js_ticket_tickets` WHERE id = ".esc_sql($this->ticketid);
                $foldername = jssupportticket::$_db->get_var($query);
            }elseif($this->uploadfor == 'article'){
                $path = $path . '/articles/article_'.$this->articleid;
            }elseif($this->uploadfor == 'download'){
                $path = $path . '/downloads/download_'.$this->downloadid;
            }elseif($this->uploadfor == 'category'){
                $path = $datadirectory . '/knowledgebasedata/categories/category_'.$this->categoryid;
            }elseif($this->uploadfor == 'agent'){
                $path = $datadirectory . '/staffdata/staff_'.$this->staffid;
            }

            $userpath = $path . '/' . $foldername;
            $array = array(
                'path'   => $dir['basedir'] . '/' . $userpath,
                'url'    => $dir['baseurl'] . '/' . $userpath,
                'subdir' => '/'. $userpath,
            ) + $dir;
            return $array;
        }elseif($this->uploadfor == 'notificationlogo'){
            $datadirectory = jssupportticket::$_config['data_directory'];
            $path = $datadirectory;
            return $path;

        }else{
            return $dir;
        }
    }

    function storeTicketAttachment($data, $caller){
        $ticketid = $data['ticketid'];
        $filesize = jssupportticket::$_config['file_maximum_size'];
        if (!function_exists('wp_handle_upload')) {
            do_action('jssupportticket_load_wp_file');
        }
        $this->ticketid = $ticketid;
        $this->uploadfor = 'ticket';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        if(!isset($_FILES['filename'])){
            return;
        }
        $files = filter_var_array($_FILES['filename']);

        if(!is_array($files['name'])){
            return;
        }

        foreach ($files['name'] as $key => $value) {
            if ($files['name'][$key]) {
                $file = array(
                        'name'     => $files['name'][$key],
                        'type'     => $files['type'][$key],
                        'tmp_name' => $files['tmp_name'][$key],
                        'error'    => $files['error'][$key],
                        'size'     => $files['size'][$key]
                        );
                $uploadfilesize = $file['size'] / 1024; //kb
                if($uploadfilesize > $filesize){
                    JSSTmessage::setMessage(esc_html(__('Error file size too large', 'js-support-ticket')), 'error');
                    return;
                }
                $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES['filename']['name'][$key]));
                if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
                    $document_file_types = JSSTincluder::getJSModel('configuration')->getConfigValue('file_extension');
                    if(stristr($document_file_types, $filetyperesult['ext'])){

                        $result = wp_handle_upload($file, array('test_form' => false));
                        if ( $result && ! isset( $result['error'] ) ) {
                            // Get the folder where the file was uploaded
                            $file_directory = dirname($result['file']);
                            $filename = jssupportticketphplib::JSST_basename( $result['file'] );
                            $replyattachmentid = isset($data['replyattachmentid']) ? $data['replyattachmentid'] : '';
                            $result = $caller->storeTicketAttachment($ticketid, $replyattachmentid, $uploadfilesize, $filename);
                        } else {
                            /**
                             * Error generated by _wp_handle_upload()
                             * @see _wp_handle_upload() in wp-admin/includes/file.php
                             */
                            JSSTmessage::setMessage($result['error'], 'error');
                        }
                    }
                }
            }
        }
        // generate index file
        if (!empty($file_directory)) {
            JSSTincluder::getJSModel('jssupportticket')->generateIndexFile($file_directory);
        }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        return;
    }

    function storeTicketViaEmailAttachment($idsarray,$key,$value){
        $ticketid = $idsarray[0];
        if(!is_numeric($ticketid))
            return;
        $datadirectory = jssupportticket::$_config['data_directory'];
        $maindir = wp_upload_dir();
        $path = $maindir['basedir'];
        $path = $path .'/'.$datadirectory;
        if (!file_exists($path)) { // create user directory
            JSSTincluder::getJSModel('jssupportticket')->makeDir($path);
        }
        $path = $path . '/attachmentdata';
        if (!file_exists($path)) { // create user directory
            JSSTincluder::getJSModel('jssupportticket')->makeDir($path);
        }
        $path = $path . '/ticket';
        if (!file_exists($path)) { // create user directory
            JSSTincluder::getJSModel('jssupportticket')->makeDir($path);
        }
        $query = "SELECT attachmentdir FROM `".jssupportticket::$_db->prefix."js_ticket_tickets` WHERE id = ".esc_sql($idsarray[0]);
        $foldername = jssupportticket::$_db->get_var($query);

        $path = $path . '/' . $foldername;
        if (!file_exists($path)) { // create user directory
            JSSTincluder::getJSModel('jssupportticket')->makeDir($path);
        }

        file_put_contents($path . '/' . $key, $value); // save the file
        return true;
    }

    function storeArticleAttachment($data, $caller){
        $id = $data['id'];
        $filesize = jssupportticket::$_config['file_maximum_size'];
        if (!function_exists('wp_handle_upload')) {
            do_action('jssupportticket_load_wp_file');
        }
        $this->articleid = $id;
        $this->uploadfor = 'article';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        if(!isset($_FILES['filename'])){
            return;
        }
        $files = filter_var_array($_FILES['filename']);
        if(!is_array($files['name'])){
            return;
        }

        foreach ($files['name'] as $key => $value) {
            if ($files['name'][$key]) {
                $file = array(
                        'name'     => $files['name'][$key],
                        'type'     => $files['type'][$key],
                        'tmp_name' => $files['tmp_name'][$key],
                        'error'    => $files['error'][$key],
                        'size'     => $files['size'][$key]
                        );
                $uploadfilesize = $file['size'] / 1024; //kb
                if($uploadfilesize > $filesize){
                    JSSTmessage::setMessage(esc_html(__('Error file size too large', 'js-support-ticket')), 'error');
                    return;
                }

                $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES['filename']['name'][$key]));
                if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
                    $document_file_types = JSSTincluder::getJSModel('configuration')->getConfigValue('file_extension');
                    if(stristr($document_file_types, $filetyperesult['ext'])){

                        $result = wp_handle_upload($file, array('test_form' => false));
                        if ( $result && ! isset( $result['error'] ) ) {
                            // Get the folder where the file was uploaded
                            $file_directory = dirname($result['file']);
                            $filename = jssupportticketphplib::JSST_basename( $result['file'] );
                            $result = $caller->storeArticleAttachmet($id , $uploadfilesize, $filename);
                        } else {
                            /**
                             * Error generated by _wp_handle_upload()
                             * @see _wp_handle_upload() in wp-admin/includes/file.php
                             */
                            JSSTmessage::setMessage($result['error'], 'error');
                        }
                    }
                }
            }
        }
        // generate index file
        if (!empty($file_directory)) {
            JSSTincluder::getJSModel('jssupportticket')->generateIndexFile($file_directory);
        }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        return;
    }

    function storeDownloadAttachment($data, $caller){
        $id = $data['id'];
        $filesize = jssupportticket::$_config['file_maximum_size'];
        if (!function_exists('wp_handle_upload')) {
            do_action('jssupportticket_load_wp_file');
        }
        $this->downloadid = $id;
        $this->uploadfor = 'download';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        if(!isset($_FILES['filename'])){
            return;
        }
        $files = filter_var_array($_FILES['filename']);
        if(!is_array($files['name'])){
            return;
        }

        foreach ($files['name'] as $key => $value) {
            if ($files['name'][$key]) {
                $file = array(
                        'name'     => $files['name'][$key],
                        'type'     => $files['type'][$key],
                        'tmp_name' => $files['tmp_name'][$key],
                        'error'    => $files['error'][$key],
                        'size'     => $files['size'][$key]
                        );
                $uploadfilesize = $file['size'] / 1024; //kb
                if($uploadfilesize > $filesize){
                    JSSTmessage::setMessage(esc_html(__('Error file size too large', 'js-support-ticket')), 'error');
                    return;
                }
                $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES['filename']['name'][$key]));
                if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
                    $document_file_types = JSSTincluder::getJSModel('configuration')->getConfigValue('file_extension');
                    if(stristr($document_file_types, $filetyperesult['ext'])){
                        $result = wp_handle_upload($file, array('test_form' => false));
                        if ( $result && ! isset( $result['error'] ) ) {
                            // Get the folder where the file was uploaded
                            $file_directory = dirname($result['file']);
                            $filename = jssupportticketphplib::JSST_basename( $result['file'] );
                            $result = $caller->storeDownloadAttachment($id , $uploadfilesize, $filename);
                        } else {
                            /**
                             * Error generated by _wp_handle_upload()
                             * @see _wp_handle_upload() in wp-admin/includes/file.php
                             */
                            JSSTmessage::setMessage($result['error'], 'error');
                        }
                    }
                }
            }
        }
        // generate index file
        if (!empty($file_directory)) {
            JSSTincluder::getJSModel('jssupportticket')->generateIndexFile($file_directory);
        }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        return;
    }

    function uploadCategoryLogo($id , $caller){

        if(!is_numeric($id))
            return false;
        $filesize = jssupportticket::$_config['file_maximum_size'];
        if (!function_exists('wp_handle_upload')) {
            do_action('jssupportticket_load_wp_file');
        }
        $this->categoryid = $id;
        $this->uploadfor = 'category';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        $file = array(
            'name'     => sanitize_file_name($_FILES['filename']['name']),
            'type'     => jssupportticket::JSST_sanitizeData($_FILES['filename']['type']),
            'tmp_name' => jssupportticket::JSST_sanitizeData($_FILES['filename']['tmp_name']),
            'error'    => jssupportticket::JSST_sanitizeData($_FILES['filename']['error']),
            'size'     => jssupportticket::JSST_sanitizeData($_FILES['filename']['size']),
        ); // JSST_sanitizeData() function uses wordpress santize functions
        $uploadfilesize = $file['size'] / 1024; //kb
        if($uploadfilesize > $filesize){
            JSSTmessage::setMessage(esc_html(__('Error file size too large', 'js-support-ticket')), 'error');
            return;
        }

        $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES['filename']['name']));
        if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
            $image_file_types = JSSTincluder::getJSModel('configuration')->getConfigValue('file_extension');

            if(stristr($image_file_types, $filetyperesult['ext'])){

                $result = wp_handle_upload($file, array('test_form' => false));
                if ( $result && ! isset( $result['error'] ) ) {
                    // Get the folder where the file was uploaded
                    $file_directory = dirname($result['file']);
                    $filename = jssupportticketphplib::JSST_basename( $result['file'] );
                    $result = $caller->storeCategoryLogo($id , $filename);
                    // generate index file
                    JSSTincluder::getJSModel('jssupportticket')->generateIndexFile($file_directory);
                } else {
                    /**
                     * Error generated by _wp_handle_upload()
                     * @see _wp_handle_upload() in wp-admin/includes/file.php
                     */
                    JSSTmessage::setMessage($result['error'], 'error');
                }
            }
        }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        return;
    }

    function uploadStaffLogo($id , $caller){
        if(!is_numeric($id))
            return false;
        $filesize = jssupportticket::$_config['file_maximum_size'];
        if (!function_exists('wp_handle_upload')) {
            do_action('jssupportticket_load_wp_file');
        }
        $this->staffid = $id;
        $this->uploadfor = 'agent';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        $file = array(
            'name'     => sanitize_file_name($_FILES['filename']['name']),
            'type'     => jssupportticket::JSST_sanitizeData($_FILES['filename']['type']),
            'tmp_name' => jssupportticket::JSST_sanitizeData($_FILES['filename']['tmp_name']),
            'error'    => jssupportticket::JSST_sanitizeData($_FILES['filename']['error']),
            'size'     => jssupportticket::JSST_sanitizeData($_FILES['filename']['size']),
        ); // JSST_sanitizeData() function uses wordpress santize functions
        $uploadfilesize = $file['size'] / 1024; //kb
        if($uploadfilesize > $filesize){
            JSSTmessage::setMessage(esc_html(__('Error file size too large', 'js-support-ticket')), 'error');
            return;
        }
        $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES['filename']['name']));
        if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
            $image_file_types = JSSTincluder::getJSModel('configuration')->getConfigValue('file_extension');
            if(stristr($image_file_types, $filetyperesult['ext'])){

                $result = wp_handle_upload($file, array('test_form' => false));
                if ( $result && ! isset( $result['error'] ) ) {
                    // Get the folder where the file was uploaded
                    $file_directory = dirname($result['file']);
                    $filename = jssupportticketphplib::JSST_basename( $result['file'] );
                    $result = $caller->storeStaffLogo($id , $filename);
                    // generate index file
                    JSSTincluder::getJSModel('jssupportticket')->generateIndexFile($file_directory);
                } else {
                    /**
                     * Error generated by _wp_handle_upload()
                     * @see _wp_handle_upload() in wp-admin/includes/file.php
                     */
                    JSSTmessage::setMessage($result['error'], 'error');
                }
            }
        }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        return;
    }

    function storeTicketCustomUploadFile($id, $field){
        if(!isset($_FILES[$field])){
            return;
        }
        if (!function_exists('wp_handle_upload')) {
            do_action('jssupportticket_load_wp_file');
        }
        $filesize = jssupportticket::$_config['file_maximum_size'];
        $this->ticketid = $id;
        $this->uploadfor = 'ticket';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        $file = array(
            'name'     => sanitize_file_name($_FILES[$field]['name']),
            'type'     => jssupportticket::JSST_sanitizeData($_FILES[$field]['type']),
            'tmp_name' => jssupportticket::JSST_sanitizeData($_FILES[$field]['tmp_name']),
            'error'    => jssupportticket::JSST_sanitizeData($_FILES[$field]['error']),
            'size'     => jssupportticket::JSST_sanitizeData($_FILES[$field]['size'])
        ); // JSST_sanitizeData() function uses wordpress santize functions
        $uploadfilesize = jssupportticket::JSST_sanitizeData($_FILES[$field]['size']) / 1024; //kb // JSST_sanitizeData() function uses wordpress santize functions
        if($uploadfilesize > $filesize){
            JSSTmessage::setMessage(esc_html(__('Error file size too large', 'js-support-ticket')), 'error');
            return;
        }
        $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES[$field]['name']));
        if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
            $image_file_types = JSSTincluder::getJSModel('configuration')->getConfigValue('file_extension');
            if(strstr($image_file_types, $filetyperesult['ext'])){

                $result = wp_handle_upload($file, array('test_form' => false));
                if (isset( $result['error'] ) ) {
                    /**
                     * Error generated by _wp_handle_upload()
                     * @see _wp_handle_upload() in wp-admin/includes/file.php
                     */
                    JSSTmessage::setMessage($result['error'], 'error');
                }else{
                    $filename = jssupportticketphplib::JSST_basename( $result['file'] );
                    // Get the folder where the file was uploaded
                    $file_directory = dirname($result['file']);
                    // generate index file
                    JSSTincluder::getJSModel('jssupportticket')->generateIndexFile($file_directory);
                }
            }
        }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        //to store name of custom file in params
        JSSTincluder::getJSModel('ticket')->storeUploadFieldValueInParams($id,$filename,$field);
        return;
    }

	function uploadInternalNoteAttachment($id,$field){
        if(!isset($_FILES[$field])){
            return;
        }
        $filename = '';
        $filesize = '';
        if (!function_exists('wp_handle_upload')) {
            do_action('jssupportticket_load_wp_file');
        }
        $filesize = jssupportticket::$_config['file_maximum_size'];
        $this->ticketid = $id;
        $this->uploadfor = 'ticket';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        $file = array(
            'name'     => sanitize_file_name($_FILES[$field]['name']),
            'type'     => jssupportticket::JSST_sanitizeData($_FILES[$field]['type']),
            'tmp_name' => jssupportticket::JSST_sanitizeData($_FILES[$field]['tmp_name']),
            'error'    => jssupportticket::JSST_sanitizeData($_FILES[$field]['error']),
            'size'     => jssupportticket::JSST_sanitizeData($_FILES[$field]['size'])
        ); // JSST_sanitizeData() function uses wordpress santize functions
        $uploadfilesize = jssupportticket::JSST_sanitizeData($_FILES[$field]['size']) / 1024; //kb // JSST_sanitizeData() function uses wordpress santize functions
        if($uploadfilesize > $filesize){
            JSSTmessage::setMessage(esc_html(__('Error file size too large', 'js-support-ticket')), 'error');
            return;
        }
        $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES[$field]['name']));
        if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
            $image_file_types = JSSTincluder::getJSModel('configuration')->getConfigValue('file_extension');
            if(strstr($image_file_types, $filetyperesult['ext'])){

                $result = wp_handle_upload($file, array('test_form' => false));
                if (isset( $result['error'] ) ) {
                    /**
                     * Error generated by _wp_handle_upload()
                     * @see _wp_handle_upload() in wp-admin/includes/file.php
                     */
                    JSSTmessage::setMessage($result['error'], 'error');
                }else{
					$filename = jssupportticketphplib::JSST_basename( $result['file'] );
					$filesize = $file['size'];
                    // Get the folder where the file was uploaded
                    $file_directory = dirname($result['file']);
                    // generate index file
                    JSSTincluder::getJSModel('jssupportticket')->generateIndexFile($file_directory);
				}
            }
        }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
		if($filename != '' && $filesize != ''){
			$array = array('filename' => $filename, 'filesize' => $filesize);
			return $array;
		}else{
			return false;
		}
	}

    function uploadDesktopNotificationLogo(){
        $filesize = jssupportticket::$_config['file_maximum_size'];
        if (!function_exists('wp_handle_upload')) {
            do_action('jssupportticket_load_wp_file');
        }
        $this->uploadfor = 'notificationlogo';
        // Register our path override.
        add_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        // Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
        $result = array();
        $file = array(
            'name'     => sanitize_file_name($_FILES['logo_for_desktop_notfication']['name']),
            'type'     => jssupportticket::JSST_sanitizeData($_FILES['logo_for_desktop_notfication']['type']),
            'tmp_name' => jssupportticket::JSST_sanitizeData($_FILES['logo_for_desktop_notfication']['tmp_name']),
            'error'    => jssupportticket::JSST_sanitizeData($_FILES['logo_for_desktop_notfication']['error']),
            'size'     => jssupportticket::JSST_sanitizeData($_FILES['logo_for_desktop_notfication']['size']),
        ); // JSST_sanitizeData() function uses wordpress santize functions
        $uploadfilesize = $file['size'] / 1024; //kb
        if($uploadfilesize > $filesize){
            JSSTmessage::setMessage(esc_html(__('Error file size too large', 'js-support-ticket')), 'error');
            return;
        }
        $filetyperesult = wp_check_filetype(sanitize_file_name($_FILES['logo_for_desktop_notfication']['name']));
        if(!empty($filetyperesult['ext']) && !empty($filetyperesult['type'])){
            $image_file_types = JSSTincluder::getJSModel('configuration')->getConfigValue('file_extension');
            if(stristr($image_file_types, $filetyperesult['ext'])){
                $result = wp_handle_upload($file, array('test_form' => false));
                if ( $result && ! isset( $result['error'] ) ) {
                    $filename = jssupportticketphplib::JSST_basename( $result['file'] );
                    $result = JSSTincluder::getJSModel('configuration')->storeDesktopNotificationLogo($filename);
                } else {
                    JSSTmessage::setMessage($result['error'], 'error');
                }
            }
        }
        // Set everything back to normal.
        remove_filter( 'upload_dir', array($this,'jssupportticket_upload_dir'));
        return;
    }

}

?>
