/**
  * Get database connection which will be used by PHPUnit
  * for clean-up and fixture loading into the test DB.
  *
  * @return PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection
  */
 public final function getConnection()
 {
     $this->factory = NDB_Factory::singleton();
     $this->config = $this->factory->Config(CONFIG_XML);
     $database = $this->config->getSetting('database');
     if ($this->_conn === null) {
         if (self::$_pdo == null) {
             self::$_pdo = new PDO('mysql:dbname=' . $database['database'] . ';host=' . $database['host'], $database['username'], $database['password']);
         }
         $this->_conn = $this->createDefaultDBConnection(self::$_pdo);
     }
     return $this->_conn;
 }
 /**
  * Set up sets a fake $_SESSION object that we can use for
  * assertions
  */
 function setUp()
 {
     global $_SESSION;
     if (!defined("UNIT_TESTING")) {
         define("UNIT_TESTING", true);
     }
     $this->Session = $this->getMock('stdClass', array('getProperty', 'setProperty', 'getUsername', 'isLoggedIn'));
     $this->MockSinglePointLogin = $this->getMock('SinglePointLogin');
     $this->Session->method("getProperty")->willReturn($this->MockSinglePointLogin);
     $_SESSION = array('State' => $this->Session);
     $factory = \NDB_Factory::singleton();
     $factory->setTesting(true);
     $mockdb = $this->getMockBuilder("\\Database")->getMock();
     $mockconfig = $this->getMockBuilder("\\NDB_Config")->getMock();
     \NDB_Factory::$db = $mockdb;
     \NDB_Factory::$testdb = $mockdb;
     \NDB_Factory::$config = $mockconfig;
     $this->QuickForm = new \LorisForm();
     //$this->getMock("HTML_Quickform");
     $this->Client = new \NDB_Client();
     $this->Client->makeCommandLine();
     $this->Client->initialize(__DIR__ . "/../../project/config.xml");
     $this->i = $this->getMockBuilder("\\NDB_BVL_Instrument")->setMethods(array("getFullName"))->getMock();
     $this->i->method('getFullName')->willReturn("Test Instrument");
     $this->i->form = $this->QuickForm;
     $this->i->testName = "Test";
 }
示例#3
0
文件: Images.php 项目: spaiva/Loris
 /**
  * Gets a list of images for this visit. Filename only.
  *
  * @return an array of strings of filenames
  */
 function getVisitImages()
 {
     $factory = \NDB_Factory::singleton();
     $DB = $factory->database();
     $rows = $DB->pselect("SELECT OutputType,\n                    SUBSTRING_INDEX(File, '/', -1) as Filename,\n                    mst.Scan_type as AcquisitionType \n                FROM files f \n                    JOIN mri_scan_type mst ON (mst.ID=f.AcquisitionProtocolID)\n                    JOIN session s ON (s.ID=f.SessionID)\n                    JOIN candidate c ON (s.CandID=c.CandID)\n                WHERE s.Visit_label=:VL AND c.CandID=:CID \n                    AND c.Active='Y' AND s.Active='Y'", ['VL' => $this->VisitLabel, 'CID' => $this->CandID]);
     return $rows;
 }
示例#4
0
 /**
  * Constructor to handle basic validation
  *
  * @param string $method The HTTP request method
  */
 function __construct($method)
 {
     if (empty($this->AllowedMethods)) {
         $this->AllowedMethods = ['GET'];
     }
     // Verify that method is allowed for this type of request.
     if (!in_array($method, $this->AllowedMethods)) {
         $this->header("HTTP/1.1 405 Method Not Allowed");
         $this->header("Allow: " . join(", ", $this->AllowedMethods));
         $this->safeExit(0);
     }
     $this->HTTPMethod = $method;
     //Load config file and ensure paths are correct
     set_include_path(get_include_path() . ":" . __DIR__ . "/../../../php/libraries");
     include_once 'NDB_Client.class.inc';
     $this->Factory = \NDB_Factory::singleton();
     $this->client = new \NDB_Client();
     if (defined("UNIT_TESTING")) {
         // Unit tests are run from the command line, so avoid all
         // the session stuff if we're in a unit test
         $this->client->makeCommandLine();
     }
     $this->client->initialize(__DIR__ . "/../../../project/config.xml");
     if (!defined("UNIT_TESTING")) {
         if (!$this->client->isLoggedIn()) {
             $this->header("HTTP/1.1 401 Unauthorized");
             $this->error("User not authenticated");
             $this->safeExit(0);
         }
     }
     $this->DB = $this->Factory->database();
     if ($this->AutoHandleRequestDelegation) {
         $this->handleRequest();
     }
 }
