Exemplo n.º 1
0
/**
 * Get the last changed log file using in the 
 * $paths['base'] . "/" . $paths['log']."/MRI_upload" directory
 * @return String latest log file
 */
function getLatestLogFile()
{
    $config = NDB_Config::singleton();
    $paths = $config->getSetting('paths');
    ///////////////////////////////////////////////////////////////////////////
    ///////////////////get the path from the config file///////////////////////
    ///////////////////////////////////////////////////////////////////////////
    if (empty($paths)) {
        print "config setting is missing";
        error_log("ERROR: Config settings are missing");
    }
    ///////////////////////////////////////////////////////////////////////////
    //////////////////////Get the directory name///////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    $log_directory = $paths['base'] . "/" . $paths['log'] . "/MRI_upload";
    //print "log directory " . $log_directory . "<BR>";
    //get the last file modified
    ///////////////////////////////////////////////////////////////////////////
    ////////////////find the file last changed/////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    $files = glob($log_directory . "/*MRI_upload*");
    $files = array_combine($files, array_map("filemtime", $files));
    arsort($files);
    $data_source_file = key($files);
    if (!file_exists($data_source_file)) {
        print "File doesn't exist";
    }
    return $data_source_file;
}
Exemplo n.º 2
0
/**
 * Returns the path under which minc files are located in this Loris
 * install.
 *
 * @return string Path which contains MINC files
 */
function getMincLocation()
{
    $config =& NDB_Config::singleton();
    $paths = $config->getSetting('paths');
    $minc_path = $paths['mincPath'];
    return $minc_path;
}
Exemplo n.º 3
0
/**
 * Handles the media upload process
 *
 * @throws DatabaseException
 *
 * @return void
 */
function uploadFile()
{
    $db =& Database::singleton();
    $config = NDB_Config::singleton();
    $user =& User::singleton();
    if (!$user->hasPermission('media_write')) {
        header("HTTP/1.1 403 Forbidden");
        exit;
    }
    // Validate media path and destination folder
    $mediaPath = $config->getSetting('paths')['mediaPath'];
    if (!isset($mediaPath)) {
        showError("Error! Media path is not set in Loris Settings!");
        exit;
    }
    if (!file_exists($mediaPath)) {
        showError("Error! The upload folder '{$mediaPath}' does not exist!");
        exit;
    }
    // Make sure folder is writable
    chmod($mediaPath, 0777);
    // Process posted data
    $pscid = isset($_POST['pscid']) ? $_POST['pscid'] : null;
    $visit = isset($_POST['visit_label']) ? $_POST['visit_label'] : null;
    $instrument = isset($_POST['instrument']) ? $_POST['instrument'] : null;
    $site = isset($_POST['for_site']) ? $_POST['for_site'] : null;
    $dateTaken = isset($_POST['date_taken']) ? $_POST['date_taken'] : null;
    $comments = isset($_POST['comments']) ? $_POST['comments'] : null;
    // If required fields are not set, show an error
    if (!isset($_FILES) || !isset($pscid) || !isset($visit) || !isset($site)) {
        showError("Please fill in all required fields!");
        return;
    }
    $fileName = $_FILES["file"]["name"];
    $fileType = $_FILES["file"]["type"];
    $userID = $user->getData('UserID');
    $sessionID = $db->pselectOne("SELECT s.ID as session_id FROM candidate c " . "LEFT JOIN session s USING(CandID) WHERE c.PSCID = :v_pscid AND " . "s.Visit_label = :v_visit_label AND s.CenterID = :v_center_id", ['v_pscid' => $pscid, 'v_visit_label' => $visit, 'v_center_id' => $site]);
    if (!isset($sessionID) || count($sessionID) < 1) {
        showError("Error! A session does not exist for candidate '{$pscid}'' " . "and visit label '{$visit}'.");
        return;
    }
    // Build insert query
    $query = ['session_id' => $sessionID, 'instrument' => $instrument, 'date_taken' => $dateTaken, 'comments' => $comments, 'file_name' => $fileName, 'file_type' => $fileType, 'data_dir' => $mediaPath, 'uploaded_by' => $userID, 'hide_file' => 0, 'date_uploaded' => date("Y-m-d H:i:s")];
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $mediaPath . $fileName)) {
        $db->insert('media', $query);
    } else {
        showError("Could not upload the file. Please try again!");
    }
}
<?php

