示例#1
0
 /**
  * Extract the dicom metadata from a revision.
  *
  * @param item the id of the item to be extracted
  * @return the id of the revision
  */
 public function extract($args)
 {
     /** @var ApihelperComponent $ApihelperComponent */
     $ApihelperComponent = MidasLoader::loadComponent('Apihelper');
     $ApihelperComponent->renameParamKey($args, 'item', 'id');
     return $this->_callModuleApiMethod($args, 'extract', 'item');
 }
示例#2
0
 /**
  * Get default reception directory.
  */
 public function getDefaultReceptionDir()
 {
     /** @var UtilityComponent $utilityComponent */
     $utilityComponent = MidasLoader::loadComponent('Utility');
     $defaultReceptionDirectory = $utilityComponent->getTempDirectory('dicomserver');
     return $defaultReceptionDirectory;
 }
 /** test index action */
 public function testIndexAction()
 {
     /** @var GroupModel $groupModel */
     $groupModel = MidasLoader::loadModel('Group');
     /** @var ItempolicygroupModel $itempolicygroupModel */
     $itempolicygroupModel = MidasLoader::loadModel('Itempolicygroup');
     /** @var UserModel $userModel */
     $userModel = MidasLoader::loadModel('User');
     /** @var FolderModel $folderModel */
     $folderModel = MidasLoader::loadModel('Folder');
     /** @var UploadComponent $uploadComponent */
     $uploadComponent = MidasLoader::loadComponent('Upload');
     $usersFile = $this->loadData('User', 'default');
     $userDao = $userModel->load($usersFile[0]->getKey());
     Zend_Registry::set('notifier', new MIDAS_Notifier(false, null));
     $privateFolder = $folderModel->load(1002);
     $item = $uploadComponent->createUploadedItem($userDao, 'test.png', BASE_PATH . '/tests/testfiles/search.png', $privateFolder, null, '', true);
     $anonymousGroup = $groupModel->load(MIDAS_GROUP_ANONYMOUS_KEY);
     $itempolicygroupModel->createPolicy($anonymousGroup, $item, MIDAS_POLICY_READ);
     $this->params['itemId'] = $item->getKey();
     $this->dispatchUrl('/visualize/index/index');
     $this->assertController('index');
     $this->dispatchUrl('/visualize/image/index');
     $this->assertController('image');
     $this->dispatchUrl('/visualize/media/index');
     $this->assertController('media');
     $this->dispatchUrl('/visualize/pdf/index');
     $this->assertController('pdf');
     $this->dispatchUrl('/visualize/txt/index');
     $this->assertController('txt');
     $this->dispatchUrl('/visualize/webgl/index');
     $this->assertController('webgl');
 }
