<?php
/**
 * @version        1.11.3
 * @package        Joomla
 * @subpackage     Edocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011 - 2025 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
// No direct access.
defined('_JEXEC') or die();
use Joomla\CMS\Factory;
use Joomla\Filesystem\Folder;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Path;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Application\ApplicationHelper;
use Joomla\CMS\Table\Table;
use Joomla\String\StringHelper;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Environment\Browser;
use Joomla\CMS\User\UserHelper;
use Joomla\CMS\Router\Route;
use Joomla\Registry\Registry;
use Joomla\CMS\Mail\MailerFactoryInterface;

/**
 * Edocman model.
 */
class EDocmanModelCommonDocument extends OSModelAdmin
{
	/**
	 * Override getdata method
	 *
	 * @see OSModelItem::getData()
	 */
	public function getData()
	{
		$config = EDocmanHelper::loadConfig();
		if (empty($this->data))
		{
			$data = parent::getData();
			if ($data->id)
			{
				$db    = $this->getDbo();
				$query = $db->getQuery(true);
				$query->select('category_id, is_main_category')
					->from('#__edocman_document_category')
					->where('document_id=' . (int) $data->id);
				$db->setQuery($query);
				$categories               = $db->loadObjectList();
				$data->extra_category_ids = [];
				$data->category_id        = 0;
				if (count($categories))
				{
					foreach ($categories as $category)
					{
						if ($category->is_main_category)
						{
							$data->category_id = $category->category_id;
						}
						else
						{
							$data->extra_category_ids[] = $category->category_id;
						}
					}
				}
				$data->select_filename = $data->filename;
				if ($data->indicators)
				{
					$data->indicators      = explode(',', $data->indicators);
				}
				else
				{
					$data->indicators = [];
				}
				//Get license title
				if ($data->license_id > 0)
				{
					$query->clear();
					$query->select('title')
						->from('#__edocman_licenses')
						->where('id = '. $data->license_id);
					$db->setQuery($query);
					$data->license_title = $db->loadResult();
				}
			}
			elseif ($this->state->catid)
			{
				$data->category_id = $this->state->catid;
			}
			else
			{
				$data->hide_search_engines = 2;
			}
			$this->data = $data;
		}

		if($config->get('user_group_ids'))
		{
			$group_ids = $this->data->owner_group_ids;
			if($group_ids != "")
			{
				$tempGroupIds		   = [];
				$this->data->group_ids = [];
				$group_ids = explode(",",$group_ids);
				foreach($group_ids as $gid)
				{
					$temp				= new \stdClass();
					$temp->value		= $gid;
					$tempGroupIds[]	    = $temp;
				}
				$this->data->group_ids = $tempGroupIds;
			}
		}

		return $this->data;
	}

