<?php

/**
 * @version        1.11.3
 * @package        Joomla
 * @subpackage     Edocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011 - 2024 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */

// No direct access
defined('_JEXEC') or die();
use Joomla\CMS\Factory;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Path;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Uri\Uri;

class EDocmanControllerUpload extends EDocmanController
{
	/**
	 * Upload files and store it to the correct folder
	 */
	public function upload()
	{
        $session    = Factory::getApplication()->getSession();
        $files      = $session->get('files', array());
        $app        = Factory::getApplication();
		$config     = EDocmanHelper::getConfig();
		$rootDir    = $config->documents_path;
		$categoryId = $this->input->getInt('category_id', 0);
		$file       = $this->input->files->get('file',null,'raw');
		$fileName   = $file['name'];
		if($config->make_filename_safely)
		{
			$fileName = File::makeSafe($fileName);
		}
		$uploadPath = $rootDir;
		
        //die('{"jsonrpc" : "2.0", "error" : {"code": 500, "message": "THIS IS AN ERROR."}, "id" : "id"}');
        PluginHelper::importPlugin('edocman');
        $results        = array();
        $results        = $app->triggerEvent('onBeforeDocumentBatchUpload', array($file,count($files)));

		if ($categoryId > 0 && $config->activate_herachical_folder_structure)
		{
			$db     = Factory::getContainer()->get('db');
			$query  = $db->getQuery(true);
			$query->select('`path`')
				  ->from('#__edocman_categories')
				  ->where('id=' . (int) $categoryId);
			$db->setQuery($query);
			$path = $db->loadResult();
			if ($path)
			{
				$uploadPath .= '/' . $path;
			}
		}
		else
		{
            $path = "";
        }

		if (is_file(Path::clean($uploadPath . '/' . $fileName) && !$config->overwrite_existing_file))
		{
            if(!EDocmanHelper::isDropBoxTurnedOn() && !EDocmanHelper::isGdriveTurnedOn() && !EDocmanHelper::isAmazonS3TurnedOn())
            {
                if($config->position_of_unique_number == 0)
				{
					$savedFilename  = uniqid('file_') . '_' . $fileName;
				}
				elseif($config->position_of_unique_number == 1)
				{
					$fileNameArr	= explode(".", $fileName);
					$fileNameRaw	= "";
					for($i = 0;$i < count($fileNameArr) - 1;$i++)
					{
						$fileNameRaw .= $fileNameArr[$i].".";
					}
					$fileNameRaw    = substr($fileNameRaw, 0, strlen($fileNameRaw) - 1);
					$fileNameRaw    .= '_'.uniqid('file_');
					$savedFilename  = $fileNameRaw.'.'.$fileNameArr[count($fileNameArr) - 1];
				}
            }
            else
            {
                $savedFilename = $fileName;
            }
		}
		else
		{
			$savedFilename = $fileName;
		}

		

        // Give plugin a change to upload the file

        PluginHelper::importPlugin('edocman');
        $results        = array();
        $results        = $app->triggerEvent('onDocumentBatchUpload', array($savedFilename, $file, $path, $categoryId));
        $return         = $results[0][0];

        if ($return != true)
        {
            if (version_compare(JVERSION, '3.4.4', 'ge'))
            {
				$ext = EdocmanHelper::getExt($savedFilename);
				if(in_array($ext, ['zip','rar','7z','gzip']))
				{
					File::upload($file['tmp_name'], $uploadPath . '/' . $savedFilename, false, true);
				}
				else
				{
					File::upload($file['tmp_name'], $uploadPath . '/' . $savedFilename, false, false);
				}
                $results[0][1] = @filesize($uploadPath . '/' . $savedFilename);
            }
            else
            {
                File::upload($file['tmp_name'], $uploadPath . '/' . $savedFilename);
                $results[0][1] = @filesize($uploadPath . '/' . $savedFilename);
            }
        }
        else
        {
            $savedFilename = Factory::getApplication()->getInput()->getString('fileName','');
        }

        $filesize        = $session->get('filesize', array());
		$originalFiles   = $session->get('originalFiles', array());
		$files           = (array) $files;
		$originalFiles   = (array) $originalFiles;
		$files[]         = empty($path) ? $savedFilename : $path . '/' . $savedFilename;
		$originalFiles[] = $savedFilename;
        $filesize[]      = $results[0][1];
        //for google drive
        $fileid[]        = $results[0][2];

		$session->set('files', $files);
        $session->set('filesize', $filesize);
		$session->set('originalFiles', $originalFiles);
        $session->set('fileid', $fileid);
	}