示例#4
0
 /** Post database upgrade. */
 public function postUpgrade()
 {
     /** @var RandomComponent $randomComponent */
     $randomComponent = MidasLoader::loadComponent('Random');
     $securityKey = $randomComponent->generateString(32);
     /** @var SettingModel $settingModel */
     $settingModel = MidasLoader::loadModel('Setting');
     $configPath = LOCAL_CONFIGS_PATH . DIRECTORY_SEPARATOR . $this->moduleName . '.local.ini';
     if (file_exists($configPath)) {
         $config = new Zend_Config_Ini($configPath, 'global');
         $settingModel->setConfig(MIDAS_REMOTEPROCESSING_SECURITY_KEY_KEY, $config->get('securitykey', $securityKey), $this->moduleName);
         $showButton = $config->get('showbutton');
         if ($showButton === 'true') {
             $showButton = 1;
         } elseif ($showButton === 'false') {
             $showButton = 0;
         } else {
             $showButton = MIDAS_REMOTEPROCESSING_SHOW_BUTTON_DEFAULT_VALUE;
         }
         $settingModel->setConfig(MIDAS_REMOTEPROCESSING_SHOW_BUTTON_KEY, $showButton, $this->moduleName);
         $config = new Zend_Config_Ini($configPath, null, true);
         unset($config->securitykey->securitykey);
         unset($config->showbutton->showbutton);
         $writer = new Zend_Config_Writer_Ini();
         $writer->setConfig($config);
         $writer->setFilename($configPath);
         $writer->write();
     } else {
         $settingModel->setConfig(MIDAS_REMOTEPROCESSING_SECURITY_KEY_KEY, $securityKey, $this->moduleName);
         $settingModel->setConfig(MIDAS_REMOTEPROCESSING_SHOW_BUTTON_KEY, MIDAS_REMOTEPROCESSING_SHOW_BUTTON_DEFAULT_VALUE, $this->moduleName);
     }
 }
 /**
  * Generate an upload token that will act as the authentication token for the upload.
  * This token is the filename of a unique file which will be placed under the
  * directory specified by the dirname parameter, which should be used to ensure that
  * the user can only write into a certain logical space.
  *
  * @param array $args
  * @param string $dirname
  * @return array
  * @throws Exception
  */
 public function generateToken($args, $dirname = '')
 {
     if (!array_key_exists('filename', $args)) {
         throw new Exception('Parameter filename is not defined', MIDAS_HTTPUPLOAD_FILENAME_PARAM_UNDEFINED);
     }
     $tempDirectory = UtilityComponent::getTempDirectory();
     $dir = $dirname === '' ? '' : '/' . $dirname;
     $dir = $tempDirectory . $dir;
     if (!file_exists($dir)) {
         if (!mkdir($dir, 0777, true)) {
             throw new Exception('Failed to create temporary upload dir', MIDAS_HTTPUPLOAD_TMP_DIR_CREATION_FAILED);
         }
     }
     /** @var RandomComponent $randomComponent */
     $randomComponent = MidasLoader::loadComponent('Random');
     $uniqueIdentifier = $randomComponent->generateString(64);
     if ($dirname != '') {
         $uniqueIdentifier = $dirname . '/' . $uniqueIdentifier;
     }
     $path = $tempDirectory . '/' . $uniqueIdentifier;
     if (file_exists($path)) {
         throw new Exception('Failed to generate upload token', MIDAS_HTTPUPLOAD_UPLOAD_TOKEN_GENERATION_FAILED);
     }
     if (touch($path) === false) {
         mkdir($path, 0777, true);
         $uniqueIdentifier .= '/';
     }
     return array('token' => $uniqueIdentifier);
 }
 /**
  * Fetch the information about an ItemRevision.
  *
  * @path /itemrevision/{id}
  * @http GET
  * @param id The id of the ItemRevision
  * @return ItemRevision object
  *
  * @param array $args parameters
  * @throws Exception
  */
 public function itemrevisionGet($args)
 {
     /** @var ApihelperComponent $apihelperComponent */
     $apihelperComponent = MidasLoader::loadComponent('Apihelper');
     $apihelperComponent->validateParams($args, array('id'));
     $apihelperComponent->requirePolicyScopes(array(MIDAS_API_PERMISSION_SCOPE_READ_DATA));
     $userDao = $apihelperComponent->getUser($args);
     $itemrevision_id = $args['id'];
     /** @var ItemRevisionModel $itemRevisionModel */
     $itemRevisionModel = MidasLoader::loadModel('ItemRevision');
     $itemRevision = $itemRevisionModel->load($itemrevision_id);
     /** @var ItemModel $itemModel */
     $itemModel = MidasLoader::loadModel('Item');
     $item = $itemModel->load($itemRevision->getItemId());
     if ($item === false || !$itemModel->policyCheck($item, $userDao, MIDAS_POLICY_READ)) {
         throw new Exception("This item doesn't exist or you don't have the permissions.", MIDAS_INVALID_POLICY);
     }
     $in = $itemRevision->toArray();
     $out = array();
     $out['id'] = $in['itemrevision_id'];
     $out['item_id'] = $in['item_id'];
     $out['date_created'] = $in['date'];
     $out['date_updated'] = $in['date'];
     // fix this
     $out['changes'] = $in['changes'];
     $out['user_id'] = $in['user_id'];
     $out['license_id'] = $in['license_id'];
     $out['uuid'] = $in['uuid'];
     $out['bitstreams'] = array_map(array($this, 'getBitstreamId'), $itemRevision->getBitstreams());
     return $out;
 }
 /**
  * Create the database record for inviting a user via email that is not registered yet.
  *
  * @param email The email of the user (should not exist in Midas already)
  * @param group The group to invite the user to
  * @param inviter The user issuing the invitation (typically the session user)
  * @return the created NewUserInvitationDao
  */
 public function createInvitation($email, $group, $inviter)
 {
     /** @var RandomComponent $randomComponent */
     $randomComponent = MidasLoader::loadComponent('Random');
     $email = strtolower($email);
     /** @var NewUserInvitationDao $newUserInvitation */
     $newUserInvitation = MidasLoader::newDao('NewUserInvitationDao');
     $newUserInvitation->setEmail($email);
     $newUserInvitation->setAuthKey($randomComponent->generateString(64, '0123456789abcdef'));
     $newUserInvitation->setInviterId($inviter->getKey());
     $newUserInvitation->setGroupId($group->getKey());
     $newUserInvitation->setCommunityId($group->getCommunityId());
     $newUserInvitation->setDateCreation(date('Y-m-d H:i:s'));
     /** @var UserModel $userModel */
     $userModel = MidasLoader::loadModel('User');
     $existingUser = $userModel->getByEmail($email);
     if ($existingUser) {
         throw new Zend_Exception('User with that email already exists');
     }
     // If the user has already been sent an invitation to this community, delete existing record
     $existingInvitation = $this->getByParams(array('email' => $email, 'community_id' => $group->getCommunityId()));
     if ($existingInvitation) {
         $this->delete($existingInvitation);
     }
     $this->save($newUserInvitation);
     return $newUserInvitation;
 }
