<?php

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

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Path;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\Registry\Registry;
use Joomla\CMS\Filter\InputFilter;

class EDocmanViewDocumentHtml extends OSViewHtml
{
	function display()
	{
		$db       = Factory::getContainer()->get('db');
		$document = Factory::getApplication()->getDocument();
		// Load dependencies class
		require_once JPATH_ROOT . '/components/com_edocman/helper/file.class.php';
		
		//Handle upload/delete document in a separate method
		if ($this->getLayout() == 'edit')
		{
			EdocmanHelper::addStyleSheet(Uri::root().'components/com_edocman/assets/css/document_edit.css','com_edocman.document.edit');
			$this->_displayForm();
			return;
		}
		elseif ($this->getLayout() == 'modal')
		{
			$this->_displayModal();

			return;
		}
		elseif ($this->getLayout() == 'sharing')
		{

			$this->_displaySharingModal();

			return;
		}
		elseif ($this->getLayout() == 'login')
		{
			$this->_displayLoginModal();

			return;
		}
        elseif($this->getLayout() == "edit_documents")
        {
            $this->_displayEditDocumentsForm();
            return;
        }
		elseif($this->getLayout() == "viewpdf")
        {
			$docId = Factory::getApplication()->getInput()->getInt('id');
			$itemId = Factory::getApplication()->getInput()->getInt('Itemid');
			if($itemId > 0)
			{
				$db->setQuery("Select title from `#__edocman_documents` where id = '$docId'");
				$documentTitle = $db->loadResult();
				$document->setTitle($documentTitle);
			}
			if(!EdocmanHelper::canDownload($docId))
			{
				return false;
			}
            $this->_viewpdf();

            return;
        }
		elseif($this->getLayout() == "viewdoc")
        {
            $this->_viewdoc();

            return;
        }
		
		$app      = Factory::getApplication();
		$user     = Factory::getApplication()->getIdentity();
		$query    = $db->getQuery(true);
		$config   = EDocmanHelper::getConfig();
		$userId   = $user->id;
		$model    = $this->getModel();
		$state    = $model->getState();
		$id       = $state->id;
		$option	  =	$app->getInput()->getString('option','');
		
		$related_items = [];
		$this->Itemid = Factory::getApplication()->getInput()->getInt('Itemid',0);
		// Check document access
		if (!EDocmanHelper::canAccessDocument($id))
		{
			if (!$userId)
			{
				$returnUrl = base64_encode(EDocmanHelperRoute::getDocumentRoute($id, $state->catid, $this->Itemid));
				$app->enqueueMessage(Text::_('EDOCMAN_LOGIN_TO_ACCESS'));
				$app->redirect('index.php?option=com_users&view=login&return=' . $returnUrl);
			}
			else
			{
				$url = EDocmanHelper::getViewUrl(array('categories', 'category', 'document'));
				if (!$url)
				{
					$url = Route::_('index.php?option=com_edocman&Itemid=' . $this->Itemid);
				}
				$app->enqueueMessage(Text::_('EDOCMAN_INVALID_DOCUMENT'), 'error');
				$app->redirect($url);
			}
		}

		// Make sure a valid document ID is passed in URL
		$item = $model->getData();
		if (!$item->id || !$item->published)
		{
			if (!$user->authorise('core.admin'))
			{
				$url = EDocmanHelper::getViewUrl(array('categories', 'category', 'document'));
				if (!$url)
				{
					$url = Route::_('index.php?option=com_edocman&Itemid=' . $this->Itemid);
				}
				$app->enqueueMessage(Text::_('EDOCMAN_INVALID_DOCUMENT'), 'error');
				$app->redirect($url);
			}
		}

		// Handle hits
		$model->hitCounter();

		// Handle breadcrumb
		$categoryId = $state->catid;
		if (!$categoryId)
		{
			$query->clear();
			$query->select('category_id')
				->from('#__edocman_document_category AS a')
				->where('document_id=' . (int) $id)
				->where('is_main_category=1');
			$db->setQuery($query);
			$categoryId = (int) $db->loadResult();
		}
		$menuItem = $app->getMenu()->getActive();
		$layout	  = "";
		if ($menuItem)
		{
			if (isset($menuItem->query['view']) && ($menuItem->query['view'] == 'categories' || $menuItem->query['view'] == 'category'))
			{
				$parentId = (int) $menuItem->query['id'];
				if ($categoryId)
				{
					$pathway = $app->getPathway();
					$paths   = EDocmanHelper::getCategoriesBreadcrumb($categoryId, $parentId);
					for ($i = count($paths) - 1; $i >= 0; $i--)
					{
						$category = $paths[$i];
						$pathUrl  = EDocmanHelperRoute::getCategoryRoute($category->id, $this->Itemid);
						$pathway->addItem($category->title, $pathUrl);
					}
					$pathway->addItem($item->title);
				}
			}

			if (isset($menuItem->query['view']) && $menuItem->query['view'] == 'document')
			{
				$params = new Registry() ;
				$params->loadString($menuItem->getParams());
				$this->setLayout($params->get('document_layout','default'));
				$layout = $params->get('document_layout','default');
				
			}
		}

		//find layout
		if($categoryId > 0 && $layout == '')
		{
			$canonical_link = EDocmanHelperRoute::getDocumentRoute($id, $categoryId);
			$category = EdocmanHelper::getCategory($categoryId);
			$category_layout = $category->category_layout;
			if($category_layout == "blog")
			{
				$this->setLayout('blog');
			}
			else
			{
				$this->setLayout('default');
			}
		}
		else
		{
			$canonical_link = EDocmanHelperRoute::getDocumentRoute($id, 0);
			$this->setLayout($layout);
		}
		//$document->addCustomTag('<link rel="canonical" content="'.Route::_($canonical_link, true, 0, true).'" />');

		if (strlen(trim(strip_tags($item->description))) == 0)
		{
			$item->description = $item->short_description;
		}
		else
		{
			$item->description = $item->short_description.$item->description;
		}
		if (empty($item->document_url))
		{
			$item->data		= new EDocman_File($item->id, $item->filename, $config->documents_path);
		}

		if($option != "com_content")
		{
			$metaKey			= $item->metakey;
			$metaDescription	= $item->metadesc;
			if ($metaKey)
			{
				$document->setMetaData('keywords', $metaKey);
			}
			if ($metaDescription)
			{
				$document->setMetaData('description', $metaDescription);
				$document->addCustomTag( '<meta property="og:description" content="'.$metaDescription.'" />' );
			}
			if ($item->image && is_file(Path::clean(JPATH_ROOT.'/media/com_edocman/document/thumbs/'.$item->image)))
			{
				$imgSrc = Uri::base().'media/com_edocman/document/'.$item->image ;
				$document->addCustomTag('<link rel="image_src" href="'.$imgSrc.'" />');
				$document->addCustomTag('<meta property="og:image" content="'.$imgSrc.'" />');
			}

			$document->setTitle(EdocmanHelper::getSiteTitle().$item->title);
		}

		if ($config->process_plugin)
		{
			$item->description = HTMLHelper::_('content.prepare', $item->description);
		}		
		if ($state->tmpl == 'component')
		{
			$showTaskBar	= false;
		}
		else
		{
			$showTaskBar	= true;
		}

		//check link
		$active_item_id		= $this->input->getInt('Itemid');
		$category			= EdocmanHelper::getDocumentCategory($item->id);
		$categoryId			= $category->id;
		$document_itemid	= EDocmanHelperRoute::getDocumentMenuId($item->id, $categoryId, $active_item_id);
		$catid				= $this->input->getInt('catid');
		if($document_itemid > 0 && $document_itemid != $active_item_id)
		{
			$canonicallink = Uri::getInstance()->toString(array('scheme', 'user', 'pass', 'host')).Route::_('index.php?option=com_edocman&view=document&id='.$item->id.'&Itemid='.$document_itemid);
			$document->addCustomTag('<link rel="canonical" content="'.$canonicallink.'" />');
		}
		if($catid > 0 && $catid != $categoryId)
		{
			$canonicallink = Uri::getInstance()->toString(array('scheme', 'user', 'pass', 'host')).Route::_('index.php?option=com_edocman&view=document&id='.$item->id.'&catid='.$categoryId.'&Itemid='.$document_itemid);
			$document->addCustomTag('<link rel="canonical" content="'.$canonicallink.'" />');
		}

		if($item->hide_search_engines == 1 || ($item->hide_search_engines == 2 && $config->hide_search_engines))
		{
			$document->addCustomTag('<meta name="robots" content="nofollow" />');
            $document->setMetaData( "robots", "noindex" );
		}

        $item->canView = EDocmanHelper::canView($item);

		if (count((array)$item->params))
		{
			$this->fields = $this->model->getForm()->getGroup('params');
		}
		// Set new indicator
		if ($config->day_for_new > 0)
		{
			EDocmanHelper::setNewIndicator(array($item), (int) $config->day_for_new);
		}
		// Set new indicator
		if ($config->day_for_update > 0)
		{
			EDocmanHelper::setUpdateIndicator(array($item), (int) $config->day_for_update);
		}
		if ($config->use_default_license)
		{
            $query->clear();
			$query->select('id');
			$query->from('#__edocman_licenses');
			$query->where('published=1 and default_license=1');
			$db->setQuery($query);
			$this->default_license = (int)$db->loadResult();
		}

		if($item->license_id > 0){
			$this->default_license = $item->license_id;
		}

		if($this->default_license > 0){
			$query->clear();
			$query->select('*')->from('#__edocman_licenses')->where('id = "'.$this->default_license.'"');
			$db->setQuery($query);
			$this->license = $db->loadObject();
		}

		$isRelated = 0;
        if($config->show_related_documents)
        {
            JLoader::register('EDocmanModelList', JPATH_ROOT . '/components/com_edocman/model/list.php');
		    $documentsModel    = OSModel::getInstance('List','EDocmanModel');
		    if($config->related_documents_in_same_cat)
		    {
				$isRelated = 1;
		        $documentsModel->set('filter_category_id',$categoryId);
            }
            if($config->related_documents_in_author)
            {
				$isRelated = 1;
		        $documentsModel->set('filter_created_user',$item->created_user_id);
            }
            if($config->related_documents_in_tags)
            {
                $query->clear();
                $query->select('tag_id')->from('#__edocman_document_tags')->where('document_id='.$item->id);
                $db->setQuery($query);
                $tags = $db->loadColumn(0);
				if(count($tags) > 0 || $isRelated == 1)
				{
					$isRelated = 1;
				}
                $documentsModel->set('filter_tags', $tags);
            }
            $documentsModel->set('filter_related_documents',1);
            $documentsModel->set('document_id',$item->id);
            $documentsModel->set('limit',($config->number_related_documents > 0) ? $config->number_related_documents:6);
		    $documentsModel->set('filter_order','rand()');
		    $documentsModel->set('filter_order_Dir','');
			if($isRelated == 1)
			{
				$related_items      = $documentsModel->getData();
			}
			else
			{
				$related_items      = [];
			}
        }

        PluginHelper::importPlugin('edocman');
        $plugins = Factory::getApplication()->triggerEvent('onDocumentDisplay', array($item));

		//check to see if created user is exists
		$query->clear();
		$query->select('count(id)')->from('#__users')->where('id = '.$item->created_user_id)->where('`block` = 0');
		$db->setQuery($query);
		$existing_created_user = $db->loadResult();
	
		$item->tags		   = EdocmanHelper::getTags($item->id);

		$this->existing_created_user = $existing_created_user;
		$this->item        = $item;
		$this->config      = $config;
		$this->showTaskBar = $showTaskBar;
		$this->userId      = $userId;
		$this->viewLevels  = $user->getAuthorisedViewLevels();
		$this->categoryId  = $categoryId;
		$this->category	   = EdocmanHelper::getCategory($categoryId);
		$this->related_items = $related_items;
		$this->plugins     = $plugins;
		$this->bootstrapHelper = new EDocmanHelperBootstrap($config->twitter_bootstrap_version);
		
		$this->rating	   = EdocmanHelper::getDocumentRating($item->id);

		//load modal && jQuery color box
		EDocmanHelperHtml::initModal();

		parent::display();
	}