示例#5
0
 function setUp()
 {
     if (!defined("UNIT_TESTING")) {
         define("UNIT_TESTING", true);
     }
     $this->getMockBuilder('NDB_Config')->setMockClassName("MockNDB_Config")->getMock();
     $this->getMockBuilder('Database')->setMockClassName("MockDatabase")->getMock();
     $this->getMockBuilder('Candidate')->setMockClassName("MockCandidate")->getMock();
     $this->getMockBuilder('TimePoint')->setMockClassName("MockTimePoint")->getMock();
     $this->Factory = \NDB_Factory::singleton();
     $this->Factory->setTesting(true);
     $this->Config = $this->Factory->config();
     $this->Database = $this->Factory->database();
     $this->Database->method("pselect")->will($this->returnCallback(function ($query, $params) {
         if ($query == "SELECT CandID FROM candidate WHERE Active='Y'") {
             return [["CandID" => "123456"], ["CandID" => "222222"]];
         }
         if (strpos($query, 'SELECT ID, Visit_label FROM session') === 0) {
             return [["ID" => 444, "Visit_label" => "VisitTwo"]];
         }
         if (strpos($query, "SELECT DISTINCT Test_name FROM flag f JOIN session s") === 0 && $params == array('CID' => "123456", 'VL' => 'VisitTwo')) {
             return [["Test_name" => "Test"], ["Test_name" => "TestTwo"]];
         }
         if ($query == "SELECT * FROM subproject") {
             return [0 => ['SubprojectID' => '1', 'title' => 'Test Battery', 'useEDC' => 0, 'WindowDifference' => 'optimal']];
         }
         return array();
     }));
     $this->Candidate = $this->Factory->Candidate("123456");
     $this->Candidate->method("getListOfVisitLabels")->willReturn(["320" => "Test", "323" => "VisitTwo"]);
     $this->Candidate->method("getCandidateGender")->willReturn("Male");
     $this->Candidate->method("getCandidateDoB")->willReturn("1900-02-20");
     $this->Candidate->method("getCandidateSite")->willReturn("Test");
     $this->Candidate->method("getPSCID")->willReturn("TestCandidate");
     $this->Candidate->method("getProjectTitle")->willReturn("loris");
     $this->Database->method("pselectRow")->will($this->returnCallback(function ($query, $params) {
         if (strpos($query, "SELECT c.CenterID, c.CandID, c.") == 0 && $params == ['Candidate' => "123456"]) {
             return ['CenterID' => 1, "CandID" => 123456, "PSCID" => "TestCandidate", "DoB" => "1900-02-20", "EDC" => null, "Gender" => "Male", "PSC" => "Test"];
         }
         if (strpos($query, "SELECT MAX(c.Testdate) as CandChange") === 0) {
             return ['CandChange' => '24343', 'VisitChange' => '23433', 'VisitCount' => '3'];
         }
         return array();
     }));
     $this->Database->method("pselectOne")->will($this->returnCallback(function ($query, $params) {
         if (strpos($query, "SELECT CommentID FROM flag f") == 0 && $params == ['VL' => 'VisitTwo', 'TN' => 'Test', 'CID' => "123456"]) {
             return 'AFakeCommentID';
         }
         print "Oh noes";
         return array();
     }));
 }