示例#8
0
 /**
  * Submit your OTP after calling core login, and you will receive your api token.
  *
  * @param otp The one-time password
  * @param mfaTokenId The id of the temporary MFA token
  * @return The api token
  * @throws Exception
  */
 public function otpLogin($params)
 {
     $this->_checkKeys(array('otp', 'mfaTokenId'), $params);
     /** @var Mfa_ApitokenModel $tempTokenModel */
     $tempTokenModel = MidasLoader::loadModel('Apitoken', 'mfa');
     /** @var Mfa_OtpdeviceModel $otpDeviceModel */
     $otpDeviceModel = MidasLoader::loadModel('Otpdevice', 'mfa');
     /** @var TokenModel $apiTokenModel */
     $apiTokenModel = MidasLoader::loadModel('Token');
     $tempToken = $tempTokenModel->load($params['mfaTokenId']);
     if (!$tempToken) {
         throw new Exception('Invalid MFA token id', -1);
     }
     $apiToken = $apiTokenModel->load($tempToken->getTokenId());
     if (!$apiToken) {
         $tempTokenModel->delete($tempToken);
         throw new Exception('Corresponding api token no longer exists', -1);
     }
     $user = $tempToken->getUser();
     $otpDevice = $otpDeviceModel->getByUser($user);
     if (!$otpDevice) {
         $tempTokenModel->delete($tempToken);
         throw new Exception('User does not have an OTP device', -1);
     }
     $tempTokenModel->delete($tempToken);
     /** @var Mfa_OtpComponent $otpComponent */
     $otpComponent = MidasLoader::loadComponent('Otp', 'mfa');
     if (!$otpComponent->authenticate($otpDevice, $params['otp'])) {
         throw new Exception('Incorrect OTP', -1);
     }
     $token = $apiToken->getToken();
     return array('token' => $token);
 }
示例#9
0
 /**
  * Get the readme text from the specified folder.
  */
 public function fromFolder($folder)
 {
     /** @var FolderModel $folderModel */
     $folderModel = MidasLoader::loadModel('Folder');
     /** @var ItemModel $itemModel */
     $itemModel = MidasLoader::loadModel('Item');
     $readmeItem = null;
     $candidates = array('readme.md', 'readme.txt', 'readme');
     foreach ($candidates as $candidate) {
         $readmeItem = $folderModel->getItemByName($folder, $candidate, false);
         if ($readmeItem != null) {
             break;
         }
     }
     if ($readmeItem == null) {
         return array('text' => '');
     }
     $revisionDao = $itemModel->getLastRevision($readmeItem);
     if ($revisionDao === false) {
         return array('text' => '');
     }
     $bitstreams = $revisionDao->getBitstreams();
     if (count($bitstreams) === 0) {
         return array('text' => '');
     }
     $bitstream = $bitstreams[0];
     $path = $bitstream->getAssetstore()->getPath() . '/' . $bitstream->getPath();
     $contents = file_get_contents($path);
     MidasLoader::loadComponent('Utility');
     $parsedContents = UtilityComponent::markdown(htmlspecialchars($contents, ENT_COMPAT, 'UTF-8'));
     return array('text' => $parsedContents);
 }
示例#10
0
 /** Post database upgrade. */
 public function postUpgrade()
 {
     /** @var SettingModel $settingModel */
     $settingModel = MidasLoader::loadModel('Setting');
     $config = new Zend_Config_Ini(APPLICATION_CONFIG, 'global');
     $settingModel->setConfig('address_verification', $config->get('verifyemail', 0), 'mail');
     if ($config->get('smtpfromaddress')) {
         $fromAddress = $config->get('smtpfromaddress');
     } elseif (ini_get('sendmail_from')) {
         $fromAddress = ini_get('sendmail_from');
     } else {
         $fromAddress = '*****@*****.**';
         // RFC2606
     }
     $settingModel->setConfig('from_address', $fromAddress, 'mail');
     if ($config->get('smtpserver')) {
         $components = parse_url($config->get('smtpserver'));
         if (isset($components['host'])) {
             $settingModel->setConfig('smtp_host', $components['host'], 'mail');
         }
         if (isset($components['port'])) {
             $settingModel->setConfig('smtp_port', $components['port'], 'mail');
             if ($components['port'] === 587) {
                 $settingModel->setConfig('smtp_use_ssl', 1, 'mail');
             }
         }
         if (isset($components['user'])) {
             $settingModel->setConfig('smtp_username', $components['user'], 'mail');
         }
         if (isset($components['pass'])) {
             $settingModel->setConfig('smtp_password', $components['pass'], 'mail');
         }
     }
     if ($config->get('smtpuser')) {
         $settingModel->setConfig('smtp_username', $config->get('smtpuser'), 'mail');
     }
     if ($config->get('smtppassword')) {
         $settingModel->setConfig('smtp_password', $config->get('smtppassword'), 'mail');
     }
     if ($settingModel->getValueByName('smtp_host', 'mail')) {
         $provider = 'smtp';
     } else {
         $provider = 'mail';
     }
     $settingModel->setConfig('provider', $provider, 'mail');
     /** @var UtilityComponent $utilityComponent */
     $utilityComponent = MidasLoader::loadComponent('Utility');
     $utilityComponent->installModule('mail');
     $config = new Zend_Config_Ini(APPLICATION_CONFIG, null, true);
     unset($config->global->smtpfromaddress);
     unset($config->global->smtpserver);
     unset($config->global->smtpuser);
     unset($config->global->smtppassword);
     unset($config->global->verifyemail);
     $writer = new Zend_Config_Writer_Ini();
     $writer->setConfig($config);
     $writer->setFilename(APPLICATION_CONFIG);
     $writer->write();
 }