	/**
	 * Display form allow submitting/editing document
	 */
	function _displayForm()
	{
		$app = Factory::getApplication();
        $db    = Factory::getContainer()->get('db');
		// Permission checking
		$user = Factory::getApplication()->getIdentity();
		if (!$user->id)
		{
			// Redirect user to login page
			$returnUrl = Route::_('index.php?option=com_edocman&view=document&layout=edit&Itemid=' . $this->Itemid, false);
			$app->enqueueMessage(Text::_('EDOCMAN_LOGIN_TO_UPLOAD'));
			$app->redirect(Route::_('index.php?option=com_users&view=login&return=' . base64_encode($returnUrl)));
		}
		
		$newdocument = Factory::getApplication()->getInput()->getInt('newdocument', 0);
		$id = Factory::getApplication()->getInput()->getInt('id', 0);
		if($newdocument == 1)
		{
			$this->model->set('id', 0);
			$id = 0;
		}
		else
		{
			$id = $this->model->getState()->id;
		}
		if (!$id)
		{
			$catId = $this->model->getState()->catid;
			if ($catId)
			{
				$ret   = $user->authorise('core.create', 'com_edocman.category.' . $catId);
				$query = $db->getQuery(true);
				$query->select('title')
					->from('#__edocman_categories')
					->where('id=' . $catId);
				$db->setQuery($query);
				$this->categoryTitle = $db->loadResult();
			}
			else
			{
				$ret = $user->authorise('core.create', 'com_edocman');
			}
			if (!$ret)
			{
				$app->enqueueMessage(Text::_('EDOCMAN_DO_NOT_HAVE_UPLOAD_PERMISSION'), 'error');
				$url = EDocmanHelper::getViewUrl(array('categories', 'category', 'document'));
				if (!$url)
				{
					$url = Route::_('index.php?option=com_edocman&Itemid=' . $this->input->getInt('Itemid'));
				}
				$app->redirect($url);
			}

			//limit upload
            PluginHelper::importPlugin('edocman');
			$results = [];
			$results[] = true;
            $results = $app->triggerEvent('onBeforeUploadDocument', array());
            if (in_array(false, $results, true))
            {
                $url = EDocmanHelper::getViewUrl(array('categories', 'category', 'document'));
                if (!$url)
                {
                    $url = Route::_('index.php?option=com_edocman&Itemid=' . $this->input->getInt('Itemid'));
                }
                $app->redirect($url);
            }
		}

		EdocmanHelper::addStyleSheet(Uri::base(true) . '/components/com_edocman/assets/css/form.css');
		$document           = Factory::getApplication()->getDocument();
		if (version_compare(JVERSION, '3.0.0', 'ge')) {
			HTMLHelper::_('jquery.framework');
		}
		EdocmanHelper::addScript('//code.jquery.com/ui/1.8.24/jquery-ui.min.js');
		EdocmanHelper::addStyleSheet('//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.min.css');
		$this->params = Factory::getApplication()->getParams();
		$this->state  = $this->model->getState();
		$this->item   = $this->model->getData();
		$this->form   = $this->model->getForm();
		$this->canDo  = EDocmanHelper::getActions('document', $this->state);
		$this->config = EDocmanHelper::getConfig();
		$this->catId  = (isset($catId)) ? $catId : 0; //$catId;

        $header_text  = $this->config->header_text;
        $header_text  = str_replace("[CATEGORY]",(isset($this->categoryTitle)) ? $this->categoryTitle : '',$header_text);
        $this->header_text = $header_text;

		if ($this->config->use_default_license){
			$this->default_license = EdocmanHelper::getDefaultLicense();
		}

		if($this->item->license_id > 0){
			$this->default_license = $this->item->license_id;
		}

        switch ($this->config->use_simple_upload_form)
        {
            case "2":
                if($id > 0)
                {
                    $this->setLayout('edit');
                }
                else
                {
                    EDocmanHelperJquery::upload();
                    $maxFilesize = $this->config->max_file_size ? (int)$this->config->max_file_size : 2;
                    $maxFilesizeType = $this->config->max_filesize_type ? (int)$this->config->max_filesize_type : 3;
                    if ($maxFilesizeType == 1) {
                        $maxFilesize = ceil($maxFilesize / (1024 * 1024));
                    } elseif ($maxFilesizeType == 2) {
                        $maxFilesize = ceil($maxFilesize / 1024);
                    }
                    if (!$maxFilesize) {
                        $maxFilesize = 2;
                    }
                    $allowedFiletypes = $this->config->allowed_file_types;
                    if (!$allowedFiletypes) {
                        $allowedFiletypes = 'doc, docx, ppt, pptx, pdf, zip, rar, png, zipx';
                    }
                    $allowedFiletypes = explode(',', $allowedFiletypes);
                    $allowedFiletypes = array_map('trim', $allowedFiletypes);
                    $this->maxFilesize = $maxFilesize;
                    $this->allowedFiletypes = implode(',', $allowedFiletypes);
                    $this->setLayout('ajax');
                }
                break;
            case "1":
                $this->setLayout('simple');
                break;
        }

		$this->bootstrapHelper = new EDocmanHelperBootstrap($this->config->twitter_bootstrap_version);

		$documentTags = EdocmanHelper::getTags($this->item->id);

		$this->tags	  = $documentTags;

		parent::display();
	}

