<?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\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Table\Table;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Path;
use Joomla\Registry\Registry;
use Smalot\PdfParser\Parser;
use Joomla\Utilities\ArrayHelper;


class EdocmanControllerDocument extends EDocmanController
{

	function move_category()
	{
		$this->bootstrapHelper			= new EDocmanHelperBootstrap(EDocmanHelperHtml::getAdminBootstrapHelper());
		$this->input->set('view', 'document');
		$this->input->set('layout', 'movecategory');

		$this->display();
	}

	function duplicate()
	{
		$this->bootstrapHelper			= new EDocmanHelperBootstrap(EDocmanHelperHtml::getAdminBootstrapHelper());
		$this->input->set('view', 'document');
		$this->input->set('layout', 'duplicate');

		$this->display();
	}

	function move_subcategory()
	{
		$this->bootstrapHelper			= new EDocmanHelperBootstrap(EDocmanHelperHtml::getAdminBootstrapHelper());
		$this->input->set('view', 'document');
		$this->input->set('layout', 'movesubcategory');

		$this->display();
	}

	function docuplicate()
	{
		$config                     = EDocmanHelper::loadConfig();
        $access_level_inheritance   = $config->get('access_level_inheritance');
        $moving_category_id         = $this->input->getInt('moving_category_id',0);
        $id                         = $this->input->getInt('id',0);
        $db                         = Factory::getContainer()->get('db');
		$this->getModel()->duplicateDocument($id, $moving_category_id);
		$this->app->enqueueMessage(Text::_('EDOCMAN_DOCUMENT_HAS_BEEN_DUPLICATED'));
        $this->app->redirect('index.php?option=com_edocman&view=documents');
	}

	protected function allowAdd($data = array())
	{
		$user = Factory::getApplication()->getIdentity();

		if (isset($data['category_id']))
		{
			$categoryId = (int) $data['category_id'];
		}
		else
		{
			$categoryId = 0;
		}

		if(!Factory::getApplication()->isClient('administrator'))
		{
			
			if ($categoryId)
			{
				return $user->authorise('core.create', 'com_edocman.category.' . $categoryId);
			}
			else
			{
				return $user->authorise('core.create', 'com_edocman') || count(EDocmanHelper::getAuthorisedCategories('core.create'));
			}
		}
		else
		{
			if ($categoryId)
			{
				return $user->authorise('core.create', 'com_edocman.category.' . $categoryId);
			}
			else
			{
				return $user->authorise('core.create', 'com_edocman');
			}
		}
	}
	/**
	 * Method to check whether edit action is allowed for the given document
	 *
	 * @see OSControllerAdmin::allowEdit()
	 */
	protected function allowEdit($data = array())
	{
		// Initialise variables.
		$id   = (int) $data['id'];
		$user = Factory::getApplication()->getIdentity();
		// Check general edit permission first.
		if ($user->authorise('core.edit', 'com_edocman.document.' . $id))
		{
			return true;
		}
		// Fallback on edit.own.
		if ($user->authorise('core.edit.own', 'com_edocman.document.' . $id))
		{
			$item = $this->getModel()->getData();

			return $item->created_user_id == $user->id;
		}

		// Since there is no asset tracking, fallback to the component permissions.
		return parent::allowEdit($data);
	}

	protected function allowEditState($id)
	{
		if ((int) $id > 0)
		{
			return Factory::getApplication()->getIdentity()->authorise('core.edit.state', 'com_edocman.document.' . (int) $id);
		}
		else
		{
			return parent::allowEditState($id);
		}
	}

	/**
	 * Method to download file associated with selected document
	 */
	public function download()
	{
		$id    = $this->input->getInt('id', 0);
		$model = $this->getModel('Document');
		if ($model->canDownload($id))
		{
			$model->download($id);
		}
		else
		{
			$this->app->enqueueMessage(Text::_('EDOCMAN_NOT_ALLOWED_ACTION'));
			$this->app->redirect('index.php?option=com_edocman&view=' . $this->defaultView);
		}
	}