示例#11
0
 /**
  * Call module API method.
  *
  * @param array $args
  * @param string $coreApiMethod
  * @param null|string $resource
  * @param bool $hasReturn
  * @return null|mixed
  * @throws Zend_Exception
  */
 private function _callModuleApiMethod($args, $coreApiMethod, $resource = null, $hasReturn = true)
 {
     $ApiComponent = MidasLoader::loadComponent('Api' . $resource, 'sizequota');
     $rtn = $ApiComponent->{$coreApiMethod}($args);
     if ($hasReturn) {
         return $rtn;
     }
     return;
 }
示例#12
0
 /** Post database install. */
 public function postInstall()
 {
     /** @var RandomComponent $randomComponent */
     $randomComponent = MidasLoader::loadComponent('Random');
     $securityKey = $randomComponent->generateString(32);
     /** @var SettingModel $settingModel */
     $settingModel = MidasLoader::loadModel('Setting');
     $settingModel->setConfig(MIDAS_REMOTEPROCESSING_SECURITY_KEY_KEY, $securityKey, $this->moduleName);
     $settingModel->setConfig(MIDAS_REMOTEPROCESSING_SHOW_BUTTON_KEY, MIDAS_REMOTEPROCESSING_SHOW_BUTTON_DEFAULT_VALUE, $this->moduleName);
 }
示例#13
0
 /**
  * Get the readme text for a folder.
  *
  * @path /readmes/folder/{id}
  * @http GET
  * @param id the id of the folder from which to get the readme
  * @return the text of the readme
  */
 public function get($args)
 {
     /** @var ApihelperComponent $apihelperComponent */
     $apihelperComponent = MidasLoader::loadComponent('Apihelper');
     /** @var Readmes_GetReadmeComponent $readmeComponent */
     $readmeComponent = MidasLoader::loadComponent('GetReadme', 'readmes');
     $apihelperComponent->validateParams($args, array('id'));
     /** @var FolderModel $folderModel */
     $folderModel = MidasLoader::loadModel('Folder');
     $folderDao = $folderModel->load($args['id']);
     $readme = $readmeComponent->fromFolder($folderDao);
     return $readme;
 }
示例#14
0
 /** Get json to pass to the view initially */
 public function getJson($params)
 {
     $json = array('limit' => 10, 'offset' => 0);
     if ($this->userSession->Dao != null) {
         $json['user'] = $this->userSession->Dao;
     }
     /** @var Comments_CommentComponent $commentComponent */
     $commentComponent = MidasLoader::loadComponent('Comment', $this->moduleName);
     list($comments, $total) = $commentComponent->getComments($params['item'], $json['limit'], $json['offset']);
     $json['comments'] = $comments;
     $json['total'] = $total;
     return $json;
 }
 /** Test extraction of a zip file */
 public function testPerformAction()
 {
     // Simulate uploading our zip file into the assetstore (cp instead of mv)
     /** @var UploadComponent $uploadComponent */
     $uploadComponent = MidasLoader::loadComponent('Upload');
     $adminUser = $this->User->load(3);
     $adminFolders = $adminUser->getFolder()->getFolders();
     $parent = $adminFolders[0];
     $path = BASE_PATH . '/modules/archive/tests/data/test.zip';
     $item = $uploadComponent->createUploadedItem($adminUser, 'test.zip', $path, $parent, null, '', true);
     // Should fail when we try without privileges
     $url = '/archive/extract/perform?deleteArchive=true&itemId=' . $item->getKey();
     $this->dispatchUrl($url, null, true);
     // Now run with proper privileges
     $this->resetAll();
     $this->dispatchUrl($url, $adminUser);
     // The original item should have been deleted
     $item = $this->Item->load($item->getKey());
     $this->assertFalse($item);
     // It should be replaced by the expected hierarchy
     /** @var SortdaoComponent $sortDaoComponent */
     $sortDaoComponent = MidasLoader::loadComponent('Sortdao');
     $sortDaoComponent->field = 'name';
     $childItems = $parent->getItems();
     $this->assertEquals(count($childItems), 2);
     usort($childItems, array($sortDaoComponent, 'sortByName'));
     $child0 = $childItems[0];
     $this->assertEquals($child0->getName(), 'AppController.php');
     $child1 = $childItems[1];
     $this->assertEquals($child1->getName(), 'Notification.php');
     $childFolders = $parent->getFolders();
     $this->assertEquals(count($childFolders), 2);
     usort($childFolders, array($sortDaoComponent, 'sortByName'));
     $childPublic = $childFolders[0];
     $this->assertEquals($childPublic->getName(), 'public');
     $childTranslation = $childFolders[1];
     $this->assertEquals($childTranslation->getName(), 'translation');
     $translationChildFolders = $childTranslation->getFolders();
     $this->assertEquals(count($translationChildFolders), 0);
     $translationChildItems = $childTranslation->getItems();
     $this->assertEquals(count($translationChildItems), 1);
     $this->assertEquals($translationChildItems[0]->getName(), 'fr-main.csv');
     $publicChildItems = $childPublic->getItems();
     $this->assertEquals(count($publicChildItems), 0);
     $publicChildFolders = $childPublic->getFolders();
     $this->assertEquals(count($publicChildFolders), 2);
     usort($publicChildFolders, array($sortDaoComponent, 'sortByName'));
     $this->assertEquals($publicChildFolders[0]->getName(), 'css');
     $this->assertEquals($publicChildFolders[1]->getName(), 'js');
     // The rest is assumed to follow by induction :)
 }