    /**
     * This function is used to edit documents uploaded through Ajax mode
     */
	function _displayEditDocumentsForm()
    {
        $session                = Factory::getApplication()->getSession();
        $config                 = EDocmanHelper::getConfig();
        $files                  = $session->get('files', array());
        $filesize               = $session->get('filesize', array());
        $originalFiles          = $session->get('originalFiles', array());
        $fileid                 = $session->get('fileid', array());
        $form                   = Factory::getApplication()->getInput()->get('jform',array(),'array');
        $category_id            = $form['category_id'];
        $this->category_id      = $category_id;
        $this->files            = $files;
        $this->filesize         = $filesize;
        $this->originalFiles    = $originalFiles;
        $this->fileid           = $fileid;
        $this->bootstrapHelper	= new EDocmanHelperBootstrap($config->twitter_bootstrap_version);
        parent::display();
    }

	function _displayModal()
	{
		$model					= $this->getModel();
		$item					= $model->getData();
		$bootstrapHelper		= new EDocmanHelperBootstrap($config->twitter_bootstrap_version);
		$config                 = EDocmanHelper::getConfig();
		echo EDocmanHelperHtml::loadCommonLayout('common/modalj4.php', array('bootstrapHelper' => $bootstrapHelper,'config' => $config, 'item' => $item));
	}