	/**
	 * Save document from Ajax request
	 */
	public function saveDocument()
	{
		$response = [];
		try
		{
			$model = $this->getModel('Document');
			$model->saveDocument($this->input);
			$response['success']	= 1;
			$response['id']			= $this->input->getInt('id', 0);
			$response['title']		= $this->input->getString('title');
			$defaultItemId			= $this->input->getInt('defaultItemId',0);
			$onclick				= $this->input->getString('onclick','');
			$response['btnClass']	= $this->input->getString('btnClass','');
			$editor					= $this->input->getCmd('editor', '');
			$isJoomla4				= EdocmanHelper::isJoomla4();
			$app					= Factory::getApplication();
			$app->getDocument()->addScriptOptions('EDEditor', $editor)
				->addScriptOptions('isJoomla4', true)
				->addScriptOptions('defaultItemid', $defaultItemId)
				->addScriptOptions('btnClass', $response['btnClass'])
				->getWebAssetManager()
				->useScript('core');
				
			EdocmanHelper::addScript(Uri::root() . 'components/com_edocman/assets/js/admin-documents-modal.js');
			?>
			<script type="text/javascript">
				<?php
				if(!EdocmanHelper::isJoomla4())
				{
				?>
					if (window.parent)
					{
						window.parent.jSelectEdocman(<?php echo $response['id'];?>, "<?php echo $response['title']; ?>");
					}
				<?php
				}
				else
				{
				?>
					window.<?php echo $onclick;?>(<?php echo $response['id'];?>,<?php echo $defaultItemId;?>, "<?php echo $response['title']; ?>","<?php echo $response['btnClass']; ?>");
				<?php
				}	
				?>
			</script>
		<?php
		}
		catch (Exception $e)
		{
			Factory::getApplication()->enqueueMessage($e->getMessage());
			$this->input->set('view', 'documents');
			$this->input->set('layout', 'modal');
			$this->input->set('tmpl', 'component');
			$this->input->set('choose_document_option', 1);
			$this->display();
		}
	}

	function indexcontent()
	{
		$id    = $this->input->getInt('id', 0);
		$db    = Factory::getContainer()->get('db');
		$row   = &Table::getInstance('Document', 'EDocmanTable');
		if($id > 0)
		{
			$row->load($id);
			$config = EDocmanHelper::loadConfig() ;
			if(!EDocmanHelper::isDropBoxTurnedOn() && !EDocmanHelper::isGdriveTurnedOn() && !EDocmanHelper::isAmazonS3TurnedOn())
            {
				if (file_exists($config->get('documents_path').'/'.$row->filename)) 
				{
					jimport('joomla.filesystem.file');
					$ext = strtolower(EdocmanHelper::getExt($row->filename)) ;

					if ($ext == 'pdf' || $ext == 'doc' || $ext == 'docx' || $ext == 'xlsx')
					{
						if($ext == 'pdf')
						{
							$query = $db->getQuery(true);
							$query->select('`params`')->from('#__extensions')->where('type="plugin" and `element`= "indexer" and enabled = "1"');
							$db->setQuery($query);
							$params = $db->loadResult();
							$registry = new Registry ();
							$registry->loadString ( $params );
							$data = $registry->toArray ();
							if($data['use_popen'] == 1)
							{
								require_once JPATH_ROOT.'/plugins/edocman/indexer/adapter.php' ;
								$content = IndexerAdapter::getText($config->get('documents_path').'/'.$row->filename);	
								$row->indexed_content = $content ;
								if(!$row->store())
								{
									throw new Exception($row->getError(), 500);
								}
							}
							else
							{
								require_once JPATH_ROOT . '/plugins/edocman/indexer/pdfparse/autoload.php';
								$parser = new Parser();
								$pdf = $parser->parseFile($config->get('documents_path').'/'.$row->filename);
								$content = $pdf->getText();
								$row->indexed_content = $content ;
								if(!$row->store())
								{
									throw new Exception($row->getError(), 500);
								}
							}
						}
						else
						{
							require_once JPATH_ROOT.'/plugins/edocman/indexer/adapter.php' ;
							$content = IndexerAdapter::getText($config->get('documents_path').'/'.$row->filename);	
							$row->indexed_content = $content ;
							if(!$row->store())
							{
								throw new Exception($row->getError(), 500);
							}
						}
					}
				}
			}
			else
			{
				$filePath = 
				EDocmanHelper::processDownloadtotmp('', $row->filename, $row->original_filename,  true, $id, 'tmp');
				jimport('joomla.filesystem.file');
				if($filePath != "" && file_exists($filePath))
				{
					$ext = strtolower(EdocmanHelper::getExt($row->filename)) ;
					if ($ext == 'pdf' || $ext == 'doc' || $ext == 'docx' || $ext == 'xls' || $ext == 'xlsx')
					{
						if($ext == 'pdf')
						{
							$query = $db->getQuery(true);
							$query->select('`params`')->from('#__extensions')->where('type="plugin" and `element`= "indexer" and enabled = "1"');
							$db->setQuery($query);
							$params = $db->loadResult();
							$registry = new Registry ();
							$registry->loadString ( $params );
							$data = $registry->toArray ();
							if($data['use_popen'] == 1)
							{
								require_once JPATH_ROOT.'/plugins/edocman/indexer/adapter.php' ;
								$content = IndexerAdapter::getText($filePath);	
								$row->indexed_content = $content ;
								if(!$row->store())
								{
									throw new Exception($row->getError(), 500);
								}
							}
							else
							{
								require_once JPATH_ROOT . '/plugins/edocman/indexer/pdfparse/autoload.php';
								$parser = new Parser();
								$pdf = $parser->parseFile($filePath);
								$content = $pdf->getText();
								$row->indexed_content = $content ;
								if(!$row->store())
								{
									throw new Exception($row->getError(), 500);
								}
							}
						}
						else
						{
							require_once JPATH_ROOT.'/plugins/edocman/indexer/adapter.php' ;
							$content = IndexerAdapter::getText($filePath);	
							$row->indexed_content = $content ;
							if(!$row->store())
							{
								throw new Exception($row->getError(), 500);
							}
						}
					}
					File::delete($filePath);
				}
			}
		}
		$this->app->enqueueMessage(Text::_('EDOCMAN_DOCUMENT_HAS_BEEN_INDEXED'));
		$this->app->redirect('index.php?option=com_edocman&view=documents' );
	}

