<?php
ob_start();

require_once "inc/lang/lang.php";
include_once LANG_PATH."/index.php";
include_once LANG_PATH."/manu.php";

require_once "class/config.class.php";
require_once "class/journal.class.php";
require_once "class/article.class.php";
require_once 'class/cache.class.php';
require_once "class/pdate.php";

$cnf = new ArticleManager();
if (isset($_GET["verb"])) {
	$_GET["_action"] = "export";
	$_GET["rf"] = "oai";
	$CRON_SC = 1;
}

//Theme Manager Object
require_once "class/theme.class.php";
$tcnf = new ThemeManager();
if (in_array($tcnf->frontTheme, ["old", "base", "old_fixed", "base_fixed"])) {
    $cnf->themeTp = 2;
}
//Export Article
if(isset($_GET['_action']) && $_GET['_action'] == "export" && isset($_GET['rf'])) {
    ob_clean();
	require_once "class/export.class.php";
	$exp = new ExportArticle();
	$exp->manageExportActions($_GET);

	exit();
}


//Click on Ads [Load the url provided in admin section]
if(isset($_GET['adsc'])) {

	$qStr = "SELECT ads_code,ads_link 
			FROM ju_ads
			WHERE ads_code = ".$cnf->mt($_GET['adsc'], 3)."
			AND journal_code = ".$cnf->journalCode;
	$ads = $cnf->doDBQuery($qStr);
	
	if($ads->rowCount()== 0) {
	    __redirect("/");
	    exit();
	}
	
	$thisAds = $ads->fetchObject();

	$qStr = "UPDATE ju_ads SET
			ads_clicks = ads_clicks + 1
			WHERE ads_code = ".$cnf->mt($thisAds->ads_code, 3)."
			AND journal_code = ".$cnf->journalCode;
	$cnf->doDBQuery($qStr);
	
	$ads_link = $thisAds->ads_link;
	if(!preg_match("/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i", $ads_link)) {
		__redirect("/");
		exit();
	}

	header("Location: ".$ads_link);
	exit();

}

if (!isset($_REQUEST['_action'])){
	$_REQUEST['_action'] = "";
}

//Show PDF file
if ($_REQUEST['_action'] == "showPDF") {

	$setting = $cnf->getJuSetting("'login_for_fulltext','ft_label'", "", 4, 0);

	if(!isset($_SESSION[SESSION_NAME_ID]) && $setting["login_for_fulltext"] == "1") {
		$_SESSION['pLoc'] = "./";
		__redirect("contacts?_action=login");
		exit();
	}
	ob_clean();
	//$_SERVER['QUERY_STRING'] = base64_encode('showPDF='.$_REQUEST['article']."&rb=1&".$_SERVER['QUERY_STRING']);
	require_once "jufile.php";
	exit();
}

//Show XML file
elseif($_REQUEST['_action'] == 'xml') {

	$cnf->showXML($_GET);
	exit();
}
elseif(isset($_REQUEST['sso'])) {
    
    require_once 'class/sso.class.php';
    $sso = new SSOManager();
    $sso->manageActions($_REQUEST);
    exit();
}

//Anotations
elseif($_REQUEST['_action'] == 'get_annot') {

	$cnf->getAnnotationOptions($_GET);
	exit();
}
elseif($_REQUEST['_action'] == 'trnsf') {
    
    $ar_code = $cnf->getTransferredArticle($_REQUEST);
    if ($ar_code == 0) {
        header('HTTP/1.0 403 Forbidden');
        exit();
    }
    if (isset($_GET["pdf"])) {
        header('location: '.$cnf->juBaseURL."article_".$ar_code."_".md5($ar_code).".pdf");
    }
    else {
        header('location: '.$cnf->juBaseURL."article_".$ar_code.".html");
    }
    exit();
}
elseif(isset($_GET["sid"])) {
	$_REQUEST['_action'] = "linkout";
}