示例#6
0
 protected function setUp()
 {
     $Factory = NDB_Factory::singleton();
     $Factory->setTesting(true);
     $mockdb = $this->getMockBuilder("\\Database")->getMock();
     $mockconfig = $this->getMockBuilder("\\NDB_Config")->getMock();
     $this->_configMap = array(array('JWTKey', "example_key"));
     $mockconfig->method('getSetting')->will($this->returnValueMap($this->_configMap));
     $Factory->setConfig($mockconfig);
     $Factory->setDatabase($mockdb);
     $method = array('JWTAuthenticate', 'PasswordAuthenticate', 'authenticate');
     $this->login = $this->getMock('SinglePointLogin', $this->_getAllMethodsExcept($method));
 }
示例#7
0
文件: Full.php 项目: spaiva/Loris
 /**
  * Retrieves all headers for this file from the database.
  *
  * @return array
  */
 protected function getHeaders()
 {
     $factory = \NDB_Factory::singleton();
     $db = $factory->Database();
     // Get all fields from parameter_type "magically created by
     // neurodb", since those are the dicom headers.
     // There's a few headers that get magically created which
     // aren't header fields, so we manually exclude them.
     // Namely:
     //
     // md5hash, tarchiveMD5, image_comments, check_pic_filename,
     // jiv_path
     return $db->pselect("SELECT pt.Name as Header, Value\n            FROM parameter_file pf \n                JOIN parameter_type pt USING (ParameterTypeID)\n                JOIN files f USING (FileID)\n                JOIN session s ON (f.SessionID=s.ID)\n                JOIN candidate c ON (s.CandID=c.CandID)\n            WHERE c.Active='Y' AND s.Active='Y' AND c.CandID=:CID AND \n                s.Visit_label=:VL AND f.File LIKE CONCAT('%', :Fname) \n                AND pt.Description LIKE '%magically%'\n                AND pt.Name NOT IN (\n                    'md5hash',\n                    'tarchiveMD5',\n                    'image_comments',\n                    'check_pic_filename',\n                    'jiv_path'\n                )\n                ", array('CID' => $this->CandID, 'VL' => $this->VisitLabel, 'Fname' => $this->Filename));
 }
示例#8
0
 function setUp()
 {
     if (!defined("UNIT_TESTING")) {
         define("UNIT_TESTING", true);
     }
     // Create the Mock classes, so that the factory doesn't die.
     $this->getMockBuilder('NDB_Config')->setMockClassName("MockNDB_Config")->getMock();
     $this->getMockBuilder('Database')->setMockClassName("MockDatabase")->getMock();
     $this->Factory = \NDB_Factory::singleton();
     $this->Factory->setTesting(true);
     // Make sure the references used by the test are the same ones
     // returned by the factory
     $this->Config = $this->Factory->config();
     $this->Database = $this->Factory->database();
     $this->Config->expects($this->any())->method('getSetting')->will($this->returnCallback(function ($arg) {
         if ($arg === 'useProjects') {
             return "true";
         }
         if ($arg === 'Projects') {
             return ["project" => [["id" => 1, "title" => "TestProject"]]];
         }
         if ($arg === 'DoubleDataEntryInstruments') {
             return ["testInst2"];
         }
         return null;
     }));
     $this->Database->method("pselect")->will($this->returnCallback(function ($query, $params) {
         // If trying to get all candidates
         if ($query === "SELECT CandID FROM candidate WHERE ProjectID=:projID" && $params === array('projID' => 1)) {
             return [["CandID" => "123456"], ["CandID" => "111111"]];
         }
         // Called Utility::getAllInstruments()
         if ($query === "SELECT Test_name,Full_name FROM test_names") {
             return [["Test_name" => "testInst", "Full_name" => "Test Instrument"], ["Test_name" => "testInst2", "Full_name" => "Another Test Instrument"]];
         }
         if (strpos($query, "SELECT DISTINCT Visit_label FROM") === 0) {
             return [["Visit_label" => "V001"], ["Visit_label" => "AnotherVisit"]];
         }
     }));
     $this->Database->method("pselectOne")->will($this->returnCallback(function ($query, $params) {
         if (strpos($query, "SELECT sg.Subgroup_name") === 0) {
             return "Test Instruments";
         }
         return null;
     }));
     //$this->getMockBuilder('NDB_Config')->setMockClassName("MockNDB_Config")->getMock();
     //$this->getMockBuilder('Database')->setMockClassName("MockDatabase")->getMock();
 }
