<?php

/**
 * @version        1.9.7
 * @package        Joomla
 * @subpackage     Edocman
 * @author         Dang Thuc Dam
 * @copyright      Copyright (C) 2011 - 2025 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */

// No direct access
defined('_JEXEC') or die();
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\Updater\Updater;
use Joomla\Component\Installer\Administrator\Model\UpdateModel;
use Joomla\Filesystem\Folder;
use Joomla\Filesystem\Path;
use Joomla\Filesystem\File;
use Joomla\CMS\Table\Table;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\Registry\Registry;
use Joomla\Application\Web\WebClient;
use Joomla\CMS\Environment\Browser;

class EDocmanController extends OSControllerAdmin
{
	/**
	 * Method to display a view.
	 *
	 * @param    boolean $cachable  If true, the view output will be cached
	 * @param    array   $urlparams An array of safe url parameters and their variable types, for valid values see {@link JFilterInput::clean()}.
	 *
	 * @return    OSControllerAdmin        This object to support chaining.
	 */
	public function display($cachable = false, array $urlparams = [])
	{
		$wa      = Factory::getApplication()->getDocument()->getWebAssetManager();
		$wa->registerAndUseStyle('com_edocman.style', Uri::root() . 'administrator/components/com_edocman/assets/css/style.css');
		if (version_compare(JVERSION, '4.0.0-dev', 'ge'))
		{
			$wa->registerAndUseStyle('com_edocman.style4', Uri::root() . 'administrator/components/com_edocman/assets/css/style4.css');
		}
        $wa->registerAndUseStyle('com_edocman.font', Uri::root() . 'administrator/components/com_edocman/assets/css/font.css');
		
		// Thêm CSS/JS exportimport nếu cần
		$view = $this->input->get('view');
    	if (in_array($view, ['exportimport', 'exportdb', 'exportdb'])) {
			$wa->registerAndUseStyle('com_edocman.exportimport', Uri::root() . 'administrator/components/com_edocman/assets/css/exportimport.css');
			$wa->registerAndUseScript('com_edocman.exportimport', Uri::root() . 'administrator/components/com_edocman/assets/js/exportimport.js');
		}
		parent::display();

		EdocmanHelper::displayCopyright();

		return $this;
	}

	/**
	 * Run update script to update database schema to latest version
	 */
	function upgrade()
	{
		require_once JPATH_ROOT . '/administrator/components/com_edocman/install.edocman.php';
		com_edocmanInstallerScript::com_install();
	}

	/**
	 * Check to see the installed version is up to date or not
	 *
	 * @return int 0 : error, 1 : Up to date, 2 : outof date
	 */
	function check_update()
	{
		$installedVersion = EDocmanHelper::getInstalledVersion();
		$result           = array();
		$result['status'] = 0;

		$params        = ComponentHelper::getComponent('com_installer')->getParams();		
		$cache_timeout = $params->get('cachetimeout', 6, 'int');
		$cache_timeout = 3600 * $cache_timeout;
		// Get the minimum stability.
		$minimum_stability = (int) $params->get('minimum_stability', Updater::STABILITY_STABLE);

		if (EdocmanHelper::isJoomla4())
		{
			/* @var UpdateModel $model */
			$model = Factory::getApplication()->bootComponent('com_installer')->getMVCFactory()
				->createModel('Update', 'Administrator', ['ignore_request' => true]);
		}
		else
		{
			BaseDatabaseModel::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_installer/models');
			/** @var InstallerModelUpdate $model */
			$model = BaseDatabaseModel::getInstance('Update', 'InstallerModel');
		}
		$model->purge();
		$db    = Factory::getContainer()->get('db');
		$query = $db->getQuery(true);
		$query->select('extension_id')
			->from('#__extensions')
			->where('`type` = "package"')
			->where('`element` = "pkg_edocman"');
		$db->setQuery($query);
		$eid = (int) $db->loadResult();
		$result['status'] = 0;
		if ($eid)
		{
			$ret = Updater::getInstance()->findUpdates($eid, $cache_timeout, $minimum_stability);
			if ($ret)
			{
				$model->setState('list.start', 0);
				$model->setState('list.limit', 0);
				$model->setState('filter.extension_id', $eid);
				$updates          = $model->getItems();
				$result['status'] = 2;
				if (count($updates))
				{
					$result['status']  = 2;
					$result['message'] = Text::sprintf('EDOCMAN_UPDATE_CHECKING_UPDATEFOUND', $updates[0]->version);
				}
				else
				{
					$result['status']  = 2;
					$result['message'] = Text::sprintf('EDOCMAN_UPDATE_CHECKING_UPDATEFOUND', null);
				}
			}
			else
			{
				$result['status']  = 1;
				$result['message'] = Text::_('EDOCMAN_UPDATE_CHECKING_UPTODATE');
			}
		}
		echo json_encode($result);
		Factory::getApplication()->close();
	}
	
	public function rebuild_categories()
	{
		require_once JPATH_ADMINISTRATOR.'/components/com_edocman/table/category.php';
		$db = Factory::getContainer()->get('db');
		$query = $db->getQuery(true);
		$arrCats    = array(0);
		while (count($arrCats))
		{
			$catId = array_pop($arrCats);
			$query->clear();
			$query->select('id')
				->from('#__edocman_categories')
				->where('parent_id = '. $catId);
			$db->setQuery($query);
			$rows = $db->loadObjectList();
			for ($i = 0, $n = count($rows); $i < $n; $i++)
			{
				$row       = $rows[$i];
				$arrCats[] = $row->id;
				$rowCategory = Table::getInstance('Category', 'EDocmanTable');
				$rowCategory->load($row->id);
				if ($rowCategory->id)
				{
					$rowCategory->store();
				}
			}
		}
	}