	/**
	 * Display form which allows batch editing the uploaded documents
	 */
	public function edit_documents()
	{
		$session        = Factory::getApplication()->getSession();
		$files          = $session->get('files', array());
		$category_id    = Factory::getApplication()->getInput()->getInt('category_id',0);
		$itemid         = Factory::getApplication()->getInput()->getInt('Itemid',0);
		if (!count($files))
		{
			//Redirect back to upload page, display error message
			$this->setRedirect('index.php?option=com_edocman&view=document&layout=edit&catid='.$category_id.'&Itemid='.$itemid, Text::_('EDOCMAN_NO_FILES_UPLOADED'), 'warning');
			return;
		}
		$this->input->set('view', 'document');
		$this->input->set('layout', 'edit_documents');
		$this->input->set('category_id',$category_id);
		$this->input->set('itemid',$itemid);
		$this->input->set('files',$files);
		$this->display();
	}

	/**
	 * Store title, description of the documents which were entered in batch-edit screen
	 */
	public function store_documents()
	{
	    $config     = EDocmanHelper::getConfig();
		$model      = $this->getModel();
		$data       = $this->input->getData();
		$model->store($data);
        $Itemid     = $this->input->getInt('Itemid');
        $categoryId = (int) $data['category_id'];
		$session    = Factory::getApplication()->getSession();
		$session->clear('files');
		$session->clear('originalFiles');
        $session->clear('filesize');
        $session->clear('fileid');
        switch ($config->redirect_after_uploading)
        {
			default:
            case "0":
                $manageItemId = EDocmanHelperRoute::findView('userdocuments', 0);
                //$url = JRoute::_('index.php?option=com_edocman&view=userdocuments&Itemid='.$manageItemId);
                if ($manageItemId)
                {
                    $url = Route::_('index.php?option=com_edocman&view=userdocuments&Itemid='.$manageItemId);
                }
                else
                {
                    $url = Route::_(EDocmanHelperRoute::getCategoryRoute($categoryId, 9999));
                }
                break;
            case "1":
                $url = Route::_(EDocmanHelperRoute::getCategoryRoute($categoryId, 9999));
                break;
            case "2":
                $url = Uri::root();
                break;
        }
        $this->setRedirect($url, Text::_('EDOCMAN_DOCUMENT_SUCCESSFULLY_UPLOADED'));
	}

	/**
	 * Cancel Bulk upload action, redirect user to documents management page
	 */
	public function cancel()
	{
		$session    = Factory::getApplication()->getSession();
		$session->clear('files');
		$session->clear('originalFiles');
        $session->clear('filesize');
        $session->clear('fileid');
		$return		= Factory::getApplication()->getInput()->getString('return','');
		$db			= Factory::getContainer()->get('db');
		$Itemid		= Factory::getApplication()->getInput()->getInt('Itemid');
		if($return != "")
		{
			$return = base64_decode($return);
			Factory::getApplication()->redirect($return);
		}
		if($Itemid > 0)
		{
			$db->setQuery("Select `link` from #__menu where id = '$Itemid'");
			$link = $db->loadResult();
			if($link != "")
			{
				Factory::getApplication()->redirect(Route::_($link));
			}
		}
		$this->setRedirect('index.php?option=com_edocman&view=documents');
	}
}