示例#9
0
 function setUp()
 {
     if (!defined("UNIT_TESTING")) {
         define("UNIT_TESTING", true);
     }
     $this->Config = $this->getMockBuilder('NDB_Config')->setMockClassName("MockNDB_Config")->getMock();
     $this->Factory = \NDB_Factory::singleton();
     $this->Factory->setTesting(true);
     $this->Config = $this->Factory->config();
     $this->Database = $this->Factory->database();
     $this->getMockBuilder('NDB_Config')->setMockClassName("MockNDB_Config")->getMock();
     $this->getMockBuilder('Database')->setMockClassName("MockDatabase")->getMock();
     $this->Database->method("pselect")->will($this->returnCallback(function ($query, $params) {
         if ($query == "SELECT * FROM Project") {
             return [["ProjectID" => 1, "Name" => "Sample Project"], ["ProjectID" => 2, "Name" => "Another Sample Project"]];
         }
         return array();
     }));
     /*
             $this->Config->method("getSetting")->will($this->returnCallback(
                     function ($setting) {
                         // Stuff relevant to this test
                         if($setting === "useEDC") {
                             return "false";
                         }
                         if($setting === "useProjects") {
                             return "false";
                         }
                         if($setting === "PSCID") {
                             return [
                                 ];
                         }
                         // Stuff that gets called around Loris that we don't want to
                         // throw an exception for
                         if($setting === "database") {
                             return false;
                         }
                         if($setting === "extLibs") {
                             return "";
                         }
                         if($setting === "showPearErrors") {
                             return "true";
                         }
     
                         throw new \ConfigurationException("Unmocked config setting $setting");
                     }
             )); */
 }
示例#10
0
 /**
  */
 function setUp()
 {
     if (!defined("UNIT_TESTING")) {
         define("UNIT_TESTING", true);
     }
     $this->getMockBuilder('NDB_Config')->setMockClassName("MockNDB_Config")->getMock();
     $this->getMockBuilder('Database')->setMockClassName("MockDatabase")->getMock();
     $this->getMockBuilder('Candidate')->setMockClassName("MockCandidate")->getMock();
     $this->Factory = NDB_Factory::singleton();
     $this->Factory->setTesting(true);
     $this->Config = $this->Factory->config();
     $this->Database = $this->Factory->database();
     $this->Database->method("pselect")->will($this->returnCallback(function ($query, $params) {
         if (strpos($query, "SELECT CandID, ProjectID") === 0) {
             return [["CandID" => "123456", "ProjectID" => null, "PSCID" => "TestCandidate2", "Site" => "DCC", "EDC" => null, "DoB" => "1833-10-24", "Gender" => "Male"], ["CandID" => "222222", "ProjectID" => null, "PSCID" => "TestCandidate", "Site" => "DCC", "EDC" => null, "DoB" => "1933-10-24", "Gender" => "Female"]];
         }
         return array();
     }));
 }
示例#11
0
文件: Login.php 项目: spaiva/Loris
 /**
  * Return a valid JWT encoded identification token for the user
  *
  * @param string $user The user to return an identification token for
  *
  * @return string JWT encoded token
  */
 function getEncodedToken($user)
 {
     $factory = \NDB_Factory::singleton();
     $config = $factory->config();
     $www = $config->getSetting("www");
     $baseURL = $www['url'];
     $token = array("iss" => $baseURL, "aud" => $baseURL, "iat" => time(), "nbf" => time(), "exp" => time() + 86400, "user" => $user);
     $key = $config->getSetting("JWTKey");
     return \Firebase\JWT\JWT::encode($token, $key, "HS256");
 }
 /**
  * Creates LORIS database connection
  *
  * @throws DatabaseException
  * @return void
  */
 protected function createLorisDBConnection()
 {
     $this->database = Database::singleton($this->factory->settings()->dbName(), $this->factory->settings()->dbUserName(), $this->factory->settings()->dbPassword(), $this->factory->settings()->dbHost());
 }
