<?php
/*******************************************************************************
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2009-07-27
 * Modified    : 2009-09-04
 * For LOVD    : 2.0-21
 *
 * Access      : Public
 * Purpose     : Provide feeds for new and updated variant entries.
 *
 * Copyright   : 2004-2009 Leiden University Medical Center; http://www.LUMC.nl/
 * Programmer  : 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';





// We're not even going to start, if we're turned off.
if (!$_CONF['api_feed_history']) {
    exit;
}

// Start feed class.
require ROOT_PATH . 'class/feeds.php';
$sFormat = (!empty($_GET['format']) && in_array($_GET['format'], array('atom', 'rss'))? $_GET['format'] : 'atom');
$sLink   = ($_CONF['location_url']? $_CONF['location_url'] : PROTOCOL . $_SERVER['HTTP_HOST'] . lovd_cleanDirName(dirname($_SERVER['PHP_SELF']) . '/' . ROOT_PATH)) . 'api/feed.php';
$_FEED   = new Feed($_CONF['system_title'], $sLink, 'tag:' . $_SERVER['HTTP_HOST'] . ',' . $_STAT['date_install'] . ':' . $_STAT['signature'] . '/updates', $sFormat);

// I require this one, also, to get the sMutationCol.
require ROOT_PATH . 'class/currdb.php';

// Gather entries that need to be put into the feed.
// I want to show ALL entries which have been created or changed the last three months.
// So first, check the genes which have been changed the last three months.
$aGenes = array();
$sDateCheck = date('Y-m-d', strtotime('-' . $_CONF['api_feed_history'] . ' months'));
$qGenes = mysql_query('SELECT symbol FROM ' . TABLE_DBS . ' WHERE updated_date >= "' . $sDateCheck . '"' . (empty($_GET['select_db'])? '' : ' AND symbol = "' . $_GET['select_db'] . '"'));
while ($r = mysql_fetch_row($qGenes)) {
    $aGenes[] = $r[0]; // Store the genes that have been changed in the last three months.
}

// Now, query all of these genes, in one big query using UNION, and get the necessary fields.
if ($aGenes) {
    $sQ = '';
    foreach ($aGenes as $n => $sSymbol) {
        // Because we need to know which column we need to fetch...
        $_CURRDB = new CurrDB(true, $sSymbol);
        $sMutationCol = $_CURRDB->getMutationCol();
        $sQ .= ($n? ' UNION ' : '') . 'SELECT p2v.symbol, p2v.patientid, p2v.variantid, p2v.allele, v.`' . $sMutationCol . '` AS variant_name, p2v.pathogenic, p2v.created_date, p2v.edited_date, u_c.name AS created_by, u_e.name AS edited_by, CONCAT(s.firstname, " ", s.lastname) AS submitter FROM ' . TABLEPREFIX . '_' . $sSymbol . '_variants AS v LEFT JOIN ' . TABLE_PAT2VAR . ' AS p2v ON (v.variantid = p2v.variantid AND p2v.symbol = "' . $sSymbol . '") LEFT JOIN ' . TABLE_USERS . ' AS u_c ON (p2v.created_by = u_c.userid) LEFT JOIN ' . TABLE_USERS . ' AS u_e ON (p2v.edited_by = u_e.userid) LEFT JOIN ' . TABLE_PATIENTS . ' AS p ON (p2v.patientid = p.patientid) LEFT JOIN ' . TABLE_SUBS . ' AS s USING (submitterid) WHERE p2v.status >= ' . STATUS_MARKED . ' AND GREATEST(p2v.created_date, p2v.edited_date) >= "' . $sDateCheck . '"';
    }
    $sQ .= ' GROUP BY patientid, symbol, variantid ORDER BY GREATEST(' . ($n? '' : 'p2v.') . 'created_date, ' . ($n? '' : 'p2v.') . 'edited_date) DESC, patientid DESC, symbol, variantid DESC LIMIT 500';
    $q = mysql_query($sQ);

    // Now we will create entries in the feed with the fetched data.
    while ($zData = mysql_fetch_assoc($q)) {
        // Because we lost the zerofill in the UNION...
        $zData['patientid']  = str_pad($zData['patientid'], 7, '0', STR_PAD_LEFT);
        $zData['variantid']  = str_pad($zData['variantid'], 7, '0', STR_PAD_LEFT);
        // Prepare other fields to be included.
        // FIXME; New submissions are virtually never shown because they're not public. Curated new submissions appear as edited variants.
        $sTitle              = ($zData['edited_date']? 'Update' : 'New submission') . ' of variant in ' . $zData['symbol'] . ' gene database';
        $sURL                = ($_CONF['location_url']? $_CONF['location_url'] : PROTOCOL . $_SERVER['HTTP_HOST'] . lovd_cleanDirName(dirname($_SERVER['PHP_SELF']) . '/' . ROOT_PATH)) . 'variants.php?select_db=' . $zData['symbol'] . '&amp;action=view&amp;view=' . $zData['patientid'] . '%2C' . $zData['variantid'] . '%2C' . $zData['allele'];
        $sID                 = 'tag:' . $_SERVER['HTTP_HOST'] . ',' . substr($zData['created_date'], 0, 10) . ':' . $zData['symbol'] . '/' . $zData['patientid'] . '/' . $zData['variantid'];
        $zData['created_by'] = ($zData['created_by']? $zData['created_by'] : $zData['submitter']);
        $zData['edited_by']  = ($zData['edited_by']? $zData['edited_by'] : $zData['submitter']);
        $sSummary            = substr($zData['symbol'], 0, strpos($zData['symbol'] . '_', '_')) . ':' . $zData['variant_name'] . '; ' . ($zData['pathogenic']{0} == 5? 'pathogenicity ' : 'reported as ') . strtolower($_SETT['var_pathogenic'][$zData['pathogenic']{0}]);

        $_FEED->addEntry($sTitle, $sURL, $sID, $zData['created_by'], $zData['created_date'], $zData['edited_by'], $zData['edited_date'], $sSummary);
    }
}

$_FEED->publish();
?>