//Page Tytles
$thisPage = "home";
$pgTitle = "";
switch ($_REQUEST['_action']) {
	case 'advSearch':
		$pgTitle = ___('IND_ADVANCED_SEARCH');
		break;
	case 'article':
		$pgTitle = ___('IND_ARTICLES_LIST');
		break;
	case 'press':
		$pgTitle = ___('IND_IN_PRESS');
		break;
	case 'articleInfo':
		$pgTitle = ___('IND_ARTICLE_DETAILS');
		break;
	case 'current':
		$pgTitle = ___('IND_CURRENT_ISSUE');
		break;
	case 'xml':
		$pgTitle = "XML";
		break;
}

$pageTitle = $pgTitle;

//*********************** Article info */
if($_REQUEST['_action'] == "articleInfo" && ctype_digit($_GET['article'])) {

    if (strpos($_SERVER["REQUEST_URI"], "/mobile/") !== false || strpos($_SERVER["REQUEST_URI"], "/m/") !== false || strpos($_SERVER["REQUEST_URI"], "&url=") !== false || strpos($_SERVER["REQUEST_URI"], "/index.php/") !== false || strpos($_SERVER["REQUEST_URI"], "/article/view/") !== false) {
        require_once 'class/crawler.detect.php';
        if (isset($_SERVER['HTTP_USER_AGENT']) && !isCrawler($_SERVER['HTTP_USER_AGENT'])) {
            header("Location: ".$cnf->juBaseURL."article_".$cnf->mt($_GET['article'], 3).".html");
        }
    }
    
	$_PARAMS = $_GET;
	$_PARAMS['article_code'] = $cnf->mt($_GET['article'], 3);
	$qStr = "SELECT print_issn,online_issn
			FROM ju_journals
			WHERE journal_code = ".$cnf->journalCode;
	$res = $cnf->doDBQuery($qStr);
	$thisJu = $res->fetchObject();

	$thisArticle = $cnf->getArticleInfo($_PARAMS);
	if(is_null($thisArticle)) {
	    __redirect("./error_page");
	}
	if($thisArticle->article_title != "") {

		//$_PARAMS['list'] = 1;
		$authors = $cnf->getArticleAuthors($_PARAMS);
		$keywords = $cnf->getArticleKeywords($_PARAMS);
		$kw = [];
		while($thisKw = $keywords->fetchObject()) {
			$kw[] = $thisKw->kw_name;
		}

		$_REQUEST["vol"] = $thisArticle->vi_code;

		$thisArticle->article_title = $pageTitle = strip_tags($cnf->removeExtraChars(preg_replace("/[\r\n]+/", " ", $thisArticle->article_title)));
		$thisArticle->article_abstract = $cnf->removeExtraChars(strip_tags($thisArticle->article_abstract), 2);
		$tcnf->addMeta("keywords", strip_tags($cnf->removeExtraChars(implode(",", $kw))));
		$tcnf->addMeta("description", $thisArticle->article_abstract);
		$tcnf->addMeta("title", $pageTitle);
		$tcnf->addMeta("googlebot", "NOODP");
		$tcnf->addMeta("citation_title", $pageTitle);

		$authors = $authors->fetchAll(PDO::FETCH_OBJ);
		foreach ($authors as $thisAuthor) {
		    $tcnf->addMeta("citation_author", $cnf->removeExtraChars(ucwords($thisAuthor->author_lname.", ".$thisAuthor->author_fname." ".$thisAuthor->author_middle)));
		    $thisAuthor->author_address = $thisAuthor->author_address != "" ? explode("|", $thisAuthor->author_address) : [];
			foreach ($thisAuthor->author_address as $author_address) {
			    $tcnf->addMeta("citation_author_institution", $cnf->removeExtraChars($author_address));
			}
		}
		if ($thisArticle->ar_id_no == "") {
		    $thisArticle->ar_id_no = $thisArticle->article_code;
		}
		
		$tcnf->addStyle($cnf->juBaseURL."article_".$thisArticle->article_code.(LANG_CODE == 2 ? "_".JU_SECOND_LNG : "").".html", false, "canonical");
		$tcnf->addMeta("citation_abstract", $thisArticle->article_abstract);
		$tcnf->addMeta("citation_id", $thisArticle->article_code);
		$tcnf->addMeta("citation_publication_date", date("Y/m/d", strtotime($thisArticle->publish_date)));
		$tcnf->addMeta("citation_date", date("Y-m-d", strtotime($thisArticle->publish_date)));
		$tcnf->addMeta("citation_journal_title", $cnf->juName);
		$tcnf->addMeta("citation_issn", $thisJu->print_issn != "" ? $thisJu->print_issn : $thisJu->online_issn);
		$tcnf->addMeta("citation_volume", $cnf->mt($thisArticle->article_volume), 3);
		$tcnf->addMeta("citation_issue", $thisArticle->article_issue);
		$tcnf->addMeta("citation_firstpage", ($thisArticle->page_from == "" ? "e".$thisArticle->ar_id_no : $thisArticle->page_from));
		$tcnf->addMeta("citation_lastpage", $thisArticle->page_to);
		$tcnf->addMeta("citation_publisher", $cnf->getJuSetting("'ow_note'", ___('JU_LOCALE'), 1));

		if($thisArticle->doi){
			$tcnf->addMeta("citation_doi", $thisArticle->doi);
			$tcnf->addMeta("DC.Identifier", $thisArticle->doi);
		}
		$tcnf->addMeta("citation_abstract_html_url", $cnf->juBaseURL.'article_'.$thisArticle->article_code.(LANG_CODE == 2 ? "_".JU_SECOND_LNG : "").'.html');
		$tcnf->addMeta("citation_fulltext_html_url", $cnf->juBaseURL.'article_'.$thisArticle->article_code.(LANG_CODE == 2 ? "_".JU_SECOND_LNG : "").'.html');
		
		if ($thisArticle->full_text_file != "" && file_exists($cnf->Full_Text_Path.$thisArticle->full_text_file)) {
		    $pdf_link = "article_".$thisArticle->article_code."_".md5($thisArticle->article_code).".pdf";
		    /*
		    if ($thisArticle->doi != "" && strlen($thisArticle->doi) > 15 && substr($thisArticle->doi, 0, 3) == "10.") {
		        $pdf_link = $thisArticle->doi.".pdf";
		    }
		    */
		    $tcnf->addMeta("citation_pdf_url", $cnf->juBaseURL.$pdf_link);
		}
		
		$tcnf->addMeta("DC.Title", $pageTitle);
		$tcnf->addMeta("DC.Source", $cnf->juName);
		$tcnf->addMeta("DC.Date", date("d/m/Y", strtotime($thisArticle->publish_date)));
		$tcnf->addMeta("DC.Date.issued", date("Y-m-d", strtotime($thisArticle->publish_date)));
		$tcnf->addMeta("DC.Format", "application/pdf");

		foreach ($authors as $thisAuthor) {
		    $tcnf->addMeta("DC.Contributor", $cnf->removeExtraChars(ucwords(trim($thisAuthor->author_lname.", ".$thisAuthor->author_fname." ".$thisAuthor->author_middle))));
		}
		$tcnf->addMeta("og:title", $pageTitle);
		$tcnf->addMeta("og:type", "article");
		$tcnf->addMeta("og:description", $thisArticle->article_abstract);
		$tcnf->addMeta("og:url", $cnf->juBaseURL.'article_'.$thisArticle->article_code.(LANG_CODE == 2 ? "_".JU_SECOND_LNG : "").'.html');
		$thisArticle->authors = $authors;
		$tcnf->addHFVariable("ar_schema", $thisArticle);
	}
}