    /**
     * This function is used to move main category of documents
     */
    function movingcategory()
	{
        $config                     = EDocmanHelper::loadConfig();
        $access_level_inheritance   = $config->get('access_level_inheritance');
        $moving_category_id         = $this->input->getInt('moving_category_id',0);
        $cid                        = $this->input->get('cid',[],'array');
        $db                         = Factory::getContainer()->get('db');
		$query						= $db->getQuery(true);
        if(count($cid))
		{
            foreach($cid as $id)
			{
                $query->clear();
                $query->select("count(id)")->from('#__edocman_document_category')->where('document_id="'.$id.'" and is_main_category = "1"');
                $db->setQuery($query);
                $count = $db->loadResult();

                if($count) 
				{
					$query->clear();
					$query->select("category_id")->from('#__edocman_document_category')->where('document_id="'.$id.'" and is_main_category = "1"');
					$db->setQuery($query);
					$old_category_id = $db->loadResult();

                    $query->clear();
                    $query->update('#__edocman_document_category')->set('category_id = "' . $moving_category_id . '"')->where('document_id="' . $id . '" and is_main_category = "1"');
                    $db->setQuery($query);
                    $db->execute();
                }
				else
				{
                    $query->clear();
                    $columns = array('id', 'document_id', 'category_id', 'is_main_category');
                    $values  = array('NULL',$id,$moving_category_id,'1');
                    $query->insert("#__edocman_document_category")->columns($columns)->values(implode(',',$values));
                    $db->setQuery($query);
                    $db->execute();
                }

				if($old_category_id > 0 && $old_category_id != $moving_category_id && $config->get('move_document_when_changing_category') == 1)
				{
					$uploadPath             = $config->get('documents_path');
					$originalUploadPath     = $uploadPath;					

					$query->clear();
					$query->select('`path`')
						->from('#__edocman_categories')
						->where('id=' . (int) $moving_category_id);
					$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];
					}
					//echo $uploadPath.'/'.$filename;die();
					if(file_exists($document_file))
					{
						File::copy($document_file,$uploadPath.'/'.$filename);
						$new_document_path	= $path.'/'.$filename;
						if(is_file(Path::clean($document_file)))
						{
							File::delete($document_file);
						}
						$db->setQuery("Update #__edocman_documents set `filename` = ".$db->quote($new_document_path)." where id = '$id'");
						$db->execute();
					}
				}

                $query->clear();
                $query->delete('#__edocman_document_category')->where('category_id = "'.$moving_category_id.'" and document_id="'.$id.'" and is_main_category = "0"');
                $db->setQuery($query);
                $db->execute();

                $query->clear();
                $query->select('asset_id')->from('#__edocman_categories')->where("id = '$moving_category_id'");
                $db->setQuery($query);
                $asset_id = $db->loadResult();

                if ($access_level_inheritance == 1) 
				{
                    $query->clear();
                    // Fields to update.
                    $fields = array(
                        $db->quoteName('asset_id') . ' = ' . $asset_id
                    );

                    // Conditions for which records should be updated.
                    $conditions = array(
                        $db->quoteName('id') . ' = '.$id
                    );
                    $query->update('#__edocman_documents')->set($fields)->where($conditions);
                    $db->setQuery($query);
                    $db->execute();
                }
            }
        }
		$this->app->enqueueMessage(Text::_('EDOCMAN_MOVING_CATEGORY_COMPLETED'));
        $this->app->redirect('index.php?option=com_edocman&view=documents');
    }

	function movingcategory1(){
        $config                     = EDocmanHelper::loadConfig();
        $access_level_inheritance   = $config->get('access_level_inheritance');
        $moving_category_id         = $this->input->getInt('moving_category_id1',0);
        $cid                        = $this->input->get('cid', array(),'array');
        $db                         = Factory::getContainer()->get('db');
        if((count($cid) && ($moving_category_id > 0))){
            foreach($cid as $id){
                $query      = $db->getQuery(true);

				$query->select("count(id)")->from('#__edocman_document_category')->where('document_id="'.$id.'" and category_id = "' . $moving_category_id . '" and is_main_category = "1"');
                $db->setQuery($query);
                $count1 = $db->loadResult();


				$query->clear();
                $query->select("count(id)")->from('#__edocman_document_category')->where('document_id="'.$id.'" and is_main_category <> "1"');
                $db->setQuery($query);
                $count = $db->loadResult();

				if($count1 == 0){//only process if this category isn't main category of document
					if($count) {
						$query = $db->getQuery(true);
						$query->update('#__edocman_document_category')->set('category_id = "' . $moving_category_id . '"')->where('document_id="' . $id . '" and is_main_category = "0"');
						$db->setQuery($query);
						$db->execute();
					}else{
						$query = $db->getQuery(true);
						$columns = array('id', 'document_id', 'category_id', 'is_main_category');
						$values  = array('NULL',$id,$moving_category_id,'0');
						$query->insert("#__edocman_document_category")->columns($columns)->values(implode(',',$values));
						$db->setQuery($query);
						$db->execute();
					}
				}
            }
        }
		$this->app->enqueueMessage(Text::_('EDOCMAN_MOVING_CATEGORY_COMPLETED'));
        $this->app->redirect('index.php?option=com_edocman&view=documents');
    }

    /**
     * Remove Orphan Documents
     */
    function removeorphan(){
        $db = Factory::getContainer()->get('db');
        $query = $db->getQuery(true);
        $query->select('id')->from('#__edocman_documents')->where('id not in (Select document_id from #__edocman_document_category)');
        $db->setQuery($query);
        $rows = $db->loadColumn(0);
        $document = Table::getInstance('Document','EDocmanTable');
        if(count($rows) > 0)
		{
            foreach($rows as $row)
			{
                $document->delete($row);
            }
        }
        $query->clear();
        $query->select('id')->from('#__edocman_documents')->where('id in (Select document_id from #__edocman_document_category where category_id not in (Select id from #__edocman_categories))');
        $db->setQuery($query);
        $rows = $db->loadColumn(0);
        $document = Table::getInstance('Document','EDocmanTable');
        if(count($rows) > 0)
		{
            foreach($rows as $row)
			{
                $document->delete($row);
            }
        }
		$this->app->enqueueMessage(Text::_('EDOCMAN_ORPHAN_DOCUMENTS_HAVE_BEEN_REMOVED_SUCCESSFULLY'));
        $this->app->redirect('index.php?option=com_edocman');
    }

    /**
     * Batch function
     */
    public function batch($model = null)
    {
        Session::checkToken() or jexit(Text::_('JINVALID_TOKEN'));

        // Set the model
        $model = $this->getModel('Document');
        // Preset the redirect
        $this->setRedirect('index.php?option=com_edocman&view=documents');

        return parent::batch($model);
    }

	function delete()
	{
		$cid = $this->input->get('cid', array(), 'array');

		// Sanitize the data
		$cid = ArrayHelper::toInteger($cid);

		$db = Factory::getContainer()->get('db');

		if(count($cid) > 0)
		{
			$db->setQuery("Select `image` from #__edocman_documents where id in (".implode(",", $cid).")");
			$images = $db->loadColumn(0);
			if(count($images) > 0)
			{
				foreach($images as $image)
				{
					if(is_file(Path::clean(JPATH_ROOT.'/media/com_edocman/document/thumbs/'.$image)))
					{
						File::delete(JPATH_ROOT.'/media/com_edocman/document/thumbs/'.$image);
					}
				}
			}
		}
		parent::delete();
	}

    public function copydocument()
    {

    }

	public function excluding_indexing()
	{
		$cid = $this->input->get('cid', array(), 'array');

		// Sanitize the data
		$cid = ArrayHelper::toInteger($cid);

		$db = Factory::getContainer()->get('db');
		
		if(count($cid) > 0)
		{
			$db->setQuery("Update #__edocman_documents set indexed_content = '', exclude_indexing = '1' where id in (".implode(",", $cid).")");
			$db->execute();
		}
		
		$msg = Text::_('EDOCMAN_DOCUMENTS_HAVE_BEEN_EXCLUDED_INDEXING');
		$this->setRedirect('index.php?option=com_edocman&view=documents', $msg);
	}

	public function document_remove_exclude_indexing()
	{
		$id = $this->input->getInt('id',0);
		$db = Factory::getContainer()->get('db');
		if($id > 0)
		{
			$db->setQuery("Update #__edocman_documents set exclude_indexing = '0' where id = '$id'");
			$db->execute();

			$row   = &Table::getInstance('Document', 'EDocmanTable');
			$row->load($id);
			$config = EDocmanHelper::loadConfig() ;	
			if (file_exists($config->get('documents_path').'/'.$row->filename)) 
			{
				jimport('joomla.filesystem.file');
				$ext = strtolower(EdocmanHelper::getExt($row->filename)) ;
				if ($ext == 'pdf' || $ext == 'doc' || $ext == 'docx' || $ext == 'xls' || $ext == 'xlsx')
				{
					require_once JPATH_ROOT.'/plugins/edocman/indexer/adapter.php' ;
					$content = IndexerAdapter::getText($config->get('documents_path').'/'.$row->filename);	
					$row->indexed_content = $content ;
					$row->store();
				}
			}	
		}
		$msg = Text::_('EDOCMAN_DOCUMENT_HAVS_BEEN_REMOVED_OUT_OF_EXCLUDED_INDEXING');
		$this->setRedirect('index.php?option=com_edocman&view=documents', $msg);
	}

	function documentlist()
	{
		$this->setRedirect('index.php?option=com_edocman&view=documents');
	}

	function export()
	{
		ini_set('memory_limit','999M');
		jimport('joomla.filesystem.folder');
		jimport('joomla.filesystem.file');
		jimport('joomla.filesystem.archive');
		jimport('joomla.archive.archive');

		$config  = EDocmanHelper::loadConfig();
		$csv_separator = $config->get('csv_separator',',');
		$db = Factory::getContainer()->get('db');
		$query = "Select a.title, a.original_filename, c.title as category_title from #__edocman_documents as a inner join #__edocman_document_category as b on a.id = b.document_id inner join #__edocman_categories as c on c.id = b.category_id where b.is_main_category = 1";
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		
		$labels   = [];
		$labels[] = Text::_('EDOCMAN_DOCUMENT');
		$labels[] = Text::_('EDOCMAN_ORIGINAL_FILE');
		$labels[] = Text::_('EDOCMAN_CATEGORY');

		$filecsv = JPATH_ROOT."/tmp/documents.csv";
		$fp = fopen($filecsv, 'w');
		fwrite($fp,"\xEF\xBB\xBF");
		fputcsv($fp, $labels, $csv_separator);
	
		if(count($rows))
		{
			foreach($rows as $row)
			{
				$tmp = [];
				$tmp[] = $row->title;
				$tmp[] = $row->original_filename;
				$tmp[] = $row->category_title;
				fputcsv($fp, $tmp,$csv_separator);
			}
		}
		fclose($fp);
		EdocmanHelper::processDocumentCsv($filecsv);
		Factory::getApplication()->close();
	}

	function massdownload()
	{
		$config  = EDocmanHelper::getConfig();
		$cid	 = Factory::getApplication()->getInput()->get('cid',[],'array');
		$cid	 = ArrayHelper::toInteger($cid);
		$db		 = Factory::getContainer()->get('db');
		$query   = $db->getQuery(true);
		if(count($cid))
		{
			$query->select('*')->from('#__edocman_documents')->where('id in (' . implode(",", $cid) . ')');
			$db->setQuery($query);
			$documents  = $db->loadObjectList();
			$rootDir    = $config->documents_path;
			$zip_files_array = [];
			foreach($documents as $document)
			{
				$filePath = $rootDir . '/' . $document->filename;
				$zip_files_array[] = $filePath;
			}
			$destination = JPATH_ROOT.'/tmp/'.rand(10000,99999).'.zip';
			$success     = EDocmanHelper::createZipFile($zip_files_array, $destination, true);
			if($success)
			{
				while (@ob_end_clean()) ;
				EDocmanHelper::processMassDownload($destination);
				Factory::getApplication()->close(0);
			}
		}
	}
}
