<?php
/*******************************************************************************
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2009-07-23
 * Modified    : 2009-08-25
 * For LOVD    : 2.0-21
 *
 * Access      : Public
 * Purpose     : Provide an list of the PubMed references (and links)
 *               associated with the present variants and/or patients.
 *
 * Copyright   : 2004-2009 Leiden University Medical Center; http://www.LUMC.nl/
 * Programmers : Ir. Gerard C.P. Schaafsma <G.C.P.Schaafsma@LUMC.nl>
 *               Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 * Last edited : Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 *
 *
 * This file is part of LOVD.
 *
 * LOVD is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * LOVD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LOVD; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *************/

define('ROOT_PATH', './');
require ROOT_PATH . 'inc-init.php';

if (HAS_AUTH) {
    // If authorized, check for updates.
    require ROOT_PATH . 'inc-upgrade.php';
}

// If no gene selected, present the selection list.
if (!$_SESSION['currdb'] || $_GET['action'] == 'switch_db') {
    lovd_switchDB();
}





// Whether or not a user can see non-public data.
if (lovd_isCurator($_SESSION['currdb'])) {
    define('IS_CURATOR', true);
} else {
    define('IS_CURATOR', false);
}

require ROOT_PATH . 'inc-top.php';
lovd_printGeneHeader();
lovd_printHeader('pubmed_references', 'LOVD - PubMed References');

// Create arrays for the PubMed references.
$aReferences = array();
$aData = array(); // Fake data array with column that will render the PubMed links.

// To check which columns have the PubMed custom link enabled, we need the CurrDB class.
require ROOT_PATH . 'class/currdb.php';
$_CURRDB = new CurrDB();

// Check which columns are active for PubMed (linkid=1)
$qCols = mysql_query('SELECT colid FROM ' . TABLE_COLS2LINKS . ' WHERE linkid = 1');

while (list($sColumn) = mysql_fetch_row($qCols)) {
    if ($_CURRDB->colExists($sColumn)) {
        $sQ = 'SELECT `' . $sColumn . '` FROM ' . (substr($sColumn, 0, 7) == 'Patient' ? TABLE_PATIENTS : TABLE_CURRDB_VARS) .
              ' LEFT JOIN ' . TABLE_PAT2VAR . ' AS p2v USING ' . (substr($sColumn, 0, 7) == 'Patient' ? '(patientid)' : '(variantid)') .
              ' WHERE `' . $sColumn . '` LIKE "%{PMID%"' .
              ' AND p2v.symbol = "' . $_SESSION['currdb'] . '"' .
              ' GROUP BY `' . $sColumn . '`';
    } elseif ($sColumn == 'Gene/Reference') {
        $sQ = 'SELECT reference FROM ' . TABLE_DBS . ' WHERE symbol = "' . $_SESSION['currdb'] . '"';
    } else {
        continue;
    }
    $q = mysql_query($sQ);
    while (list($sReference) = mysql_fetch_row($q)) {
        // There can be more than one reference per result.
        if (preg_match_all('/\{(PMID\d+:)([^}]+)\}/', $sReference, $aMatches)) {
            foreach ($aMatches[1] as $key => $value) {
                $aReferences[$value][] = $aMatches[2][$key]; // $aReferences['PMID15977173:'][] = 'Fokkema et al. (2005)';
            }
        }
    }
    $sPubMedColumn = $sColumn; // Needed for later, so we can have the links rendered.
}


// Check if there are any PubMed references.
if (!count($aReferences)) {
    print('      There are no PubMed references for this gene.<BR>' . "\n");
    lovd_printGeneFooter();
    require ROOT_PATH . 'inc-bot.php';
    exit;
}



// Remove the duplicates.
foreach ($aReferences as $key => $aReference) {
    $aReferences[$key] = array_unique($aReference);
}

// Now create a sort function for use with usort
// compare function 
function lovd_sortReferences($a, $b)
{ 
    return strcmp(strtolower($a[0]), strtolower($b[0])); 
} 
// do the array sorting 
uasort($aReferences, 'lovd_sortReferences');

// Rebuild the references for use with lovd_buildLinks(), keeping references
// with the same PMID together.
foreach ($aReferences as $sPMID => $aReference) {
    foreach ($aReference as $key => $sAuthor) {
        $aReference[$key] = '{' . $sPMID . $sAuthor . '}';
    }
    // Use $sPubMedColumn as an index, necessary for lovd_buildLinks().
    $aData[$sPubMedColumn][] = implode($aReference, ', ');
}

// Parse and build Custom Links.
lovd_buildLinks($aData);

// Table.
print('      <TABLE border="0" cellpadding="0" cellspacing="1" width="600" class="gene">');

// Table header.
print("\n" .
      '        <TR>' . "\n" .
      '          <TH colspan="2" class="S15">PubMed References</TH></TR>');

$i = 1; // counter for numbering the references
foreach ($aData[$sPubMedColumn] as $sReference) {
    print("\n" .
          '        <TR>' . "\n" .
          '          <TH valign="top">' . $i . '</TH>' . "\n");
    print('          <TD>' . $sReference . '</TD></TR>');
    $i++;
}
print('</TABLE>' . "\n\n");

lovd_printGeneFooter();
require ROOT_PATH . 'inc-bot.php';
?>