示例#16
0
 /** save */
 public function save($dao)
 {
     if (!isset($dao->uuid) || empty($dao->uuid)) {
         /** @var UuidComponent $uuidComponent */
         $uuidComponent = MidasLoader::loadComponent('Uuid');
         $dao->setUuid($uuidComponent->generate());
     }
     $name = $dao->getName();
     if (empty($name) && $name !== '0') {
         throw new Zend_Exception('Please set a name for the Community.');
     }
     $cleanDescription = UtilityComponent::filterHtmlTags($dao->getDescription());
     $dao->setDescription($cleanDescription);
     parent::save($dao);
 }
示例#17
0
 /**
  * Extract an archive out of an item and into the hierarchy in place.
  *
  * @param ItemDao $itemDao item representing the archive to extract
  * @param bool $deleteArchive whether to delete the archive item when finished extraction
  * @param UserDao $user user DAO
  * @param null|ProgressDao $progressDao progress DAO
  * @return FolderDao
  * @throws Zend_Exception
  */
 public function extractInPlace($itemDao, $deleteArchive, $user, $progressDao = null)
 {
     $this->Item = MidasLoader::loadModel('Item');
     $this->Folder = MidasLoader::loadModel('Folder');
     $this->Folderpolicyuser = MidasLoader::loadModel('Folderpolicyuser');
     $this->Folderpolicygroup = MidasLoader::loadModel('Folderpolicygroup');
     $this->Progress = MidasLoader::loadModel('Progress');
     $this->Setting = MidasLoader::loadModel('Setting');
     $this->UploadComponent = MidasLoader::loadComponent('Upload');
     $this->user = $user;
     $rev = $this->Item->getLastRevision($itemDao);
     if (!$rev) {
         throw new Zend_Exception('This item has no revisions');
     }
     $bitstreams = $rev->getBitstreams();
     if (count($bitstreams) !== 1) {
         throw new Zend_Exception('Head revision must have only one bitstream');
     }
     if ($progressDao) {
         $this->Progress->updateProgress($progressDao, 0, 'Preparing to extract archive...');
     }
     $bitstreamDao = $bitstreams[0];
     $name = $bitstreamDao->getName();
     $folders = $itemDao->getFolders();
     $parentFolder = $folders[0];
     // First extract the archive into a temp location on disk
     if ($this->_isFileExtension($name, '.zip')) {
         $extractedPath = $this->_extractZip($bitstreamDao, $progressDao);
     } else {
         throw new Zend_Exception('This file is not a supported archive type');
     }
     // Next create the hierarchy from the temp location
     if ($progressDao) {
         $this->Progress->updateProgress($progressDao, 0, 'Adding items to Midas tree...');
     }
     $this->_addToHierarchy($extractedPath, $parentFolder, $progressDao);
     // Clean up the dirs we made in the temp directory
     UtilityComponent::rrmdir($extractedPath);
     // Finally, delete existing archive item if user has specified to do so
     if ($deleteArchive) {
         if ($progressDao) {
             $progressDao->setMessage('Deleting old archive...');
             $this->Progress->save($progressDao);
         }
         $this->Item->delete($itemDao);
     }
     return $parentFolder;
 }
示例#18
0
 /**
  * @param tmp_dir the path to the batchmake temp dir
  * @param bin_dir the path to the batchmake bin dir, should have BatchMake exe
  * @param script_dir the path to the batchmake script dir, where bms files live
  * @param app_dir the path to the dir housing executables
  * @param data_dir the path to the data export dir
  * @param condor_bin_dir the path to the location of the condor executables
  * @return an array, the first value is a 0 if the config is incorrect or 1
  *            if the config is correct, the second value is a list of individual config values and their statuses.
  */
 public function testconfig($params)
 {
     // any values that aren't filled in, fill them in with a blank
     $expectedKeys = array('tmp_dir', 'bin_dir', 'script_dir', 'app_dir', 'data_dir', 'condor_bin_dir');
     $configParams = array();
     foreach ($expectedKeys as $propKey) {
         if (!isset($params[$propKey])) {
             $configParams[$propKey] = '';
         } else {
             $configParams[$propKey] = $params[$propKey];
         }
     }
     /** @var Batchmake_KWBatchmakeComponent $kwbatchmakeComponent */
     $kwbatchmakeComponent = MidasLoader::loadComponent('KWBatchmake', 'batchmake');
     return $kwbatchmakeComponent->testconfig($configParams);
 }