// else {

	if($_REQUEST['_action'] == "") {
		$setting = $cnf->getJuSetting("'show_current_issue','show_top_articles','show_editor_choice','show_keyword_cloud','has_tex','hide_vol_year','indx_limit','only_edb','top_article_setting','enable_ju_sld'", "", 4);
	}
	else {
		$setting = $cnf->getJuSetting("'show_current_issue','has_tex','hide_vol_year','enable_ju_sld'", "", 4);
	}

	//$tcnf->addScript('inc/js/article.js?v=0.31',false,true);

	if($setting['has_tex'] == "1") {
		//$tcnf->addScript("MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\\\(','\\\\)']]}});", true,true,'text/x-mathjax-config');
		//$tcnf->addScript('https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML',false,true,"text/javascript","async");
		$tcnf->addScript("MathJax = {tex: {inlineMath: [['$', '$'], ['\\\\(','\\\\)']]}};", true,true);
		$tcnf->addScript('https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js',false,true,"text/javascript","async");
	}

	////////////////////////////////////////////////////////////////////////////////////////
	if($_REQUEST['_action'] != "" || $setting["show_current_issue"] == "1") {
		$__pageAction=$cnf->pageActions(true);
		$tcnf->addVariable('pageAction',$__pageAction);
	}

	$__hFactFigure = [];
	
	$tcnf->addVariable('h_factFigure',$__hFactFigure);	

	$_PARAMS = $_REQUEST;
	if($setting["show_current_issue"] == "1") {
		$_PARAMS['currentt'] = 1;
	}
						
	$juCover = $cnf->getJournalCoversheet($_PARAMS);
	if(!file_exists($juCover)) {
		$juCover = null;
	}
	$tcnf->addVariable('journalCover',$cnf->mt($juCover));

	
	$_PARAM = array("iss" => (($setting["show_current_issue"] == "1" && $_REQUEST['_action'] == "") || $_REQUEST['_action'] == "current") ? 1 : 0);
	if ($setting["hide_vol_year"] == "1") {
		$_PARAM["hide_vol_year"] = $setting["hide_vol_year"];
	}

	$__browseVolumeIssue=$cnf->browseVolumeIssue($_PARAM,true);
	$tcnf->addVariable('browseVolumeIssue',$__browseVolumeIssue);

	if ($_REQUEST["_action"] == "") {

		//Facts and Figures
	    $h_setting = $cnf->getJuSetting("'facts_figures','facts_figurs','ow_note','ow_link','home_page_notes','about_journal'", ___('JU_LOCALE'), 4);
	    $__factsFigures = $cnf->getFactsFigures($h_setting["facts_figures"], true);
		$tcnf->addVariable('factsFigures', $__factsFigures);
		$__factsFigurs = $cnf->getFactsFigures($h_setting["facts_figurs"], true);
		$tcnf->addVariable('factsFigurs', $__factsFigurs);
		
		//publication info
		$__showJournalHome = $cnf->showJournalHome(["ow_note" => $h_setting["ow_note"], "ow_link" => $h_setting["ow_link"], "only_edb" => $setting["only_edb"]], true);
		$tcnf->addVariable('publicationInfo', $__showJournalHome);
		$tcnf->addHFVariable('publicationInfo', $__showJournalHome);

		$__ads = $cnf->getAds([],true);
		$tcnf->addVariable('ads',$__ads);

		$__relj = $cnf->getRelatedJournals([],true);
		$tcnf->addVariable('relatedJournals',$__relj);

		$__indexing = $cnf->getIndexing($setting, true);
		$tcnf->addVariable('indexing',$__indexing);
		$tcnf->addVariable('indx_limit',$setting["indx_limit"]);

		$__journalNews = $cnf->getJournalNews("", true);
		$tcnf->addVariable('journalNews',$__journalNews);
	}


	switch ($_REQUEST['_action']) {
		case 'advSearch':
			$__searchForm = $cnf->articleSearchForm("", true);
			$tcnf->addStyle($cnf->juBaseURL."?_action=advSearch".(LANG_CODE == 2 ? "&lang=".JU_SECOND_LNG : ""), false, "canonical");
			
			$tcnf->addVariable('searchForm',$__searchForm);
			$tcnf->loadPageTemplate('adv_search',$pageTitle);
			break;

		case 'article':
		case 'press':

			$_PARAMS = $_REQUEST;
			$_PARAMS["theme"] = $tcnf->frontTheme;
			if(isset($_GET['vol']) && !isset($_GET['issue'])) {

			    $issue = $cnf->getLastVolumeIssue(3, $_GET['vol'], $setting["hide_vol_year"]);
				__redirect("issue_".$cnf->mt($_GET['vol'], 3)."_".$issue.".html");
				return ;
			}
			
			if ($_REQUEST['_action'] == "press") {
			    $tcnf->addStyle($cnf->juBaseURL."?_action=press&issue=-1&_is=".htmlentities(___('IND_IN_PRESS'), ENT_QUOTES, "UTF-8").(LANG_CODE == 2 ? "&lang=".JU_SECOND_LNG : ""), false, "canonical");
			}
			elseif (isset($_GET['vol']) && isset($_GET['issue'])) {
			    $tcnf->addStyle($cnf->juBaseURL."issue_".$cnf->mt($_GET['vol'], 3)."_".$cnf->mt($_GET['issue'], 3)."".(LANG_CODE == 2 ? "_".JU_SECOND_LNG : "").".html", false, "canonical");
			}
			elseif (isset($_GET['au'])) {
			    $tcnf->addStyle($cnf->juBaseURL."?_action=article&au=".$cnf->mt($_GET["au"], 3).(isset($_GET["_au"]) ? "&_au=".$cnf->mt(urlencode($_GET["_au"])) : "").(LANG_CODE == 2 ? "&lang=".JU_SECOND_LNG : ""), false, "canonical");
			}
			elseif (isset($_GET['kw'])) {
			    $tcnf->addStyle($cnf->juBaseURL."?_action=article&kw=".$cnf->mt($_GET["kw"], 3).(isset($_GET["_kw"]) ? "&_kw=".$cnf->mt(urlencode($_GET["_kw"])) : "").(LANG_CODE == 2 ? "&lang=".JU_SECOND_LNG : ""), false, "canonical");
			}
			elseif (isset($_GET['sb'])) {
			    $tcnf->addStyle($cnf->juBaseURL."?_action=article&sb=".$cnf->mt($_GET["sb"], 3).(isset($_GET["_sb"]) ? "&_sb=".$cnf->mt(urlencode($_GET["_sb"])) : "").(LANG_CODE == 2 ? "&lang=".JU_SECOND_LNG : ""), false, "canonical");
			}
			
			$__articleList=$cnf->articleList($_PARAMS,true);
			$tcnf->addVariable('articleList',(object)$__articleList);
			
			if ($setting["enable_ju_sld"] == "1") {
			    $juSubjects = $cnf->getSubjectsInfo($_PARAMS);
                $tcnf->addVariable('subjectsCategory', $juSubjects);
			}
			$tcnf->addVariable('articleList',(object)$__articleList);

			$tcnf->loadPageTemplate('article_list',$pageTitle);
			break;
		case "linkout":

			$__articleInfo = $cnf->getLinkoutArticle($_GET);
			$tcnf->addVariable('articleInfo',$__articleInfo);


			$tcnf->loadPageTemplate('article_info',$pageTitle);
		break;
		case 'articleInfo':

			if(isset($_POST['save_comment'])) {
				$_PARAMS = $_POST;
			}
			else {
				$_PARAMS = array('article_code' => $_REQUEST['article']);
			}

			$__articleInfo = $cnf->articleInfo($_PARAMS,true);
			if (is_null($__articleInfo)) {
			    __redirect("./error_page");
			    return;
			}
			$tcnf->addVariable('articleInfo',$__articleInfo);
			if($__articleInfo->setting->showFulltextJats && $__articleInfo->article->jatsFulltext){
				$tcnf->addScript('inc/js/jats.js?v=' . time());
				$tcnf->addStyle('inc/css/jats.min.css?v=' . time());
			}

			$tcnf->loadPageTemplate('article_info',$pageTitle);
			break;
		case 'current':

		    list($volume, $issue) = $cnf->getLastVolumeIssue(4, 0, $setting["hide_vol_year"]);
		    __redirect("issue_".$cnf->mt($volume, 3)."_".$cnf->mt($issue, 3).".html");
			break;

		case "cite":

			require_once "class/article.citation.class.php";
			$ar_cite = new ArticleCitation();
			$ar_cite->manageActions($_PARAMS);
			break;
		case "":
			//Index Page
		    
		    $tcnf->addVariable('aboutJournal', $h_setting["home_page_notes"]);
			$tcnf->addVariable('about_journal', $h_setting["about_journal"]);
			$tcnf->addStyle($cnf->juBaseURL.(LANG_CODE == 2 ? "?lang=".JU_SECOND_LNG : ""), false, "canonical");
			$__topArticles = [];
			if(isset($setting["show_top_articles"]) && ($setting["show_top_articles"] == "1" || $setting["show_top_articles"] == 2)) {
				$_PARAM = array("top" => $setting["show_top_articles"], "top_article_setting" => $setting["top_article_setting"]);
				$__topArticles= $cnf->getTopArticles(2, $_PARAM,true); 
				$__topArticles = $__topArticles ? (object)$__topArticles : [];
			}
			$tcnf->addVariable('topArticles',$__topArticles);
			
			$__currentArticleList = [];
			if($setting["show_current_issue"] == "1") {

			    $issue = $cnf->getLastVolumeIssue(3, 0, $setting["hide_vol_year"]);
				if ($issue != 0) {
					
					$_PARAMS = ['issue'=> $issue, '_is'=> "", 'shSP'=>1, "lastIssue" => 1, "theme" => $tcnf->frontTheme];
					$__currentArticleList= $cnf->articleList($_PARAMS,true);
					$__currentArticleList = $__currentArticleList ? (object)$__currentArticleList : [];
				}
				$tcnf->addVariable('currentIssueArticles',$__currentArticleList);
                
				if ($cnf->themeTp == 1) {
    			    
        			$__articleInPress = [];
        			$_SERVER['QUERY_STRING'] = "_action=press&issue=-1&_is=".___('IND_IN_PRESS');
        			$_PARAMS = array('_action' => "press", 'issue'=> -1);
        			$__articleInPress=$cnf->articleList($_PARAMS,true);
        			$__articleInPress = $__articleInPress ? (object)$__articleInPress : [];
        			$tcnf->addVariable('inPressArticles',$__articleInPress);
    			}
			}
			
			$__articleEditorChoice = [];
			if(isset($setting["show_editor_choice"]) && $setting["show_editor_choice"] == "1") {
				$__articleEditorChoice = $cnf->getEditorChoiceArticles();
				$__articleEditorChoice = $__articleEditorChoice ? (object)$__articleEditorChoice : [];
			}
			$tcnf->addVariable('editorChoiceArticles',$__articleEditorChoice);

			$__keywordsCload = [];
			if(isset($setting["show_keyword_cloud"]) && $setting["show_keyword_cloud"] == "1") {

				$cache_cnf = new CacheManager();
				$__keywordsCload = $cache_cnf->get('keyword_cloud');

				if($__keywordsCload === null){
					$__keywordsCload = $cnf->getTopKeywords(200);
					$cache_cnf->set('keyword_cloud',$__keywordsCload);
				}
			}
			$tcnf->addScript('inc/js/d3/kw_cloud.min.js');
			$tcnf->addVariable('keywordsCload',$__keywordsCload);
			if ($setting["enable_ju_sld"] == "1") {
			    
			    $juSlides = $cnf->getSlidShow($_PARAMS);
			    $tcnf->addHFVariable('juSlides', $juSlides);
			    $juSubjects = $cnf->getSubjectsInfo($_PARAMS);
			    $tcnf->addVariable('juSubjects', $juSubjects);
			}

			$tcnf->loadPageTemplate('index','');
		break;
		default:
		    header('HTTP/1.0 403 Forbidden');
		    exit();
		    break;
	}
	
ob_flush();
?>
<div id="actn_modal" class="modal fade" tabindex="-1">
	<div id="modal_dlg" class="modal-dialog modal_aw modal-lg">
		<div class="modal-content">
			<div class="modal-header py-2">
				<button type="button" class="btn px-1 float-end" data-bs-dismiss="modal" title="<?php echo ___("FORM_CLOSE")?>" aria-label="Close"><i class="fa-solid fa-xmark text-secondary"></i></button>
				<span class="modal-title"></span>
			</div>
			<div class="modal-body"></div>
		</div>
	</div>
</div>