	public function rebuild_documents()
	{
		require_once JPATH_ADMINISTRATOR.'/components/com_edocman/table/document.php';
		$db = Factory::getContainer()->get('db');
		$query = $db->getQuery(true);
		$query->select('a.id, b.category_id')
			->from('#__edocman_documents AS a')
			->innerJoin('#__edocman_document_category AS b ON (a.id = b.document_id AND b.is_main_category = 1)');
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		for ($i = 0, $n = count($rows); $i < $n; $i++)
		{
			$row       = $rows[$i];
			$arrCats[] = $row->id;
			$rowDocument = new EDocmanTableDocument($db);
			$rowDocument->load($row->id);
			if ($rowDocument->id)
			{
				$rowDocument->setMainCategory($row->category_id);
				$rowDocument->store();
			}
		}
	}

	public function regenerate_pictures()
    {
        $db = Factory::getContainer()->get('db');
        $db->setQuery("Select * from #__edocman_documents");
        $rows = $db->loadObjectList();
        if(count($rows) > 0)
        {
            foreach($rows as $row)
            {
                EDocmanHelper::generateThumbImages($row);
            }
        }
		//Factory::getApplication()->enqueueMessage('Thumbnail pictures have been created');
		$this->setRedirect('index.php?option=com_edocman','Thumbnail pictures have been created');
    }