示例#19
0
 /**
  * Constructs the link that is used to initiate a google oauth authentication.
  * This link redirects the user to google so they can approve of the requested
  * oauth scopes, and in turn google will redirect them back to our callback
  * url with an authorization code.
  */
 public function googleAuthLink()
 {
     $clientId = $this->Setting->getValueByName(GOOGLE_AUTH_CLIENT_ID_KEY, $this->moduleName);
     $scheme = array_key_exists('HTTPS', $_SERVER) && $_SERVER['HTTPS'] ? 'https://' : 'http://';
     $fc = Zend_Controller_Front::getInstance();
     /** @var RandomComponent $randomComponent */
     $randomComponent = MidasLoader::loadComponent('Random');
     $csrfToken = $randomComponent->generateString(30);
     $redirectUri = $scheme . $_SERVER['HTTP_HOST'] . $fc->getBaseUrl() . '/' . $this->moduleName . '/callback';
     $scopes = array('profile', 'email');
     $href = 'https://accounts.google.com/o/oauth2/auth?response_type=code' . '&client_id=' . urlencode($clientId) . '&redirect_uri=' . urlencode($redirectUri) . '&scope=' . urlencode(implode(' ', $scopes)) . '&state=' . urlencode($csrfToken);
     $userNs = new Zend_Session_Namespace('Auth_User');
     $userNs->oauthToken = $csrfToken;
     session_write_close();
     return '<div style="margin-top: 10px; display: inline-block;">Or ' . '<a class="googleauth-login" style="text-decoration: underline;" href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '">' . 'Login with your Google account</a></div><script type="text/javascript"' . ' src="' . $fc->getBaseUrl() . '/modules/' . $this->moduleName . '/public/js/login/googleauth.login.js"></script>';
 }
 /**
  * Test geolocation.
  */
 public function testGeolocationTask()
 {
     // We need the module constants to be imported, and the notifier to be set
     require_once BASE_PATH . '/modules/scheduler/constant/module.php';
     Zend_Registry::set('notifier', new MIDAS_Notifier(false, null));
     // Use the admin user so we can configure the module
     $usersFile = $this->loadData('User', 'default');
     $userDao = $this->User->load($usersFile[2]->getKey());
     /** @var Scheduler_JobModel $jobModel */
     $jobModel = MidasLoader::loadModel('Job', 'scheduler');
     /** @var Statistics_IpLocationModel $ipLocationModel */
     $ipLocationModel = MidasLoader::loadModel('IpLocation', 'statistics');
     $ipLocations = $ipLocationModel->getAllUnlocated();
     $this->assertEquals(count($ipLocations), 1);
     $this->assertEquals($ipLocations[0]->getLatitude(), '');
     $this->assertEquals($ipLocations[0]->getLongitude(), '');
     $ip = $ipLocations[0]->getIp();
     /** @var $adminComponent Statistics_AdminComponent */
     $adminComponent = MidasLoader::loadComponent('Admin', 'statistics');
     $adminComponent->schedulePerformGeolocationJob('1234', $userDao);
     // Assert that the task is now scheduled
     $jobs = $jobModel->getJobsByTask('TASK_STATISTICS_PERFORM_GEOLOCATION');
     $this->assertEquals(count($jobs), 1);
     $job = $jobs[0];
     $params = json_decode($job->getParams());
     $this->assertEquals($params->apikey, '1234');
     // Make it so the job will fire on the next scheduler run
     $job->setFireTime(date('Y-m-d', strtotime('-1 day')) . ' 01:00:00');
     $jobModel->save($job);
     // Run the scheduler
     $this->resetAll();
     $this->dispatchUrl('/scheduler/run/index', $userDao);
     // Assert that geolocation task was performed
     $ipLocations = $ipLocationModel->getAllUnlocated();
     $this->assertEquals(count($ipLocations), 0);
     $ipLocation = $ipLocationModel->getByIp($ip);
     $this->assertTrue($ipLocation != false);
     $this->assertEquals($ipLocation->getLatitude(), '0');
     $this->assertEquals($ipLocation->getLongitude(), '0');
     // We should have a message in the log now
     $logs = $job->getLogs();
     $this->assertEquals(count($logs), 1);
     $this->assertTrue(strpos($logs[0]->getLog(), 'IpInfoDb lookup failed') !== false);
     echo 'Log = ' . $logs[0]->getLog();
 }
示例#21
0
 /**
  * Returns a page of comments and all required information
  * to be rendered in the view.
  */
 public function getComments($item, $limit, $offset)
 {
     /** @var Comments_ItemcommentModel $itemCommentModel */
     $itemCommentModel = MidasLoader::loadModel('Itemcomment', 'comments');
     /** @var DateComponent $dateComponent */
     $dateComponent = MidasLoader::loadComponent('Date');
     $comments = $itemCommentModel->getComments($item, $limit, $offset);
     $total = $itemCommentModel->getTotal($item);
     $commentsList = array();
     foreach ($comments as $comment) {
         $commentArray = $comment->toArray();
         $commentArray['user'] = $comment->getUser()->toArray();
         $commentArray['comment'] = htmlspecialchars($commentArray['comment'], ENT_QUOTES, 'UTF-8');
         $commentArray['ago'] = $dateComponent->ago($commentArray['date']);
         $commentsList[] = $commentArray;
     }
     return array($commentsList, $total);
 }
示例#22
0
 /**
  * Create and return a new oauth client owned by the given user.
  *
  * @param UserDao $userDao owner of the client
  * @param string $name human readable name of the client
  * @return Oauth_ClientDao
  * @throws Zend_Exception
  */
 public function create($userDao, $name)
 {
     if (!$userDao instanceof UserDao) {
         throw new Zend_Exception('Invalid userDao');
     }
     if (empty($name)) {
         throw new Zend_Exception('Client name must not be empty');
     }
     /** @var RandomComponent $randomComponent */
     $randomComponent = MidasLoader::loadComponent('Random');
     /** @var Oauth_ClientDao $clientDao */
     $clientDao = MidasLoader::newDao('ClientDao', $this->moduleName);
     $clientDao->setName($name);
     $clientDao->setOwnerId($userDao->getKey());
     $clientDao->setSecret($randomComponent->generateString(40));
     $clientDao->setCreationDate(date('Y-m-d H:i:s'));
     $this->save($clientDao);
     return $clientDao;
 }