	function _displaySharingModal()
	{
		$model					= $this->getModel();
		$item					= $model->getData();
		$bootstrapHelper		= new EDocmanHelperBootstrap($config->twitter_bootstrap_version);
		$config                 = EDocmanHelper::getConfig();
		echo EDocmanHelperHtml::loadCommonLayout('common/sharingj4.php', array('bootstrapHelper' => $bootstrapHelper,'config' => $config, 'item' => $item));
	}

	function _displayLoginModal()
	{
		$model					= $this->getModel();
		$item					= $model->getData();
		$bootstrapHelper		= new EDocmanHelperBootstrap($config->twitter_bootstrap_version);
		$config                 = EDocmanHelper::getConfig();
		echo EDocmanHelperHtml::loadCommonLayout('common/loginj4.php', array('bootstrapHelper' => $bootstrapHelper,'config' => $config, 'item' => $item));
	}

	function _viewpdf()
	{
		$filter						= new InputFilter();
		$input						= Factory::getApplication()->getInput();
		$id							= $input->getInt('id', 0);
		$documenturl				= $input->getString('documenturl','');
		$documenturl				= $filter->clean($documenturl);
		$user						= Factory::getApplication()->getIdentity();
		$config						= EDocmanHelper::loadConfig();
		$canDownload				= EdocmanHelper::canDownload($id);
		
		$this->documenturl			= $documenturl;
		parent::display();
	}


	function _viewdoc()
	{
		$filter						= new InputFilter();
		$input						= Factory::getApplication()->getInput();
		$id							= $input->getInt('id', 0);
		$documenturl				= $input->getString('documenturl','');
		$documenturl				= $filter->clean($documenturl);
		$user						= Factory::getApplication()->getIdentity();
		$config						= EDocmanHelper::loadConfig();
		$canDownload				= EdocmanHelper::canDownload($id);
		$this->documenturl			= $documenturl;
		require JPATH_ROOT.'/components/com_edocman/helper/phpword/vendor/autoload.php';
		parent::display();
	}
}