示例#13
0
文件: Imaging.php 项目: spaiva/Loris
 /**
  * Handle a PUT request by validating the metadata matches the URL
  * and updating the database
  *
  * @return none
  */
 public function handlePUT()
 {
     $fp = fopen("php://input", "r");
     $data = '';
     while (!feof($fp)) {
         $data .= fread($fp, 1024);
     }
     fclose($fp);
     //parse_str(urldecode($data), $data);
     $data = json_decode($data, true);
     if (!isset($data['Meta']['CandID']) || $data['Meta']['CandID'] != $this->CandID) {
         $this->header("HTTP/1.1 400 Bad Request");
         $this->error("Candidate from URL does not match metadata.");
         $this->safeExit(0);
     }
     if (!isset($data['Meta']['Visit']) || $data['Meta']['Visit'] != $this->VisitLabel) {
         $this->header("HTTP/1.1 400 Bad Request");
         $this->error("Visit from URL does not match metadata");
         $this->safeExit(0);
     }
     if (!isset($data['SessionQC'])) {
         $this->header("HTTP/1.1 400 Bad Request");
         $this->error("Missing SessionQC to save.");
         $this->safeExit(0);
     }
     if ($data['SessionQC'] != "Pass" && $data['SessionQC'] != "Fail" && !empty($data['SessionQC'])) {
         $this->header("HTTP/1.1 400 Bad Request");
         $this->error("Invalid value for SessionQC." . " Must be Pass, Fail, or the empty string.");
         $this->safeExit(0);
     }
     if (!isset($data['Pending'])) {
         $this->header("HTTP/1.1 400 Bad Request");
         $this->error("Missing Pending flag.");
         $this->safeExit(0);
     }
     // We know that it's set to something, because we checked above,
     // so verify that Pending is a valid value.
     // true is equal to "true", but false is not equal to "false".
     if ($data['Pending'] != "true" && $data['Pending'] != "false" && $data['Pending'] !== false) {
         $this->header("HTTP/1.1 400 Bad Request");
         $this->error("Invalid value for Pending. Must be true or false.");
         $this->safeExit(0);
     }
     switch ($data['Pending']) {
         case 'true':
             $savePending = 'Y';
             break;
         case 'false':
         case false:
             $savePending = 'N';
             break;
         default:
             $savePending = null;
     }
     // Manually extract the sessionID with a select statement,
     // since the keys used to look it up are in different tables
     // and we can't join in the update wrapper.
     $factory = \NDB_Factory::singleton();
     $DB = $factory->database();
     $sessionID = $DB->pselectOne("SELECT s.ID\n               FROM session s \n                 JOIN candidate c ON (c.CandID=s.CandID) \n               WHERE c.Active='Y' AND s.Active='Y'\n                 AND s.Visit_label=:VL AND c.CandID=:CID", array('VL' => $this->VisitLabel, 'CID' => $this->CandID));
     $qcstatus = $DB->update('session', ['MRIQCStatus' => $data['SessionQC'], 'MRIQCPending' => $savePending], ['ID' => $sessionID]);
     $this->JSON = ["success" => "Updated QC"];
 }
示例#14
0
 /**
  * Tears down the fixture, for example, close a network connection.
  * This method is called after a test is executed.
  *
  * @return void
  */
 protected function tearDown()
 {
     parent::tearDown();
     $this->_factory->reset();
 }
示例#15
0
文件: Image.php 项目: spaiva/Loris
 /**
  * Gets the filename saved in the database for this file
  *
  * @return string
  */
 protected function getDatabaseDir()
 {
     $factory = \NDB_Factory::singleton();
     $db = $factory->Database();
     return $db->pselectOne("SELECT File\n                FROM files f\n                    JOIN session s ON (f.SessionID=s.ID)\n                    JOIN candidate c ON (s.CandID=c.CandID)\n                WHERE c.Active='Y' AND s.Active='Y' \n                    AND c.CandID=:CID AND s.Visit_label=:VL\n                    AND f.File LIKE CONCAT('%', :Fname)", array('CID' => $this->CandID, 'VL' => $this->VisitLabel, 'Fname' => $this->Filename));
 }