示例#23
0
 /**
  * Used to refresh the list of comments on the page.
  *
  * @param itemId The item id whose comments to get
  * @param limit Max number of comments to display at once
  * @param offset Offset count for pagination
  * @throws Zend_Exception
  */
 public function getAction()
 {
     $itemId = $this->getParam('itemId');
     if (!isset($itemId) || !$itemId) {
         throw new Zend_Exception('Must set itemId parameter');
     }
     $item = $this->Item->load($itemId);
     if (!$item) {
         throw new Zend_Exception('Not a valid itemId');
     }
     $limit = $this->getParam('limit');
     $offset = $this->getParam('offset');
     $this->disableView();
     $this->disableLayout();
     /** @var Comments_CommentComponent $commentComponent */
     $commentComponent = MidasLoader::loadComponent('Comment', $this->moduleName);
     list($comments, $total) = $commentComponent->getComments($item, $limit, $offset);
     echo JsonComponent::encode(array('status' => 'ok', 'comments' => $comments, 'total' => $total));
 }
示例#24
0
 /**
  * Test uploading a scalar with a submission attached via uuid.
  *
  * @throws Zend_Exception
  */
 public function testUploadScalarWithSubmission()
 {
     $uuidComponent = MidasLoader::loadComponent('Uuid');
     $uuid = $uuidComponent->generate();
     $token = $this->_loginAsAdministrator();
     $outputs = array();
     $outputs['metric_0'] = $this->_submitScalar($token, $uuid, 'metric_0', '18');
     $outputs['metric_1'] = $this->_submitScalar($token, $uuid, 'metric_1', '19', 'meters');
     $outputs['metric_2'] = $this->_submitScalar($token, $uuid, 'metric_2', '20', 'mm');
     /** @var Tracker_SubmissionModel $submissionModel */
     $submissionModel = MidasLoader::loadModel('Submission', 'tracker');
     /** @var Tracker_SubmissionDao $submissionDao */
     $submissionDao = $submissionModel->getSubmission($uuid);
     $scalarDaos = $submissionModel->getScalars($submissionDao);
     /** @var Tracker_ScalarDao $scalarDao */
     foreach ($scalarDaos as $scalarDao) {
         $curOutput = $outputs[$scalarDao->getTrend()->getMetricName()];
         $this->assertEquals($curOutput->value, $scalarDao->getValue());
         $this->assertEquals($submissionDao->getKey(), $scalarDao->getSubmissionId());
     }
 }
示例#25
0
 /**
  * Extract the dicom metadata from a revision.
  *
  * @path /dicomextractor/item/{id}
  * @http PUT
  * @param id the id of the item to be extracted
  * @return the id of the revision
  *
  * @param array $args parameters
  * @throws Exception
  */
 public function extract($args)
 {
     /** @var ApihelperComponent $apihelperComponent */
     $apihelperComponent = MidasLoader::loadComponent('Apihelper');
     $apihelperComponent->validateParams($args, array('id'));
     /** @var ItemModel $itemModel */
     $itemModel = MidasLoader::loadModel('Item');
     /** @var AuthenticationComponent $authComponent */
     $authComponent = MidasLoader::loadComponent('Authentication');
     $itemDao = $itemModel->load($args['id']);
     $userDao = $authComponent->getUser($args, Zend_Registry::get('userSession')->Dao);
     if (!$itemModel->policyCheck($itemDao, $userDao, MIDAS_POLICY_WRITE)) {
         throw new Exception('You didn\'t log in or you don\'t have the write ' . 'permission for the given item.', MIDAS_INVALID_POLICY);
     }
     $revisionDao = $itemModel->getLastRevision($itemDao);
     if ($revisionDao === false) {
         throw new Exception('The item has no revisions', MIDAS_INVALID_POLICY);
     }
     /** @var Dicomextractor_ExtractorComponent $dicomComponent */
     $dicomComponent = MidasLoader::loadComponent('Extractor', 'dicomextractor');
     $dicomComponent->extract($revisionDao);
     $dicomComponent->thumbnail($itemDao);
     return json_encode($revisionDao);
 }