    /**
     * Method to run batch operations.
     *
     * @param   JModelLegacy  $model  The model of the component being processed.
     *
     * @return	boolean	 True if successful, false otherwise and internal error is set.
     *
     * @since	12.2
     */
    public function batch($model)
    {
        $vars = $this->input->post->get('batch', array(), 'array');
        $cid  = $this->input->post->get('cid', array(), 'array');
        // Attempt to run the batch operation.
        if ($model->batch($vars, $cid))
        {
            $this->setMessage(Text::_('JLIB_APPLICATION_SUCCESS_BATCH'));
            return true;
        }
        else
        {
            $this->setMessage(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_FAILED', $model->getError()), 'warning');
            return false;
        }
    }

	public function updatedatabase(){
        //Get document path config option
        $db = Factory::getContainer()->get('db');
        $sql = 'SELECT config_value FROM #__edocman_configs WHERE config_key="documents_path"';
        $db->setQuery($sql);
        $path = $db->loadResult();
        if (!$path)
        {
            $path = JPATH_ROOT . '/edocman';
            if (!is_dir(Path::clean($path)))
            {
                //Create the folder
                Folder::create($path);
                //Copy htaccess file
                File::copy(JPATH_ADMINISTRATOR . '/components/com_edocman/htaccess.txt', $path . '/.htaccess');
            }
            $path = str_replace("\\", "/", $path);
            $sql  = 'UPDATE #__edocman_configs SET config_value="' . $path . '" WHERE config_key="documents_path"';
            $db->setQuery($sql);
            $db->execute();
        }

        $sql = 'SELECT config_value FROM #__edocman_configs WHERE config_key="default_sort_option"';
        $db->setQuery($sql);
        $defaultSortOption = $db->loadResult();
        if ($defaultSortOption)
        {
            $defaultSortOption = str_replace('a.', 'tbl.', $defaultSortOption);
            $sql               = "UPDATE #__edocman_configs SET config_value='$defaultSortOption' WHERE config_key='default_sort_option'";
            $db->setQuery($sql);
            $db->execute();
        }

        $fields = array_keys($db->getTableColumns('#__edocman_licenses'));
        if (!in_array('default_license', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_licenses` ADD `default_license` tinyint(1) NOT NULL DEFAULT '0' AFTER `published`;";
            $db->setQuery($sql);
            $db->execute();
        }


        $fields = array_keys($db->getTableColumns('#__edocman_categories'));
        if (in_array('directory', $fields))
        {
            //We need to update data here
            $sql = 'SELECT a.id, a.filename, c.path 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 b.category_id = c.id ';
            $db->setQuery($sql);
            $rows = $db->loadObjectList();
            for ($i = 0, $n = count($rows); $i < $n; $i++)
            {
                $row = $rows[$i];
                if ($row->path)
                {
                    $newFileName = $row->path . '/' . $row->filename;
                    $sql         = 'UPDATE #__edocman_documents SET filename="' . $newFileName . '" WHERE id=' . $row->id;
                    $db->setQuery($sql);
                    $db->execute();
                }
            }
            //Now, remove the unnecessary columns
            $sql = 'ALTER TABLE #__edocman_categories DROP COLUMN `directory`';
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('path', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_categories` ADD  `path` VARCHAR( 255 ) NULL DEFAULT  '';";
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('level', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_categories` ADD  `level` TINYINT( 4 ) NOT NULL DEFAULT '1';";
            $db->setQuery($sql);
            $db->execute();

            // Update level for categories
            $query = $db->getQuery(true);
            $query->select('id, title, parent_id');
            $query->from('#__edocman_categories');
            $query->where('published=1');
            $db->setQuery($query);
            $rows = $db->loadObjectList();
            // first pass - collect children
            if (count($rows))
            {
                $children = array();
                foreach ($rows as $v)
                {
                    $pt   = $v->parent_id;
                    $list = @$children[$pt] ? $children[$pt] : array();
                    array_push($list, $v);
                    $children[$pt] = $list;
                }

                require_once JPATH_ROOT . '/components/com_edocman/helper/helper.php';
                $list = EDocmanHelper::calculateCategoriesLevel(0, array(), $children, 4);
                foreach ($list as $id => $category)
                {
                    $sql = "UPDATE #__edocman_categories SET `level`=$category->level WHERE id=$id";
                    $db->setQuery($sql);
                    $db->execute();
                }
            }

        }

        if (!in_array('user_ids', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_categories` ADD  `user_ids` VARCHAR( 255 ) NULL DEFAULT  '';";
            $db->setQuery($sql);
            $db->execute();
        }


        if (!in_array('notify_group_ids', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_categories` ADD  `notify_group_ids` VARCHAR( 255 ) NULL DEFAULT  '';";
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('language', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_categories` ADD  `language` VARCHAR( 50 ) NULL DEFAULT  '*';";
            $db->setQuery($sql);
            $db->execute();

            $sql = 'UPDATE #__edocman_categories SET `language`="*" ';
            $db->setQuery($sql);
            $db->execute();
        }
        if (!in_array('notification_emails', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_categories` ADD  `notification_emails` VARCHAR( 255 ) NULL DEFAULT  '';";
            $db->setQuery($sql);
            $db->execute();
        }
        $fields = array_keys($db->getTableColumns('#__edocman_documents'));
        if (!in_array('user_ids', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_documents` ADD  `user_ids` VARCHAR( 255 ) NULL DEFAULT  '';";
            $db->setQuery($sql);
            $db->execute();
        }
        if (!in_array('language', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_documents` ADD  `language` VARCHAR( 50 ) NULL DEFAULT  '*';";
            $db->setQuery($sql);
            $db->execute();

            $sql = 'UPDATE `#__edocman_documents` SET `language`="*" ';
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('indexed_content', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_documents` ADD  `indexed_content` text NULL DEFAULT  '';";
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('tags', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_documents` ADD  `tags` text NULL DEFAULT NULL;";
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('indicators', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_documents` ADD  `indicators` VARCHAR( 50 ) NULL;";
            $db->setQuery($sql);
            $db->execute();
        }
        if (!in_array('publish_up', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_documents` ADD  `publish_up` datetime NOT NULL DEFAULT '0000-00-00 00:00:00';";
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('publish_down', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_documents` ADD  `publish_down` datetime NOT NULL DEFAULT '0000-00-00 00:00:00';";
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('params', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_documents` ADD  `params` text NULL DEFAULT  '';";
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('view_url', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_documents` ADD  `view_url` varchar(255) DEFAULT '';";
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('file_size', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_documents` ADD  `file_size` varchar(100) NOT NULL;";
            $db->setQuery($sql);
            $db->execute();
        }

        $fields = array_keys($db->getTableColumns('#__edocman_document_category'));
        if (!in_array('is_main_category', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_document_category` ADD  `is_main_category` TINYINT NOT NULL DEFAULT  '0' ;";
            $db->setQuery($sql);
            $db->execute();

            $sql = 'UPDATE `#__edocman_document_category` SET is_main_category=1';
            $db->setQuery($sql);
            $db->execute();
        }
        #Add index to improve the speed
        $sql = 'SHOW INDEX FROM #__edocman_document_category';
        $db->setQuery($sql);
        $rows   = $db->loadObjectList();
        $fields = array();
        for ($i = 0, $n = count($rows); $i < $n; $i++)
        {
            $row      = $rows[$i];
            $fields[] = $row->Column_name;
        }
        if (!in_array('document_id', $fields))
        {
            $sql = 'ALTER TABLE `#__edocman_document_category` ADD INDEX ( `document_id` )';
            $db->setQuery($sql);
            $db->execute();
        }
        if (!in_array('category_id', $fields))
        {
            $sql = 'ALTER TABLE `#__edocman_document_category` ADD INDEX ( `category_id` )';
            $db->setQuery($sql);
            $db->execute();
        }

        $fields = array_keys($db->getTableColumns('#__edocman_statistics'));
        if (!in_array('name', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_statistics` ADD  `name` VARCHAR( 255 ) NULL DEFAULT  '';";
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('email', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_statistics` ADD  `email` VARCHAR( 255 ) NULL DEFAULT  '';";
            $db->setQuery($sql);
            $db->execute();
        }

        if (!in_array('download_code', $fields))
        {
            $sql = "ALTER TABLE  `#__edocman_statistics` ADD  `download_code` VARCHAR( 50 ) NULL DEFAULT  '';";
            $db->setQuery($sql);
            $db->execute();
        }

        $sql = "CREATE TABLE IF NOT EXISTS `#__edocman_tags` (
	    `id` int(11) NOT NULL AUTO_INCREMENT,
	    `tag` varchar(100) DEFAULT NULL,
	    `published` tinyint(3) unsigned DEFAULT NULL,
	    PRIMARY KEY (`id`)
		) DEFAULT CHARSET=utf8;";

        $db->setQuery($sql);
        $db->execute();

        $sql = "CREATE TABLE IF NOT EXISTS `#__edocman_document_tags` (
	    `id` int(11) NOT NULL AUTO_INCREMENT,
	    `document_id` int(11) DEFAULT NULL,
	    `tag_id` int(11) DEFAULT NULL,
	    PRIMARY KEY (`id`)
		) DEFAULT CHARSET=utf8;";
        $db->setQuery($sql);
        $db->execute();

        $sql = "CREATE TABLE IF NOT EXISTS `#__edocman_urls` (
	      `id` int(11) NOT NULL AUTO_INCREMENT,
	      `md5_key` text,
	      `query` text,
	      `object_name` varchar(50) DEFAULT NULL,
	      `object_id` int(11) NOT NULL DEFAULT '0',
	      PRIMARY KEY (`id`)
	    )DEFAULT CHARSET=utf8;";
        $db->setQuery($sql);
        $db->execute();

        $sql = "TRUNCATE TABLE `#__edocman_urls`";
        $db->setQuery($sql);
        $db->execute();

        // Fix documents date from old version
        $query = $db->getQuery(true);
        $query->select('id, filename, created_time, modified_time')
            ->from('#__edocman_documents')
            ->where('(created_time LIKE "0000-00-00 00:00:00" OR created_time IS NULL OR modified_time LIKE "0000-00-00 00:00:00" OR modified_time IS NULL)')
            ->where('document_url LIKE "" OR document_url IS NULL');
        $db->setQuery($query);
        $documents = $db->loadObjectList();
        if (count($documents))
        {
            $sql = 'SELECT config_value FROM #__edocman_configs WHERE config_key="documents_path"';
            $db->setQuery($sql);
            $documentPath = $db->loadResult();
            foreach ($documents as $document)
            {
                $filePath = $documentPath . '/' . $document->filename;
                if (file_exists($filePath))
                {
                    $createDate   = (empty($document->created_time) || $document->created_time = '0000-00-00 00:00:00' || $document->created_time = 'NULL') ? Factory::getDate(strftime('%Y-%m-%d %H:%M:%S', filectime($filePath))) : $document->created_time;
                    $modifiedDate = (empty($document->modified_time) || $document->modified_time = '0000-00-00 00:00:00' || $document->modified_time = 'NULL') ? Factory::getDate(strftime('%Y-%m-%d %H:%M:%S', filemtime($filePath))) : $document->created_time;
                    $query->clear();
                    $query->update('#__edocman_documents')
                        ->set('created_time=' . $db->quote($createDate))
                        ->set('modified_time=' . $db->quote($modifiedDate))
                        ->where('id=' . (int) $document->id);
                    $db->setQuery($query);
                    $db->execute();
                }
            }
        }
		$msg = "DATABASE SCHEMA HAS BEEN UPDATED SUCCESSFULLY !";
		Factory::getApplication()->enqueueMessage($msg);
		Factory::getApplication()->redirect("index.php?option=com_edocman");
    }

	public function sefoptimize(){
		$db = Factory::getContainer()->get('db');
    	$db->setQuery("Delete from #__edocman_urls");
    	$db->execute();
    	$this->setRedirect("index.php?option=com_edocman", Text::_('EDOCMAN_SEF_URLS_OPTIMIZATION_HAS_BEEN_COMPLETED'));
	}

	public function googledriveauthenticate(){
        $db = Factory::getContainer()->get('db');
		if(file_exists(JPATH_ROOT . '/plugins/edocman/googledrivev3/Google.php'))
		{
			JLoader::register('EdocmanGoogle', JPATH_PLUGINS.'/edocman/googledrivev3/Google.php');
		}
		else
		{
			JLoader::register('EdocmanGoogle', JPATH_PLUGINS.'/edocman/googledrive/Google.php');
		}
        $google = new EdocmanGoogle();
        $credentials = $google->authenticate();
       // echo $credentials;
        $google->storeCredentials($credentials);
        //Check if dropfiles folder exists and create if not
        $plugin = PluginHelper::getPlugin('edocman','googledrive');
        if($plugin)
		{
            $addrootpath        = 0;
            $pluginParams       = new Registry($plugin->params);
            $root_path          = $pluginParams->get('root_path','edocman');
            $db->setQuery("Select count(id) from #__edocman_googledrive where `type` = 0 and element_name like '$root_path' and element_id = '0'");
            $count              = $db->loadResult();
            if($count == 0)
			{
                $addrootpath    = 1;
            }
			else
			{
                $db->setQuery("Select cloud_id from #__edocman_googledrive where `type` = 0 and element_name like '$root_path' and element_id = '0'");
                $cloud_id       = $db->loadResult();
                if($cloud_id    != '')
				{
                    if(! $google->folderExists($cloud_id))
					{
                        $addrootpath = 1;
                    }
                }
            }
            if ($addrootpath == 1) 
			{
                $folderId       = $google->createFolder($root_path);
                $folderId       = $folderId->id;
                $db->setQuery("Select count(id) from #__edocman_googledrive where `type` = 0 and element_id = '0' and element_name like '$root_path' ");
                $count          = $db->loadResult();
                if($count == 0)
				{
                    $db->setQuery("Insert into #__edocman_googledrive (id,`type`,element_id,element_name,cloud_id) values (NULL,'0','0','$root_path','$folderId')");
                    $db->execute();
                }
				else
				{
                    $db->setQuery("Update #__edocman_googledrive set cloud_id = '$folderId' where `type`= '0' and element_name like '$root_path' and element_id = '0'");
                    $db->execute();
                }
            }
        }

        $this->setRedirect('index.php?option=com_edocman&view=configuration&layout=redirect');
        $this->redirect();
    }

    public function googledrivelogout()
	{
        if(file_exists(JPATH_ROOT . '/plugins/edocman/googledrivev3/Google.php'))
		{
			JLoader::register('EdocmanGoogle', JPATH_PLUGINS.'/edocman/googledrivev3/Google.php');
		}
		else
		{
			JLoader::register('EdocmanGoogle', JPATH_PLUGINS.'/edocman/googledrive/Google.php');
		}
        $google = new EdocmanGoogle();
        $google->logout();
        $this->setRedirect($_SERVER['HTTP_REFERER']);
        $this->redirect();
    }

    public function copydocument()
    {

    }

    public function cleantmpfolder()
    {
        jimport('joomla.filesystem.folder');
        if(is_dir(Path::clean(JPATH_ROOT.'/tmp/edocman')))
        {
            Folder::delete(JPATH_ROOT.'/tmp/edocman');
            Folder::create(JPATH_ROOT.'/tmp/edocman');
        }
		if(is_dir(Path::clean(JPATH_ROOT.'/edocmanviewer')))
        {
            Folder::delete(JPATH_ROOT.'/edocmanviewer');
            Folder::create(JPATH_ROOT.'/edocmanviewer');
        }
        $this->setRedirect('index.php?option=com_edocman', Text::_('EDOCMAN_TEMP_FOLDER_HAS_BEEN_CLEANED'));
    }

	public function tags()
	{
		$app		= Factory::getApplication();
		$input		= $app->getInput();
        $db			= Factory::getContainer()->get('db');
        $word		= $input->getString('q', null);
        $id			= $input->getInt('id');
        $word		= $db->Quote($db->escape($word, true).'%', false);

        if ($id) {
            $query = "SELECT id,tag FROM `#__edocman_tags` WHERE tag LIKE ".$word;
            $db->setQuery($query);
            $result = $db->loadObjectList();
        } else {
            $query = "SELECT `tag` FROM `#__edocman_tags` WHERE tag LIKE ".$word;
            $db->setQuery($query);
            $result = $db->loadColumn();
        }

        echo json_encode($result);
        $app->close();
	}

	public function downloadtrend()
	{
		$app		= Factory::getApplication();
		$input		= $app->getInput();
        $db			= Factory::getContainer()->get('db');
		$data		= [];

		$config		= Factory::getApplication()->getConfig();
		
		$range_option = $input->getInt('range_option', 0 );

		switch ($range_option)
		{
			case '0':
				$current_month = date("n");
				$current_year  = date("Y");
				for($i = 11; $i >= 0; $i--)
				{
				
					$date = Factory::getDate('first day of now -'.$i.' month', $config->get('offset'));
					$date->setTime(0, 0, 0);
					$date->setTimezone(new DateTimeZone('UCT'));
					$fromDate = $date->toSql(true);
					//echo $fromDate;
					//echo "<BR />";
					$date     = Factory::getDate('last day of now -'.$i.' month', $config->get('offset'));
					$date->setTime(23, 59, 59);
					$date->setTimezone(new DateTimeZone('UCT'));
					$toDate = $date->toSql(true);

					$db->setQuery("Select count(id) as ndownloads from #__edocman_statistics where download_time >= ".$db->quote($fromDate) . " and download_time <= ".$db->quote($toDate));
					$row = $db->loadObject();

					$tmp			 = new stdClass();
					$tmp->month		 = $date->format('F Y');
					$tmp->ndownloads = (int)$row->ndownloads;
					$data[]			 = $tmp;
				}
			break;
			case '1':
				//9 months
				$current_month = date("n");
				$current_year  = date("Y");
				for($i = 8; $i >= 0; $i--)
				{
					$date = Factory::getDate('first day of now -'.$i.' month', $config->get('offset'));
					$date->setTime(0, 0, 0);
					$date->setTimezone(new DateTimeZone('UCT'));
					$fromDate = $date->toSql(true);
					//echo $fromDate;
					//echo "<BR />";
					$date     = Factory::getDate('last day of now -'.$i.' month', $config->get('offset'));
					$date->setTime(23, 59, 59);
					$date->setTimezone(new DateTimeZone('UCT'));
					$toDate = $date->toSql(true);

					$db->setQuery("Select count(id) as ndownloads from #__edocman_statistics where download_time >= ".$db->quote($fromDate) . " and download_time <= ".$db->quote($toDate));
					$row = $db->loadObject();

					$tmp				= new stdClass();
					$tmp->month			= $date->format('F Y');
					$tmp->ndownloads	= (int)$row->ndownloads;

					$data[]				= $tmp;
				}
			break;
			case '2':
				//6 months
				$current_month = date("n");
				$current_year  = date("Y");
				for($i = 5; $i >= 0; $i--)
				{
				
					$date = Factory::getDate('first day of now -'.$i.' month', $config->get('offset'));
					$date->setTime(0, 0, 0);
					$date->setTimezone(new DateTimeZone('UCT'));
					$fromDate = $date->toSql(true);
					//echo $fromDate;
					//echo "<BR />";
					$date     = Factory::getDate('last day of now -'.$i.' month', $config->get('offset'));
					$date->setTime(23, 59, 59);
					$date->setTimezone(new DateTimeZone('UCT'));
					$toDate = $date->toSql(true);

					$db->setQuery("Select count(id) as ndownloads from #__edocman_statistics where download_time >= ".$db->quote($fromDate) . " and download_time <= ".$db->quote($toDate));
					$row = $db->loadObject();

					$tmp				= new stdClass();
					$tmp->month			= $date->format('F Y');
					$tmp->ndownloads	= (int)$row->ndownloads;

					$data[]				= $tmp;
				}
			break;
			case '3':
				//3 months
				$current_month = date("n");
				$current_year  = date("Y");
				for($i = 2; $i >= 0; $i--)
				{
				
					$date = Factory::getDate('first day of now -'.$i.' month', $config->get('offset'));
					$date->setTime(0, 0, 0);
					$date->setTimezone(new DateTimeZone('UCT'));
					$fromDate = $date->toSql(true);
					//echo $fromDate;
					//echo "<BR />";
					$date     = Factory::getDate('last day of now -'.$i.' month', $config->get('offset'));
					$date->setTime(23, 59, 59);
					$date->setTimezone(new DateTimeZone('UCT'));
					$toDate = $date->toSql(true);

					$db->setQuery("Select count(id) as ndownloads from #__edocman_statistics where download_time >= ".$db->quote($fromDate) . " and download_time <= ".$db->quote($toDate));
					$row = $db->loadObject();

					$tmp					= new stdClass();
					$tmp->month				= $date->format('F Y');
					$tmp->ndownloads		= (int)$row->ndownloads;

					$data[]					= $tmp;
				}
			break;
			case '4':
				$current_month = date("n");
				$current_year  = date("Y");
				$date1 = Factory::getDate('first day of last month', $config->get('offset'));
				$first_date = $date1->format('j');
				$date2 = Factory::getDate('last day of last month', $config->get('offset'));
				$last_date = $date2->format('j');

				$lastMonth = $date1->format('m');
				$lastYear  = $date1->format('Y');

				for($i = $first_date; $i <= $last_date; $i++)
				{
				
					$date = Factory::getDate($i.'-'.$lastMonth.'-'.$lastYear, $config->get('offset'));
					$date->setTime(0, 0, 0);
					$date->setTimezone(new DateTimeZone('UCT'));
					$fromDate = $date->toSql(true);
					$date->setTime(23, 59, 59);
					$toDate = $date->toSql(true);

					$db->setQuery("Select count(id) as ndownloads from #__edocman_statistics where download_time >= ".$db->quote($fromDate) . " and download_time <= ".$db->quote($toDate));
					$row = $db->loadObject();

					$tmp				= new stdClass();
					$tmp->month			= $date->format('jS F Y');
					$tmp->ndownloads	= (int)$row->ndownloads;

					$data[]				= $tmp;
				}
			break;
			case '5':
				$current_month = date("n");
				$current_year  = date("Y");
				$date = Factory::getDate('now', $config->get('offset'));
				$currentDate = $date->format('j');
				$currentMonth = $date->format('m');
				$currentYear  = $date->format('Y');

				for($i = 1; $i <= $currentMonth; $i++)
				{
					$date = Factory::getDate($i.'-'.$currentMonth.'-'.$currentYear, $config->get('offset'));
					$date->setTime(0, 0, 0);
					$date->setTimezone(new DateTimeZone('UCT'));
					$fromDate = $date->toSql(true);
					$date->setTime(23, 59, 59);
					$toDate = $date->toSql(true);

					$db->setQuery("Select count(id) as ndownloads from #__edocman_statistics where download_time >= ".$db->quote($fromDate) . " and download_time <= ".$db->quote($toDate));
					$row = $db->loadObject();

					$tmp				= new stdClass();
					$tmp->month			= $date->format('jS F Y');
					$tmp->ndownloads	= (int)$row->ndownloads;

					$data[]				= $tmp;
				}
			break;
			case '6':
				$current_month = date("n");
				$current_year  = date("Y");
				$last5Year     = $current_year - 5;
				$date = Factory::getDate('now', $config->get('offset'));
				$currentDate = $date->format('j');
				$currentMonth = $date->format('m');
				$currentYear  = $date->format('Y');

				for($i = $last5Year; $i <= $current_year; $i++)
				{
					$date = Factory::getDate($i.'-01-01', $config->get('offset'));
					$date->setTime(0, 0, 0);
					$date->setTimezone(new DateTimeZone('UCT'));
					$fromDate = $date->toSql(true);

					$date1 = Factory::getDate($i.'-12-31', $config->get('offset'));
					$date1->setTime(0, 0, 0);
					$date1->setTimezone(new DateTimeZone('UCT'));
					$date1->setTime(23, 59, 59);
					$toDate = $date1->toSql(true);

					$db->setQuery("Select count(id) as ndownloads from #__edocman_statistics where download_time >= ".$db->quote($fromDate) . " and download_time <= ".$db->quote($toDate));

					$row = $db->loadObject();

					$tmp				= new stdClass();
					$tmp->month			= $date->format('Y');
					$tmp->ndownloads	= (int)$row->ndownloads;

					$data[]				= $tmp;
				}
			break;
		}

		echo json_encode($data);
		Factory::getApplication()->close();
	}

	function removeterms()
	{
		$db = Factory::getContainer()->get('db');
		$cid = Factory::getApplication()->getInput()->get('cid', [] , 'array');
		if(count($cid))
		{
			$db->setQuery("Delete from #__edocman_search_terms where id in (".implode(',', $cid).")");
			$db->execute();
		}
		$this->setRedirect('index.php?option=com_edocman&view=terms', Text::_('EDOCMAN_ITEMS_REMOVED'));
	}

	function converttags()
	{
		$db = Factory::getContainer()->get('db');
		$cid = Factory::getApplication()->getInput()->get('cid', [] , 'array');
		if(count($cid))
		{
			foreach($cid as $id)
			{
				$db->setQuery("Select keyword from #__edocman_search_terms where id = '$id'");
				$keyword = $db->loadResult();
				
				$db->setQuery("Select count(id) from #__edocman_tags where tag = ".$db->quote($keyword));
				$count = $db->loadResult();
				if($count == 0)
				{
					$db->setQuery("Insert into #__edocman_tags (id, tag, published) values (NULL, '$keyword', 1)");
					$db->execute();
				}
			}
		}
		$this->setRedirect('index.php?option=com_edocman&view=terms', Text::_('EDOCMAN_TAGS_CREATED'));
	}

	function exportterms()
	{
		$db				= Factory::getContainer()->get('db');
		$config			= EDocmanHelper::loadConfig();
		$csv_separator  = $config->get('csv_separator',',');
		$input			= Factory::getApplication()->getInput();
		$filter_search	= $input->getString('filter_search', '');
		$start_date		= $input->getString('start_date', '');
		$end_date		= $input->getString('end_date', '');
		
		$query			= $db->getQuery(true);
		$query->select('*')->from('#__edocman_search_terms');
		if($filter_search != "")
		{
			
			$query->where(' keyword like "' . $filter_search . '"');
			
		}		

		if($start_date != "" && $start_date != "0000-00-00")
		{
			$query->where('searched_on >= "'.$start_date. '"');
		}

		if($end_date != "" && $end_date != "0000-00-00")
		{
			$query->where('searched_on <= "'.$end_date. '"');
		}

		$db->setQuery($query);
		$rows			= $db->loadObjectList();
		ini_set('memory_limit','999M');
		jimport('joomla.filesystem.folder');
		jimport('joomla.filesystem.file');
		jimport('joomla.filesystem.archive');
		jimport('joomla.archive.archive');

		$labels   = [];
		$labels[] = Text::_('EDOCMAN_TERM');
		$labels[] = Text::_('EDOCMAN_CREATED_ON');
		$labels[] = Text::_('IP Address');
		$labels[] = Text::_('City');
		$labels[] = Text::_('Postcode');
		$labels[] = Text::_('Country');

		$filecsv = JPATH_ROOT."/tmp/searchterms.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->keyword;
				$tmp[] = $row->searched_on;
				$tmp[] = $row->ip_address;
				$tmp[] = $row->city;
				$tmp[] = $row->postcode;
				$tmp[] = $row->country;
				fputcsv($fp, $tmp,$csv_separator);
			}
		}
		fclose($fp);
		EdocmanHelper::processDocumentCsv($filecsv, 'searchterms.csv');
		Factory::getApplication()->close();

	}


	/**
	 * Fix "Row size too large" issue
	 */
	public function fix_row_size()
	{
		$db = Factory::getContainer()->get('db');

		$tables = [
			'#__edocman_categories',
			'#__edocman_documents',
		];

		foreach ($tables as $table)
		{
			$query = "ALTER TABLE `$table` ROW_FORMAT = DYNAMIC";
			$db->setQuery($query)
				->execute();
		}
	}


	public function showfilesbasedonselectcategory()
	{
		$db				= Factory::getContainer()->get('db');
		$config			= EDocmanHelper::loadConfig();

		$category_id	= $this->input->getInt('category_id', 0);
		$current_file	= $this->input->getString('current_file', '');
		if($category_id > 0)
		{
			$category	= EdocmanHelper::getCategory($category_id);
		}
		$path			= EdocmanHelper::getConfigValue('documents_path');
		if($category->path != "")
		{
			$path	   .= "/".$category->path;
		}

		$pathLength = strlen($path) ;
		// Prepend some default options based on field attributes.
		
		$options[] = HTMLHelper::_('select.option', '-1', Text::alt('JOPTION_DO_NOT_USE', preg_replace('/[^a-zA-Z0-9_\-]/', '_', $current_file)));
		
		

		// Get a list of files in the search path with the given filter.
		$files = Folder::files($path, $filter, true, true);
		sort($files) ;        
		// Build the options list from the list of files.
		if (is_array($files)) {
			foreach($files as $file) {

				// Check to see if the file is in the exclude mask.
				if ($exclude) {
					if (preg_match(chr(1).$exclude.chr(1), $file)) {
						continue;
					}
				}

				// If the extension is to be stripped, do it.
				if ($stripExt) {
					$file = File::stripExt($file);
				}
                
				//Strip the path from filename
				$file = substr($file, $pathLength + 1) ;
				
				//Replace all "\" character with "/"
				$file = str_replace("\\", '/', $file) ;
				if($category->path != "")
				{
					$file = $category->path.'/'.$file;
				}
					
				$options[] = HTMLHelper::_('select.option', $file , $file );
			}
		}

		// Merge any additional options in the XML definition.
		//$options = array_merge(parent::getOptions(), $options);

		echo EdocmanHelper::getChoicesJsSelect(HTMLHelper::_('select.genericlist', $options, 'jform[select_filename]','class="input-large ilarge form-select"','value','text', $current_file));

		$this->app->close();
	}

	function deletedocuments()
	{
		$db = Factory::getContainer()->get('db');
		$config = EdocmanHelper::loadConfig();
		if(is_dir(Path::clean($config->documents_path)))
		{
			Folder::delete($config->documents_path);
		}
		Folder::create($config->documents_path);
		File::copy(JPATH_ADMINISTRATOR . '/components/com_edocman/htaccess.txt', $config->documents_path. '/.htaccess');
		$message = Text::_('EDOCMAN_ALL_SUB_FOLDERS_AND_DOCUMENTS_ARE_REMOVED');
		$mainframe = Factory::getApplication();
		$mainframe->enqueueMessage($message);
		$mainframe->redirect('index.php?option=com_edocman');
	}

	function fixDocumentPaths()
	{
		//$categoryId = Factory::getApplication()->getInput()->getInt('category_id',0);
		$db = Factory::getContainer()->get('db');
		$config = EdocmanHelper::loadConfig();
		//$category = EdocmanHelper::getCategory($categoryId);
		$db->setQuery("Select * from #__edocman_categories");
		$categories = $db->loadObjectList();
		foreach($categories as $category)
		{
			
			$path = $category->path;
			$firstChar = substr($path, 0, 1);
			if($path != "" && $firstChar != "/")
			{
				$checkingPath = $config->documents_path."/".$path;
			}
			else
			{
				$checkingPath = $config->documents_path.$path;
			}

			if($path != "" && is_dir( $checkingPath ))
			{
			
				$db->setQuery("Select a.id, a.filename, a.original_filename from #__edocman_documents as a inner join #__edocman_document_category as b on a.id = b.document_id where b.category_id = '$category->id' and b.is_main_category = '1'");
				$documents = $db->loadObjectList();

				
				if(count($documents))
				{
					foreach($documents as $document)
					{
						$old_file_name = $document->filename;
						$old_file_name = explode("/", $old_file_name);
						$old_file_name = $old_file_name[count($old_file_name)-1];
						$filename = $path."/".$old_file_name;
						$db->setQuery("Update #__edocman_documents set `filename` = ".$db->quote($filename)." where id = '$document->id'");
						$db->execute();
					}
				}
			}
		}
	}

	function exportchart()
	{
		$sales			 = $this->getModel('Chart')->getData();
		$category_id	 = $this->getModel('Chart')->get('filter_category_id',0);
		$title			 = "";
		if(count($sales))
		{
			$results_arr = [];
			$csv_output  = Text::_('Month');
			$csv_output .= ", " . Text::_('Download Time');
			$labels		 = array_keys($sales);
			$values      = array_values($sales);
			for($i = 0; $i < count($labels); $i++)
			{
				$results_arr   = [];
				$results_arr[] = $labels[$i];
				$results_arr[] = $values[$i];
				$csv_output .= "\n\"" . implode("\",\"", $results_arr) . "\"";
			}
			$csv_output .= "\n";

			$browser   = Factory::getApplication()->client->browser;
			$mime_type = ($browser == WebClient::IE || $browser == WebClient::OPERA) ? 'application/octetstream' : 'application/octet-stream';
			if($category_id > 0)
			{
				$category = EdocmanHelper::getCategory($category_id);
				$title    = $category->title;
				$title    = "_".strtolower(str_replace(" ","_", $title));
			}
			$filename  = "Statistic_log".$title;
			@ob_end_clean();
			ob_start();
			header('Content-Type: ' . $mime_type);
			header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
			$UserBrowser = Browser::getInstance()->getBrowser();
			
			if ($UserBrowser == 'IE')
			{
				header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
				header('Pragma: public');
			}
			else
			{
				header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
				header('Pragma: no-cache');
			}
			print $csv_output;
			exit();
		}
	}

	public function listcategoriesjson()
	{
		$db = Factory::getContainer()->get('db');
		$user = Factory::getApplication()->getIdentity();
		$db->setQuery("Select id, title as name, parent_id from #__edocman_categories where published = '1' order by ordering");
		$categories = $db->loadObjectList();
		if(count($categories))
		{
			foreach($categories as $key => $category)
			{
				if ($user->authorise('core.create', 'com_edocman.category.' . $category->id) != true)
				{
					unset($categories[$key]);
				}
			}
			// Reset array keys to ensure sequential JSON array
			$categories = array_values($categories);
		}
		echo json_encode($categories);
		exit();
	}

	function downloadFileHistory()
	{
		$file_path = $this->input->getString('file_path','');
		$file_path = base64_decode($file_path);
		$file_name = "backup/".basename($file_path);
		$clould_id = $this->input->getString('clould_id','');
		EDocmanHelper::processDownload($file_path, $file_name, $file_name,true,0,$clould_id);
	}

	public function restoreVersion()
	{
		$config = EDocmanHelper::loadConfig();
		// Lấy input
		$input = $this->input;
		$documentId = $input->getInt('id');
		$versionId = $input->getInt('version');

		if (!$documentId || !$versionId) {
			Factory::getApplication()->enqueueMessage(Text::_('EDOCMAN_MISSING_PARAMETERS'), 'error');
			$this->setRedirect('index.php?option=com_edocman&view=document&cid[]=' . $documentId);
			return false;
		}

		$db = Factory::getContainer()->get('db');
		$query = $db->getQuery(true)
			->select('*')
			->from('#__edocman_document_versions')
			->where('id = ' . (int)$versionId . ' AND document_id = ' . (int)$documentId);
		$db->setQuery($query);
		$version = $db->loadObject();

		if (!$version) {
			Factory::getApplication()->enqueueMessage(Text::_('EDOCMAN_VERSION_IS_NOT_AVAILABLE'), 'error');
			$this->setRedirect('index.php?option=com_edocman&view=document&cid[]=' . $documentId);
			return false;
		}

		$query->clear()
			->select('*')
			->from('#__edocman_documents')
			->where('id = ' . (int)$documentId);
		$db->setQuery($query);
		$document = $db->loadObject();

		if (!$document) {
			Factory::getApplication()->enqueueMessage(Text::_('EDOCMAN_DOCUMENT_IS_NOT_EXISTING'), 'error');
			$this->setRedirect('index.php?option=com_edocman&view=document&cid[]=' . $documentId);
			return false;
		}

		$filename = $document->filename;
		$document_name = pathinfo($filename, PATHINFO_BASENAME);

		if(EDocmanHelper::isDropBoxTurnedOn() || EDocmanHelper::isGoogleDrivePluginEnabled() || EDocmanHelper::isAmazonS3TurnedOn())
		{
			PluginHelper::importPlugin('edocman');
			$results = [];
			$results = Factory::getApplication()->triggerEvent('onRestoreversion', array($document, $version->file_name, $version->cloud_file_id));
			$newFileName = str_replace($document_name, $version->file_name, $filename);
		}
		else
		{
			$documentsPath = $config->documents_path.'/';
			$backupDir = $documentsPath . 'backup/';
			if (!is_dir(Path::clean($backupDir))) {
				Folder::create($backupDir);
			}
			if ($document->filename && file_exists($documentsPath . $document->filename)) {
				$currentBackup = $backupDir . pathinfo($document->filename, PATHINFO_FILENAME) . '_restore_' . date('YmdHis') . '.' . pathinfo($document->filename, PATHINFO_EXTENSION);
				File::copy($documentsPath . $document->filename, $currentBackup);
			}
			
			$newFileName = str_replace($document_name, $version->file_name, $filename);

			if (!$version->cloud_provider || $version->cloud_provider == 'local') {
				$backupFile = $backupDir . $version->file_name;
				$restorePath = $documentsPath . $newFileName;
				if (!file_exists($backupFile)) {
					Factory::getApplication()->enqueueMessage(Text::_('EDOCMAN_CANNOT_FIND_BACKUP_FILE'), 'error');
					$this->setRedirect('index.php?option=com_edocman&view=document&cid[]=' . $documentId);
					return false;
				}
				File::copy($backupFile, $restorePath);
			}
		}

		$fields = [
			$db->quoteName('filename') . ' = ' . $db->quote($newFileName),
			$db->quoteName('original_filename') . ' = ' . $db->quote($version->file_name),
			$db->quoteName('file_size') . ' = ' . (int)$version->file_size
		];
		$query->clear()
			->update('#__edocman_documents')
			->set($fields)
			->where('id = ' . (int)$documentId);
		$db->setQuery($query);
		$db->execute();

		Factory::getApplication()->enqueueMessage(Text::_('EDOCMAN_RESTORE_DOCUMENT_IS_SUCCESSFULLY'));
		$this->setRedirect('index.php?option=com_edocman&view=document&cid[]=' . $documentId);
		return true;
	}

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