<?php



/**
 * A simple controller for AJAX requests related to the REDCap Publication Matching.
 *
 * IMPORTANT: if you add actions to this page, make sure that you check that
 * the given $secret is associated in some way with the data that the user
 * is attempting to access.
 *
 * NOTE: all JS for the HTML generated by this script is in index.php
 */

// Disable authentication (because person hitting this page may NOT actually be a REDCap user)
define("NOAUTH", true);

// Config for non-project pages
require dirname(dirname(__FILE__)) . "/Config/init_global.php";

$db = new RedCapDB();

$toJSON = "Invalid AJAX call!"; // holds the data that will be returned by the AJAX call

// Check that the user has a valid secret to access this page at all
if (!$db->isValidPubMatchHash($_REQUEST['secret'])) exit(RCL::accessDenied());
$secret = $_REQUEST['secret'];

if ($_GET['action'] == 'getMatchDisplay') {
	$toJSON = new stdClass();
	$toJSON->display = '';
	$todos = $db->getPubMatchTodosByHash($secret);
	$toJSON->todoCount = count($todos);
	// do a first pass to 1) accumulate all aliases for this PI, and 2) group
	// projects by type
	$aliases = array();
	$typeGroups = array();
	foreach ($todos as $articleId => $matches) {
		$typeGroups[$articleId] = array();
		foreach ($matches as $p) {
			$last = strtolower(trim($p->project_pi_lastname));
			$first = strtolower(trim($p->project_pi_firstname));
			$mi = strtolower(trim($p->project_pi_mi));
			$alias = strtolower(trim($p->project_pi_alias));
			// clear any commas the user may have entered in the alias because we
			// display names like "Harris PA" and *NOT* like "Harris, PA"
			$alias = preg_replace('/,\s*/', ' ', $alias);
			$author = "$last " . substr($first, 0, 1);
			$aliases[$author] = true;
			$author .= substr($mi, 0, 1);
			$aliases[$author] = true;
			$aliases[$alias] = true;
			// squash any empty or all-whitespace types into a single "Other" type
			$type = $p->custom_type;
			if (empty($type) || strlen(trim($type)) === 0) $type = RCL::other();
			$typeGroups[$articleId][$type][] = $p;
		}
	}
	// reorder the types so that REDCap comes first, then the rest of the
	// alphabetized types, and lastly the "Other" type
	foreach ($typeGroups as $articleId => $types) {
		$rcTypes = array();
		if (!empty($types['REDCap'])) {
			$rcTypes = $types['REDCap'];
			unset($types['REDCap']);
		}
		$otherTypes = array();
		if (!empty($types[RCL::other()])) {
			$otherTypes = $types[RCL::other()];
			unset($types[RCL::other()]);
		}
		ksort($types);
		$newTypes = array();
		if (count($rcTypes)) $newTypes['REDCap'] = $rcTypes;
		$newTypes = array_merge($newTypes, $types);
		if (count($otherTypes)) $newTypes[RCL::other()] = $otherTypes;
		$typeGroups[$articleId] = $newTypes;
	}
	foreach ($todos as $articleId => $matches) {
		reset($matches);
		$match = current($matches);
		$h = '';
		$h .= RCView::div(array('id' => "matchStatusSaving_$articleId",
				'style' => 'float: right; vertical-align: top; display: none;'),
						RCView::i(RCL::saving()) . RCView::SP .
						RCView::img(array('src' => 'loader_simple.gif', 'style' => 'vertical-align: top;')));
		$h .= RCView::div(array('id' => "matchStatusSaved_$articleId",
				'style' => 'float: right; vertical-align: top; display: none;'),
						RCView::i(RCL::saved()) . RCView::SP .
						RCView::img(array('src' => 'tick.png', 'style' => 'vertical-align: top;')));
		$h .= RCView::div(array('id' => "matchStatusSaveRetry_$articleId",
				'style' => 'float: right; vertical-align: top; display: none;'),
						RCView::i(RCL::saveRetry()) . RCView::SP .
						RCView::img(array('src' => 'loader_simple.gif', 'style' => 'vertical-align: top;')));
		$h .= RCView::span(array('style' => 'clear: both;'), '');
		$h .= RCView::p(array(),
					RCView::font(array('class' => 'redcapBlockTitle'),
									RCView::escape(RCL::pubPIIsYours())) .
					RCView::SP . RCView::SP .
					RCView::radio(array('name' => "isMyPub_$articleId", 'id' => "isMyPub_$articleId" . 'Yes',
							'value' => '1', 'data-article-id' => $articleId)) . RCL::yes() . RCView::SP .
					RCView::radio(array('name' => "isMyPub_$articleId", 'id' => "isMyPub_$articleId" . 'No',
							'value' => '0', 'data-article-id' => $articleId)) . RCL::no() . RCView::SP .
					RCView::radio(array('name' => "isMyPub_$articleId", 'id' => "isMyPub_$articleId" . 'Later',
							'value' => '99', 'data-article-id' => $articleId, 'checked' => 'checked')) . RCL::decideLater());
		$pmlink = ($match->pubsrc_id == RedCapDB::PUBSRC_PUBMED && $match->pub_id && preg_match('/^\d+$/', $match->pub_id)) ?
						RCView::a(array('href' => "http://www.ncbi.nlm.nih.gov/pubmed/$match->pub_id", 'target' => '_blank'),
										'PMID:' . RCView::SP . RCView::escape($match->pub_id)) : '';
		// highlight the relevant author; HTML escape all authors
		$htmlAuthors = array();
		foreach (explode('; ', $match->AuthorList) as $author) {
			$a = RCView::escape($author);
			foreach (array_keys($aliases) as $alias)
				if (stristr($author, $alias)) {
					$a = RCView::font(array('style' => 'font-weight: bold; color: blue; font-size: larger;'), $a);
					break;
				}
			$htmlAuthors[] = $a;
		}
		// build the citation
		$htmlCitation = array();
		if (!empty($pmlink))
			$htmlCitation[] = $pmlink;
		if (!empty($match->journal_abbrev))
			$htmlCitation[] = RCView::i(RCView::escape($match->journal_abbrev));
		if (!empty($match->volume))
			$htmlCitation[] = RCView::b(RCView::escape($match->volume));
		if (!empty($match->issue))
			$htmlCitation[] = RCView::b('(' . RCView::escape($match->issue) . ')');
		if (!empty($match->pages))
			$htmlCitation[] = RCView::escape($match->pages);
		if (!empty($match->ConsensusDate))
			$htmlCitation[] = RCView::escape('(' . substr($match->ConsensusDate, 0, 4) . ')');
		$h .= RCView::p(array(),
					RCView::font(array('style' => 'font-size: larger; font-weight: bold;'),
									RCView::escape($match->title)) .
						RCView::br() .
						implode('; ', $htmlAuthors) .
						RCView::br() .
						implode(' ', $htmlCitation));
		$relatedProj = '';
		$relatedProj .= RCView::p(array(),
					RCView::font(array('class' => 'redcapBlockTitle'),
						RCView::escape(RCL::pubPIWhichProjects())));
		$relatedProj .= RCView::radio(array('id' => "matchNone_$articleId",
					'name' => "matchRadio_$articleId",
					'data-article-id' => $articleId)) .
							RCView::b(RCView::escape(RCL::noneOfThese()));
		$relatedProj .= RCView::SP . RCView::SP . RCView::SP;
		$relatedProj .= RCView::radio(array('id' => "matchAll_$articleId",
					'name' => "matchRadio_$articleId",
					'data-article-id' => $articleId)) .
							RCView::b(RCView::escape(RCL::allOfThese()));
		$relatedProj .= RCView::br();
		foreach ($typeGroups[$articleId] as $type => $projects) {
			if (!$pub_matching_experimental && $type !== 'REDCap') continue;
			$relatedProj .= RCView::div(array('style' => 'margin-top: 10px;'),
				($pub_matching_experimental ?
					RCView::i('[' . RCView::escape($type . ' ' . RCL::projects()) . ']') : ''));
			$projNames = array();
			foreach ($projects as $p) {
				$projDisplay = $p->isExternal ?
						RCView::span(array(),
										RCView::escape($p->app_title)) :
						RCView::a(array('href' => APP_PATH_WEBROOT . "index.php?pid=$p->project_id",
								'target' => '_blank'),
										RCView::escape($p->app_title));
				$projNames[] = RCView::checkbox(array('id' => "matchProj_" . RCView::getId(),
					'data-article-id' => $articleId, 'data-match-id' => $p->match_id)) .
							RCView::SP . $projDisplay;
			}
			$relatedProj .= RCView::simpleList($projNames, false, array('style' => 'margin-top: 5px;'));
		}
		$h .= RCView::div(array('id' => "relatedProjs_$articleId", 'style' => 'display: none;',
				'data-article-id' => $articleId, 'class' => 'yellow'),
						$relatedProj);
		$toJSON->display .= RCView::div(array('class' => 'redcapSimple'), $h);
	}
}
elseif ($_POST['action'] == 'matchPubs') {
	$toJSON = new stdClass();
	$matchIds = explode(',', $_POST['matchIds']);
	if ($db->canAccessPubMatches($matchIds, $secret)) {
		$isMatch = null;
		if ($_POST['isMatch'] === "1") $isMatch = true;
		elseif ($_POST['isMatch'] === "0") $isMatch = false;
		$sqlArr = $db->matchPubMatches($matchIds, $isMatch);
		$toJSON->success = count($sqlArr) > 0;
		// Log the match
		if ($isMatch) Logging::logEvent("", "redcap_pub_matches", RCLog::EVENT_MANAGE, "", "match_id in (".$_POST['matchIds'].")", RCLog::DESC_PUBMATCH);
	}
	else {
		$toJSON->success = 0;
	}
}

exit(json_encode_rc($toJSON));