示例#26
0
 /**
  * Create and return a new oauth authorization code for the given client and user. Expires after 10 minutes
  * in accordance with the recommendation in the IETF draft v31.
  *
  * @param UserDao $userDao resource owner (end user to authenticate via the client)
  * @param Oauth_ClientDao $clientDao client that will be receiving the code
  * @param array $scopes array of permission scopes (see api module constants)
  * @return Oauth_CodeDao
  * @throws Zend_Exception
  */
 public function create($userDao, $clientDao, $scopes)
 {
     if (!$userDao instanceof UserDao) {
         throw new Zend_Exception('Invalid userDao');
     }
     if (!$clientDao instanceof Oauth_ClientDao) {
         throw new Zend_Exception('Invalid userDao');
     }
     if (!is_array($scopes)) {
         throw new Zend_Exception('Scopes must be an array');
     }
     /** @var RandomComponent $randomComponent */
     $randomComponent = MidasLoader::loadComponent('Random');
     /** @var Oauth_CodeDao $codeDao */
     $codeDao = MidasLoader::newDao('CodeDao', $this->moduleName);
     $codeDao->setCode($randomComponent->generateString(32));
     $codeDao->setScopes(JsonComponent::encode($scopes));
     $codeDao->setUserId($userDao->getKey());
     $codeDao->setClientId($clientDao->getKey());
     $codeDao->setCreationDate(date('Y-m-d H:i:s'));
     $codeDao->setExpirationDate(date('Y-m-d H:i:s', strtotime('+10 minutes')));
     $this->save($codeDao);
     return $codeDao;
 }
示例#27
0
 /**
  * Generate an upload token and upload URL.
  *
  * @param array $args
  * @return array
  */
 public function uploadGeneratetoken($args)
 {
     /** @var Googleappengine_ApiuploadComponent $apiuploadComponent */
     $apiuploadComponent = MidasLoader::loadComponent('Apiupload', $this->moduleName);
     return $apiuploadComponent->uploadToken($args);
 }
示例#28
0
 /**
  * Date ago view helper.
  *
  * @param int|string $timestamp timestamp
  * @return string date ago as a formatted string
  */
 public function dateago($timestamp)
 {
     /** @var DateComponent $dateComponent */
     $dateComponent = MidasLoader::loadComponent('Date');
     return htmlspecialchars($dateComponent->ago($timestamp), ENT_QUOTES, 'UTF-8');
 }
示例#29
0
 /**
  * Call this to stream the large thumbnail for the item.  Should only be called if the item has a thumbnail;
  * otherwise the request produces no output.
  *
  * @param itemthumbnail The itemthumbnail_id to stream
  * @throws Zend_Exception
  */
 public function itemAction()
 {
     $itemthumbnailId = $this->getParam('itemthumbnail');
     if (!isset($itemthumbnailId)) {
         throw new Zend_Exception('Must pass an itemthumbnail parameter');
     }
     $itemthumbnail = $this->Thumbnailcreator_Itemthumbnail->load($itemthumbnailId);
     if (!$itemthumbnail) {
         throw new Zend_Exception('Invalid itemthumbnail parameter');
     }
     if (!$this->Item->policyCheck($itemthumbnail->getItem(), $this->userSession->Dao)) {
         throw new Zend_Exception('Invalid policy');
     }
     $this->disableLayout();
     $this->disableView();
     if ($itemthumbnail->getThumbnailId() !== null) {
         $bitstream = $this->Bitstream->load($itemthumbnail->getThumbnailId());
         /** @var DownloadBitstreamComponent $downloadBitstreamComponent */
         $downloadBitstreamComponent = MidasLoader::loadComponent('DownloadBitstream');
         $downloadBitstreamComponent->download($bitstream);
     }
 }
示例#30
0
 /**
  * Set a single scalar result value.
  *
  * @param dashboard_id the id of the target dashboard
  * @param folder_id the id of the target result folder
  * @param item_id the id of the result item
  * @param value the value of the result being set
  * @return the id of the created scalar result
  * @throws Exception
  */
 public function setScalarResult($value)
 {
     // check for the proper parameters
     $this->_checkKeys(array('dashboard_id', 'folder_id', 'item_id', 'value'), $value);
     // Verify authentication (only admins can set results)
     /** @var AuthenticationComponent $authComponent */
     $authComponent = MidasLoader::loadComponent('Authentication');
     $userDao = $authComponent->getUser($value, Zend_Registry::get('userSession')->Dao);
     if (!$userDao || !$userDao->isAdmin()) {
         throw new Exception('Only administrators can write result scalars.', -1);
     }
     // Load the necessary models
     /** @var Validation_DashboardModel $dashboardModel */
     $dashboardModel = MidasLoader::loadModel('Dashboard', 'validation');
     // Verify that the dashboard exists
     $dashboardDao = $dashboardModel->load($value['dashboard_id']);
     if (!$dashboardDao) {
         throw new Exception('No dashboard found with that id.', -1);
     }
     // Verify that the folder_id is associated with the dashboard as a result
     $results = $dashboardDao->getResults();
     $tgtResult = null;
     foreach ($results as $result) {
         if ($result->getKey() == $value['folder_id']) {
             $tgtResult = $result;
             break;
         }
     }
     if (!$tgtResult) {
         throw new Exception('No result found with that folder_id.', -1);
     }
     // Verify that an item with item_id is in that result set
     $resultItems = $tgtResult->getItems();
     $tgtItem = null;
     foreach ($resultItems as $resultItem) {
         if ($resultItem->getKey() == $value['item_id']) {
             $tgtItem = $resultItem;
         }
     }
     if (!$tgtItem) {
         throw new Exception('No result item found with that item_id.', -1);
     }
     // Assuming everything went according to plan, set the result scalar
     $scalarResult = $dashboardModel->setScore($dashboardDao, $tgtResult, $tgtItem, $value['value']);
     return array('scalarresult_id' => $scalarResult->getScalarresultId());
 }