/** * Set a rating on an item. * * @param itemId The item id to set the rating on * @param rating The rating (0-5) to set for the currently logged user. 0 means remove user's rating. * @throws Zend_Exception */ public function rateitemAction() { if (!$this->logged) { throw new Zend_Exception('Must be logged in to rate an item'); } $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'); } $rating = (int) $this->getParam('rating'); if ($rating < 0 || $rating > 5) { throw new Zend_Exception('Rating must be 0-5'); } $this->disableView(); $this->disableLayout(); /** @var Ratings_ItemratingModel $itemRatingModel */ $itemRatingModel = MidasLoader::loadModel('Itemrating', $this->moduleName); $itemRatingModel->setRating($this->userSession->Dao, $item, $rating); $info = $itemRatingModel->getAggregateInfo($item); $message = $rating == 0 ? 'Rating removed' : 'Rating saved'; echo JsonComponent::encode(array_merge(array('status' => 'ok', 'message' => $message), $info)); }
/** * Instance. * * @return JsonComponent */ public static function getInstance() { if (!self::$_instance instanceof self) { self::$_instance = new self(); } return self::$_instance; }
/** * Perform the extraction. Requires admin privileges on the item. * * @param itemId The item to extract * @throws Zend_Exception */ public function performAction() { $this->disableView(); $this->disableLayout(); $itemId = $this->getParam('itemId'); $deleteArchive = $this->getParam('deleteArchive'); $deleteArchive = $deleteArchive !== 'false'; // passed as a string if (!isset($itemId)) { throw new Zend_Exception('Must pass itemId parameter'); } $item = $this->Item->load($itemId); if (!$item) { throw new Zend_Exception('Invalid itemId'); } if (!$this->Item->policyCheck($item, $this->userSession->Dao, MIDAS_POLICY_ADMIN)) { throw new Zend_Exception('Admin privileges on item required'); } try { $parentFolder = $this->ModuleComponent->Extract->extractInPlace($item, $deleteArchive, $this->userSession->Dao, $this->progressDao); echo JsonComponent::encode(array('status' => 'ok', 'redirect' => $this->view->webroot . '/folder/' . $parentFolder->getKey())); } catch (Exception $e) { echo JsonComponent::encode(array('status' => 'error', 'message' => $e->getMessage())); } }
/** * When the user actually submits their otp, this authenticates it. */ public function submitAction() { $this->disableLayout(); $this->disableView(); Zend_Session::start(); $mfaSession = new Zend_Session_Namespace('Mfa_Temp_User'); $user = $mfaSession->Dao; if (!isset($user) || !$user) { echo JsonComponent::encode(array('status' => 'error', 'message' => 'Session has expired, refresh and try again')); return; } $otpDevice = $this->Mfa_Otpdevice->getByUser($user); if (!$otpDevice) { throw new Zend_Exception('User does not have an OTP device'); } $token = $this->getParam('token'); try { $valid = $this->ModuleComponent->Otp->authenticate($otpDevice, $token); } catch (Zend_Exception $exc) { $this->getLogger()->crit($exc->getMessage()); echo JsonComponent::encode(array('status' => 'error', 'message' => $exc->getMessage())); return; } if ($valid) { session_start(); $authUser = new Zend_Session_Namespace('Auth_User'); $authUser->setExpirationSeconds(60 * Zend_Registry::get('configGlobal')->session->lifetime); $authUser->Dao = $user; $authUser->lock(); $this->getLogger()->debug(__METHOD__ . ' Log in : ' . $user->getFullName()); echo JsonComponent::encode(array('status' => 'ok')); } else { echo JsonComponent::encode(array('status' => 'error', 'message' => 'Incorrect token')); } }
/** Handle web API authentication with an OAuth token */ public function handleAuth($params) { $apiArgs = $params['args']; if (array_key_exists('oauth_token', $apiArgs)) { if (Zend_Registry::isRegistered('oauthRequiredScopes')) { $requiredScopes = Zend_Registry::get('oauthRequiredScopes'); } else { $requiredScopes = array(MIDAS_API_PERMISSION_SCOPE_ALL); } $tokenDao = $this->Oauth_Token->getByToken($apiArgs['oauth_token']); if (!$tokenDao || $tokenDao->getType() != MIDAS_OAUTH_TOKEN_TYPE_ACCESS) { throw new Zend_Exception('Invalid OAuth access token', 400); } if ($tokenDao->isExpired()) { throw new Zend_Exception('Token has expired', 403); } $grantedScopes = JsonComponent::decode($tokenDao->getScopes()); if (!in_array(MIDAS_API_PERMISSION_SCOPE_ALL, $grantedScopes)) { foreach ($requiredScopes as $requiredScope) { if (!in_array($requiredScope, $grantedScopes)) { return array('userDao' => null); // Missing required scope, let caller determine permission failure } } } return array('userDao' => $tokenDao->getUser()); } else { return false; // fall through to normal authentication } }
/** * Schedule the perform cleanup job. * * @param int $days days to keep partial files * @param string $tempDirectory temporary directory * @param null|UserDao $userDao user scheduling the job */ public function schedulePerformCleanupJob($days, $tempDirectory, $userDao = null) { /** @var Scheduler_JobModel $jobModel */ $jobModel = MidasLoader::loadModel('Job', 'scheduler'); $jobDaos = $jobModel->getJobsByTask('TASK_CLEANUP_PERFORM_CLEANUP'); $cleanupJobDao = false; foreach ($jobDaos as $jobDao) { if ($jobDao->getTask() === 'TASK_CLEANUP_PERFORM_CLEANUP') { $cleanupJobDao = $jobDao; break; } } if ($cleanupJobDao === false) { /** @var Scheduler_JobDao $cleanupJobDao */ $cleanupJobDao = MidasLoader::newDao('JobDao', 'scheduler'); $cleanupJobDao->setTask('TASK_CLEANUP_PERFORM_CLEANUP'); $cleanupJobDao->setPriority(1); $cleanupJobDao->setRunOnlyOnce(0); $cleanupJobDao->setFireTime(date('Y-m-d', strtotime('+1 day' . date('Y-m-d H:i:s'))) . ' 01:00:00'); $cleanupJobDao->setTimeInterval(86400); $cleanupJobDao->setStatus(SCHEDULER_JOB_STATUS_TORUN); if (!is_null($userDao)) { $cleanupJobDao->setCreatorId($userDao->getKey()); } } $cleanupJobDao->setParams(JsonComponent::encode(array('days' => $days, 'tempDirectory' => $tempDirectory))); $jobModel->save($cleanupJobDao); }
/** * Process the request data. * * @param array $requestData request data */ protected function handleRequest($requestData) { try { $methodName = isset($requestData['method']) ? $requestData['method'] : $this->apiMethodPrefix . 'system.listMethods'; $resultData = $this->call($methodName, $requestData); $output = array('code' => 0, 'data' => $resultData, 'message' => '', 'stat' => 'ok'); } catch (Exception $exception) { $output = array('code' => $exception->getCode(), 'data' => '', 'message' => $exception->getMessage(), 'stat' => 'fail'); } echo JsonComponent::encode($output); }
/** index */ public function indexAction() { $this->disableLayout(); $folderid = $this->getParam('folder'); $items = array(); if (is_numeric($folderid)) { $folder = $this->Folder->load($folderid); $items = $folder->getItems(); } $itemid = $this->getParam('itemId'); if (is_numeric($itemid)) { $items[] = $this->Item->load($itemid); } $data = array(); foreach ($items as $item) { if ($item === false || !$this->Item->policyCheck($item, $this->userSession->Dao, MIDAS_POLICY_READ)) { continue; } $revision = $this->Item->getLastRevision($item); if ($revision === false) { continue; } $bitstreams = $revision->getBitstreams(); if (count($bitstreams) == 1) { continue; } $binFound = false; $jsFile = false; foreach ($bitstreams as $b) { $ext = end(explode('.', $b->getName())); if ($ext == 'bin') { $binFound = true; } if ($ext == 'js') { $jsFile = $b; } } if (!$binFound || !$jsFile) { continue; } $data[$jsFile->getName()] = array('bitstream' => $jsFile->toArray()); $data[$jsFile->getName()]['visible'] = true; $data[$jsFile->getName()]['red'] = 192 / 255; $data[$jsFile->getName()]['green'] = 192 / 255; $data[$jsFile->getName()]['blue'] = 195 / 255; $data[$jsFile->getName()]['hexa'] = $this->_rgb2hex((int) (192 * 255), (int) (192 * 255), (int) (192 * 255)); $data[$jsFile->getName()]['name'] = ''; } $this->view->data = JsonComponent::encode(array('webroot' => $this->view->webroot, 'objects' => $data)); }
/** * We override __call to intercept the path and transform * it into a resource and module name, and pass that into the ApidocsComponent. */ public function __call($name, $args) { $pathParams = UtilityComponent::extractPathParams(); $module = ''; $resource = $this->getRequest()->getActionName(); if (count($pathParams)) { if (in_array($this->getRequest()->getActionName(), Zend_Registry::get('modulesEnable'))) { $module = $this->getRequest()->getActionName(); $resource = $pathParams[0]; } } $results = $this->Component->Apidocs->getResourceApiDocs($resource, $module); echo JsonComponent::encode($results); }
/** * Action for querying progress of a certain event. Should be called with ajax. * * @param progressId The id of the progress object to query * @return Echoes the progress dao if one exists, or false if it is completed or DNE. */ public function getAction() { $progressId = $this->getParam('progressId'); if (!isset($progressId)) { throw new Zend_Exception('Must pass progressId parameter'); } $this->disableLayout(); $this->disableView(); $progress = $this->Progress->load($progressId); if (!$progress) { echo JsonComponent::encode(array()); } else { echo JsonComponent::encode($progress->toArray()); } }
/** * Configuration action for a user's api keys. * * @param userId The id of the user to display * @throws Zend_Exception */ public function usertabAction() { $this->disableLayout(); if (!$this->logged) { throw new Zend_Exception('Please Log in'); } $userId = $this->getParam('userId'); if ($this->userSession->Dao->getKey() != $userId && !$this->userSession->Dao->isAdmin()) { throw new Zend_Exception('Only admins can view other user API keys'); } $user = $this->User->load($userId); $this->view->Date = $this->Component->Date; $form = $this->Form->Apikey->createKeyForm(); $formArray = $this->getFormAsArray($form); $formArray['expiration']->setValue('100'); $this->view->form = $formArray; // Create a new API key $createAPIKey = $this->getParam('createAPIKey'); $deleteAPIKey = $this->getParam('deleteAPIKey'); if (isset($createAPIKey)) { $this->disableView(); $applicationName = $this->getParam('appplication_name'); $tokenExperiationTime = $this->getParam('expiration'); $userapiDao = $this->Userapi->createKey($user, $applicationName, $tokenExperiationTime); if ($userapiDao != false) { echo JsonComponent::encode(array(true, $this->t('Changes saved'))); } else { echo JsonComponent::encode(array(false, $this->t('Error'))); } } elseif (isset($deleteAPIKey)) { $this->disableView(); $element = $this->getParam('element'); $userapiDao = $this->Userapi->load($element); // Make sure the key belongs to the user if ($userapiDao != false && ($userapiDao->getUserId() == $userId || $this->userSession->Dao->isAdmin())) { $this->Userapi->delete($userapiDao); echo JsonComponent::encode(array(true, $this->t('Changes saved'))); } else { echo JsonComponent::encode(array(false, $this->t('Error'))); } } // List the previously generated API keys $userapiDaos = $this->Userapi->getByUser($user); $this->view->userapiDaos = $userapiDaos; $this->view->user = $user; $this->view->serverURL = $this->getServerURL(); }
/** * Creates a thumbnail. * * @param bitstreamId The bitstream to create the thumbnail from * @param itemId The item to set the thumbnail on * @param width (Optional) The width in pixels to resize to (aspect ratio will be preserved). Defaults to 575 * @return array('thumbnail' => path to the thumbnail) * @throws Zend_Exception */ public function createAction() { $itemId = $this->getParam('itemId'); if (!isset($itemId)) { throw new Zend_Exception('itemId parameter required'); } $bitstreamId = $this->getParam('bitstreamId'); if (!isset($bitstreamId)) { throw new Zend_Exception('bitstreamId parameter required'); } $width = $this->getParam('width'); if (!isset($width)) { $width = 575; } $this->disableView(); $this->disableLayout(); $bitstream = $this->Bitstream->load($bitstreamId); $item = $this->Item->load($itemId); if (!$this->Item->policyCheck($item, $this->userSession->Dao, MIDAS_POLICY_WRITE)) { echo JsonComponent::encode(array('status' => 'error', 'message' => 'Write permission required')); return; } /** @var Thumbnailcreator_ImagemagickComponent $imComponent */ $imComponent = MidasLoader::loadComponent('Imagemagick', 'thumbnailcreator'); $itemThumbnail = $this->Thumbnailcreator_Itemthumbnail->getByItemId($item->getKey()); if (!$itemThumbnail) { $itemThumbnail = new Thumbnailcreator_ItemthumbnailDao(); $itemThumbnail->setItemId($item->getKey()); } else { $oldThumb = $this->Bitstream->load($itemThumbnail->getThumbnailId()); $this->Bitstream->delete($oldThumb); } try { $thumbnail = $imComponent->createThumbnailFromPath($bitstream->getName(), $bitstream->getFullPath(), (int) $width, 0, false); if (!file_exists($thumbnail)) { echo JsonComponent::encode(array('status' => 'error', 'message' => 'Could not create thumbnail from the bitstream')); return; } $thumb = $this->Bitstream->createThumbnail($this->Assetstore->getDefault(), $thumbnail); $itemThumbnail->setThumbnailId($thumb->getKey()); $this->Thumbnailcreator_Itemthumbnail->save($itemThumbnail); echo JsonComponent::encode(array('status' => 'ok', 'message' => 'Thumbnail saved', 'itemthumbnail' => $itemThumbnail)); } catch (Exception $e) { echo JsonComponent::encode(array('status' => 'error', 'message' => 'Error: ' . $e->getMessage())); } }
/** community agreement tab * Shown in the community manage page when the 'community agreement' module is enabled. * * @throws Zend_Exception on invalid communityId */ public function agreementtabAction() { $this->disableLayout(); $communityId = $this->getParam('communityId'); if (!isset($communityId) || !is_numeric($communityId)) { throw new Zend_Exception('Community ID should be a number'); } $community = $this->Community->load($communityId); if (!$community) { throw new Zend_Exception('Community does not exist', 404); } if (!$this->Community->policyCheck($community, $this->userSession->Dao, MIDAS_POLICY_WRITE)) { throw new Zend_Exception('Must have write permission on the community', 403); } $agreementDao = $this->Communityagreement_Agreement->getByCommunityId($communityId); // If cannot find any community agreement using the given communityID, // initialize the community agreement using an empty string and then create an agreementDao if ($agreementDao == false) { $agreement = ''; $agreementDao = $this->Communityagreement_Agreement->createAgreement($communityId, $agreement); } $formAgreement = $this->ModuleForm->Community->createCreateAgreementForm($communityId); if ($this->_request->isPost() && $formAgreement->isValid($this->getRequest()->getPost())) { $this->disableView(); $agreementDao->setAgreement($formAgreement->getValue('agreement')); if ($agreementDao != false) { echo JsonComponent::encode(array(true, $this->t('Changes saved'))); } else { echo JsonComponent::encode(array(false, $this->t('Error'))); } } // If a community agreement only contains white spaces, it is treated as an empty agreement // and will be deleted from the database if it exists $chopped_agreement = rtrim($agreementDao->getAgreement()); if ($chopped_agreement != '') { $this->Communityagreement_Agreement->save($agreementDao); } elseif ($this->Communityagreement_Agreement->getByCommunityId($communityId) != false) { $this->Communityagreement_Agreement->delete($agreementDao); } // init form $agreement = $formAgreement->getElement('agreement'); $agreement->setValue($agreementDao->getAgreement()); $this->view->agreementForm = $this->getFormAsArray($formAgreement); $this->view->agreementDao = $agreementDao; }
/** Test the AJAX get free space call. */ public function testGetFreeSpace() { $usersFile = $this->loadData('User', 'default'); $user1 = $this->User->load($usersFile[0]->getKey()); $adminUser = $this->User->load($usersFile[2]->getKey()); $commFile = $this->loadData('Community', 'default'); $comm = $this->Community->load($commFile[0]->getKey()); // Exception if no folder id is set $this->resetAll(); $this->dispatchUrl('/' . $this->moduleName . '/folder/getfreespace', $adminUser); $resp = JsonComponent::decode($this->getBody()); $this->assertTrue($resp['status'] == false); $this->assertEquals($resp['message'], 'Missing folderId parameter'); // Exception if invalid folder id is set $this->resetAll(); $this->dispatchUrl('/' . $this->moduleName . '/folder/getfreespace?folderId=-7', $adminUser); $resp = JsonComponent::decode($this->getBody()); $this->assertTrue($resp['status'] == false); $this->assertEquals($resp['message'], 'Invalid folder'); // Exception if no read privileges $this->resetAll(); $this->dispatchUrl('/' . $this->moduleName . '/folder/getfreespace?folderId=' . $user1->getFolderId(), null); $resp = JsonComponent::decode($this->getBody()); $this->assertTrue($resp['status'] == false); $this->assertEquals($resp['message'], 'Invalid policy'); // User with read privileges should be able to get free space $this->resetAll(); $this->dispatchUrl('/' . $this->moduleName . '/folder/getfreespace?folderId=' . $user1->getFolderId(), $user1); $resp = JsonComponent::decode($this->getBody()); $this->assertTrue($resp['status'] == true); // This should also work on non-root folders $this->resetAll(); $this->dispatchUrl('/' . $this->moduleName . '/folder/getfreespace?folderId=1001', $user1); $resp = JsonComponent::decode($this->getBody()); $this->assertTrue($resp['status'] == true); // Should also work for community folders $this->resetAll(); $this->Setting->setConfig('defaultcommunityquota', 12345, $this->moduleName); $commFolders = $comm->getFolder()->getFolders(); $this->dispatchUrl('/' . $this->moduleName . '/folder/getfreespace?folderId=' . $commFolders[0]->getKey(), $adminUser); $resp = JsonComponent::decode($this->getBody()); $this->assertTrue($resp['status'] == true); $this->assertEquals($resp['freeSpace'], 12345); }
/** * Add scheduled tasks for notifying users that a threshold was crossed. * * @param Tracker_ScalarDao $scalarDao scalar DAO * @param array $thresholdNotificationDaos threshold notification DAOs */ public function scheduleNotifications($scalarDao, $thresholdNotificationDaos) { /** @var Scheduler_JobModel $jobModel */ $jobModel = MidasLoader::loadModel('Job', 'scheduler'); /** @var Tracker_ThresholdNotificationDao $thresholdNotificationDao */ foreach ($thresholdNotificationDaos as $thresholdNotificationDao) { /** @var Scheduler_JobDao $jobDao */ $jobDao = MidasLoader::newDao('JobDao', 'scheduler'); $jobDao->setTask('TASK_TRACKER_SEND_THRESHOLD_NOTIFICATION'); $jobDao->setPriority(1); $jobDao->setRunOnlyOnce(1); $jobDao->setFireTime(date('Y-m-d H:i:s')); $jobDao->setTimeInterval(0); $jobDao->setStatus(SCHEDULER_JOB_STATUS_TORUN); $jobDao->setCreatorId($thresholdNotificationDao->getRecipientId()); $jobDao->setParams(JsonComponent::encode(array('notification' => $thresholdNotificationDao, 'scalar' => $scalarDao))); $jobModel->save($jobDao); } }
/** * Submit an advanced search query. Responds with JSON results. * * @param query The Lucene query to perform * @param solrOffset The offset into the actual solr results * @param displayOffset The offset of actually displayed items * @param limit The limit of the result set */ public function submitAction() { $this->disableLayout(); $this->disableView(); $query = $this->getParam('query'); // Extract <element>.<qualifier> from between '-' and ':' in '<type>-<element>.<qualifier>: <value>' $query = preg_replace_callback('/(?<=-)[\\w. ]*(?=:)/', array(&$this, 'strReplaceSpaces'), $query); $limit = (int) $this->getParam('limit'); $solrOffset = (int) $this->getParam('solrOffset'); $displayOffset = (int) $this->getParam('displayOffset'); $itemIds = array(); try { $index = $this->ModuleComponent->Solr->getSolrIndex(); UtilityComponent::beginIgnoreWarnings(); // underlying library can generate warnings, we need to eat them $response = $index->search($query, $solrOffset, $limit * 5, array('fl' => '*,score')); // extend limit to allow some room for policy filtering UtilityComponent::endIgnoreWarnings(); $totalResults = $response->response->numFound; foreach ($response->response->docs as $doc) { $itemIds[] = $doc->key; } } catch (Exception $e) { echo JsonComponent::encode(array('status' => 'error', 'message' => 'Syntax error in query ' . $e->getMessage())); return; } $items = array(); $count = 0; foreach ($itemIds as $itemId) { ++$solrOffset; $item = $this->Item->load($itemId); if ($item && $this->Item->policyCheck($item, $this->userSession->Dao)) { $items[] = array('name' => $item->getName(), 'id' => $item->getKey()); ++$count; if ($count >= $limit) { break; } } } $displayOffset += $count; echo JsonComponent::encode(array('status' => 'ok', 'totalResults' => $totalResults, 'solrOffset' => $solrOffset, 'displayOffset' => $displayOffset, 'items' => $items)); }
/** * When a user logs in, if they have an OTP device we want to override the normal behavior of writing * them to the session, and instead write a temporary session entry that will be moved to the expected * place only after they successfully pass the OTP challenge. */ public function authIntercept($params) { $user = $params['user']; /** @var Mfa_OtpdeviceModel $otpDeviceModel */ $otpDeviceModel = MidasLoader::loadModel('Otpdevice', $this->moduleName); $otpDevice = $otpDeviceModel->getByUser($user); if ($otpDevice) { // write temp user into session for asynchronous confirmation Zend_Session::start(); $userSession = new Zend_Session_Namespace('Mfa_Temp_User'); $userSession->setExpirationSeconds(60 * min(10, Zend_Registry::get('configGlobal')->session->lifetime)); // "limbo" state should invalidate after 10 minutes $userSession->Dao = $user; $userSession->lock(); $resp = JsonComponent::encode(array('dialog' => '/mfa/login/dialog', 'title' => 'Enter One-Time Password', 'options' => array('width' => 250))); return array('override' => true, 'response' => $resp); } else { return array(); } }
/** get Config Tabs */ public function scheduleTask($params) { $tasks = Zend_Registry::get('notifier')->tasks; if (!isset($params['task']) || !isset($tasks[$params['task']])) { throw new Zend_Exception('Unable to identify task: ' . $params['task']); } if (!isset($params['priority'])) { $params['priority'] = MIDAS_EVENT_PRIORITY_NORMAL; } if (!isset($params['run_only_once'])) { $params['run_only_once'] = true; } if (!isset($params['fire_time'])) { $params['fire_time'] = date('Y-m-d H:i:s'); } elseif (is_numeric($params['fire_time'])) { $params['fire_time'] = date('Y-m-d H:i:s', $params['fire_time']); } if (!$params['run_only_once']) { if (!isset($params['time_interval'])) { throw new Zend_Exception('Please set time interval'); } } $job = new Scheduler_JobDao(); $job->setTask($params['task']); $job->setPriority($params['priority']); $job->setRunOnlyOnce($params['run_only_once']); $job->setFireTime($params['fire_time']); if (!$params['run_only_once']) { $job->setTimeInterval($params['time_interval']); } if ($this->logged) { $job->setCreatorId($this->userSession->Dao->getKey()); } $job->setStatus(SCHEDULER_JOB_STATUS_TORUN); $job->setParams(JsonComponent::encode($params['params'])); $this->Scheduler_Job->save($job); return; }
/** * 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; }
/** Get entries (ajax) */ public function getentryAction() { $this->disableLayout(); $this->disableView(); $type = $this->getParam('type'); if (!is_string($type)) { echo JsonComponent::encode(false); return; } switch ($type) { case 'getRecentExecutable': // We no longer store a list of "recent uploads" in the session. For now // this action is vestigial. echo JsonComponent::encode(array()); return; default: echo JsonComponent::encode(false); return; } }
/** * Outputs a json object of and item's download history filtered by the following parameters. * * @param itemId The id of the item (key) * @param startdate Start of the date range (date string) * @param enddate End of the date range (date string) * @param limit Limit of the result count (integer) * @return An array with a "download" key, which is a list of tuples with the following data: * -latitude * -longitude * -date * @throws Zend_Exception */ public function filterAction() { $this->disableLayout(); $this->disableView(); $itemIds = $this->getParam('itemId'); $ids = explode(',', $itemIds); $idArray = array(); foreach ($ids as $id) { if ($id != '') { $item = $this->Item->load($id); if (!$item) { throw new Zend_Exception('Item ' . $id . " doesn't exist"); } if (!$this->Item->policyCheck($item, $this->userSession->Dao, MIDAS_POLICY_READ)) { throw new Zend_Exception('You do not have read permission on item ' . $id); } $idArray[] = $item->getKey(); } } if ($this->getParam('startdate') == '') { $startDate = date('Y-m-d'); } else { $startDate = date('Y-m-d', strtotime($this->getParam('startdate'))); } if ($this->getParam('enddate') == '') { $endDate = date('Y-m-d 23:59:59'); } else { $endDate = date('Y-m-d 23:59:59', strtotime($this->getParam('enddate'))); } $limit = $this->getParam('limit'); if (!isset($limit) || $limit < 0) { $limit = 1000; } $downloads = $this->Statistics_Download->getLocatedDownloads($idArray, $startDate, $endDate, $limit); $totalCount = $this->Statistics_Download->getCountInRange($idArray, $startDate, $endDate, $limit); $markers = array(); foreach ($downloads as $download) { $latitude = $download->getIpLocation()->getLatitude(); $longitude = $download->getIpLocation()->getLongitude(); if ($latitude || $longitude) { $markers[] = array('latitude' => $latitude, 'longitude' => $longitude); } } echo JsonComponent::encode(array('downloads' => $markers, 'count' => $totalCount)); }
/** * Handle form submission from email notification dialog. * * Request parameters: * trendId - The trend id * doNotify - Will be either "yes" or "no" * operator - One of "<", ">", "<=", ">=", "==", "!=" * value - The comparison value (must be numeric) * * @throws Zend_Exception */ public function notifysubmitAction() { $this->disableLayout(); $this->disableView(); if (!$this->logged) { echo JsonComponent::encode(array('status' => 'error', 'message' => 'You are not logged in')); return; } /** @var int $trendId */ $trendId = $this->getParam('trendId'); if (!isset($trendId)) { throw new Zend_Exception('The required trendId parameter is missing'); } /** @var Tracker_TrendDao $trendDao */ $trendDao = $this->Tracker_Trend->load($trendId); if ($this->Tracker_Trend->policyCheck($trendDao, $this->userSession->Dao, MIDAS_POLICY_READ) === false) { throw new Zend_Exception('The trend does not exist or you do not have the necessary permission', 403); } $thresholdNotificationDao = $this->Tracker_ThresholdNotification->getUserSetting($this->userSession->Dao, $trendDao); if ($thresholdNotificationDao !== false) { $this->Tracker_ThresholdNotification->delete($thresholdNotificationDao); } /** @var string $doNotify */ $doNotify = $this->getParam('doNotify'); if (isset($doNotify) && $doNotify === 'yes') { /** @var string $operator */ $operator = $this->getParam('operator'); /** @var float $value */ $value = $this->getParam('value'); if (is_numeric($value) === false) { echo JsonComponent::encode(array('status' => 'error', 'message' => 'Threshold value must be numeric')); return; } /** @var Tracker_ThresholdNotificationDao $thresholdNotificationDao */ $thresholdNotificationDao = MidasLoader::newDao('ThresholdNotificationDao', $this->moduleName); $thresholdNotificationDao->setTrendId($trendDao->getKey()); $thresholdNotificationDao->setValue((double) $value); $thresholdNotificationDao->setComparison($operator); $thresholdNotificationDao->setAction(MIDAS_TRACKER_EMAIL_USER); $thresholdNotificationDao->setRecipientId($this->userSession->Dao->getKey()); $this->Tracker_ThresholdNotification->save($thresholdNotificationDao); } echo JsonComponent::encode(array('status' => 'ok', 'message' => 'Changes saved')); }
/** * Ajax action for determining what action to take based on the size of the requested download. * * @throws Zend_Exception */ public function checksizeAction() { $this->disableView(); $this->disableLayout(); $itemIds = $this->getParam('itemIds'); $folderIds = $this->getParam('folderIds'); if (isset($itemIds)) { $itemIdArray = explode(',', $itemIds); } else { $itemIdArray = array(); } if (isset($folderIds)) { $folderIdArray = explode(',', $folderIds); } else { $folderIdArray = array(); } $items = array(); $folders = array(); foreach ($itemIdArray as $itemId) { if ($itemId) { $item = $this->Item->load($itemId); if (!$item || !$this->Item->policyCheck($item, $this->userSession->Dao, MIDAS_POLICY_READ)) { throw new Zend_Exception('Permission denied on item ' . $itemId, 403); } $items[] = $item; } } foreach ($folderIdArray as $folderId) { if ($folderId) { $folder = $this->Folder->load($folderId); if (!$folder || !$this->Folder->policyCheck($folder, $this->userSession->Dao, MIDAS_POLICY_READ)) { throw new Zend_Exception('Permission denied on folder ' . $folderId, 403); } $folders[] = $folder; } } $totalSize = 0; $folders = $this->Folder->getSizeFiltered($folders, $this->userSession->Dao, MIDAS_POLICY_READ); foreach ($folders as $folder) { $totalSize += $folder->size; } foreach ($items as $item) { $totalSize += $item->getSizebytes(); } if ($totalSize > 2000000000.0 && in_array('javauploaddownload', Zend_Registry::get('modulesEnable'))) { echo JsonComponent::encode(array('action' => 'promptApplet', 'sizeStr' => UtilityComponent::formatSize($totalSize))); } else { echo JsonComponent::encode(array('action' => 'download')); } }
/** controller for applying policies recursively to a folder */ public function applyrecursivedialogAction() { $this->disableLayout(); $folderId = $this->getParam('folderId'); $this->view->folderId = $folderId; if ($this->_request->isPost()) { $this->disableView(); $folder = $this->Folder->load($folderId); if (!$folder) { echo JsonComponent::encode(array(false, $this->t('Invalid folder id'))); return; } if ($this->progressDao) { // Need to count up all the child folders and items of the folder $this->progressDao->setMaximum($this->Folder->getRecursiveChildCount($folder)); $this->progressDao->setMessage('total count = ' . $this->progressDao->getMaximum()); $this->Progress->save($this->progressDao); } $results = $this->Component->Policy->applyPoliciesRecursive($folder, $this->userSession->Dao, $this->progressDao); echo JsonComponent::encode(array(true, $results)); return; } }
/** * Remove a user from a group. */ public function removeuserfromgroupAction() { $this->disableLayout(); $this->_helper->viewRenderer->setNoRender(); if (!$this->logged) { throw new Zend_Exception('Must be logged in'); } $groupId = $this->getParam('groupId'); $userId = $this->getParam('userId'); if (!isset($groupId)) { throw new Zend_Exception('Must pass a groupId parameter'); } if (!isset($userId)) { throw new Zend_Exception('Must pass a userId parameter'); } $group = $this->Group->load($groupId); $user = $this->User->load($userId); if (!$user || !$group) { throw new Zend_Exception('Invalid user or group parameter'); } $community = $group->getCommunity(); if (!$this->Community->policyCheck($community, $this->userSession->Dao, MIDAS_POLICY_ADMIN)) { throw new Zend_Exception('Community Admin permissions required.', 403); } $this->Group->removeUser($group, $user); echo JsonComponent::encode(array(true, 'Removed user ' . $user->getFullName() . ' from group ' . $group->getName())); }
/** * The form for user OTP device configuration submits to this action. * * @param userId The user id to check * @param useOtp If set, enable OTP device, otherwise delete OTP device record * @param algorithm The OTP algorithm to use (see constants.php) * @param secret The device key or secret to use * @param length The length of the client tokens */ public function usersubmitAction() { $this->disableLayout(); $this->disableView(); $userOtpSetting = $this->Setting->GetValueByName('userOtpControl', 'mfa'); $userOtpControl = $userOtpSetting === 'true'; if (!$userOtpControl && !$this->userSession->Dao->isAdmin()) { throw new Zend_Exception('Only administrators are allowed to manage OTP settings'); } $userId = $this->getParam('userId'); if (!isset($userId)) { throw new Zend_Exception('Must pass a userId parameter'); } $user = $this->User->load($userId); if (!$user) { throw new Zend_Exception('Invalid userId'); } $currentUser = $this->userSession->Dao; if (!$currentUser) { throw new Zend_Exception('Must be logged in'); } if ($currentUser->getKey() != $user->getKey() && !$currentUser->isAdmin()) { throw new Zend_Exception('Permission denied'); } $otpDevice = $this->Mfa_Otpdevice->getByUser($user); $useOtp = $this->getParam('useOtp'); if (!isset($useOtp)) { if ($otpDevice) { $this->Mfa_Otpdevice->delete($otpDevice); } echo JsonComponent::encode(array('status' => 'warning', 'message' => 'OTP Authentication disabled')); } else { if (!$otpDevice) { $otpDevice = new Mfa_OtpdeviceDao(); $otpDevice->setUserId($user->getKey()); $otpDevice->setCounter('0'); } $otpDevice->setAlgorithm($this->getParam('algorithm')); $otpDevice->setSecret($this->getParam('secret')); $otpDevice->setLength($this->getParam('length')); $this->Mfa_Otpdevice->save($otpDevice); echo JsonComponent::encode(array('status' => 'ok', 'message' => 'OTP Authentication enabled')); } }
/** upgrade database */ public function upgradeAction() { $this->requireAdminPrivileges(); $this->disableLayout(); $db = Zend_Registry::get('dbAdapter'); $dbtype = Zend_Registry::get('configDatabase')->database->adapter; $modulesConfig = Zend_Registry::get('configsModules'); if ($this->_request->isPost()) { $this->disableView(); $upgraded = false; foreach ($modulesConfig as $key => $module) { $this->Component->Upgrade->initUpgrade($key, $db, $dbtype); if ($this->Component->Upgrade->upgrade($module->version)) { $upgraded = true; } } $this->Component->Upgrade->initUpgrade('core', $db, $dbtype); if ($this->Component->Upgrade->upgrade(Zend_Registry::get('configDatabase')->version)) { $upgraded = true; } if ($upgraded) { echo JsonComponent::encode(array(true, 'Upgraded')); } else { echo JsonComponent::encode(array(false, 'Nothing to upgrade')); } return; } $modules = array(); foreach ($modulesConfig as $key => $module) { $this->Component->Upgrade->initUpgrade($key, $db, $dbtype); $modules[$key]['target'] = $this->Component->Upgrade->getNewestVersion(); $modules[$key]['targetText'] = $this->Component->Upgrade->getNewestVersion(true); $modules[$key]['currentText'] = $module->version; $modules[$key]['current'] = $this->Component->Upgrade->transformVersionToNumeric($module->version); } $this->view->modules = $modules; $this->Component->Upgrade->initUpgrade('core', $db, $dbtype); $core['target'] = $this->Component->Upgrade->getNewestVersion(); $core['targetText'] = $this->Component->Upgrade->getNewestVersion(true); $core['currentText'] = Zend_Registry::get('configDatabase')->version; $core['current'] = $this->Component->Upgrade->transformVersionToNumeric(Zend_Registry::get('configDatabase')->version); $this->view->core = $core; }
/** * Helper method to make sure that a web api call failed. */ private function _assertApiFailure() { $json = JsonComponent::decode($this->getBody()); $this->assertEquals($json['stat'], 'fail'); $this->assertTrue($json['code'] != 0); }
/** * Move all bitstreams from one assetstore into another. Asynchronous progress enabled. * * @param srcAssetstoreId The id of the source assetstore * @param dstAssetstoreId The id of the destination assetstore */ public function movecontentsAction() { $this->requireAdminPrivileges(); $this->disableView(); $this->disableLayout(); $srcAssetstoreId = $this->getParam('srcAssetstoreId'); $dstAssetstoreId = $this->getParam('dstAssetstoreId'); if (!$srcAssetstoreId || !$dstAssetstoreId) { throw new Zend_Exception('Must provide srcAssetstoreId and dstAssetstoreId parameters'); } if ($srcAssetstoreId == $dstAssetstoreId) { return; } $srcAssetstore = $this->Assetstore->load($srcAssetstoreId); $dstAssetstore = $this->Assetstore->load($dstAssetstoreId); if (!$srcAssetstore instanceof AssetstoreDao || !$dstAssetstore instanceof AssetstoreDao) { throw new Zend_Exception('Invalid srcAssetstoreId or dstAssetstoreId'); } if ($this->progressDao) { $this->progressDao->setMaximum($this->Bitstream->countAll($srcAssetstore)); $this->progressDao->setMessage('Moving all bitstreams...'); $this->Progress->save($this->progressDao); } $this->Assetstore->moveBitstreams($srcAssetstore, $dstAssetstore, $this->progressDao); echo JsonComponent::encode(array('status' => 'ok', 'message' => 'Bitstreams moved')); }
/** * The client sends the results to Midas Server (put request). * * @param token * * @param array $args parameters * @throws Exception */ public function resultsserver($args) { $testingmode = false; if (isset($_GET['testingmode']) && $_GET['testingmode'] == 1) { $testingmode = true; } if (!$testingmode && $_SERVER['REQUEST_METHOD'] != 'POST') { throw new Exception('Should be a put request.', MIDAS_INVALID_PARAMETER); } $authComponent = MidasLoader::loadComponent('Authentication'); $userDao = $authComponent->getUser($args, Zend_Registry::get('userSession')->Dao); if ($userDao == false) { throw new Exception('Unable to authenticate as a server. Please check credentials.', MIDAS_INVALID_PARAMETER); } /** @var GroupModel $groupModel */ $groupModel = MidasLoader::loadModel('Group'); $groupServer = $groupModel->load(MIDAS_GROUP_SERVER_KEY); $users = $groupServer->getUsers(); $isServer = false; foreach ($users as $user) { if ($user->getKey() == $userDao->getKey()) { $isServer = true; } } if ($isServer == false) { throw new Exception('Unable to authenticate as a server. Please check credentials.', MIDAS_INVALID_PARAMETER); } if (!file_exists(UtilityComponent::getTempDirectory() . '/remoteprocessing')) { mkdir(UtilityComponent::getTempDirectory() . '/remoteprocessing'); } /** @var RandomComponent $randomComponent */ $randomComponent = MidasLoader::loadComponent('Random'); $destination = UtilityComponent::getTempDirectory() . '/remoteprocessing/' . $randomComponent->generateInt(); while (file_exists($destination)) { $destination = UtilityComponent::getTempDirectory() . '/remoteprocessing/' . $randomComponent->generateInt(); } mkdir($destination); if (!$testingmode) { move_uploaded_file($_FILES['file']['tmp_name'], $destination . '/results.zip'); } if ($testingmode) { return array(); } if (file_exists($destination . '/results.zip')) { mkdir($destination . '/content'); $target_directory = $destination . '/content'; $filter = new Zend_Filter_Decompress(array('adapter' => 'Zip', 'options' => array('target' => $target_directory))); $compressed = $filter->filter($destination . '/results.zip'); if ($compressed && file_exists($target_directory . '/parameters.txt')) { $info = file_get_contents($target_directory . '/parameters.txt'); $info = JsonComponent::decode($info); $job_id = $info['job_id']; /** @var Remoteprocessing_JobModel $jobModel */ $jobModel = MidasLoader::loadModel('Job', 'remoteprocessing'); $jobDao = $jobModel->load($job_id); $jobDao->setStatus(MIDAS_REMOTEPROCESSING_STATUS_DONE); $jobModel->save($jobDao); $info['pathResults'] = $destination . '/content'; $info['log'] = file_get_contents($target_directory . '/log.txt'); $info['userKey'] = $userDao->getKey(); Zend_Registry::get('notifier')->callback($info['resultCallback'], $info); } else { throw new Exception('Error, unable to unzip results.', MIDAS_INVALID_PARAMETER); } } else { throw new Exception('Error, unable to find results.', MIDAS_INVALID_PARAMETER); } $this->_rrmdir($destination); return array(); }