/**
 * User: Stella
 * Date: 15-08-15
 *
 * Project Statistics - Updating Counts From Each LORIS
 */
set_include_path(get_include_path() . ":../php/libraries:");
require_once __DIR__ . "/../vendor/autoload.php";
$client = new NDB_Client();
$client->makeCommandLine();
$client->initialize('../project/config.xml');
$db =& Database::singleton();
$config = NDB_Config::singleton();
$date = date("m_d_Y");
$output_file = "project_statistics_{$date}.csv";
$fp = fopen($output_file, 'w');
echo "PROJECT STATISTICS SCRIPT - {$date}\n\n";
echo "Data can be found in {$output_file}.\n\n";
$headers = array('Project', 'Number of Scanning - Visits', 'Number of Sites', 'Variable Count', 'Number of instruments', 'total number of visits (for all candidates)', 'number of candidates', 'GB of imaging data (raw and processed)', '# of scans');
$counter = 0;
// Where project's statistics will be stored
$project_statistics = array();
// Project name
$projectname = $config->getSetting('title');
// Number of Scanning - Visits
$number_scanning_visits = $db->pselect("select count(*) from session where Scan_done='Y'", array());
// Number of Sites
$number_sites = $db->pselect("select count(*) from psc WHERE CenterID <>1", array());
// Variable Count
Exemplo n.º 5
0
 function run()
 {
     $config = $this->CouchDB->replaceDoc('Config:BaseConfig', $this->Config);
     print "Updating Config:BaseConfig: {$config}";
     // Run query
     $demographics = $this->SQLDB->pselect($this->_generateQuery(), array());
     $this->CouchDB->beginBulkTransaction();
     $config_setting = NDB_Config::singleton();
     foreach ($demographics as $demographics) {
         $id = 'Demographics_Session_' . $demographics['PSCID'] . '_' . $demographics['Visit_label'];
         $demographics['Cohort'] = $this->_getSubproject($demographics['SubprojectID']);
         unset($demographics['SubprojectID']);
         if (isset($demographics['ProjectID'])) {
             $demographics['Project'] = $this->_getProject($demographics['ProjectID']);
             unset($demographics['ProjectID']);
         }
         if ($config_setting->getSetting("useFamilyID") === "true") {
             $familyID = $this->SQLDB->pselectOne("SELECT FamilyID FROM family\n                                                          WHERE CandID=:cid", array('cid' => $demographics['CandID']));
             if (!empty($familyID)) {
                 $this->Dictionary["FamilyID"] = array('Description' => 'FamilyID of Candidate', 'Type' => "int(6)");
                 $demographics['FamilyID'] = $familyID;
                 $familyFields = $this->SQLDB->pselect("SELECT candID as Family_ID,\n                                    Relationship_type as Relationship_to_candidate\n                                    FROM family\n                                    WHERE FamilyID=:fid AND CandID<>:cid", array('fid' => $familyID, 'cid' => $demographics['CandID']));
                 $num_family = 1;
                 if (!empty($familyFields)) {
                     foreach ($familyFields as $row) {
                         //adding each sibling id and relationship to the file
                         $this->Dictionary["Family_CandID" . $num_family] = array('Description' => 'CandID of Family Member ' . $num_family, 'Type' => "varchar(255)");
                         $this->Dictionary["Relationship_type_Family" . $num_family] = array('Description' => 'Relationship of candidate to Family Member ' . $num_family, 'Type' => "enum('half_sibling','full_sibling','1st_cousin')");
                         $demographics['Family_CandID' . $num_family] = $row['Family_ID'];
                         $demographics['Relationship_type_Family' . $num_family] = $row['Relationship_to_candidate'];
                         $num_family += 1;
                     }
                 }
             }
         }
         $success = $this->CouchDB->replaceDoc($id, array('Meta' => array('DocType' => 'demographics', 'identifier' => array($demographics['PSCID'], $demographics['Visit_label'])), 'data' => $demographics));
         print "{$id}: {$success}\n";
     }
     $this->_updateDataDict();
     $this->CouchDB->replaceDoc('DataDictionary:Demographics', array('Meta' => array('DataDict' => true), 'DataDictionary' => array('demographics' => $this->Dictionary)));
     print $this->CouchDB->commitBulkTransaction();
 }