示例#16
0
 /**
  * Get the root directory that images are stored under.
  *
  * @return string a directory on the server
  */
 protected function getAssemblyRoot()
 {
     $factory = \NDB_Factory::singleton();
     $config = $factory->Config();
     return $config->getSetting("imagePath") . "/pic/";
 }
示例#17
0
文件: QC.php 项目: spaiva/Loris
 /**
  * Save the QC value to the database. Only call this after everything
  * has been validated
  *
  * @param string $qcval  The Pass/Fail status
  * @param string $selval The value to set the selected field to.
  *
  * @return none
  */
 private function _saveFileQC($qcval, $selval)
 {
     $factory = \NDB_Factory::singleton();
     $DB = $factory->Database();
     $FileID = $DB->pselectOne("SELECT f.FileID FROM files f\n                WHERE f.File LIKE CONCAT('%', :FName)", array('FName' => $this->Filename));
     $AlreadySavedQC = $DB->pselectOne("SELECT COUNT(*) FROM files_qcstatus WHERE FileID=:FID", array('FID' => $FileID));
     if ($AlreadySavedQC > 0) {
         $DB->update("files_qcstatus", ['QCStatus' => $qcval, 'Selected' => $selval], ['FileID' => $FileID]);
     } else {
         $DB->insert("files_qcstatus", ['QCStatus' => $qcval, 'Selected' => $selval, 'FileID' => $FileID]);
     }
 }
 /**
  * Constructor for CouchDBMRIImporter
  */
 function __construct()
 {
     $factory = NDB_Factory::singleton();
     $this->SQLDB = $factory->Database();
     $this->CouchDB = $factory->couchDB();
 }
示例#19
0
 *
 * PHP Version 5
 *
 *  @category Loris
 *  @package  Data_Release
 *  @author   Justin Kat <*****@*****.**>
 *  @license  http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
 *  @link     https://github.com/aces/Loris
 */
$DB =& Database::singleton();
$user =& User::singleton();
if ($_POST['action'] == 'upload') {
    $fileName = $_FILES["file"]["name"];
    $version = $_POST['version'];
    $upload_date = date('Y-m-d');
    $base_path = __DIR__ . "/../user_uploads/";
    $target_path = $base_path . $fileName;
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_path)) {
        $success = $DB->insert('data_release', array('file_name' => $fileName, 'version' => $version, 'upload_date' => $upload_date));
        $user_ID = $DB->pselectOne("SELECT ID FROM users WHERE userid=:UserID", array('UserID' => $user->getUsername()));
        $ID = $DB->pselectOne("SELECT id FROM data_release WHERE " . "file_name=:file_name AND " . "version=:version AND " . "upload_date=:upload_date", array('file_name' => $fileName, 'version' => $version, 'upload_date' => $upload_date));
        $success = $DB->insert('data_release_permissions', array('userid' => $user_ID, 'data_release_id' => $ID));
    }
    $factory = NDB_Factory::singleton();
    $settings = $factory->settings();
    $baseURL = $settings->getBaseURL();
    header("Location: {$baseURL}/data_release/?uploadSuccess=true");
} else {
    header("HTTP/1.1 400 Bad Request");
    echo "There was an error uploading the file";
}
示例#20
0
 function testUnsafeInsertDoesntEscapeHTML()
 {
     $this->_factory = NDB_Factory::singleton();
     $stub = $this->getMockBuilder('FakeDatabase')->setMethods($this->_getAllMethodsExcept(array('unsafeinsert')))->getMock();
     $stub->_PDO = $this->getMockBuilder('FakePDO')->getMock();
     $stmt = $this->getMockBuilder('PDOStatement')->getMock();
     $stmt->expects($this->once())->method("execute")->with($this->equalTo(array('field' => '<b>Hello</b>')));
     $stub->_PDO->expects($this->once())->method("prepare")->will($this->returnValue($stmt));
     $stub->unsafeinsert("test", array('field' => '<b>Hello</b>'), array());
 }