<?php

/**
 * @version		   1.9.7
 * @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\Utilities\ArrayHelper;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Folder;
use Joomla\Filesystem\Path;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Environment\Browser;
use Joomla\CMS\Table\Table;

class EDocmanControllerDocument extends EDocmanController
{

	/**
	 * Contructor
	 *
	 * @param OSInput $input
	 * @param array   $config
	 */
	public function __construct(OSInput $input = null, array $config = array())
	{
		parent::__construct($input, $config);
		$this->registerTask('viewdoc', 'viewDocument');
	}

	/**
	 * Publish/unpublish the selected document
	 *
	 * @see OSControllerAdmin::publish()
	 */
	public function publish()
	{
		parent::publish();
		$Itemid     = $this->input->getInt('Itemid');
		$categoryId = $this->input->getInt('category_id', 0);
		$current_url = $this->input->getString('return','');
		if($current_url != "")
		{
			$url		= base64_decode($current_url);
		}
		elseif ($categoryId)
		{
			$url = Route::_(EDocmanHelperRoute::getCategoryRoute($categoryId, $Itemid), false);
		}
		else
		{
			$url = EDocmanHelper::getViewUrl(array('categories', 'category', 'document'));
			if (!$url)
			{
				$url = Route::_('index.php?option=com_edocman&Itemid=' . $Itemid);
			}
		}
		$this->app->redirect($url);
	}

	/**
	 * Delete the selected document
	 *
	 * @see OSModelAdmin::delete()
	 */
	function delete()
	{
		jimport('joomla.filesystem.file');
		$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();
		$redirect   = $this->input->getString('redirect','');
		$current_url = $this->input->getString('return','');
		if($redirect != "")
		{
			$url		= $redirect;
		}
		elseif($current_url != "")
		{
			$url		= base64_decode($current_url);
		}
		else
		{
			$Itemid     = $this->input->getInt('Itemid');
			$categoryId = $this->input->getInt('category_id', 0);
			$manageItemId = EDocmanHelperRoute::findView('userdocuments', 0);
			if ($manageItemId)
			{
				$url = Route::_('index.php?option=com_edocman&view=userdocuments&Itemid='.$manageItemId);
			}
			else
			{
				if ($categoryId)
				{
					$url = Route::_(EDocmanHelperRoute::getCategoryRoute($categoryId, $Itemid), false);
				}
				else
				{
					$url = EDocmanHelper::getViewUrl(array('categories', 'category', 'document'));
					if (!$url)
					{
						$url = Route::_('index.php?option=com_edocman&Itemid=' . $Itemid);
					}
				}
			}
		}

		$this->app->redirect($url);
	}

	/**
	 * Cancel add/editing document
	 *
	 * @see OSControllerAdmin::cancel()
	 */
	function cancel()
	{
		$db		= Factory::getContainer()->get('db');
		$Itemid = $this->input->getInt('Itemid');
		$data   = $this->input->post->get('jform', array(), 'array');
		$id     = $this->input->getInt('id');
		if ($id)
		{
			$model = $this->getModel();
			$model->checkin($id);
		}
		$return = $this->app->input->getString('return','');
		if($return != "")
		{
			$return = base64_decode($return);
			$this->app->redirect($return);
		}
		if($Itemid > 0)
		{
			$db->setQuery("Select `link` from #__menu where id = '$Itemid'");
			$link = $db->loadResult();
			if($link != "")
			{
				$this->app->redirect(Route::_($link));
			}
		}
		$manageItemId = EDocmanHelperRoute::findView('userdocuments', 0);
		if ($manageItemId)
		{
			$url = Route::_('index.php?option=com_edocman&view=userdocuments&Itemid='.$manageItemId);
		}
		else
		{
			$categoryId = isset($data['category_id']) ? (int) $data['category_id'] : 0;

			if ($categoryId)
			{
				$url = Route::_(EDocmanHelperRoute::getCategoryRoute($categoryId, $Itemid));
			}
			else
			{
				$url = EDocmanHelper::getViewUrl(array('categories', 'category', 'document'));
				if (!$url)
				{
					$url = Route::_('index.php?option=com_edocman&Itemid=' . $Itemid);
				}
			}
		}
		$this->app->redirect($url);
		return true;
	}

	/**
	 *Process download/view the selected document
	 *
	 */
	public function download()
	{
		$session	   = Factory::getApplication()->getSession();
		$session->set('send_notify',1);
		$name		   = $session->get('name','');
		$email		   = $session->get('email','');
		$model         = $this->getModel();
		$task          = $this->getTask();
		$userId        = Factory::getApplication()->getIdentity()->get('id');
		$config        = EDocmanHelper::getConfig();
		$logDownload   = true;
		$forceDownload = $task == 'download' ? true : false;
		$id            = $this->input->getInt('id');
		$downloadCode  = $this->input->getString('download_code');
		$document      = Factory::getApplication()->getDocument();
		$document->setMetaData( 'robots', 'noindex, nofollow' );
		if ($downloadCode && (int)$userId == 0)
		{
			$db          = Factory::getContainer()->get('db');
			$query       = $db->getQuery(true);
			$currentDate = HTMLHelper::_('date', 'Now', 'Y-m-d H:i:s');
			$query->select('document_id')
				->select("DATEDIFF(download_time, '$currentDate') AS number_days")
				->from('#__edocman_statistics')
				->where('download_code = ' . $db->quote($downloadCode));
			$db->setQuery($query);
			$document = $db->loadObject();
			if (!$document)
			{
				$this->app->enqueueMessage(Text::_('EDOCMAN_INVALID_DOWNLOAD_CODE'), 'error');
				$this->app->redirect(Uri::root());
			}

			if ($document->number_days > 3)
			{
				$this->app->enqueueMessage(Text::_('EDOCMAN_DOWNLOAD_LINK_EXPIRED'), 'error');
				$this->app->redirect(Uri::root());
			}

			$id            = $document->document_id;
			$logDownload   = false;
			$forceDownload = true;
		}
		elseif ($config->collect_downloader_information && (int)$userId == 0 && ($name == '' || $email == ''))
		{
			$this->app->enqueueMessage(Text::_('EDOCMAN_DIRECT_ACCESS_DOWNLOAD_IS_NOT_ALLOWED'), 'error');
			$this->app->redirect(Uri::root());
		}
		
		// Everything is OK, process download
		if ($model->canDownload($id))
		{
			$model->download($id, $forceDownload, $logDownload);
		}
		else
		{
			$user = Factory::getApplication()->getIdentity();
			if ($user->id)
			{
				$url = EDocmanHelper::getViewUrl(array('categories', 'category', 'document'));
				if (!$url)
				{
					$Itemid = $this->input->getInt('Itemid', 0);
					$url    = Route::_('index.php?option=com_edocman&Itemid=' . $Itemid);
				}
				$this->app->enqueueMessage(Text::_('EDOCMAN_NOT_ALLOWED_ACTION'), 'error');
				//$this->setRedirect($url);
				$this->app->redirect($url);
			}
			else
				// Give not logged in user a chance to login to download
			{
				$return = base64_encode(Uri::getInstance()->toString());
				$url    = 'index.php?option=com_users&view=login&return=' . $return;
				if ($task == 'download')
				{
					$msg = Text::_('EDOCMAN_LOGIN_TO_VIEW_DOWNLOAD');
				}
				else
				{
					$msg = Text::_('EDOCMAN_LOGIN_TO_VIEW_DOCUMENT');
				}
				$this->app->enqueueMessage($msg);
				$this->app->redirect($url);
			}
		}
	}
	
	
	public function forcedownload()
	{
		$config		   = EDocmanHelper::getConfig();
		$id			   = $this->input->getInt('id');
		$model         = $this->getModel();
		if($config->use_googleviewer)
		{
			if($config->showing_document_googleviewer)
			{
				$model->forcedownload($id);
			}
			else
			{
				if($model->canDownload($id))
				{
					$model->forcedownload($id);
				}
				else
				{
					exit(0);
				}
			}
		}
		
	}

	/**
	 *Process download/view the selected document
	 *
	 */
	public function viewDocument()
	{
		$session		= Factory::getApplication()->getSession();
		$session->set('send_notify',0);
		$model			= $this->getModel();
		$task			= $this->getTask();
		$userId			= Factory::getApplication()->getIdentity()->id;
		$config			= EDocmanHelper::getConfig();
		$id				= $this->input->getInt('id');
		$tmpl			= $this->input->getString('tmpl','');
		$itemid			= $this->input->getInt('Itemid',0);
		$db				= Factory::getContainer()->get('db');
		$db->setQuery("Select id,view_url,published, filename from #__edocman_documents where id = '$id'");
		$document		= $db->loadObject();
		$view_url		= $document->view_url;
		$published		= $document->published;
		$filename		= $document->filename;
		$user 			= Factory::getApplication()->getIdentity();
		$app			= Factory::getApplication();
		if($published == 0)
		{
			$app->enqueueMessage(Text::_('EDOCMAN_DOCUMENT_UNAVAILABLE'));
			$app->redirect(Uri::base());
			return false;
		}
		if (!EDocmanHelper::canAccessDocument($id))
		{
			
			if ($user->id) {
				// Đã login, redirect về trang chủ với thông báo
				$app->enqueueMessage(Text::_('EDOCMAN_DIRECT_ACCESS_DOWNLOAD_IS_NOT_ALLOWED'));
				$app->redirect(Uri::base());
			} else {
				// Chưa login, redirect tới trang login, kèm biến return
				$return = EDocmanHelper::currentUrl();
				$url = 'index.php?option=com_users&view=login&return=' . $return;
				$msg = Text::_('EDOCMAN_LOGIN_TO_VIEW_DOCUMENT');
				$app->enqueueMessage($msg);
				$app->redirect($url);
			}
		}
		
		PluginHelper::importPlugin('edocman');
        $results = $app->triggerEvent('onDocumentView', array($document));

		if($config->view_url && $view_url != "")
		{
			$this->app->redirect($view_url);
		}
		else
		{

			// Everything is OK, process download
			if($config->use_googleviewer && $config->showing_document_googleviewer)
			{
				$link = Uri::getInstance()->toString(array('scheme', 'user', 'pass', 'host')).Route::_('index.php?option=com_edocman&task=document.forcedownload&id='.$id.'&Itemid=9999');
				$this->setRedirect('http://docs.google.com/viewer?url='.$link);
			}
			elseif ($model->canDownload($id))
			{
				
				if(EdocmanHelper::isPDFFile($filename) && $config->pdf_view_type == 0)
				{
					$documenturl = $model->forcedownloadforviewing($id, false, false);
					if($documenturl == "")
					{
						$model->download($id, false, false);
					}
					else
					{
						$url = Uri::root().'index.php?option=com_edocman&view=document&layout=viewpdf&id='.$id;
						$url .= '&documenturl=' . urlencode($documenturl);
						$url .= ($tmpl == '') ? "&Itemid=".$itemid : (($tmpl == 'component') ? "&tmpl=component" : '');
						$this->app->redirect(Route::_($url, false, 0));
					}
				}
				elseif(EdocmanHelper::isDOCFile($filename) && $config->pdf_view_type == 0)
				{
					$documenturl = $model->forcedownloadforviewing($id, false, false);
					if($documenturl == "")
					{
						$model->download($id, false, false);
					}
					else
					{
						$url = Uri::root().'index.php?option=com_edocman&view=document&layout=viewdoc&nohtml=1&id='.$id;
						$url .= '&documenturl=' . $documenturl;
						$url .= ($tmpl == '') ? "&Itemid=".$itemid : (($tmpl == 'component') ? "&tmpl=component" : '');
						$this->app->redirect(Route::_($url, false, 0));
					}
				}
				elseif($config->use_googleviewer)
				{
					$link = Uri::getInstance()->toString(array('scheme', 'user', 'pass', 'host')).Route::_('index.php?option=com_edocman&task=document.download&p=1&id='.$id);
					$this->setRedirect('http://docs.google.com/viewer?url='.$link);
				}
				else
				{
					$model->download($id, false, false);
				}
				
			}
			else
			{
				$user = Factory::getApplication()->getIdentity();
				if ($user->id)
				{
					$url = EDocmanHelper::getViewUrl(array('categories', 'category', 'document'));
					if (!$url)
					{
						$Itemid = $this->input->getInt('Itemid', 0);
						$url    = Route::_('index.php?option=com_edocman&Itemid=' . $Itemid);
					}
					$this->app->enqueueMessage(Text::_('EDOCMAN_NOT_ALLOWED_ACTION'), 'error');
					$this->app->redirect($url);

				}
				else
					// Give not logged in user a chance to login to download
				{
					$return = base64_encode(Uri::getInstance()->toString());
					$url    = 'index.php?option=com_users&view=login&return=' . $return;
					if ($task == 'download')
					{
						$msg = Text::_('EDOCMAN_LOGIN_TO_VIEW_DONNLOAD');
					}
					else
					{
						$msg = Text::_('EDOCMAN_LOGIN_TO_VIEW_DOCUMENT');
					}
					$this->app->enqueueMessage($msg);
					$this->app->redirect($url);
				}
			}
		}
	}

	/**
	 * Edit a document
	 * @see OSControllerAdmin::edit()
	 */
	public function edit()
	{
		$this->input->set('layout', 'edit');
		parent::edit();
	}

	/**
	 * Override save function to handle redirect
	 * @see OSModelAdmin::save()
	 */
	public function save()
	{
		$ret        = parent::save();
		$Itemid     = $this->input->getInt('Itemid');
		$data       = $this->input->get('jform', array(), 'array');
		$categoryId = (int) $data['category_id'];
		$config     = EDocmanHelper::getConfig();
		if ($ret)
		{
			$return = $this->app->input->getString('return','');
			if($return != "")
			{
				$return = base64_decode($return);
				$this->app->redirect($return);
			}
            switch ($config->redirect_after_uploading)
            {
				default:
                case "0":
                    $manageItemId = EDocmanHelperRoute::findView('userdocuments', 0);
                    //$url = JRoute::_('index.php?option=com_edocman&view=userdocuments&Itemid='.$manageItemId);
                    if ($manageItemId)
                    {
                        $url = Route::_('index.php?option=com_edocman&view=userdocuments&Itemid='.$manageItemId);
                    }
                    else
                    {
                        $url = Route::_(EDocmanHelperRoute::getCategoryRoute($categoryId, 9999));
                    }
                break;
                case "1":
                    $url = Route::_(EDocmanHelperRoute::getCategoryRoute($categoryId,9999));
                break;
                case "2":
                    $url = Uri::root();
                break;
            }
		}
		else
		{
			$recordId = (int) $this->getModel()->getState()->id;
			$url      = Route::_('index.php?option=com_edocman&view=document&layout=edit&id=' . $recordId . ($categoryId ? '&catid=' . $categoryId : '') . 'Itemid=' . $Itemid);
			if($this->redirect != "")
			{
				$url = $this->redirect;
			}
		}
		if($this->message != "")
		{
			$this->app->enqueueMessage($this->message,$this->messageType);
		}
		$this->app->redirect($url);
		return $ret;
	}

	/**
	 * Method to check to see whether this user can add new document
	 *
	 * @see OSControllerAdmin::allowAdd()
	 */
	protected function allowAdd($data = array())
	{
		$user = Factory::getApplication()->getIdentity();
		if (isset($data['category_id']))
		{
			$categoryId = (int) $data['category_id'];
		}
		else
		{
			$categoryId = (int) $this->input->getInt('catid', 0);
		}
		if ($categoryId)
		{
			return $user->authorise('core.create', 'com_edocman.category.' . $categoryId);
		}
		else
		{
			return parent::allowAdd();
		}
	}

	/**
	 * Method to check whether the current user can perform edit action on the document
	 *
	 * @see OSControllerAdmin::allowEdit()
	 */
	protected function allowEdit($data = array())
	{
		// Initialise variables.
		$id     = (int) isset($data['id']) ? $data['id'] : 0;
		$user   = Factory::getApplication()->getIdentity();
		$userId = $user->get('id');

		// 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))
		{
			// Now test the owner is the user.
			$ownerId = (int) isset($data['created_user_id']) ? $data['created_user_id'] : 0;
			if (empty($ownerId) && $id)
			{
				// Need to do a lookup from the model.
				$record = $this->getModel()->getData();
				if (empty($record))
				{
					return false;
				}
				$ownerId = $record->created_user_id;
			}

			// If the owner matches 'me' then do the test.
			if ($ownerId == $userId)
			{
				return true;
			}
		}

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

	/**
	 * Method to check whether the current user is allowed to delete a record
	 *
	 * @param int id Record ID
	 *
	 * @return boolean True if allowed to delete the record. Defaults to the permission for the component.
	 *
	 */
	protected function allowDelete($id)
	{
		$db = Factory::getContainer()->get('db');
		$query = $db->getQuery(true);
		$query->select('created_user_id')->from('#__edocman_documents')->where('id="'.$id.'"');
		$db->setQuery($query);
		$created_user_id = (int) $db->loadResult();
		$canDeleteOwn	= Factory::getApplication()->getIdentity()->authorise('core.edit.own',		'com_edocman.document.'.$id) && $created_user_id == Factory::getApplication()->getIdentity()->id;
		$canedit = Factory::getApplication()->getIdentity()->authorise('core.delete', 'com_edocman.document.' . $id);
		return $canDeleteOwn || $canedit;
	}

	/**
	 * Method to check whether the current user can change status (publish, unpublish of a record)
	 *
	 * @param int $id Id of the record
	 *
	 * @return boolean True if allowed to change the state of the record. Defaults to the permission for the component.
	 *
	 */
	protected function allowEditState($id)
	{
		return Factory::getApplication()->getIdentity()->authorise('core.edit.state', 'com_edocman.document.' . $id);
	}


	/**
	 * 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');
			$response['btnClass']	= $this->input->getString('btnClass','');
			$defaultItemId			= $this->input->getInt('defaultItemId',0);
			$onclick				= $this->input->getString('onclick','');
			$editor					= $this->input->getCmd('editor', '');
			$isJoomla4				= EdocmanHelper::isJoomla4();
			$app					= Factory::getApplication();
			$app->getDocument()->addScriptOptions('EDEditor', $editor)
				->addScriptOptions('isJoomla4', $isJoomla4)
				->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">
				/*
				if (window.parent)
				{
					window.parent.jSelectEdocman(<?php echo $response['id'];?>, "<?php echo $response['title']; ?>");
				}
				*/
				window.<?php echo $onclick;?>(<?php echo $response['id'];?>,<?php echo $defaultItemId;?>, "<?php echo $response['title']; ?>","<?php echo $response['btnClass']; ?>");
			</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();
		}
	}

	/**
		Share document
	**/
	public function share_document(){
		$db				= Factory::getContainer()->get('db');
		$config			= EDocmanHelper::getConfig();
		$id				= $this->input->getInt('document_id');
		$name			= $this->input->getString('name','');
		$friend_name	= $this->input->getString('friend_name','');
		$friend_email	= $this->input->getString('friend_email','');
		$message		= $this->input->getString('message','');
		$Itemid			= $this->input->getInt('Itemid');

		$query = $db->getQuery(true);
		$query->select("title")->from("#__edocman_documents")->where("id = '".$id."'");
		$db->setQuery($query);
		
		$document_title = $db->loadResult();
		$document_url	= EDocmanHelperRoute::getDocumentRoute($id,0, $Itemid);
		//$document_link	= Uri::root().Route::_($document_url);

		$root = rtrim(Uri::root(), '/');
		$relativeUrl = ltrim(Route::_($document_url), '/');

		if (strpos($relativeUrl, basename($root)) === 0) {
			$relativeUrl = substr($relativeUrl, strlen(basename($root)) + 1);
		}

		$document_link = $root . '/' . $relativeUrl;

		$document_link  = "<a href='".$document_link."' target='_blank'>".$document_link."</a>";

		$fromName       = Factory::getApplication()->get('fromname');
		$fromEmail      = Factory::getApplication()->get('mailfrom');

		$document_share_email_subject = $config->document_share_email_subject;
		$document_share_email_content = nl2br($config->document_share_email_content);
		
		$document_share_email_content = str_replace('[FRIEND_NAME]', $friend_name, $document_share_email_content);
		$document_share_email_content = str_replace('[NAME]', $name, $document_share_email_content);
		$document_share_email_content = str_replace('[DOCUMENT_TITLE]', $document_title, $document_share_email_content);
		$document_share_email_content = str_replace('[LINK]', $document_link, $document_share_email_content);
		$document_share_email_content = str_replace('[MESSAGE]', $message, $document_share_email_content);

		$mailer         = Factory::getMailer();
		$mailer->ClearAllRecipients();
		try
		{
			if($mailer->sendMail($fromEmail, $fromName, $friend_email, $document_share_email_subject, $document_share_email_content, 1))
			{
				echo Text::_('EDOCMAN_DOCUMENT_SHARE_SUCCESSFULLY');
			}
			else
			{
				echo Text::_('EDOCMAN_PLEASE_TRY_IT_LATER');
			}
		}
		catch (Exception $e)
		{
			//JFactory::getApplication()->enqueueMessage($e->getMessage(), 'warning');
			echo $e->getMessage();
		}
		$this->app->close();
	}

	/**
	 * Store downloader information and send
	 */
	public function store_download()
	{
		$id     = $this->input->getInt('document_id');
		$data   = $this->input->getData();
		$model  = $this->getModel();
		if ($model->canDownload($id))
		{
			$message = $model->storeDownload($id, $data);
			echo $message;
			$this->app->close();
		}
		else
		{
			$url = EDocmanHelper::getViewUrl(array('categories', 'category', 'document'));
			if (!$url)
			{
				$Itemid = $this->input->getInt('Itemid', 0);
				$url    = Route::_('index.php?option=com_edocman&Itemid=' . $Itemid);
			}
			$this->app->enqueueMessage(Text::_('EDOCMAN_NOT_ALLOWED_ACTION'), 'error');
			$this->app->redirect($url);
		}
	}

	public function store_mass_download()
    {
        $id      = $this->input->getInt('document_id');
        $session = Factory::getApplication()->getSession();

        $massDownloadIdsString = $session->get('massDownloadIds', '');
		$massDownloadIds = [];
        if($massDownloadIdsString != "")
        {
            $massDownloadIds = explode(",", $massDownloadIdsString);
        }
		
        if(!in_array($id, $massDownloadIds))
        {
            $massDownloadIds[] = $id;
            $massDownloadIdsString = implode(",", $massDownloadIds);
            $session->set('massDownloadIds', $massDownloadIdsString);
		}

		echo sprintf(Text::_('EDOCMAN_HAVING_DOCUMENTS_IN_MASS_DOWNLOAD_LIST'), (int) count($massDownloadIds));

		if(count($massDownloadIds))
		{
			$link = Route::_(EDocmanHelperRoute::getViewRoute('summary',0));
			?>
			<div class="masslink">
				<a href="<?php echo $link;?>" title="<?php echo Text::_('EDOCMAN_CLICK_HERE_TO_GO_TO_MY_MASS_DOWNLOAD_LIST');?>" class="massLink">
					<?php
					echo Text::_('EDOCMAN_GO_TO_MY_MASS_DOWNLOAD_LIST');
					?>
				</a>
			</div>
			<?php
		}
        
        $this->app->close();
    }

    public function processMassDownload()
    {
        $user    = Factory::getApplication()->getIdentity();
        $userId  = $user->id;
        $config  = EDocmanHelper::getConfig();
        $session = Factory::getApplication()->getSession();
		$app	 = Factory::getApplication();
        //$massDownloadIds = $session->get('massDownloadIds', '');
		$massDownloadIds = $app->getInput()->getString('ids', $session->get('massDownloadIds', ''));
        if (!$massDownloadIds) {
            throw new Exception(JText::_('EDOCMAN_ERROR_NO_DOCUMENTS_SELECTED'), 400);
        }

        if($config->download_log)
        {
            //jimport('joomla.environment.browser');
            $browser            = Browser::getInstance();
        }
        if($massDownloadIds != "")
        {
            $massDownloadIds = explode(",", $massDownloadIds);
			if (empty($massDownloadIds)) {
				throw new Exception(Text::_('EDOCMAN_ERROR_NO_DOCUMENTS_SELECTED'), 400);
			}
            if(count($massDownloadIds))
            {
                $db         = Factory::getContainer()->get('db');
                $query      = $db->getQuery(true);
                $query->select('*')->from('#__edocman_documents')->where('id in (' . implode(",", $massDownloadIds) . ')');
                $db->setQuery($query);
                $documents  = $db->loadObjectList();
                $rootDir    = $config->documents_path;
                $zip_files_array = [];
                foreach($documents as $document)
                {
					if(!EdocmanHelper::canDownload($document->id))
					{
						continue;
					}
                    if($config->download_log)
                    {
                        $row                = &Table::getInstance('statistic', 'EDocmanTable');
                        $row->id            = 0;
                        $row->document_id   = $document->id;
                        $row->user_id       = $userId;
                        $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();
                        $row->download_code = '';
                        $row->store();
                    }
                    $filePath = $rootDir . '/' . $document->filename;
					if (!file_exists($filePath)) {
						continue;
					}
                    $zip_files_array[] = $filePath;
                }
				$session->set('massDownloadIds', '');
				$tempDir = Factory::getApplication()->get('tmp_path') . '/' . uniqid('mass_download_');
				if (!Folder::create($tempDir)) {
					throw new Exception(Text::_('EDOCMAN_ERROR_CREATING_TEMP_DIR'), 500);
				}
                $destination = $tempDir . '.zip';
                $success     = EDocmanHelper::createZipFile($zip_files_array, $destination, true);
                if($success)
                {
                    while (@ob_end_clean()) ;
                    EDocmanHelper::processMassDownload($destination);

					File::delete($destination);
			        Folder::delete($tempDir);
                    $this->app->close(0);
                }
            }
        }
    }

	public function bulkdownload()
	{
		$config		= EDocmanHelper::getConfig();
		$cid		= Factory::getApplication()->getInput()->get('cid',[],'array');
		$db         = Factory::getContainer()->get('db');
		if(count($cid))
		{
			$query      = $db->getQuery(true);
			$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,'documents.zip');
				$this->app->close(0);
			}
		}
	}

	public function removeDocumentMassList()
	{
		$id				= $this->input->getInt('id',0);
		if($id > 0)
		{
			$session	= Factory::getApplication()->getSession();
			$massDownloadIds = $session->get('massDownloadIds', '');
			if(trim($massDownloadIds) != "")
			{
				$massDownloadIds = explode(",", $massDownloadIds);
				$massDownloadIds = (array) $massDownloadIds;
				if(count((array)$massDownloadIds) > 0)
				{
					for($i=0;$i<count((array)$massDownloadIds);$i++)
					{
						if($massDownloadIds[$i] == $id)
						{
							unset($massDownloadIds[$i]);
							$massDownloadIds = implode(",", $massDownloadIds);
				            $session->set('massDownloadIds', $massDownloadIds);
						}
					}
				}
			}
			$msg = Text::_('EDOCMAN_DOCUMENT_HAS_BEEN_REMOVED_OUT_OF_MASS_DOWNLOAD_LIST');
			$this->app->enqueueMessage($msg);
		}
		$itemid		= $this->input->getInt('Itemid',0);
		$this->app->redirect(Route::_('index.php?option=com_edocman&view=summary&Itemid='.$itemid));
	}

	public function disable_license_session()
	{
		$session				= Factory::getApplication()->getSession();
		$session->set('alreadyAcceptLicense',0);
		
	}

	public function store_license_session()
	{
		$session				= Factory::getApplication()->getSession();
		$session->set('alreadyAcceptLicense',1);
		
	}

    /**
     * This function is used to add document into current user's bookmark list
     */
	public function bookmark()
    {
        $id         = $this->input->getInt('id');
        $return     = [];
		$session    = Factory::getApplication()->getSession();
		$bookmark   = $session->get('bookmark','');
        if($bookmark == '')
        {
            $bookmarkArr = [];
            $bookmarkArr[0] = $id;
			$session->set('bookmark', implode(",",$bookmarkArr));
            $return['result'] = Text::_('EDOCMAN_DOCUMENT_HAS_BEEN_ADDED_INTO_BOOKMARK_LIST');
        }
        else
        {
            $bookmarkArr = explode(",", $bookmark);
            if(!in_array($id, $bookmarkArr))
            {
                $bookmarkArr[count($bookmarkArr)] = $id;
				$session->set('bookmark', implode(",",$bookmarkArr));
                $return['result'] = Text::_('EDOCMAN_DOCUMENT_HAS_BEEN_ADDED_INTO_BOOKMARK_LIST');
            }
            else
            {
                $return['result'] = Text::_('EDOCMAN_DOCUMENT_IS_ALREADY_IN_BOOKMARK_LIST');
            }
        }
        //returns data as JSON format
        echo json_encode($return);
        exit(0);
    }

    /**
     * This function is used to remove item in documents bookmark list
     */
    public function removebookmark()
    {
        $id				= $this->input->get('cid',[],'array');
        $id				= $id[0];
        $itemId			= $this->input->getInt('Itemid');
		$session		= Factory::getApplication()->getSession();
		$bookmarkArr	= $session->get('bookmark','');
        $bookmarkArr	= explode(",", $bookmarkArr);
        if(in_array($id, $bookmarkArr))
        {
            $key = array_search($id, $bookmarkArr);
            unset($bookmarkArr[$key]);
			$session->set('bookmark', implode(",",$bookmarkArr));
        }
        $app         = Factory::getApplication();
        $app->enqueueMessage(Text::_('EDOCMAN_DOCUMENT_HAS_BEEN_REMOVED_OUT_OF_BOOKMARK_LIST'));
        $app->redirect(Route::_('index.php?option=com_edocman&view=bookmark&Itemid='.$itemId));
    }

	public function rate_document()
	{
		$user		= Factory::getApplication()->getIdentity();
		$id			= $this->input->getInt('document_id');
		$rateOpt	= $this->input->getInt('rateOpt',1);
		$db			= Factory::getContainer()->get('db');
		$db->setQuery("Insert into #__edocman_ratings (id,document_id,user_id,rate, rated_on) values (NULL,'$id','".$user->id."','$rateOpt','".date("Y-m-d", time())."')");
		$db->execute();
		echo Text::_('EDOCMAN_THANKYOU_FOR_RATING');
		exit(0);
	}

	
}