	/**
	 * Method to save Document
	 *
	 * @param OSInput $input
	 *
	 * @return bool
	 */
	public function save($input)
	{

		// Initialise variables;
		$app                = Factory::getApplication();
		$data               = $input->get('jform', array(), 'array');

		if(isset ($data['groups']) && count($data['groups']) == 0)
		{
			$data['groups']	= $input->get('groups', [], 'array');
		}

		if(count($input->get('groups', [], 'array')) > 0)
		{
			$data['groups']	= $input->get('groups', [], 'array');
		}

		$download_password	= $input->getString('download_password');
		$data['download_password'] = $download_password;
		$disable_download	= $input->getInt('disable_download', 0 );
		$data['disable_download'] = $disable_download;
		$hide_search_engines	= $input->getInt('hide_search_engines', 2 );
		$data['hide_search_engines'] = $hide_search_engines;
		$task               = $input->get('task');
		$db                 = $this->getDbo();
		$query              = $db->getQuery(true);
		$row                = $this->getTable();
		$id                 = (int) $data['id'];
		$isNew              = true;
		$config             = EDocmanHelper::loadConfig();
		$backupDir 			= $config->get('documents_path') . '/backup';
		if (!is_dir(Path::clean($backupDir))) {
			Folder::create($backupDir);
		}
		$user               = Factory::getApplication()->getIdentity();
		$newupload          = false;
		$isAmazonS3turned   = EDocmanHelper::isAmazonS3TurnedOn();

		if($data['select_filename'] == "-1")
		{
			$data['select_filename'] = "";
		}

		if($data['document_name'] && $isAmazonS3turned)
        {
            $document_name  = true;
        }
        else
        {
            $document_name  = false;
        }
		// Validate to make sure a category is selected for docuument
		$categoryId         = (int) $data['category_id'];
		if ($categoryId == 0)
		{
			throw new Exception (Text::_('EDOCMAN_CHOOSE_CATEGORY'));
		}

		//$categoryId > 0
        $db->setQuery("Select * from `#__edocman_categories` where id = '$categoryId'");
        $category = $db->loadObject();
		// Load the row if saving an existing document
		if ($id > 0)
		{
			$row->load($id);
			if ($input->has('del_image') && $row->image)
			{
				$documentImagePath      = JPATH_ROOT . '/media/com_edocman/document/';
				$thumbDocumentImagePath = $documentImagePath . 'thumbs/';
				if (is_file(Path::clean($documentImagePath . $row->image)))
				{
					File::delete($documentImagePath . $row->image);
				}
				if (is_file(Path::clean($thumbDocumentImagePath . $row->image)))
				{
					File::delete($thumbDocumentImagePath . $row->image);
				}
				$data['image'] 			= '';
			}
			$oldUserIds 				= $row->user_ids;
			$isNew      				= false;

			$oldFileName 				= $row->filename;
			$oldFileUrl 				= $row->document_url ?? '';
			$oldFileSize 				= $row->file_size;
			$oldCloudProvider 			= 'local';
			$oldCloudFileId 			= '';  
			$isFileChanged 				= false;
			$files 						= $input->files->get('jform', null, 'raw');
			$file 						= $files['filename'];

			if ((isset($file['tmp_name']) && is_uploaded_file($file['tmp_name'])) || 
				(!empty($data['select_filename']) && $data['select_filename'] !== $oldFileName) || 
				(!empty($data['document_url']) && $data['document_url'] !== $oldFileUrl)) {
				$isFileChanged 			= true;
			}

			if ($isFileChanged && $oldFileName && $config->get('keep_previous_versions')) 
			{
				$query->clear();
				$query->select('MAX(version_number)')
					->from('#__edocman_document_versions')
					->where('document_id = ' . (int)$id);
				$db->setQuery($query);
				$maxVersion = (int)$db->loadResult();
				$newVersion = $maxVersion + 1;

				$backupFileName = pathinfo($oldFileName, PATHINFO_FILENAME)
                    . '_v' . ($maxVersion + 1)
                    . '_' . date('YmdHis')
                    . '.' . pathinfo($oldFileName, PATHINFO_EXTENSION);

				
				if(EDocmanHelper::isDropBoxTurnedOn() || EDocmanHelper::isGdriveTurnedOn() || EDocmanHelper::isAmazonS3TurnedOn())
				{
					PluginHelper::importPlugin('edocman');
					$results = [];
					$results = $app->triggerEvent('onBackupFile', array($row, $backupFileName));
					$oldCloudProvider = "online";
					if (!empty($results) && $results[0] !== false) {
						$oldCloudFileId = $results[0];
					} 
				}
				else
				{

					if ($config->get('activate_herachical_folder_structure')) {
						$oldFilePath = $config->get('documents_path') . '/' . $oldFileName;
					} else {
						$oldFilePath = $config->get('documents_path') . '/' . basename($oldFileName);
					}
					$backupFilePath = $backupDir . '/' . $backupFileName;

					if (is_file(Path::clean($oldFilePath))) {
						File::copy($oldFilePath, $backupFilePath);
					}
				}

				$versionNote = Text::_('EDOCMAN_UPDATE_FILE');

				$columns = [
					'document_id',
					'version_number',
					'file_name',
					'file_url',
					'file_size',
					'created_by',
					'created_at',
					'note',
					'cloud_provider',
					'cloud_file_id'
				];
				$values = [
					(int)$id,
					$newVersion,
					$db->quote($backupFileName),
					$db->quote($backupFilePath),
					(int)$oldFileSize,
					(int)$user->id,
					$db->quote(date('Y-m-d H:i:s')),
					$db->quote($versionNote),
					$db->quote($oldCloudProvider),
					$db->quote($oldCloudFileId)
				];
				$query->clear();
				$query->insert('#__edocman_document_versions')
					->columns(implode(',', $columns))
					->values(implode(',', $values));
				$db->setQuery($query);
				$db->execute();
			}

			//check publish down to update reminder_email
            $publish_down = $row->publish_down;
            if($publish_down != "" && $publish_down != "0000-00-00 00:00:00" && $data['publish_down'] != "")
            {
                if($publish_down != $data['publish_down'])
                {
                    $data['send_reminder'] = 0;
                }
            }
		}
		else
		{
            $newupload                  = true;
			$auto_approval              = $category->auto_approval;
			if($auto_approval == 0)
			{
				if (!$app->isClient('administrator') && $config->get('require_admin_approve') == 0)
				{
					$data['published']  = 1;
					//do nothing
				}
				if (!$app->isClient('administrator') && $config->get('require_admin_approve') == 1)
				{
					$data['published']  = 0;
				}
			}
			elseif($auto_approval == 1)
            {
				$data['published']      = 1;
			}
			elseif($auto_approval == 2)
            {
				$data['published']      = 0;
			}
			$oldUserIds                 = '';
		}
		//File upload processing
		$files                          = $input->files->get('jform', null, 'raw');
		//$file                           = $files['filename'];
		$file = [
			'name'     => $files['name']['filename'],
			'type'     => $files['type']['filename'],
			'tmp_name' => $files['tmp_name']['filename'],
			'error'    => $files['error']['filename'],
			'size'     => $files['size']['filename'],
		];

		$image = [
			'name'     => $files['name']['image'],
			'type'     => $files['type']['image'],
			'tmp_name' => $files['tmp_name']['image'],
			'error'    => $files['error']['image'],
			'size'     => $files['size']['image'],
		];

		//print_r($file);die();
		if ($task != 'save2copy')
		{
			// Processing file upload
			if ($isNew)
			{
				// We need to check to see whether users uploaded / choose a file for this document yet
				if ((int) $config->get('file_upload_method') == 0 || !$app->isClient('administrator'))
				{
					if (!$file['name'] && empty($data['document_url']) && !$document_name)
					{
						throw new Exception(Text::_('EDOCMAN_NO_FILE_UPLOADED'));
					}
				}
				elseif( (int) $config->get('file_upload_method') == 2 )
				{
					if (!$file['name'] && empty($data['document_url']) && !$document_name && ($data['select_filename'] == '' || $data['select_filename'] == '-1'))
					{
						throw new Exception(Text::_('EDOCMAN_NO_FILE_UPLOADED'));
					}
				}
				else
				{
					if (($data['select_filename'] == '' || $data['select_filename'] == '-1') && empty($data['document_url']))
					{
						throw new Exception(Text::_('EDOCMAN_NO_FILE_UPLOADED'));
					}
				}
			}
		}

		if (is_uploaded_file($file['tmp_name']))
		{
		    $newupload        = true;
			$uploadPath       = $config->get('documents_path');
			$fileName         = $file['name'];
			$fileSize         = $file['size'];
			$maxFileSize      = $config->get('max_file_size',2);
			$maxFileSizeType  = $config->get('max_filesize_type',3);
			$maxFileSizeInBye = 2 * 1024 * 1024;
			switch ($maxFileSizeType)
			{
				case 1:
					$maxFileSizeInBye = $maxFileSize;
					break;
				case 2:
					$maxFileSizeInBye = $maxFileSize * 1024;
					break;
				case 3:
					$maxFileSizeInBye = $maxFileSize * 1024 * 1024;
					break;
			}
			if ($maxFileSizeInBye < $fileSize)
			{
				throw new Exception(Text::sprintf('EDOCMAN_FILE_TOO_BIG', $maxFileSizeInBye));
			}
			// Check file extension
			$fileExt          = strtolower(EdocmanHelper::getExt($fileName));
			$allowedFileTypes = explode(',', $config->get('allowed_file_types'));
			for ($i = 0, $n = count($allowedFileTypes); $i < $n; $i++)
			{
				$allowedFileTypes[$i] = strtolower(trim($allowedFileTypes[$i]));
			}
			if (!in_array($fileExt, $allowedFileTypes))
			{
				throw new Exception(Text::sprintf('EDOCMAN_FILETYPE_NOT_ALLOWED', $config->get('allowed_file_types')));
			}
			// Make filename safe
			if($config->get('make_filename_safely'))
			{
				$fileName = File::makeSafe($fileName);
			}
			$query->clear();
			$query->select('`path`')
				->from('#__edocman_categories')
				->where('id=' . (int) $categoryId);
			$db->setQuery($query);
			$path = $db->loadResult();
			if ($path && $config->get('activate_herachical_folder_structure'))
			{
				$uploadPath .= '/' . $path;
			}

			$savedFilename = $fileName;

			if (file_exists($uploadPath . '/' . $fileName) && !$config->get('overwrite_existing_file'))
			{
			    if(!EDocmanHelper::isDropBoxTurnedOn() && !EDocmanHelper::isGdriveTurnedOn() && !EDocmanHelper::isAmazonS3TurnedOn())
                {
                    if($config->get('position_of_unique_number') == 0)
					{
						$savedFilename  = uniqid('file_') . '_' . $fileName;
					}
					elseif($config->get('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];
					}
                }
			}

            // Give plugin a change to upload the file
            PluginHelper::importPlugin('edocman');
			$results = [];
            $results = $app->triggerEvent('onBeforeDocumentUploadProgress', array($isNew, $file));
            if (count($results) && (!in_array(true, $results, true)) && (!$app->isClient('administrator')))
            {
                throw new Exception(Text::_('EDOCMAN_UPLOAD_LIMIT_ERROR'));
            }

            $results = $app->triggerEvent('onDocumentUpload', array($row, $isNew, $file, $path, $savedFilename, $categoryId));

			$already_upload = 0;

			if((EDocmanHelper::isDropBoxTurnedOn()  || EDocmanHelper::isGdriveTurnedOn() || EDocmanHelper::isAmazonS3TurnedOn()) && EdocmanHelper::isIndexerTurnedOn())
            {
				if(! is_dir(Path::clean(JPATH_ROOT.'/tmp/edocman')))
				{
					Folder::create(JPATH_ROOT.'/tmp/edocman');
				}
				if(! is_dir(Path::clean(JPATH_ROOT.'/tmp/edocman/upload')))
				{
					Folder::create(JPATH_ROOT.'/tmp/edocman/upload');
				}
				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'],  JPATH_ROOT.'/tmp/edocman/upload/' . $savedFilename, false, true);
					}
					else
					{
						File::upload($file['tmp_name'],  JPATH_ROOT.'/tmp/edocman/upload/' . $savedFilename, false, true);
					}
					$already_upload = 1;
                }
                else
                {
                    File::upload($file['tmp_name'], JPATH_ROOT.'/tmp/edocman/upload/' . $savedFilename);
					$already_upload = 1;
                }

				PluginHelper::importPlugin('edocman');
				$results1 = $app->triggerEvent('onDocumentBeforeSave', array($row, $savedFilename, JPATH_ROOT.'/tmp/edocman/upload/' . $savedFilename));

				//print_r($results);die();

				if(count($results1) && $results1[0] != "")
				{
					$data['indexed_content'] = $results1[0];
				}

				
				//File::delete ( JPATH_ROOT.'/tmp/edocman/upload/' . $savedFilename);
			}

            if (!in_array(true, $results, true))
            {
				if(!$isNew && $config->delete_file_when_uppload_new)
				{
					if(is_file(Path::clean($config->documents_path.'/'.$row->filename)))
					{
						File::delete($config->documents_path.'/'.$row->filename);
					}
				}
				if($already_upload == 1 && file_exists(JPATH_ROOT.'/tmp/edocman/upload/' . $savedFilename))
				{
					File::copy(JPATH_ROOT.'/tmp/edocman/upload/' . $savedFilename, $uploadPath . '/' . $savedFilename);
				}
				else
				{
					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);
						}

						
					}
					else
					{
						File::upload($file['tmp_name'], $uploadPath . '/' . $savedFilename);
					}
				}
				$data['file_size'] = filesize($uploadPath . '/' . $savedFilename);
            }
            else
            {
				//get file size
				if($isNew)
				{
					$filesize = $app->triggerEvent('onFilesizeUpload', array($row, $isNew , $path, $fileName));
					if($filesize[0] > 0)
					{
						$data['file_size'] = $filesize[0];
					}
				}

				if(EDocmanHelper::isAmazonS3TurnedOn())
                {
                    $savedFilename = Factory::getApplication()->getInput()->getString('fileName');
                }
			}

			if(is_file(Path::clean(JPATH_ROOT.'/tmp/edocman/upload/' . $savedFilename)))
			{
				File::delete ( JPATH_ROOT.'/tmp/edocman/upload/' . $savedFilename);
			}
			
			if($config->get('activate_herachical_folder_structure'))
			{
				$data['filename']           = empty($path) ? $savedFilename : $path . '/' . $savedFilename;
			}
			else
			{
				$data['filename']           = $savedFilename;
			}
			$data['original_filename']      = $file['name'];
		}
		elseif (isset($data['select_filename']) && $data['select_filename']  && $data['select_filename'] != "" && !EDocmanHelper::isDropBoxTurnedOn() && !EDocmanHelper::isGdriveTurnedOn() && !EDocmanHelper::isAmazonS3TurnedOn())
		{
			//echo "1";die();
			$data['original_filename']      = $data['filename'] = $data['select_filename'];
			$data['original_filename']		= basename($data['select_filename']);
		}
		elseif($data['document_url'] != "" && ! isset($data['select_filename']) && ! is_uploaded_file($file['tmp_name']))
		{
			//echo "2";die();
			$data['original_filename']      = $data['filename'] = '';
		}
		elseif ((isset($data['select_filename']) && $data['select_filename'] == "") || (! isset($data['select_filename']) && ! $data['select_filename']) && ! is_uploaded_file($file['tmp_name']) && ! $isNew && $config->get('activate_herachical_folder_structure') && $id > 0)
        {
			//echo "3";die();
            $uploadPath             = $config->get('documents_path');
            $originalUploadPath     = $uploadPath;
            $old_category           = EDocmanHelper::getDocumentCategory($id);
            $old_category_id        = $old_category->id;
            //update 1.9.10 with new Configure option - move_document_when_changing_category


            if($old_category_id != $categoryId && $config->get('move_document_when_changing_category') == 1)
            {
                $query->clear();
                $query->select('`path`')
                    ->from('#__edocman_categories')
                    ->where('id=' . (int) $categoryId);
                $db->setQuery($query);
                $path = $db->loadResult();
                if ($path && $config->get('activate_herachical_folder_structure'))
                {
                    $uploadPath .= '/' . $path;
                }

                $query->clear();
                $query->select('filename,original_filename')->from('#__edocman_documents')->where('id="'.$id.'"');
                $db->setQuery($query);
                $document = $db->loadObject();
                $document_file = $originalUploadPath.'/'.$document->filename;
				$filename = $document->filename;
				$filenameArr = explode("/",$filename);
				if(count($filenameArr) > 1)
				{
					$filename = $filenameArr[count($filenameArr) - 1];
				}
				
                if(file_exists($document_file))
                {
                    File::copy($document_file,$uploadPath.'/'.$filename);
                    $data['filename'] = $path.'/'.$filename;
					if(is_file(Path::clean($document_file)))
					{
						File::delete($document_file);
					}
                }
            }
        }
		

        if($document_name && $isNew)
        {
            PluginHelper::importPlugin('edocman');
            $query->clear();
            $query->select('`path`')
                ->from('#__edocman_categories')
                ->where('id = ' . (int) $categoryId);
            $db->setQuery($query);
            $path = $db->loadResult();
            $results = $app->triggerEvent('onFindDocument', array($row , $path, $data['document_name']));
            if (in_array(true, $results, true))
            {
                if($config->get('activate_herachical_folder_structure'))
                {
                    $data['filename']           = $path . '/' . $data['document_name'];
                }
                $data['original_filename']      = $data['document_name'];
            }
        }
		if (isset($image['tmp_name']) && is_uploaded_file($image['tmp_name']))
		{
			if (!getimagesize($image['tmp_name']))
			{
				throw new Exception (Text::_('COM_EDOCMAN_IMAGE_ERROR'));
			}
			$documentImagePath      = JPATH_ROOT . '/media/com_edocman/document/';
			$thumbDocumentImagePath = $documentImagePath . 'thumbs/';
			if (file_exists($documentImagePath . $image['name']))
			{
				$fileName = uniqid('document_') . $image['name'];
			}
			else
			{
				$fileName = $image['name'];
			}
			if (File::upload($image['tmp_name'], $documentImagePath . $fileName))
			{
				$width  = $config->get('document_thumb_width') ;
				$height = $config->get('document_thumb_height') ;
				EDocmanHelper::resizeImage($documentImagePath . $fileName, $thumbDocumentImagePath . $fileName, $width, $height);
				if ($row->image)
				{
					if (is_file(Path::clean($documentImagePath . $row->image)))
					{
						File::delete($documentImagePath . $row->image);
					}
					if (is_file(Path::clean($thumbDocumentImagePath . $row->image)))
					{
						File::delete($thumbDocumentImagePath . $row->image);
					}
				}
				$data['image'] = $fileName;
			}
		}

		//Prepare other data
		if (isset($data['indicators']))
		{
			$data['indicators']             = implode(',', $data['indicators']);
		}
		else
		{
			$data['indicators']             = '';
		}
		//inherit from main category
		if($config->get('access_level_inheritance'))
		{
            $query->clear();
            $query->select('`accesspicker`,`access`')
                ->from('#__edocman_categories')
                ->where('id=' . (int) $categoryId);
            $db->setQuery($query);
            $accessObj                      = $db->loadObject();
            $accesspicker                   = $accessObj->accesspicker;
            $access                         = $accessObj->access;
            if($accesspicker == 0)
            {
                $data['access']             = $access;
            }
            else
            {
                $data['groups']             = explode(",", EDocmanHelper::getGroupLevels(0,$categoryId));
            }
            $data['accesspicker']           = $accesspicker;
        }

		if(count((array)$data['group_ids']) > 0)
		{
			$group_ids                      = $data['group_ids'];
			$group_ids                      = implode(",",$group_ids);
			$data['owner_group_ids']        = $group_ids;
		}
		else
		{
		    $data['owner_group_ids']        = "";
        }

		if ($task == 'save2copy')
		{
			//If no file input uploaded, we just use file from original record
			$originalDocument               = clone $row;
			$originalDocument->load($input->getInt('id'));

			if (empty($data['filename']))
			{
				$data['filename']           = $originalDocument->filename;
				$data['original_filename']  = $originalDocument->original_filename;
			}

			if (empty($data['image']))
			{
				$data['image']              = $originalDocument->image;
			}
		}
		$owner_user_ids					   = [];
		$user_ids_array					   = [];
		

		if($config->get('owner_inheritance'))
        {
            $user_ids                      = $category->user_ids;
			$user_ids_array				   = explode(",", $user_ids);

			$owner_group_ids                = $category->owner_group_ids;
            $data['owner_group_ids']        = $owner_group_ids;
        }

		if(!$app->isClient('administrator') && $isNew && $config->get('owner_assigned') && $data['user_ids'] == "")
		{   //auto assign owner user IDs
			$current_user_id				 = Factory::getApplication()->getIdentity()->id;
			if(!in_array($current_user_id, $user_ids_array))
			{
				$user_ids_array[]			 = $current_user_id;
			}
		}

		if(count($user_ids_array))
		{
			$data['user_ids']				= implode(",", $user_ids_array);
		}

        //access level
        if($data['accesspicker'] == 1)
        {
            $data['access'] = 255;
        }
        if($config->get('increase_document_version'))
        {
			if($isNew)
			{
				$document_version = (float)$data['document_version'];
				$document_version = $document_version + 1;
				$data['document_version'] = $document_version;
			}
			else
			{
				$document_version = $row->document_version;
				$document_version = (float)$document_version + 1;
				$data['document_version'] = $document_version;
			}
        }

        if($data['alias'] == "")
        {
            $alias = $data['title'];
            $alias = ApplicationHelper::stringURLSafe($alias);
            $query->clear();
            $query->select('count(id)')->from('#__edocman_documents')->where('`alias` = "'.$alias.'"');
            $db->setQuery($query);
            $count_alias = $db->loadResult();
            if($count_alias > 0)
            {
                $count_alias = (int) $count_alias + 1;
                $alias .= "-".$count_alias;
            }
            $data['alias'] = $alias;
        }
		else
		{
			$alias = $data['alias'];
			$query->clear();
            $query->select('count(id)')->from('#__edocman_documents')->where('`alias` = "'.$alias.'"');
			if($id > 0)
			{
				$query->where('id <> '.$id);
			}
            $db->setQuery($query);
            $count_alias = $db->loadResult();
            if($count_alias > 0)
            {
                $count_alias = (int) $count_alias + 1;
                $alias .= "-".$count_alias;
            }
            $data['alias'] = $alias;
		}
		$data['doc_id'] = (int) $data['doc_id'];
		$input->set('jform', $data);
		parent::save($input);
		$id = $input->getInt('id', 0);
		$row->id  = $id;
        // Give plugin a change to upload the file
        PluginHelper::importPlugin('edocman');
        $results = $app->triggerEvent('onAfterSaveDocument', array($row, $data, $isNew));

		//$id = $input->getInt('id', 0);


        if($id > 0)
        {
            $query = $db->getQuery(true);
            $query->select('count(id)')->from('#__edocman_levels')->where('data_type = 1')->where('item_id = '.$id);
            $db->setQuery($query);
            $count = $db->loadResult();

            $groups = (array)$data['groups'];
            $groups = implode(",",$groups);
            if($count == 0)
            {
                $db->setQuery("Insert into #__edocman_levels (id,data_type,item_id,`groups`) values (NULL,'1',$id,'".$groups."')");
                $db->execute();
            }
            else
            {
                $db->setQuery("Update #__edocman_levels set `groups` = '".$groups."' where data_type = 1 and item_id = $id");
                $db->execute();
            }
        }
		//google drive
        if($isNew)
        {
            $session = Factory::getApplication()->getSession();
            $fileid = $session->get('fileid','');
            $gdrive = Table::getInstance('Googledrive', 'EdocmanTable');
            $gdrive->id = 0;
            $gdrive->type = 1;
            $gdrive->element_id = $id;
			$gdrive->element_name = '';
            $gdrive->cloud_id = $fileid;
			if (!$gdrive->store()) 
			{
				//JError::raiseError(500, $row->getError() );
				throw new Exception($gdrive->getError(), 500);
			}
            $session->clear('fileid');
        }
		//Store category relationship
		if (!$isNew)
		{
			$query->clear();
			$query->delete('#__edocman_document_category')
				->where('document_id = ' . $id);
			$db->setQuery($query);
			$db->execute();
		}
		$categoryId = $data['category_id'];
		$query->clear();
		$query->insert('#__edocman_document_category')
			->columns('category_id, document_id, is_main_category')
			->values("$categoryId, $id, 1");
		$db->setQuery($query);
		$db->execute();
		if (isset($data['extra_category_ids']))
		{
			$categoryIds = $data['extra_category_ids'];
			$categoryIds = array_diff($categoryIds, array($categoryId));
			if (count($categoryIds))
			{
				foreach ($categoryIds as $categoryId)
				{
					$query->clear();
					$query->insert('#__edocman_document_category')
						->columns('category_id, document_id, is_main_category')
						->values("$categoryId, $id, 0");
					$db->setQuery($query);
					$db->execute();
				}
			}
		}

		//locked status
		if($config->get('lock_function'))
		{
			$query->clear();
			if(($data['is_locked'] == 1) && ($data['old_locked_status'] == 0)){
				$query->clear();
				$fields =  array(
					'`locked_by` = '.$user->id,
					'`locked_time` = "'.date("Y-m-d H:i:s").'"'
					);
				$query->update($db->quoteName('#__edocman_documents'))->set($fields)->where('id = "'.$id.'"');
				$db->setQuery($query);
				$db->execute();
			}
		}

		$query->clear();
		$query->delete('#__edocman_document_tags')->where('document_id=' . $id);
		$db->setQuery($query);
		$db->execute();
		
		$tags = Factory::getApplication()->getInput()->get('tags',array(),'array');
		if (count($tags))
		{
			$rowTag = Table::getInstance('Tag', 'EDocmanTable');
			//$tags   = explode(',', $data['tags']);
			foreach ($tags as $tag)
			{
				$tag = trim($tag);
				if ($tag)
				{
					$query->clear();
					$query->select('id')
						->from('#__edocman_tags')
						->where("tag=" . $db->quote($tag));
					$db->setQuery($query);
					$tagId = $db->loadResult();
					if (!$tagId)
					{
						$rowTag->id  = 0;
						$rowTag->tag = $tag;
						$rowTag->published = 1;
						$rowTag->store();
						$tagId = $rowTag->id;
					}
					// save new data docuent tags
                    $rowDocumentTag = Table::getInstance('DocumentTag', 'EDocmanTable');
					$rowDocumentTag->id = 0;
					$rowDocumentTag->document_id = $id;
					$rowDocumentTag->tag_id = $tagId;
					$rowDocumentTag->store();
				}
			}
		}

        //update association
        if($config->activate_multilingual_feature && $data['language'] != "*" && $data['language'] != "")
        {
            $query->clear();
            $doc_lang = $data['language'];
            $query->select('lang_id, lang_code, title')->from('#__languages')->where('published = 1')->where('lang_code <> "'.$doc_lang.'"')->order('ordering');
            $db->setQuery($query);
            $langs = $db->loadObjectList();
            if(count($langs))
            {
                $db->setQuery("Delete from #__edocman_associations where document_id = '$id'");
                $db->execute();

                $assocs = $input->get('assoc',array(),'array');
                foreach($langs as $lang)
                {
                    $assoc_id = (int)$assocs[$lang->lang_code];
                    if($assoc_id > 0)
                    {
                        $db->setQuery("Delete from #__edocman_associations where document_id = '$assoc_id' and lang_code = '$lang->lang_code' and assoc_lang = '".$doc_lang."'");
                        $db->execute();

						$db->setQuery("Insert into #__edocman_associations (id, document_id, lang_code, assoc_id, assoc_lang) values (NULL,'$id','$doc_lang','$assoc_id','$lang->lang_code')");
						$db->execute();
						$db->setQuery("Insert into #__edocman_associations (id, document_id, lang_code, assoc_id, assoc_lang) values (NULL,'$assoc_id','$lang->lang_code','$id','$doc_lang')");
						$db->execute();
                    }
                }
            }
        }

        //reset download log
        //echo $config->reset_downloadlog;die();
        if($config->get('reset_downloadlog'))
        {
            $query->clear();
            $query->delete('#__edocman_statistics')->where('document_id="'.$row->id.'"');
            $db->setQuery($query);
            $db->execute();

            $query->clear();
            $query->update('#__edocman_documents')->set('downloads="0"')->where('id="'.$row->id.'"');
            $db->setQuery($query);
            $db->execute();
        }

		//Reload the document object
		$row->load($id);
		if($isNew)
        {
            //generate thumbnail picture
            if($row->image == "")
            {
                EDocmanHelper::generateThumbImages($row);
            }
        }
		if ($isNew && $config->get('upload_notification') && !$app->isClient('administrator'))
		{
			EDocmanHelper::sendUploadNotificationEmail($row, $config, (int) $data['category_id']);
		}
		if (strlen(trim($row->user_ids)) && $config->get('document_assigned_notification'))
		{
			if ($isNew || ($row->user_ids != $oldUserIds))
			{
				EDocmanHelper::sendDocumentAssignedEmails($row, $oldUserIds);
			}
		}
	}


	/**
	 *
	 * Prepare the table data, before saving record to database
	 *
	 * @param JTable $row
	 * @param string $task
	 * @param array  $data
	 */
	protected function prepareTable($row, $task, $data = array())
	{
		$row->setMainCategory((int) $data['category_id']);
		if (!$row->id)
		{
			$db    = $this->getDbo();
			$query = $db->getQuery(true);
			$query->select('MAX(ordering)')
				->from('#__edocman_documents AS a')
				->innerJoin('#__edocman_document_category AS b ON a.id = b.document_id')
				->where('b.category_id = ' . (int) $data['category_id']);
			$db->setQuery($query);
			$row->ordering = 1 + (int) $db->loadResult();
		}

		parent::prepareTable($row, $task, $data);
	}

	/**
	 * Generate new title and alias when copy a document
	 *
	 * @see OSModelAdmin::generateNewTitle()
	 */
	protected function generateNewTitle($row, $alias, $title)
	{
		$db         = $this->getDbo();
		$query      = $db->getQuery(true);
		$categoryId = $row->getMainCategoryId();
		while (true)
		{
			// Check to see whether there are any documetns in same category has this alias
			$query->select('COUNT(*)')
				->from('#__edocman_documents AS a')
				->innerJoin('#__edocman_document_category AS b ON a.id = b.document_id')
				->where('b.is_main_category = 1')
				->where('a.alias=' . $db->quote($alias))
				->where('b.category_id=' . $categoryId);
			$db->setQuery($query);
			$total = $db->loadResult();
			if ($total)
			{
				$title = StringHelper::increment($title);
				$alias = StringHelper::increment($alias, 'dash');
				$query->clear();
			}
			else
			{
				break;
			}
		}

		return array($title, $alias);
	}

	/**
	 * Get document detail
	 *
	 * @return object
	 */
	function canDownload($recordId)
	{
		$db     = $this->getDbo();
		$user   = Factory::getApplication()->getIdentity();
		$userId = $user->get('id');
		$query  = $db->getQuery(true);
		if(Factory::getApplication()->isClient('administrator')){
			$query->select('*')
				->from('#__edocman_documents')
				->where('id=' . (int) $recordId);
		}else{
			$query->select('*')
				->from('#__edocman_documents')
				->where('id=' . (int) $recordId)
				->where('published=1');
		}
		$db->setQuery($query);
		$document = $db->loadObject();

		if (!$document)
		{
			return false;
		}
        if ($user->authorise('core.admin', 'com_edocman'))
        {
            return true;
        }

		$jinput = Factory::getApplication()->getInput();
		$p = $jinput->getInt('p',0);
		if($p == 1)
		{
			return true;
		}

		
		if ($document->user_ids != "" || $document->owner_group_ids != "")
		{
			if($document->user_ids != "")
			{
				$userIds = explode(',', $document->user_ids);
				if (in_array($user->get('id'), $userIds))
				{
					return true;
				}
			}

			if($document->owner_group_ids != "")
			{
				$usergroups = $user->groups;
				
				$owner_group_ids = explode(",", $document->owner_group_ids);
				if(count($owner_group_ids) > 0 && count($usergroups) > 0)
				{
					foreach($usergroups as $group)
					{
						if(in_array($group,$owner_group_ids))
						{
							return true;
						}
					}
				}          
			}
		}
		
        //if (!in_array($document->access, $user->getAuthorisedViewLevels()))
		//{
			//return false;
		//}

		if (!in_array($document->access, $user->getAuthorisedViewLevels())  && $document->accesspicker == 0)
		{
			return false;
		}
		elseif($document->accesspicker == 1)
		{
			$exists = 0;
			$usergroup          = $user->groups;
			if(count($usergroup) > 0)
			{
				foreach ($usergroup as $group)
				{
					$query->clear();
					$query->select('count(id)')->from('#__edocman_levels')->where('data_type = 1')->where('(`groups`="'.$group.'" OR `groups` LIKE "'.$group.',%" OR `groups` LIKE "%,'.$group.',%" OR `groups` LIKE "%,'.$group.'")')->where('item_id = "'.$document->id.'"');
					$db->setQuery($query);
					$count = $db->loadResult();
					if($count > 0){
						$exists = 1;
					}
				}
			}

			if($exists == 0){
				return false;
			}
		}

		$query->clear();
		$query->select('*,a.id as catid')
			->from('#__edocman_categories AS a')
			->innerJoin('#__edocman_document_category AS b ON (a.id = b.category_id AND b.is_main_category = 1)')
			->where('b.document_id = ' . $document->id);
		$db->setQuery($query);
		$category = $db->loadObject();
		if (!$category)
		{
			return false;
		}

		if($category->accesspicker == 0) {
			if (!in_array($category->access, $user->getAuthorisedViewLevels())) {
				return false;
			}
		}else{
			$exists = 0;
			$usergroup          = $user->groups;
			if(count($usergroup) > 0){
				foreach ($usergroup as $group){
					$query->clear();
					$query->select('count(id)')->from('#__edocman_levels')->where('data_type = 0')->where('(`groups`="'.$group.'" OR `groups` LIKE "'.$group.'%" OR `groups` LIKE "%,'.$group.',%" OR `groups` LIKE "%,'.$group.'")')->where('item_id = "'.$category->catid.'"');
					$db->setQuery($query);
					$count = $db->loadResult();
					if($count > 0){
						$exists = 1;
					}
				}
			}
			if($exists == 0){
				return false;
			}
		}

		// Prevents bots from downloading files
		if (!empty($_SERVER['HTTP_USER_AGENT']) and preg_match('~(bot|crawl)~i', $_SERVER['HTTP_USER_AGENT']))
		{
			return false;
		}
		// Check if the user has download permission
		$assetName = 'com_edocman.document.' . $recordId;
		if ((($document->user_ids == "" || $document->user_ids == 0)&&
				($user->authorise('edocman.download', $assetName) || $user->authorise('core.edit', $assetName) || ($userId == $document->created_user_id))) ||
			($document->user_ids && in_array($userId, explode(',', $document->user_ids))) || ($document->created_user_id == $userId)
		)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	/**
	 * Download for viewing
	 *
	 * @ $documentID int ID of Document
	 *
	**/
	static function forcedownload($documentId)
	{
		$config		= EDocmanHelper::loadConfig();
		$app		= Factory::getApplication();
		$db			= Factory::getContainer()->get('db');
		$sql		= 'SELECT * FROM #__edocman_documents WHERE id=' . $documentId;
		$db->setQuery($sql);
		$table		= $db->loadObject();
		$rootDir	= $config->get('documents_path');
		$filePath	= $rootDir . '/' . $table->filename;
		while (@ob_end_clean()) ;
		EDocmanHelper::processDownload($filePath, $table->filename, $table->original_filename,  true, $documentId);
		$app->close(0);
	}

	static function forcedownloadforviewing($documentId)
	{
		$app	    = Factory::getApplication();
		$db			= Factory::getContainer()->get('db');
		$sql		= 'SELECT * FROM #__edocman_documents WHERE id=' . $documentId;
		$db->setQuery($sql);
		$table		= $db->loadObject();
		$user		= Factory::getApplication()->getIdentity();
		$config		= EDocmanHelper::loadConfig();
		$canEdit	= $user->authorise('core.edit',		'com_edocman.document.'.$documentId);
		

		$canDownload				= EdocmanHelper::canDownload($documentId);
		$show_download				= 1;

		if($config->get('hide_download_button') || !$canDownload)
		{
			$css_file = "viewer_nodownload.css";
		}
		else
		{
            $css_file = "viewer.css";
		}
		$document	= Factory::getApplication()->getDocument();
		$document->setTitle(sprintf(Text::_('EDOCMAN_VIEW_DOCUMENT'), $table->title));
		$rootDir	= $config->get('documents_path');
		//$fileExtension = substr(strrchr($table->filename, '.'), 1);
		//$encodedFilename = md5($table->filename . time()) . '.' . $fileExtension;
		$filePath	= $rootDir . '/' . $table->filename;

		return EDocmanHelper::processDownloadtotmp($filePath, $table->filename, $table->original_filename,  true, $documentId);
	}

	/**
	 * Process downloading document
	 *
	 * @param int  $documentId ID of the document which will be downloaded
	 *
	 * @param bool $download   true if the document will be downloaded, false if the document is viewed
	 *
	 * @param bool $logDownload  if true, will log the data and send noification....
	 *
	 */
	function download($documentId, $download = true, $logDownload = true)
	{
        $logId              = 0;
        $user               = Factory::getApplication()->getIdentity();
        $db					= Factory::getContainer()->get('db');
		$session            = Factory::getApplication()->getSession();
		$send_notify        = $session->get('send_notify',1);
		$app                = Factory::getApplication();
        $jinput             = $app->getInput();
        $pass_check         = $jinput->getInt('p',0);
		$sql                = 'SELECT * FROM `#__edocman_documents` WHERE id=' . $documentId;
		$db->setQuery($sql);
		$table              = $db->loadObject();
		$config             = EDocmanHelper::loadConfig();
		$category			= EdocmanHelper::getDocumentCategory($documentId);
		
		if($config->get('onetime_collect'))
		{
			$name           = $session->get('name');
			$email          = $session->get('email');
			if($name == "")
			{
				$name       = $user->name;
			}
			if($email == "")
			{
				$email      = $user->email;
			}
		}
		else
		{
			$session->set('name','');
			$session->set('email','');
		}

		if($name == "" && $email == "" && $jinput->getString('download_code','') != "")
		{
			$name				= $jinput->getString('name','');
			$email				= $jinput->getString('email','');
		}

		//at Backend side, we don't need to check anything
		if($app->isClient('administrator'))
		{
			if ($table->document_url)
			{
				$app->redirect($table->document_url);
			}
			else
			{
				// Give plugin a change to download the file
				PluginHelper::importPlugin('edocman');
				$results = $app->triggerEvent('onDocumentDownload', array($table));
				if (in_array(true, $results, true) || count($results) == 0)
				{
					$rootDir = $config->get('documents_path');
					$filePath = $rootDir . '/' . $table->filename;
					if(!EDocmanHelper::isAmazonS3TurnedOn() && !EDocmanHelper::isDropBoxTurnedOn() && !EDocmanHelper::isGdriveTurnedOn())
                    {
                        if (!file_exists($filePath))
                        {
                            throw new \Exception(Text::_('EDOCMAN_PHYSICAL_FILE_NOT_FOUND'), 404);
                        }
                    }
					while (@ob_end_clean()) ;
					EDocmanHelper::processDownload($filePath, $table->filename, $table->original_filename, $download, $documentId);
					$app->close(0);
				}
			}
			return true;
		}

		$received_email     = $email;
        if($pass_check == 0) 
		{
            if (!$app->isClient('administrator') && $config->get('download_log')) 
			{
                // Logs
                if ($config->get('download_log')) 
				{
					$config             = EDocmanHelper::loadConfig();
                    $browser            = Browser::getInstance();
                    $row                = $this->getTable('statistic', 'EDocmanTable');
                    $row->document_id   = $documentId;
                    $row->user_id       = $user->get('id');
					$row->name          = $name;
					$row->email         = $email;
                    $row->user_ip       = @$_SERVER['REMOTE_ADDR'];
                    $row->download_time = gmdate('Y-m-d H:i:s');
                    $row->browser       = $browser->getBrowser();
                    $row->os            = $browser->getPlatform();
					$download_code      = UserHelper::genRandomPassword(20);
                    $row->download_code = $download_code;
                    $now                = Factory::getDate()->toSql();
                    //solve the duplicate case
                    $query = $db->getQuery(true)
						->select('COUNT(id)')
						->from($db->quoteName('#__edocman_statistics'))
						->where($db->quoteName('document_id') . ' = ' . (int) $documentId)
						->where($db->quoteName('user_id') . ' = ' . (int) $user->get('id'))
						->where($db->quoteName('name') . ' LIKE ' . $db->quote($name))
						->where($db->quoteName('email') . ' LIKE ' . $db->quote($email))
						->where($db->quoteName('browser') . ' LIKE ' . $db->quote($browser->getBrowser()))
						->where($db->quoteName('os') . ' LIKE ' . $db->quote($browser->getPlatform()))
						->where($db->quoteName('user_ip') . ' LIKE ' . $db->quote($row->user_ip))
						->where('TIMESTAMPDIFF(SECOND, ' . $db->quoteName('download_time') . ', ' . $db->quote($now) . ') < 3');

					$db->setQuery($query);

                    $alreadyLog = $db->loadResult();
                    if($alreadyLog == 0)
                    {
                        $row->store();
                        $logId = $db->insertid();
                    }
                }
				else
				{
					$download_code      = UserHelper::genRandomPassword(20);
				}

                // Send notification email
                if ($config->get('download_notification')) {
                    $jconfig            = new JConfig();
                    $subject            = $config->get('download_email_subject');
                    $body               = nl2br($config->download_email_body);

                    if ($user->id) {
                        $username       = $user->username;
                        $name           = $user->name;
                        $email          = $user->email;
					} elseif($name != '' && $email != ''){
						$username       = $name;
                    } else {
                        $username       = Text::_('EDOCMAN_GUEST');
                        $name           = Text::_('EDOCMAN_GUEST');
                        $email          = Text::_('EDOCMAN_GUEST');
                    }
                    $userIp 			= @$_SERVER['REMOTE_ADDR'];
                    $documentTitle 		= $table->title;
					$body				= str_replace('[CATEGORY]', $category->title, $body);
                    $body               = str_replace('[USERNAME]', $username, $body);
                    $body               = str_replace('[NAME]', $name, $body);
                    $body               = str_replace('[USER_IP]', $userIp, $body);
                    $body               = str_replace('[DOCUMENT_TITLE]', $documentTitle, $body);
					$subject            = str_replace('[DOCUMENT_TITLE]', $documentTitle, $subject);
                    $body               = str_replace('[EMAIL]', $email, $body);
					$body				= str_replace('[CATEGORY]', $category->title, $body);
                    $notificationEmails = trim($config->notification_emails);
					if(trim($category->notification_emails) != "")
					{
						$notificationEmails = trim($category->notification_emails);
					}
                    if (strlen($notificationEmails) < 5) {
                        $notificationEmails = $jconfig->mailfrom;
                    }
                    $notificationEmails = explode(',', $notificationEmails);
                    $mailer             = Factory::getContainer()->get(MailerFactoryInterface::class)->createMailer();
                    for ($i = 0, $n = count($notificationEmails); $i < $n; $i++) 
					{
                        $email          = trim($notificationEmails[$i]);
                        if ($email && $send_notify == 1) 
						{
							try
							{
								$mailer->sendMail($jconfig->mailfrom, $jconfig->fromname, $email, $subject, $body, 1);
							}
							catch (Exception $e)
							{
								Factory::getApplication()->enqueueMessage($e->getMessage(), 'warning');
							}
                            $mailer->ClearAllRecipients();
                        }
                    }
                }
            }
        }

        if($pass_check == 0)
		{
            if ($table->document_url)
            {
				$sql = 'UPDATE `#__edocman_documents` SET downloads=downloads + 1 WHERE id=' . $documentId;
				$db->setQuery($sql);
				$db->execute();
                $app->redirect($table->document_url);
            }
            elseif($config->download_type == 1 && $jinput->getString('download_code','') == "")
            {
                $user               = Factory::getApplication()->getIdentity();
                $fromName           = Factory::getApplication()->get('fromname');
                $fromEmail          = Factory::getApplication()->get('mailfrom');
                $username           = $user->username;
                $name               = $user->name;
				if($received_email  == "" && $user->id > 0){
					$received_email = $user->email;
				}
                $userIp             = @$_SERVER['REMOTE_ADDR'];
                $downloadUrl        = Uri::getInstance()->toString(array('scheme', 'user', 'pass', 'host')) . Route::_('index.php?option=com_edocman&task=document.download&id=' . $documentId . '&download_code=' . $download_code.'&name='.$name.'&email='.$received_email, false);
                $downloadLink       = '<a href="' . $downloadUrl . '">' . Text::_('EDOCMAN_CLICK_TO_DOWNLOAD') . '</a>';
                $subject            = $config->get('download_link_email_subject');
                $body               = nl2br($config->download_link_email_body);
				$body				= str_replace('[CATEGORY]', $category->title, $body);
                $subject            = str_replace('[DOCUMENT_TITLE]', $documentTitle, $subject);
                $body               = str_replace('[USERNAME]', $username, $body);
                $body               = str_replace('[NAME]', $name, $body);
                $body               = str_replace('[USER_IP]', $userIp, $body);
                $body               = str_replace('[DOCUMENT_TITLE]', $documentTitle, $body);
				$subject		    = str_replace('[DOCUMENT_TITLE]', $documentTitle, $subject);
                $body               = str_replace('[EMAIL]', $received_email, $body);
                $body               = str_replace('[DOWNLOAD_LINK]', $downloadLink, $body);
				$body				= str_replace('[CATEGORY]', $category->title, $body);
                $mailer             = Factory::getContainer()->get(MailerFactoryInterface::class)->createMailer();
                $mailer->ClearAllRecipients();
				try
				{
					$mailer->sendMail($fromEmail, $fromName, $received_email, $subject, $body, 1);
				}
				catch (Exception $e)
				{
					Factory::getApplication()->enqueueMessage($e->getMessage(), 'warning');
				}
				Factory::getApplication()->enqueueMessage(Text::_('EDOCMAN_DOWNLOAD_LINK_HAS_BEEN_SENT'));
                Factory::getApplication()->redirect($_SERVER['HTTP_REFERER']);
            }
            else
            {
                // Give plugin a change to download the file
                PluginHelper::importPlugin('edocman');
                $results = $app->triggerEvent('onDocumentDownload', array($table));
                if (in_array(true, $results, true) || count($results) == 0)
                {
                    $sql = 'UPDATE `#__edocman_documents` SET downloads=downloads + 1 WHERE id=' . $documentId;
                    $db->setQuery($sql);
                    $db->execute();
                    $rootDir = $config->get('documents_path');
                    $filePath = $rootDir . '/' . $table->filename;
                    if(!EDocmanHelper::isAmazonS3TurnedOn() && !EDocmanHelper::isDropBoxTurnedOn() && !EDocmanHelper::isGdriveTurnedOn())
                    {
                        if (!file_exists($filePath))
                        {
                            throw new \Exception(Text::_('EDOCMAN_PHYSICAL_FILE_NOT_FOUND'), 404);
                        }
                    }
                    while (@ob_end_clean()) ;
                    EDocmanHelper::processDownload($filePath, $table->filename, $table->original_filename, $download, $documentId);
                    $app->close(0);
                }
                else
                {
                    if (!$app->isClient('administrator') && $config->get('download_log') && $logId > 0)
                    {
                        $db->setQuery("Delete from `#__edocman_statistics` where id = '$logId'");
                        $db->execute();
                    }
                }
            }
        }
        else
        {   //pass_check == 1
            if ($table->document_url)
            {
                $app->redirect($table->document_url);
            }
            else
            {
                // Give plugin a change to download the file
                PluginHelper::importPlugin('edocman');
                $results = $app->triggerEvent('onDocumentDownload', array($table));
                if (in_array(true, $results, true) || count($results) == 0)
                {
                    $sql = 'UPDATE `#__edocman_documents` SET downloads=downloads + 1 WHERE id=' . $documentId;
                    $db->setQuery($sql);
                    $db->execute();
                    $rootDir = $config->get('documents_path');
                    $filePath = $rootDir . '/' . $table->filename;
                    while (@ob_end_clean()) ;
                    EDocmanHelper::processDownload($filePath, $table->filename, $table->original_filename, $download, $documentId);
                    $app->close(0);
                }
                else
                {
                    if (!$app->isClient('administrator') && $config->get('download_log') && $logId > 0)
                    {
                        $db->setQuery("Delete from #__edocman_statistics where id = '$logId'");
                        $db->execute();
                    }
                }
            }
        }
	}

	/**
	 * Can delete the document or not
	 *
	 * @param int $record
	 *
	 * @return boolean
	 */
	protected function canDelete($record)
	{
		if ($record->asset_id == 0)
		{
			return true;
		}
		if ($record->id)
		{
			return Factory::getApplication()->getIdentity()->authorise('core.delete', 'com_edocman.document.' . (int) $record->id);
		}
	}

	/**
	 * Can edit the status of the document or not
	 *
	 * @see OSModelForm::canEditState()
	 */
	protected function canEditState($record)
	{
		$user = Factory::getApplication()->getIdentity();
		if (!empty($record->category_id))
		{
			$categoryId = $record->category_id;
		}
		else
		{
			$categoryId = $this->state->catid;
		}

		if (!empty($record->id))
		{
			return $user->authorise('core.edit.state', 'com_edocman.document.' . $record->id);
		}
		elseif ($categoryId)
		{
			return $user->authorise('core.edit.state', 'com_edocman.category.' . $categoryId);
		}
		else
		{
			return parent::canEditState($record);
		}
	}

	protected function getReorderConditions($table)
	{
		$conditions = [];
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$query->select('category_id')
			->from('#__edocman_document_category')
			->where('document_id = '. $table->id)
			->where('is_main_category = 1');
		$db->setQuery($query);
		$categoryId = $db->loadResult();
		if ($categoryId > 0)
		{
			$conditions[] = " id IN (SELECT document_id FROM #__edocman_document_category WHERE category_id=$categoryId AND is_main_category=1)";
		}

		return $conditions;
	}

	/**
	 * Save document, using for editor xtd
	 *
	 * @param $input
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function saveDocument($input)
	{
		$app					= Factory::getApplication();
		$db                     = $this->getDbo();
		$query                  = $db->getQuery(true);
		$config                 = EDocmanHelper::loadConfig();
		$data                   = $input->getData();
		$file                   = $input->files->get('filename');
		$categoryId             = $input->getInt('category_id', 0);
		if ($categoryId == 0)
		{
			throw new Exception (Text::_('EDOCMAN_CHOOSE_CATEGORY'));
		}
		// Upload file first
		if (is_uploaded_file($file['tmp_name']))
		{
			$rootDir            = $config->get('documents_path');
			$fileName           = $file['name'];
			$fileSize           = $file['size'];
			$maxFileSize        = $config->get('max_file_size',2);
			$maxFileSizeType    = $config->get('max_filesize_type',3);
			$maxFileSizeInBye   = 2 * 1024 * 1024;
			switch ($maxFileSizeType)
			{
				case 1:
					$maxFileSizeInBye = $maxFileSize;
					break;
				case 2:
					$maxFileSizeInBye = $maxFileSize * 1024;
					break;
				case 3:
					$maxFileSizeInBye = $maxFileSize * 1024 * 1024;
					break;
			}
			if ($maxFileSizeInBye < $fileSize)
			{
				throw new Exception(Text::sprintf('EDOCMAN_FILE_TOO_BIG', $maxFileSizeInBye));
			}
			// Check file extension
			$fileExt            = strtolower(EdocmanHelper::getExt($fileName));
			$allowedFileTypes   = explode(',', $config->get('allowed_file_types'));
			for ($i = 0, $n = count($allowedFileTypes); $i < $n; $i++)
			{
				$allowedFileTypes[$i] = strtolower(trim($allowedFileTypes[$i]));
			}
			if (!in_array($fileExt, $allowedFileTypes))
			{
				throw new Exception(Text::sprintf('EDOCMAN_FILETYPE_NOT_ALLOWED', $config->get('allowed_file_types')));
			}
			// Make filename safe
			if($config->get('make_filename_safely'))
			{
				$fileName           = File::makeSafe($fileName);
			}
			$query->clear();
			$query->select('`path`')
				->from('#__edocman_categories')
				->where('id=' . (int) $categoryId);
			$db->setQuery($query);
			$path = $db->loadResult();
			if (($path) and ($config->get('activate_herachical_folder_structure')))
			{
				$savedFilePath  = $rootDir . '/' . $path . '/' . $fileName;
			}
			else
			{
				$savedFilePath  = $rootDir . '/' . $fileName;
			}
			if (file_exists($savedFilePath) && !$config->get('overwrite_existing_file'))
			{
				if($config->get('position_of_unique_number') == 0)
				{
					$savedFilename  = uniqid('file_') . '_' . $fileName;
				}
				elseif($config->get('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;
			}
			if (($path) && ($config->get('activate_herachical_folder_structure')))
			{
				File::upload($file['tmp_name'], $rootDir . '/' . $path . '/' . $savedFilename);
			}
			else
			{
				File::upload($file['tmp_name'], $rootDir . '/' . $savedFilename);
			}
			if (($path) && ($config->get('activate_herachical_folder_structure')))
			{
				$data['filename'] = $path . '/' . $savedFilename;
			}
			else
			{
				$data['filename'] = $savedFilename;
			}
			$data['original_filename'] = $file['name'];
		}
		else
		{
			throw new Exception(Text::_('EDOCMAN_NO_FILE_UPLOADED'));
		}

		$row                    = $this->getTable();
		$row->bind($data);
		$row->id				= 0;
        //inherit user_ids from main category
        if($config->get('owner_inheritance'))
        {
            $query->clear();
            $query->select('*')->from('#__edocman_categories')->where('id = '.$categoryId);
            $db->setQuery($query);
            $category            = $db->loadObject();
            $row->user_ids       = $category->user_ids;
			$data['user_ids']    = $row->user_ids;

			$row->owner_group_ids       = $category->owner_group_ids;
			$data['owner_group_ids']    = $row->owner_group_ids;
        }

		$auto_approval           = $category->auto_approval;
		if($auto_approval == 0)
		{
			if (!$app->isClient('administrator') && $config->get('require_admin_approve') == 0)
			{
				$data['published']  = 1;
				//do nothing
			}
			if (!$app->isClient('administrator') && $config->get('require_admin_approve') == 1)
			{
				$data['published']  = 0;
			}
		}
		elseif($auto_approval == 1)
		{
			$data['published']      = 1;
		}
		elseif($auto_approval == 2)
		{
			$data['published']      = 0;
		}

		/*
		EDocmanHelper::prepareDocument($row, $categoryId);
		if (!$row->store())
		{
			throw new Exception ($row->getError());
		}
		$input->set('id', $row->id);
		*/

		$input->set('jform', $data);
		parent::save($input);
		$id = $input->getInt('id', 0);
		$row->id  = $id;

		PluginHelper::importPlugin('edocman');
        $results = $app->triggerEvent('onAfterSaveDocument', array($row, $data, true));

		$query->clear();
		//Insert category mapping into document category table
		$query->insert('#__edocman_document_category')
			->columns('category_id, document_id, is_main_category')
			->values("$categoryId, $row->id, 1");
		$db->setQuery($query);
		$db->execute();

        //reset download log
        //echo $config->reset_downloadlog;die();
        if($config->get('reset_downloadlog'))
        {
            $query->clear();
            $query->delete('#__edocman_statistics')->where('document_id="'.$row->id.'"');
            $db->setQuery($query);
            $db->execute();

            $query->clear();
            $query->update('#__edocman_documents')->set('downloads="0"')->where('id="'.$row->id.'"');
            $db->setQuery($query);
            $db->execute();
        }

		return true;
	}
}