Exemplo n.º 6
0
$tpl_data['baseurl'] = $baseURL;
// study title
$tpl_data['study_title'] = $config->getSetting('title');
// draw the user information table
try {
    $user =& User::singleton();
    $tpl_data['user'] = $user->getData();
    $tpl_data['user']['permissions'] = $user->getPermissions();
    $tpl_data['hasHelpEditPermission'] = $user->hasPermission('context_help');
    $site =& Site::singleton($user->getData('CenterID'));
    $tpl_data['user']['user_from_study_site'] = $site->isStudySite();
} catch (Exception $e) {
    $tpl_data['error_message'][] = "Error: " . $e->getMessage();
}
// the the list of tabs, their links and perms
$tpl_data['tabs'] = NDB_Config::GetMenuTabs();
//--------------------------------------------------
// configure browser args for the mri browser
// !!! array URL args -- need to correct query in mri_browser to
// accept candidate data
$argstring = '';
if (!empty($_REQUEST['candID'])) {
    $argstring .= "filter%5BcandID%5D=" . $_REQUEST['candID'] . "&";
}
if (!empty($_REQUEST['sessionID'])) {
    try {
        $timePoint =& TimePoint::singleton($_REQUEST['sessionID']);
        $argstring .= "filter%5Bm.VisitNo%5D=" . $timePoint->getVisitNo() . "&";
    } catch (Exception $e) {
        $tpl_data['error_message'][] = "TimePoint Error (" . $_REQUEST['sessionID'] . "): " . $e->getMessage();
    }
 /**
  * Creates LORIS database connection
  *
  * @throws DatabaseException
  * @return void
  */
 protected function createLorisDBConnection()
 {
     $database = $this->config->getSetting('database');
     $this->database = Database::singleton($database['database'], $database['username'], $database['password'], $database['host']);
 }
 /**
  * Constructor function. Instantiates references to database and
  * config class.
  *
  * @return VisitWindowPopulator
  */
 function __construct()
 {
     $this->DB = Database::singleton();
     $this->Config = NDB_Config::singleton();
 }
Exemplo n.º 9
0
/**
 * Get the excluded instruments from the config file
 *
 * @return Array   List of instruments to be skipped
 */
function getExcludedInstruments()
{
    // Get the abbreviated instruments
    $config =& NDB_Config::singleton();
    $excluded_instruments = $config->getSetting('excluded_instruments');
    $ex_instruments = array();
    foreach ($excluded_instruments as $instruments) {
        foreach (Utility::asArray($instruments) as $instrument) {
            $ex_instruments[$instrument] = $instrument;
        }
    }
    return $ex_instruments;
}
Exemplo n.º 10
0
 /**
  * Updates DQT with the new data
  *
  * @param array $data      Candidate data to be updated
  * @param array $ScanTypes All selected scan types in the database
  *
  * @return void
  */
 function updateCandidateDocs($data, $ScanTypes)
 {
     foreach ($data as $row) {
         $doc = $row;
         $identifier = array($row['PSCID'], $row['Visit_label']);
         $docid = 'MRI_Files:' . join($identifier, '_');
         unset($doc['PSCID']);
         unset($doc['Visit_label']);
         unset($doc['SessionID']);
         $success = $this->CouchDB->replaceDoc($docid, array('Meta' => array('DocType' => 'mri_data', 'identifier' => $identifier), 'data' => $doc));
         print $docid . ": " . $success . "\n";
         $config = NDB_Config::singleton();
         $paths = $config->getSetting('paths');
         foreach ($ScanTypes as $Scan) {
             // This isn't very efficient to get the document a second time, but
             // we need the rev for adding the attachments. This whole section
             // should be optimized/cleaned up. For now it's just a hack to get
             // the data into CouchDB, it isn't very clean.
             // This should all be done using a single multipart request
             // eventually.
             $latestDoc = $this->CouchDB->getDoc($docid);
             $fileName = $doc['Selected_' . $Scan['ScanType']];
             $fullPath = $paths['mincPath'] . $fileName;
             if (file_exists($fullPath)) {
                 if (!empty($fileName)) {
                     $toUpload = null;
                     if (!empty($latestDoc['_attachments'])) {
                         if (isset($latestDoc['_attachments'][$fileName])) {
                             $latest_doc = $latestDoc['_attachments'][$fileName];
                             $size = $latest_doc['length'];
                             if ($size != filesize($fullPath)) {
                                 // File has been modified, upload it.
                                 $toUpload = $fileName;
                             }
                         } else {
                             // This attachment not been uploaded - ever
                             $toUpload = $fileName;
                         }
                     } else {
                         // No current attachments, so this file has not
                         // been uploaded
                         $toUpload = $fileName;
                     }
                     if (!empty($toUpload)) {
                         $data = file_get_contents($fullPath);
                         print "Adding {$fileName} to {$docid}\n";
                         $latest = $latestDoc['_rev'];
                         $rev = $docid . '/' . $fileName . '?rev=' . $latest;
                         $output = $this->CouchDB->_postRelativeURL($rev, $data, 'PUT', 'application/x-minc');
                     }
                 }
             } else {
                 print "****COULD NOT FIND {$fullPath} TO ADD TO {$docid}***\n";
             }
         }
     }
     return;
 }
Exemplo n.º 11
0
/**
 * This create the relations between the file and the candidates
 * that have values inserted.
 *
 * @param object $fileToUpload The object containing the $_FILES
 *               and the $_POST values.
 *
 * @return void
 */
function createCandidateFileRelations(&$fileToUpload)
{
    $config = NDB_Config::singleton();
    $genomic_data_dir = $config->getSetting('GenomicDataPath');
    $DB =& Database::singleton();
    $f = fopen($genomic_data_dir . 'genomic_uploader/' . $fileToUpload->file_name, "r");
    if ($f) {
        $stmt_prefix = 'INSERT IGNORE INTO genomic_candidate_files_rel
            (CandID, GenomicFileID) VALUES ';
        $stmt = '';
        $line = fgets($f);
        fclose($f);
        $headers = explode(',', $line);
        array_shift($headers);
        $rows = array();
        foreach ($headers as $pscid) {
            $pscid = trim($pscid);
            $row = "(\n               (select CandID from candidate where PSCID = '{$pscid}'),\n               {$fileToUpload->GenomicFileID}\n            )";
            array_push($rows, $row);
        }
        $stmt .= join(',', $rows);
        try {
            $prep = $DB->prepare($stmt_prefix . $stmt);
            $result = $DB->execute($prep, array(), array('nofetch' => true));
        } catch (DatabaseException $e) {
            die(json_encode(array('message' => 'File registration failed', 'progress' => 100, 'error' => true)));
        }
    } else {
        die(json_encode(array('message' => 'Beta value file can`t be opened', 'progress' => 100, 'error' => true)));
    }
    reportProgress(50, "Creating file-candidate relations");
}