Exemplo n.º 1
0
 /** Index action */
 public function indexAction()
 {
     $this->requireAdminPrivileges();
     $this->view->pageTitle = 'Cleanup Module Configuration';
     $form = new Cleanup_Form_Admin();
     if ($this->getRequest()->isPost()) {
         $data = $this->getRequest()->getPost();
         if ($form->isValid($data)) {
             $values = $form->getValues();
             foreach ($values as $key => $value) {
                 if ($key !== 'csrf' && !is_null($value)) {
                     $this->Setting->setConfig($key, $value, $this->moduleName);
                 }
             }
             $this->ModuleComponent->Admin->schedulePerformCleanupJob($values[CLEANUP_DAYS_TO_KEEP_PARTIAL_FILES_KEY], UtilityComponent::getTempDirectory(), $this->userSession->Dao);
         }
         $form->populate($data);
     } else {
         $elements = $form->getElements();
         foreach ($elements as $element) {
             $name = $element->getName();
             if ($name !== 'csrf' && $name !== 'submit') {
                 $value = $this->Setting->getValueByName($name, $this->moduleName);
                 if (!is_null($value)) {
                     $form->setDefault($name, $value);
                 }
             }
         }
     }
     $this->view->form = $form;
     session_start();
 }
Exemplo n.º 2
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);
 }
Exemplo n.º 3
0
 /** generate report */
 public function generate()
 {
     /** @var ErrorlogModel $errorLogModel */
     $errorLogModel = MidasLoader::loadModel('Errorlog');
     /** @var AssetstoreModel $assetStoreModel */
     $assetStoreModel = MidasLoader::loadModel('Assetstore');
     $reportContent = '';
     $reportContent .= '<b>Midas Report: ' . Zend_Registry::get('configGlobal')->application->name . '</b>';
     $reportContent .= '<br/>http://' . $_SERVER['SERVER_NAME'];
     $reportContent .= '<br/><br/><b>Status</b>';
     $errors = $errorLogModel->getLog(date('Y-m-d H:i:s', strtotime('-1 day' . date('Y-m-j G:i:s'))), date('Y-m-d H:i:s'), 'all', 2);
     $reportContent .= '<br/>Yesterday Errors: ' . count($errors);
     $assetStores = $assetStoreModel->getAll();
     foreach ($assetStores as $assetStore) {
         $totalSpace = UtilityComponent::diskTotalSpace($assetStore->getPath());
         $freeSpace = UtilityComponent::diskFreeSpace($assetStore->getPath());
         $reportContent .= '<br/>Assetstore ' . $assetStore->getName();
         if ($totalSpace > 0) {
             $reportContent .= ', Free space: ' . round($freeSpace / $totalSpace * 100, 2) . '%';
         }
     }
     $reportContent .= '<br/><br/><b>Dashboard</b><br/>';
     $dashboard = Zend_Registry::get('notifier')->callback('CALLBACK_CORE_GET_DASHBOARD');
     ksort($dashboard);
     foreach ($dashboard as $module => $dasboard) {
         $reportContent .= '-' . ucfirst($module);
         $reportContent .= '<table>';
         foreach ($dasboard as $name => $status) {
             $reportContent .= '<tr>';
             $reportContent .= '  <td>' . $name . '</td>';
             if ($status) {
                 $reportContent .= '  <td>ok</td>';
             } else {
                 $reportContent .= '  <td>Error</td>';
             }
             if (isset($status[1])) {
                 $reportContent .= '  <td>' . $status[1] . '</td>';
             }
             $reportContent .= '</tr>';
         }
         $reportContent .= '</table>';
     }
     /** @var SettingModel $settingModel */
     $settingModel = MidasLoader::loadModel('Setting');
     $piwikUrl = $settingModel->getValueByName(STATISTICS_PIWIK_URL_KEY, $this->moduleName);
     $piwikId = $settingModel->getValueByName(STATISTICS_PIWIK_SITE_ID_KEY, $this->moduleName);
     $piwikApiKey = $settingModel->getValueByName(STATISTICS_PIWIK_API_KEY_KEY, $this->moduleName);
     $content = file_get_contents($piwikUrl . '/?module=API&format=json&method=VisitsSummary.get&period=day&date=yesterday&idSite=' . $piwikId . '&token_auth=' . $piwikApiKey);
     $piwik = json_decode($content);
     $reportContent .= '<br/><b>Statistics (yesterday)</b>';
     $reportContent .= '<br/>Number of visit: ' . $piwik->nb_uniq_visitors;
     $reportContent .= '<br/>Number of actions: ' . $piwik->nb_actions;
     $reportContent .= '<br/>Average time on the website: ' . $piwik->avg_time_on_site;
     $this->report = $reportContent;
     return $reportContent;
 }
Exemplo n.º 4
0
 /** index action */
 public function indexAction()
 {
     $textDaos = $this->Landingpage_Text->getAll();
     if (isset($textDaos[0])) {
         $textDao = $textDaos[0];
         $this->view->landingText = UtilityComponent::markdown(htmlspecialchars($textDao->getText(), ENT_COMPAT, 'UTF-8'));
     } else {
         $this->callCoreAction();
     }
 }
Exemplo n.º 5
0
 /**
  * will create default paths in the temporary directory
  * for any properties not already set, except for the
  * condor bin dir; imposing a firmer hand on the user.
  *
  * @param array $currentConfig current configuration
  * @return array
  */
 protected function createDefaultConfig($currentConfig)
 {
     $defaultConfigDirs = array(MIDAS_BATCHMAKE_TMP_DIR_PROPERTY => MIDAS_BATCHMAKE_DEFAULT_TMP_DIR, MIDAS_BATCHMAKE_BIN_DIR_PROPERTY => MIDAS_BATCHMAKE_DEFAULT_BIN_DIR, MIDAS_BATCHMAKE_SCRIPT_DIR_PROPERTY => MIDAS_BATCHMAKE_DEFAULT_SCRIPT_DIR, MIDAS_BATCHMAKE_APP_DIR_PROPERTY => MIDAS_BATCHMAKE_DEFAULT_APP_DIR, MIDAS_BATCHMAKE_DATA_DIR_PROPERTY => MIDAS_BATCHMAKE_DEFAULT_DATA_DIR);
     $returnedConfig = array();
     foreach ($currentConfig as $configProp => $configDir) {
         if ((!isset($configProp) || !isset($configDir) || empty($configDir)) && array_key_exists($configProp, $defaultConfigDirs)) {
             $returnedConfig[$configProp] = UtilityComponent::getTempDirectory($defaultConfigDirs[$configProp]);
         } else {
             $returnedConfig[$configProp] = $configDir;
         }
     }
     return $returnedConfig;
 }
Exemplo n.º 6
0
 /**
  * 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);
 }
Exemplo n.º 7
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);
 }
Exemplo n.º 8
0
 /**
  * Fill in the properties of this bitstream given its path. The file must
  * accessible by the web server.
  *
  * @deprecated
  * @throws Zend_Exception
  */
 public function fillPropertiesFromPath()
 {
     // Check if the path exists
     if (!isset($this->path) || empty($this->path)) {
         throw new Zend_Exception('BitstreamDao path is not set in fillPropertiesFromPath()');
     }
     // TODO: Compute the full path from the asset store. For now using the path.
     $this->setMimetype($this->Component->MimeType->getType($this->path));
     // clear the stat cache, as the underlying file might have changed
     // since the last time filesize was called on the same filepath
     clearstatcache();
     $this->setSizebytes(UtilityComponent::fileSize($this->path));
     if (!isset($this->checksum) || empty($this->checksum)) {
         $this->setChecksum(UtilityComponent::md5file($this->path));
     }
 }
Exemplo n.º 9
0
 /** index action */
 public function indexAction()
 {
     $this->requireAdminPrivileges();
     $assetstores = $this->Assetstore->getAll();
     foreach ($assetstores as $key => $assetstore) {
         // Check if we can access the path
         if (file_exists($assetstore->getPath())) {
             $assetstores[$key]->totalSpace = UtilityComponent::diskTotalSpace($assetstore->getPath());
             $assetstores[$key]->freeSpace = UtilityComponent::diskFreeSpace($assetstore->getPath());
             $assetstores[$key]->usedSpace = $assetstores[$key]->totalSpace - $assetstores[$key]->freeSpace;
             if ($assetstores[$key]->totalSpace > 0) {
                 $assetstores[$key]->usedSpaceText = round($assetstores[$key]->usedSpace / $assetstores[$key]->totalSpace * 100, 2);
                 $assetstores[$key]->freeSpaceText = round($assetstores[$key]->freeSpace / $assetstores[$key]->totalSpace * 100, 2);
             } else {
                 $assetstores[$key]->usedSpaceText = 0;
                 $assetstores[$key]->freeSpaceText = 0;
             }
         } else {
             $assetstores[$key]->totalSpaceText = false;
         }
     }
     $jqplotAssetstoreArray = array();
     foreach ($assetstores as $assetstore) {
         $jqplotAssetstoreArray[] = array($assetstore->getName() . ', ' . $assetstore->getPath(), array(array('Free Space: ' . $this->Component->Utility->formatSize($assetstore->freeSpace), $assetstore->freeSpaceText), array('Used Space: ' . $this->Component->Utility->formatSize($assetstore->usedSpace), $assetstore->usedSpaceText)));
     }
     $errors = $this->Errorlog->getLog(date('Y-m-d H:i:s', strtotime('-20 day' . date('Y-m-d H:i:s'))), date('Y-m-d H:i:s'), 'all', 2);
     $errors = $errors['logs'];
     $arrayErrors = array();
     $format = 'Y-m-d';
     for ($i = 0; $i < 21; ++$i) {
         $key = date($format, strtotime(date('Y-m-d H:i:s', strtotime('-' . $i . ' day' . date('Y-m-d H:i:s')))));
         $arrayErrors[$key] = 0;
     }
     foreach ($errors as $error) {
         $key = date($format, strtotime($error->getDatetime()));
         ++$arrayErrors[$key];
     }
     $jqplotArray = array();
     foreach ($arrayErrors as $key => $value) {
         $jqplotArray[] = array($key . ' 8:00AM', $value);
     }
     $this->view->json['stats']['errors'] = $jqplotArray;
     $this->view->json['stats']['assetstores'] = $jqplotAssetstoreArray;
     $this->view->piwikUrl = $this->Setting->getValueByName(STATISTICS_PIWIK_URL_KEY, $this->moduleName);
     $this->view->piwikId = $this->Setting->getValueByName(STATISTICS_PIWIK_SITE_ID_KEY, $this->moduleName);
     $this->view->piwikKey = $this->Setting->getValueByName(STATISTICS_PIWIK_API_KEY_KEY, $this->moduleName);
 }
Exemplo n.º 10
0
 /**
  * Move all bitstreams from one asset store to another.
  *
  * @param AssetstoreDao $srcAssetstore The source asset store
  * @param AssetstoreDao $dstAssetstore The destination asset store
  * @param null|ProgressDao $progressDao Progress dao for asynchronous updating
  * @throws Zend_Exception
  */
 public function moveBitstreams($srcAssetstore, $dstAssetstore, $progressDao = null)
 {
     $current = 0;
     /** @var ProgressModel $progressModel */
     $progressModel = MidasLoader::loadModel('Progress');
     /** @var BitstreamModel $bitstreamModel */
     $bitstreamModel = MidasLoader::loadModel('Bitstream');
     $sql = $this->database->select()->setIntegrityCheck(false)->from('bitstream')->where('assetstore_id = ?', $srcAssetstore->getKey());
     $rows = $this->database->fetchAll($sql);
     $srcPath = $srcAssetstore->getPath();
     $dstPath = $dstAssetstore->getPath();
     foreach ($rows as $row) {
         $bitstream = $this->initDao('Bitstream', $row);
         if ($progressDao) {
             ++$current;
             $message = $current . ' / ' . $progressDao->getMaximum() . ': Moving ' . $bitstream->getName() . ' (' . UtilityComponent::formatSize($bitstream->getSizebytes()) . ')';
             $progressModel->updateProgress($progressDao, $current, $message);
         }
         // Move the file on disk to its new location
         $dir1 = substr($bitstream->getChecksum(), 0, 2);
         $dir2 = substr($bitstream->getChecksum(), 2, 2);
         if (!is_dir($dstPath . '/' . $dir1)) {
             if (!mkdir($dstPath . '/' . $dir1)) {
                 throw new Zend_Exception('Failed to mkdir ' . $dstPath . '/' . $dir1);
             }
         }
         if (!is_dir($dstPath . '/' . $dir1 . '/' . $dir2)) {
             if (!mkdir($dstPath . '/' . $dir1 . '/' . $dir2)) {
                 throw new Zend_Exception('Failed to mkdir ' . $dstPath . '/' . $dir1 . '/' . $dir2);
             }
         }
         if (is_file($dstPath . '/' . $bitstream->getPath())) {
             if (is_file($srcPath . '/' . $bitstream->getPath())) {
                 unlink($srcPath . '/' . $bitstream->getPath());
             }
         } else {
             if (!rename($srcPath . '/' . $bitstream->getPath(), $dstPath . '/' . $bitstream->getPath())) {
                 throw new Zend_Exception('Error moving ' . $bitstream->getPath());
             }
         }
         // Update the asset store id on the bitstream record once it has been moved
         $bitstream->setAssetstoreId($dstAssetstore->getKey());
         $bitstreamModel->save($bitstream);
     }
 }
Exemplo n.º 11
0
 /**
  * Read in the streamed uploaded file and write it to a temporary file.
  * Returns the name of the temporary file.
  */
 private function _readUploadedFile($prefix)
 {
     UtilityComponent::setTimeLimit(0);
     $inputfile = 'php://input';
     $tmpfile = tempnam(UtilityComponent::getTempDirectory('misc'), $prefix);
     $in = fopen($inputfile, 'rb');
     $out = fopen($tmpfile, 'wb');
     $bufSize = 1024 * 1024;
     $size = 0;
     // read from input and write into file
     while (connection_status() == CONNECTION_NORMAL && ($buf = fread($in, $bufSize))) {
         $size += strlen($buf);
         fwrite($out, $buf);
     }
     fclose($in);
     fclose($out);
     return $tmpfile;
 }
Exemplo n.º 12
0
 /**
  * Make sure that we are safely filtering html tags.
  */
 public function testFilterHtmlTags()
 {
     // Assert that plain text with no tags is unchanged
     $text = 'test plain text';
     $val = UtilityComponent::filterHtmlTags($text);
     $this->assertEquals($text, $val);
     // Assert that we allow certain tags
     $text = '<b>bold</b><br><br /><i>italic</i><p>paragraph</p><a href="http://site.com">anchor</a><div>Div</div>';
     $val = UtilityComponent::filterHtmlTags($text);
     $this->assertEquals($text, $val);
     // Assert that we strip disallowed attributes such as id
     $text = '<a id="idLink">anchor</a>';
     $val = UtilityComponent::filterHtmlTags($text);
     $this->assertEquals($val, '<a>anchor</a>');
     // Assert that we strip disallowed tags such as script
     $text = '<script type="text/javascript">malicious javascript</script>';
     $val = UtilityComponent::filterHtmlTags($text);
     $this->assertEquals($val, 'malicious javascript');
 }
Exemplo n.º 13
0
 /**
  * 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));
 }
Exemplo n.º 14
0
 /** index */
 public function indexAction()
 {
     $this->requireAdminPrivileges();
     $this->view->header = 'Administration';
     $options = array('allowModifications' => true);
     $config = new Zend_Config_Ini(APPLICATION_CONFIG, null, $options);
     $configForm = $this->Form->Admin->createConfigForm();
     $formArray = $this->getFormAsArray($configForm);
     $formArray['description']->setValue($config->global->application->description);
     $formArray['lang']->setValue($config->global->application->lang);
     $formArray['name']->setValue($config->global->application->name);
     $formArray['timezone']->setValue($config->global->default->timezone);
     if (isset($config->global->allow_password_reset)) {
         $formArray['allow_password_reset']->setValue($config->global->allow_password_reset);
     }
     if (isset($config->global->closeregistration)) {
         $formArray['closeregistration']->setValue($config->global->closeregistration);
     }
     if (isset($config->global->dynamichelp)) {
         $formArray['dynamichelp']->setValue($config->global->dynamichelp);
     }
     if (isset($config->global->gravatar)) {
         $formArray['gravatar']->setValue($config->global->gravatar);
     }
     if (isset($config->global->httpproxy)) {
         $formArray['httpProxy']->setValue($config->global->httpproxy);
     }
     $this->view->configForm = $formArray;
     $this->view->selectedLicense = $config->global->defaultlicense;
     try {
         $this->view->allLicenses = $this->License->getAll();
     } catch (Exception $e) {
         $this->view->allLicenses = array();
     }
     $allModules = $this->Component->Utility->getAllModules();
     $this->view->extraTabs = Zend_Registry::get('notifier')->callback('CALLBACK_CORE_ADMIN_TABS');
     if ($this->_request->isPost()) {
         $this->_helper->layout->disableLayout();
         $this->_helper->viewRenderer->setNoRender();
         $submitConfig = $this->getParam('submitConfig');
         $submitModule = $this->getParam('submitModule');
         if (isset($submitConfig)) {
             $config->global->application->name = $this->getParam('name');
             $config->global->application->description = $this->getParam('description');
             $config->global->application->lang = $this->getParam('lang');
             $config->global->default->timezone = $this->getParam('timezone');
             $config->global->defaultlicense = $this->getParam('licenseSelect');
             $config->global->allow_password_reset = $this->getParam('allow_password_reset');
             $config->global->closeregistration = $this->getParam('closeregistration');
             $config->global->dynamichelp = $this->getParam('dynamichelp');
             $config->global->gravatar = $this->getParam('gravatar');
             $config->global->httpproxy = $this->getParam('httpProxy');
             $writer = new Zend_Config_Writer_Ini();
             $writer->setConfig($config);
             $writer->setFilename(APPLICATION_CONFIG);
             $writer->write();
             echo JsonComponent::encode(array(true, 'Changes saved'));
         }
         if (isset($submitModule)) {
             $moduleName = $this->getParam('modulename');
             $modulevalue = $this->getParam('modulevalue');
             $moduleConfigLocalFile = LOCAL_CONFIGS_PATH . '/' . $moduleName . '.local.ini';
             $moduleConfigFile = BASE_PATH . '/modules/' . $moduleName . '/configs/module.ini';
             $moduleConfigPrivateFile = BASE_PATH . '/privateModules/' . $moduleName . '/configs/module.ini';
             if (!file_exists($moduleConfigLocalFile) && file_exists($moduleConfigFile)) {
                 copy($moduleConfigFile, $moduleConfigLocalFile);
                 $this->Component->Utility->installModule($moduleName);
             } elseif (!file_exists($moduleConfigLocalFile) && file_exists($moduleConfigPrivateFile)) {
                 copy($moduleConfigPrivateFile, $moduleConfigLocalFile);
                 $this->Component->Utility->installModule($moduleName);
             } elseif (!file_exists($moduleConfigLocalFile)) {
                 throw new Zend_Exception('Unable to find config file');
             }
             $config->module->{$moduleName} = $modulevalue;
             $writer = new Zend_Config_Writer_Ini();
             $writer->setConfig($config);
             $writer->setFilename(APPLICATION_CONFIG);
             $writer->write();
             echo JsonComponent::encode(array(true, 'Changes saved'));
         }
     }
     $defaultAssetStoreId = $this->Assetstore->getDefault()->getKey();
     // get assetstore data
     $assetstores = $this->Assetstore->getAll();
     $defaultSet = false;
     foreach ($assetstores as $key => $assetstore) {
         if ($assetstore->getKey() == $defaultAssetStoreId) {
             $assetstores[$key]->default = true;
             $defaultSet = true;
         } else {
             $assetstores[$key]->default = false;
         }
         // Check if we can access the path
         if (file_exists($assetstore->getPath())) {
             $assetstores[$key]->totalSpace = UtilityComponent::diskTotalSpace($assetstore->getPath());
             $assetstores[$key]->totalSpaceText = $this->Component->Utility->formatSize($assetstores[$key]->totalSpace);
             $assetstores[$key]->freeSpace = UtilityComponent::diskFreeSpace($assetstore->getPath());
             $assetstores[$key]->freeSpaceText = $this->Component->Utility->formatSize($assetstores[$key]->freeSpace);
         } else {
             $assetstores[$key]->totalSpaceText = false;
         }
     }
     if (!$defaultSet) {
         foreach ($assetstores as $key => $assetstore) {
             $assetstores[$key]->default = true;
             $this->Setting->setConfig('default_assetstore', $assetstores[$key]->getKey());
             $writer = new Zend_Config_Writer_Ini();
             $writer->setConfig($config);
             $writer->setFilename(APPLICATION_CONFIG);
             $writer->write();
             break;
         }
     }
     $this->view->assetstores = $assetstores;
     $this->view->assetstoreForm = $this->Form->Assetstore->createAssetstoreForm();
     // get modules
     $enabledModules = Zend_Registry::get('modulesEnable');
     $adapter = Zend_Registry::get('configDatabase')->database->adapter;
     foreach ($allModules as $key => $module) {
         if (file_exists(BASE_PATH . '/modules/' . $key . '/controllers/ConfigController.php')) {
             $allModules[$key]->configPage = 'config';
         } elseif (file_exists(BASE_PATH . '/privateModules/' . $key . '/controllers/ConfigController.php')) {
             $allModules[$key]->configPage = 'config';
         } elseif (file_exists(BASE_PATH . '/modules/' . $key . '/controllers/AdminController.php')) {
             $allModules[$key]->configPage = 'admin';
         } elseif (file_exists(BASE_PATH . '/privateModules/' . $key . '/controllers/AdminController.php')) {
             $allModules[$key]->configPage = 'admin';
         } else {
             $allModules[$key]->configPage = false;
         }
         if (isset($module->db->{$adapter})) {
             $allModules[$key]->dbOk = true;
         } else {
             $allModules[$key]->dbOk = false;
         }
         $allModules[$key]->dependenciesArray = array();
         $allModules[$key]->dependenciesExist = true;
         // check if dependencies exit
         if (isset($allModules[$key]->dependencies) && !empty($allModules[$key]->dependencies)) {
             $allModules[$key]->dependenciesArray = explode(',', trim($allModules[$key]->dependencies));
             foreach ($allModules[$key]->dependenciesArray as $dependency) {
                 if (!isset($allModules[$dependency])) {
                     $allModules[$key]->dependenciesExist = false;
                 }
             }
         }
     }
     $modulesList = array();
     $countModules = array();
     foreach ($allModules as $k => $module) {
         if (!isset($module->category) || empty($module->category)) {
             $category = 'Misc';
         } else {
             $category = ucfirst($module->category);
         }
         if (!isset($modulesList[$category])) {
             $modulesList[$category] = array();
             $countModules[$category] = array('visible' => 0, 'hidden' => 0);
         }
         $modulesList[$category][$k] = $module;
         if ($module->dbOk && $module->dependenciesExist) {
             ++$countModules[$category]['visible'];
         } else {
             ++$countModules[$category]['hidden'];
         }
     }
     foreach ($modulesList as $k => $l) {
         ksort($modulesList[$k]);
     }
     ksort($modulesList);
     $this->view->countModules = $countModules;
     $this->view->modulesList = $modulesList;
     $this->view->modulesEnable = $enabledModules;
     $this->view->databaseType = Zend_Registry::get('configDatabase')->database->adapter;
 }
 /**
  * Calling this will stream the file to the client.
  * The parameter is a bitstream dao.
  * Optional second parameter is the download offset in bytes.
  *
  * @param BitstreamDao $bitstream
  * @param int $offset
  * @param bool $incrementDownload
  * @throws Zend_Exception
  */
 public function download($bitstream, $offset = 0, $incrementDownload = false)
 {
     // Disable gzip output on apache servers (otherwise no progress in browser)
     if (function_exists('apache_setenv')) {
         apache_setenv('no-gzip', '1');
     }
     $mimetype = $bitstream->getMimetype();
     $path = $bitstream->getAssetstore()->getPath() . '/' . $bitstream->getPath();
     $name = $bitstream->getName();
     if (!file_exists($path)) {
         throw new Zend_Exception('Unable to find file on the disk');
     }
     $chunkSize = 1024 * 64;
     $fileSize = UtilityComponent::fileSize($path);
     $handle = fopen($path, 'rb');
     if ($handle === false) {
         throw new Zend_Exception('Unable to open the file');
     }
     if (!$this->testingmode) {
         // don't send any headers in testing mode since it will break it
         $modified = gmdate('D, d M Y H:i:s') . ' GMT';
         $contentType = $mimetype;
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Last-Modified: ' . $modified);
         // if pdf set the content-type accordingly
         if (!isset($contentType) && pathinfo($name, PATHINFO_EXTENSION) == 'pdf') {
             $contentType = 'application/pdf';
             $enableContentDisposition = false;
         }
         if (!isset($contentType)) {
             $contentType = 'application/octet-stream';
         }
         // Hack for .vsp files (for OSA)
         if (!isset($contentType) && strlen($name) > 4 && substr($name, strlen($name) - 4, 4) == '.vsp') {
             $contentType = 'application/isp';
         }
         $agent = env('HTTP_USER_AGENT');
         if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
             header('Content-Type: ' . $contentType);
             header('Content-Disposition: attachment; filename="' . $name . '"');
             header('Expires: 0');
             header('Accept-Ranges: bytes');
             header('Cache-Control: private', false);
             header('Pragma: private');
             $httpRange = env('HTTP_RANGE');
             if (isset($httpRange)) {
                 // HTTP range is of the form "bytes=n-" where n is the offset
                 list(, $range) = explode('=', $httpRange);
                 $firstByte = strstr($range, '-', true);
                 $lastByte = $fileSize - 1;
                 $length = $fileSize - $firstByte;
                 header('HTTP/1.1 206 Partial Content');
                 header('Content-Length: ' . $length);
                 header('Content-Range: bytes ' . $firstByte . '-' . $lastByte . '/' . $fileSize);
                 fseek($handle, $firstByte);
             } else {
                 header('Content-Length: ' . $fileSize);
             }
         } else {
             header('Accept-Ranges: bytes');
             header('Expires: 0');
             header('Content-Type: ' . $contentType);
             header('Content-Length: ' . $fileSize);
             if (!isset($enableContentDisposition) || $enableContentDisposition == true) {
                 header('Content-Disposition: attachment; filename="' . $name . '"');
             }
             if (isset($httpRange)) {
                 list(, $range) = explode('=', $httpRange);
                 $firstByte = strstr($range, '-', true);
                 $lastByte = $fileSize - 1;
                 $length = $fileSize - $firstByte;
                 header('HTTP/1.1 206 Partial Content');
                 header('Content-Length: ' . $length);
                 header('Content-Range: bytes ' . $firstByte . '-' . $lastByte . '/' . $fileSize);
                 fseek($handle, $firstByte);
             }
         }
     }
     ignore_user_abort(true);
     // must call this so the script doesn't end as soon as connection closed
     // close the database connection so we don't get too many connections problems
     Zend_Registry::get('dbAdapter')->closeConnection();
     session_write_close();
     // unlock session writing for concurrent access
     // kill the whole ob stack (Zend uses double nested output buffers)
     while (!$this->testingmode && ob_get_level() > 0) {
         ob_end_clean();
     }
     if (is_numeric($offset) && $offset > 0 && $offset <= $fileSize) {
         fseek($handle, $offset);
     }
     while (!feof($handle) && connection_status() == 0) {
         echo fread($handle, $chunkSize);
     }
     if ($incrementDownload && feof($handle)) {
         // Only record downloads that actually complete
         /** @var ItemModel $itemModel */
         $itemModel = MidasLoader::loadModel('Item');
         $itemModel->incrementDownloadCount($bitstream->getItemrevision()->getItem());
     }
     fclose($handle);
     if (!$this->testingmode) {
         // don't exit if we are in testing mode
         exit;
     }
 }
Exemplo n.º 16
0
 /**
  * called from ajax.
  */
 public function addAction()
 {
     $this->requireAdminPrivileges();
     $this->disableLayout();
     $this->disableView();
     $form = $this->Form->Assetstore->createAssetstoreForm();
     if ($this->getRequest()->isPost() && !$form->isValid($_POST)) {
         echo json_encode(array('error' => 'Missing or invalid form values.'));
         return false;
     }
     if ($this->getRequest()->isPost() && $form->isValid($_POST)) {
         // Save the assetstore in the database
         $assetstoreDao = new AssetstoreDao();
         $assetstoreDao->setName($form->name->getValue());
         $assetstoreDao->setPath($form->basedirectory->getValue());
         $assetstoreDao->setType($form->assetstoretype->getValue());
         if (!is_dir($assetstoreDao->getPath())) {
             echo JsonComponent::encode(array('error' => 'The path provided is not a valid directory'));
             return false;
         }
         if (!is_writable($assetstoreDao->getPath())) {
             echo JsonComponent::encode(array('error' => 'The specified directory is not writable'));
             return false;
         }
         try {
             $this->Assetstore->save($assetstoreDao);
         } catch (Zend_Exception $ze) {
             echo JsonComponent::encode(array('error' => $ze->getMessage()));
             return false;
         }
         $totalSpace = UtilityComponent::diskTotalSpace($assetstoreDao->getPath());
         $freeSpace = UtilityComponent::diskFreeSpace($assetstoreDao->getPath());
         echo JsonComponent::encode(array('msg' => 'The assetstore has been added.', 'assetstore_id' => $assetstoreDao->getAssetstoreId(), 'assetstore_name' => $assetstoreDao->getName(), 'assetstore_type' => $assetstoreDao->getType(), 'totalSpace' => $totalSpace, 'totalSpaceText' => $this->Component->Utility->formatSize($totalSpace), 'freeSpace' => $freeSpace, 'freeSpaceText' => $this->Component->Utility->formatSize($freeSpace)));
         return true;
     }
     echo json_encode(array('error' => 'Bad request.'));
     return false;
 }
Exemplo n.º 17
0
 /**
  * Google Cloud Storage upload callback.
  *
  * @param array $args
  * @return array
  * @throws Exception
  */
 public function callback($args)
 {
     /** @var ApihelperComponent $apihelperComponent */
     $apihelperComponent = MidasLoader::loadComponent('Apihelper');
     $apihelperComponent->validateParams($args, array('uploadtoken'));
     if (!Zend_Controller_Front::getInstance()->getRequest()->isPost()) {
         throw new Exception('POST method required', MIDAS_HTTP_ERROR);
     }
     $uploadToken = $args['uploadtoken'];
     $path = UtilityComponent::getTempDirectory() . '/' . $uploadToken;
     if (!file_exists($path)) {
         throw new Exception('Invalid upload token ' . $uploadToken, MIDAS_INVALID_UPLOAD_TOKEN);
     }
     @rmdir($path);
     list($userId, $itemId) = explode('/', $uploadToken);
     /** @var UserModel $userModel */
     $userModel = MidasLoader::loadModel('User');
     $userDao = $userModel->load($userId);
     if ($userDao === false) {
         throw new Exception('Invalid user id from upload token', MIDAS_INVALID_PARAMETER);
     }
     /** @var ItemModel $itemModel */
     $itemModel = MidasLoader::loadModel('Item');
     $itemDao = $itemModel->load($itemId);
     if ($itemDao === false) {
         throw new Exception('Unable to find item', MIDAS_INVALID_PARAMETER);
     }
     if (!$itemModel->policyCheck($itemDao, $userDao, MIDAS_POLICY_WRITE)) {
         throw new Exception('Permission error', MIDAS_INVALID_POLICY);
     }
     if (array_key_exists('revision', $args)) {
         if (strtolower($args['revision']) == 'head') {
             $revision = $itemModel->getLastRevision($itemDao);
         } else {
             $revision = $itemModel->getRevision($itemDao, $args['revision']);
             if ($revision == false) {
                 throw new Exception('Unable to find revision', MIDAS_INVALID_PARAMETER);
             }
         }
     }
     if (!array_key_exists('file', $args) || !array_key_exists('file', $_FILES)) {
         throw new Exception('Parameter file is not defined', MIDAS_INVALID_PARAMETER);
     }
     $file = $_FILES['file'];
     $name = $file['name'];
     $tmpName = $file['tmp_name'];
     $size = filesize($tmpName);
     $folderDaos = $itemDao->getFolders();
     /** @var FolderDao $folderDao */
     $folderDao = $folderDaos[0];
     $validations = Zend_Registry::get('notifier')->callback('CALLBACK_CORE_VALIDATE_UPLOAD', array('filename' => $name, 'size' => $size, 'path' => $tmpName, 'folderId' => $folderDao->getFolderId()));
     foreach ($validations as $validation) {
         if (!$validation['status']) {
             throw new Exception($validation['message'], MIDAS_INVALID_POLICY);
         }
     }
     $license = isset($args['license']) ? $args['license'] : null;
     $checksum = md5_file($tmpName);
     $revisionNumber = null;
     if (isset($revision) && $revision !== false) {
         $revisionNumber = $revision->getRevision();
     }
     if (isset($args['changes'])) {
         $changes = $args['changes'];
     } elseif ($revisionNumber === 1) {
         $changes = 'Initial revision';
     } else {
         $changes = '';
     }
     move_uploaded_file($tmpName, $path);
     /** @var UploadComponent $uploadComponent */
     $uploadComponent = MidasLoader::loadComponent('Upload');
     $itemDao = $uploadComponent->createNewRevision($userDao, $name, $path, $changes, $itemDao->getKey(), $revisionNumber, $license, $checksum, false, $size);
     if ($itemDao === false) {
         throw new Exception('Upload failed', MIDAS_INTERNAL_ERROR);
     }
     return $itemDao->toArray();
 }
Exemplo n.º 18
0
 /**
  * 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();
 }
Exemplo n.º 19
0
 /**
  * Ajax action for getting the latest package of each package type for the given os and arch.
  *
  * @param os The os to match on
  * @param arch The arch to match on
  * @param applicationId The application id
  * @return (json) - The latest uploaded package of each installer type for the given os, arch, and application
  */
 public function latestAction()
 {
     $this->disableLayout();
     $this->disableView();
     $os = $this->getParam('os');
     $arch = $this->getParam('arch');
     $applicationId = $this->getParam('applicationId');
     if (!isset($applicationId)) {
         throw new Zend_Exception('Must specify an applicationId parameter');
     }
     $application = $this->Packages_Application->load($applicationId);
     if (!$application) {
         throw new Zend_Exception('Invalid applicationId', 404);
     }
     $comm = $application->getProject()->getCommunity();
     if (!$this->Community->policyCheck($comm, $this->userSession->Dao, MIDAS_POLICY_READ)) {
         throw new Zend_Exception('You do not have read permissions on the project');
     }
     $latest = $this->Packages_Package->getLatestOfEachPackageType($application, $os, $arch);
     $filtered = array();
     foreach ($latest as $package) {
         if ($this->Item->policyCheck($package->getItem(), $this->userSession->Dao, MIDAS_POLICY_READ)) {
             $sizestr = UtilityComponent::formatSize($package->getItem()->getSizebytes());
             $filtered[] = array_merge($package->toArray(), array('size_formatted' => $sizestr));
         }
     }
     echo JsonComponent::encode($filtered);
 }
Exemplo n.º 20
0
 /**
  * called from ajax.
  */
 public function importAction()
 {
     $this->requireAdminPrivileges();
     // This is necessary in order to avoid session lock and being able to run two
     // ajax requests simultaneously
     session_write_close();
     $this->nfilesprocessed = 0;
     $this->disableLayout();
     $this->disableView();
     $this->assetstores = $this->Assetstore->getAll();
     $form = $this->Form->Import->createImportForm($this->assetstores);
     if ($this->getRequest()->isPost() && !$form->isValid($_POST)) {
         echo json_encode(array('error' => $this->t('The form is invalid. Missing values.')));
         return false;
     }
     // If we just validate the form we return
     if ($this->getRequest()->getPost('validate')) {
         echo json_encode(array('stage' => 'validate'));
         return false;
     } elseif ($this->getRequest()->getPost('initialize')) {
         // Count the total number of files in the directory and return it
         $this->ntotalfiles = $this->_recursiveCountFiles($form->inputdirectory->getValue());
         echo json_encode(array('stage' => 'initialize', 'totalfiles' => $this->ntotalfiles));
         return false;
     } elseif ($this->getRequest()->isPost() && $form->isValid($_POST)) {
         $this->ntotalfiles = $this->getRequest()->getPost('totalfiles');
         // Parse the directory
         $pathName = $form->inputdirectory->getValue();
         $currentdirid = $form->importFolder->getValue();
         // we just start with te initial dir
         $currentdir = new FolderDao();
         $currentdir->setFolderId($currentdirid);
         // Set the file locations used to handle the async requests
         $this->progressfile = $this->getTempDirectory() . '/importprogress_' . $form->uploadid->getValue();
         $this->stopfile = $this->getTempDirectory() . '/importstop_' . $form->uploadid->getValue();
         $this->assetstoreid = $form->assetstore->getValue();
         $this->importemptydirectories = $form->importemptydirectories->getValue();
         try {
             if ($this->_recursiveParseDirectory($pathName, $currentdir)) {
                 echo json_encode(array('message' => $this->t('Import successful.')));
             } else {
                 echo json_encode(array('error' => $this->t('Problem occured while importing. ' . 'Check the log files or contact an ' . 'administrator.')));
             }
         } catch (Exception $e) {
             echo json_encode(array('error' => $this->t($e->getMessage())));
         }
         // Remove the temp and stop files
         UtilityComponent::safedelete($this->progressfile);
         UtilityComponent::safedelete($this->stopfile);
         return true;
     }
     echo json_encode(array('error' => $this->t('The request should be a post.')));
     return false;
 }
Exemplo n.º 21
0
 /**
  * Slice name view helper.
  *
  * @param string $name name
  * @param int $nchar number of characters
  * @return string sliced name
  */
 public function slicename($name, $nchar)
 {
     return htmlspecialchars(UtilityComponent::sliceName($name, $nchar), ENT_QUOTES, 'UTF-8');
 }
Exemplo n.º 22
0
 /** delete a folder (ajax action)*/
 public function deleteAction()
 {
     $this->disableLayout();
     $this->disableView();
     $folder_id = $this->getParam('folderId');
     $folder = $this->Folder->load($folder_id);
     if (!isset($folder_id)) {
         throw new Zend_Exception('Please set the folderId.');
     } elseif ($folder === false) {
         throw new Zend_Exception("The folder doesn't exist.");
     } elseif (!$this->Folder->policyCheck($folder, $this->userSession->Dao, MIDAS_POLICY_ADMIN)) {
         throw new Zend_Exception('Permissions error.');
     }
     // User cannot delete community's root folder, the default 'Public' folder and the default 'Private' folder
     if ($this->Folder->getCommunity($folder) != false) {
         throw new Zend_Exception('Community Root Folder. You cannot delete it.');
     }
     // User cannot delete its root folder, the default 'Public' folder and the default 'Private' folder
     if ($this->Folder->getUser($folder) != false) {
         throw new Zend_Exception('User Root Folder. You cannot delete it.');
     }
     if ($this->progressDao) {
         $this->progressDao->setMaximum($this->Folder->getRecursiveChildCount($folder) + 1);
         $this->progressDao->setMessage('Preparing to delete folder...');
         $this->Progress->save($this->progressDao);
     }
     UtilityComponent::disableMemoryLimit();
     $this->Folder->delete($folder, $this->progressDao);
     $folderInfo = $folder->toArray();
     echo JsonComponent::encode(array(true, $this->t('Changes saved'), $folderInfo));
 }
Exemplo n.º 23
0
 /** get action menu */
 public function getItemInfo($params)
 {
     if ($params['item'] instanceof ItemDao) {
         $jobs = $this->Remoteprocessing_Job->getRelatedJob($params['item']);
         $items = array();
         foreach ($jobs as $job) {
             $items = array_merge($items, $job->getItems());
         }
         Zend_Loader::loadClass('UtilityComponent', BASE_PATH . '/core/controllers/components');
         $component = new UtilityComponent();
         $html = "<div class='sideElement'>\n                    <h1>" . $this->t('Related Items') . '</h1>
                   <ul>';
         $itemIds = array();
         $i = 0;
         $nameArrayCurrent = explode('.', $params['item']->getName());
         foreach ($items as $item) {
             $nameArrayItem = explode('.', $item->getName());
             // remove doublons
             if (in_array($item->getKey(), $itemIds)) {
                 continue;
             }
             $itemIds[] = $item->getKey();
             // policy check
             if (!$this->Item->policyCheck($item, $this->userSession->Dao)) {
                 continue;
             }
             // don't show current item
             if ($params['item']->getKey() == $item->getKey()) {
                 continue;
             }
             // don't show related results
             if ($nameArrayCurrent[0] == $nameArrayItem[0] && end($nameArrayItem) == end($nameArrayCurrent)) {
                 continue;
             }
             $html .= '<li>';
             $html .= "<a  element='" . htmlspecialchars($item->getKey(), ENT_QUOTES, 'UTF-8') . "' href='" . Zend_Registry::get('webroot') . '/item/' . htmlspecialchars($item->getKey(), ENT_QUOTES, 'UTF-8') . "'>" . $component->slicename(htmlspecialchars($item->getName(), ENT_QUOTES, 'UTF-8'), 25) . '</a>';
             $html .= '</li>';
             if ($i > 7) {
                 $html .= '<li>...</li>';
                 break;
             }
             ++$i;
         }
         if ($i == 0) {
             return '';
         }
         $html .= '</ul>';
         $html .= '</div>';
         $html .= "<div class='sideElementLast'>\n                  <h1>" . $this->t('Related Jobs') . '</h1>
                 <ul>';
         $i = 0;
         foreach ($jobs as $job) {
             $name = $job->getName();
             if (empty($name)) {
                 $name = $job->getCreationDate();
             }
             $html .= '<li>';
             $html .= "<a  element='" . htmlspecialchars($job->getKey(), ENT_QUOTES, 'UTF-8') . "' href='" . Zend_Registry::get('webroot') . '/remoteprocessing/job/view/?jobId=' . htmlspecialchars($job->getKey(), ENT_QUOTES, 'UTF-8') . "'>" . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>';
             $html .= '</li>';
             if ($i > 3) {
                 $html .= '<li>...</li>';
                 break;
             }
             ++$i;
         }
         $html .= '</ul>';
         $html .= '</div>';
         return $html;
     }
     return '';
 }
Exemplo n.º 24
0
 /**
  * This action exposes downloading a single bitstream and should be called as
  *   download/bitstream/<bitstream_id>/...
  * Any extra parameters are ignored and can be used to force clients like wget to download to the correct filename
  * if the content-disposition header is ignored by the user agent.
  *
  * @throws Zend_Exception
  */
 public function bitstreamAction()
 {
     $pathParams = UtilityComponent::extractPathParams();
     if (empty($pathParams)) {
         throw new Zend_Exception('Must specify bitstream id as a path parameter');
     }
     $this->forward('index', null, null, array('bitstream' => $pathParams[0]));
 }
Exemplo n.º 25
0
 /**
  * Get the temporary directory.
  *
  * @return string
  */
 protected function getTempDirectory()
 {
     return UtilityComponent::getTempDirectory();
 }
Exemplo n.º 26
0
 /**
  * Upload a file to the server. PUT or POST is required.
  * Will add the file as a bitstream to the item that was specified when
  * generating the upload token in a new revision to that item, unless
  * <b>revision</b> param is set.
  *
  * @path /system/upload
  * @http POST
  * @param uploadtoken The upload token (see <b>midas.upload.generatetoken</b>).
  * @param filename The name of the bitstream that will be added to the item.
  * @param length The length in bytes of the file being uploaded.
  * @param mode (Optional) Stream or multipart. Default is stream.
  * @param revision (Optional)
  * If set, will add a new file into the existing passed in revision number.
  * If set to "head", will add a new file into the most recent revision,
  * and will create a new revision in this case if none exists.
  * @param changes (Optional)
  * The changes field on the affected item revision,
  * e.g. for recording what has changed since the previous revision.
  * @param license (Optional) The license for the revision.
  * @return The item information of the item created or changed.
  *
  * @param array $args parameters
  * @throws Exception
  */
 public function uploadPerform($args)
 {
     /** @var ApihelperComponent $apihelperComponent */
     $apihelperComponent = MidasLoader::loadComponent('Apihelper');
     $apihelperComponent->validateParams($args, array('uploadtoken', 'filename', 'length'));
     $request = Zend_Controller_Front::getInstance()->getRequest();
     if (!$request->isPost() && !$request->isPut()) {
         throw new Exception('POST or PUT method required', MIDAS_HTTP_ERROR);
     }
     list($userid, $itemid) = explode('/', $args['uploadtoken']);
     /** @var ItemModel $itemModel */
     $itemModel = MidasLoader::loadModel('Item');
     /** @var UserModel $userModel */
     $userModel = MidasLoader::loadModel('User');
     $userDao = $userModel->load($userid);
     if (!$userDao) {
         throw new Exception('Invalid user id from upload token', MIDAS_INVALID_PARAMETER);
     }
     $item = $itemModel->load($itemid);
     if ($item == false) {
         throw new Exception('Unable to find item', MIDAS_INVALID_PARAMETER);
     }
     if (!$itemModel->policyCheck($item, $userDao, MIDAS_POLICY_WRITE)) {
         throw new Exception('Permission error', MIDAS_INVALID_POLICY);
     }
     if (array_key_exists('revision', $args)) {
         if (strtolower($args['revision']) == 'head') {
             $revision = $itemModel->getLastRevision($item);
             // if no revision exists, it will be created later
         } else {
             $revision = $itemModel->getRevision($item, $args['revision']);
             if ($revision == false) {
                 throw new Exception('Unable to find revision', MIDAS_INVALID_PARAMETER);
             }
         }
     }
     $mode = array_key_exists('mode', $args) ? $args['mode'] : 'stream';
     /** @var HttpuploadComponent $httpUploadComponent */
     $httpUploadComponent = MidasLoader::loadComponent('Httpupload');
     $apiSetup = $apihelperComponent->getApiSetup();
     $httpUploadComponent->setTestingMode(Zend_Registry::get('configGlobal')->environment === 'testing');
     if (array_key_exists('testingmode', $args)) {
         $httpUploadComponent->setTestingMode(true);
         if (!array_key_exists('localinput', $args)) {
             $args['localinput'] = UtilityComponent::getTempDirectory() . '/' . $args['filename'];
         }
     }
     // Use the Httpupload component to handle the actual file upload
     if ($mode == 'stream') {
         $result = $httpUploadComponent->process($args);
         $filename = $result['filename'];
         $filePath = $result['path'];
         $fileSize = (int) $result['size'];
         $fileChecksum = $result['md5'];
     } elseif ($mode == 'multipart') {
         if (!array_key_exists('file', $args) || !array_key_exists('file', $_FILES)) {
             throw new Exception('Parameter file is not defined', MIDAS_INVALID_PARAMETER);
         }
         $file = $_FILES['file'];
         $filename = $file['name'];
         $filePath = $file['tmp_name'];
         $fileSize = (int) $file['size'];
         $fileChecksum = '';
     } else {
         throw new Exception('Invalid upload mode', MIDAS_INVALID_PARAMETER);
     }
     // get the parent folder of this item and notify the callback
     // this is made more difficult by the fact the items can have many parents,
     // just use the first in the list.
     $parentFolders = $item->getFolders();
     if (!isset($parentFolders) || !$parentFolders || count($parentFolders) === 0) {
         // this shouldn't happen with any self-respecting item
         throw new Exception('Item does not have a parent folder', MIDAS_INVALID_PARAMETER);
     }
     $firstParent = $parentFolders[0];
     $validations = Zend_Registry::get('notifier')->callback('CALLBACK_CORE_VALIDATE_UPLOAD', array('filename' => $filename, 'size' => $fileSize, 'path' => $filePath, 'folderId' => $firstParent->getFolderId()));
     foreach ($validations as $validation) {
         if (!$validation['status']) {
             unlink($filePath);
             throw new Exception($validation['message'], MIDAS_INVALID_POLICY);
         }
     }
     $license = array_key_exists('license', $args) ? $args['license'] : null;
     $changes = array_key_exists('changes', $args) ? $args['changes'] : '';
     $revisionNumber = null;
     if (isset($revision) && $revision !== false) {
         $revisionNumber = $revision->getRevision();
     }
     /** @var UploadComponent $uploadComponent */
     $uploadComponent = MidasLoader::loadComponent('Upload');
     $item = $uploadComponent->createNewRevision($userDao, $filename, $filePath, $changes, $item->getKey(), $revisionNumber, $license, $fileChecksum, false, $fileSize);
     if (!$item) {
         throw new Exception('Upload failed', MIDAS_INTERNAL_ERROR);
     }
     return $item->toArray();
 }
Exemplo n.º 27
0
 /** View a community */
 public function viewAction()
 {
     $this->view->Utility = $this->Component->Utility;
     $this->view->Date = $this->Component->Date;
     $communityId = $this->getParam('communityId');
     if (!isset($communityId) || !is_numeric($communityId)) {
         throw new Zend_Exception('Community ID should be a number');
     }
     $communityDao = $this->Community->load($communityId);
     if ($communityDao === false || !$this->Community->policyCheck($communityDao, $this->userSession->Dao)) {
         throw new Zend_Exception("This community doesn't exist or you don't have the permissions.", 403);
     }
     $joinCommunity = $this->getParam('joinCommunity');
     $leaveCommunity = $this->getParam('leaveCommunity');
     $canJoin = $communityDao->getCanJoin() == MIDAS_COMMUNITY_CAN_JOIN;
     $this->view->isInvited = $this->CommunityInvitation->isInvited($communityDao, $this->userSession->Dao);
     $this->view->canJoin = $canJoin;
     if ($this->userSession->Dao != null && isset($joinCommunity) && ($canJoin || $this->view->isInvited)) {
         $member_group = $communityDao->getMemberGroup();
         $this->Group->addUser($member_group, $this->userSession->Dao);
         Zend_Registry::get('notifier')->callback('CALLBACK_CORE_USER_JOINED_COMMUNITY', array('user' => $this->userSession->Dao, 'community' => $communityDao));
         if ($this->view->isInvited) {
             $invitationDao = $this->CommunityInvitation->isInvited($communityDao, $this->userSession->Dao, true);
             if ($invitationDao->getGroupId() !== $member_group->getKey()) {
                 // If user is invited to something besides the member group, we should add them to that group also
                 $this->Group->addUser($invitationDao->getGroup(), $this->userSession->Dao);
             }
             $this->CommunityInvitation->removeInvitation($communityDao, $this->userSession->Dao);
         }
     }
     if ($this->userSession->Dao != null && isset($leaveCommunity)) {
         $member_group = $communityDao->getMemberGroup();
         $this->Group->removeUser($member_group, $this->userSession->Dao);
         $this->redirect('/community');
     }
     $this->Community->incrementViewCount($communityDao);
     $this->view->communityDao = $communityDao;
     $this->view->information = array();
     $this->view->feeds = $this->Feed->getFeedsByCommunity($this->userSession->Dao, $communityDao);
     $group_member = $communityDao->getMemberGroup();
     $this->view->members = $group_member->getUsers();
     $this->view->mainFolder = $communityDao->getFolder();
     $this->view->folders = $this->Folder->getChildrenFoldersFiltered($this->view->mainFolder, $this->userSession->Dao, MIDAS_POLICY_READ);
     $this->view->items = $this->Folder->getItemsFiltered($this->view->mainFolder, $this->userSession->Dao, MIDAS_POLICY_READ);
     $this->view->isMember = false;
     if ($this->userSession->Dao != null) {
         foreach ($this->view->members as $member) {
             if ($member->getKey() == $this->userSession->Dao->getKey()) {
                 $this->view->isMember = true;
                 break;
             }
         }
     }
     $this->view->isModerator = $this->Community->policyCheck($communityDao, $this->userSession->Dao, MIDAS_POLICY_WRITE);
     $this->view->isAdmin = $this->Community->policyCheck($communityDao, $this->userSession->Dao, MIDAS_POLICY_ADMIN);
     $this->view->json['community'] = $communityDao->toArray();
     $this->view->json['community']['sendInvitation'] = $this->t('Send invitation');
     if ($this->view->isMember) {
         $this->view->shareItems = $this->Item->getSharedToCommunity($communityDao);
     }
     $this->view->title .= ' - ' . $communityDao->getName();
     $this->view->metaDescription = substr(UtilityComponent::markdown(htmlspecialchars($communityDao->getDescription(), ENT_COMPAT, 'UTF-8')), 0, 160);
     $this->view->customJSs = Zend_Registry::get('notifier')->callback('CALLBACK_CORE_GET_COMMUNITY_VIEW_JSS', array());
     $this->view->customCSSs = Zend_Registry::get('notifier')->callback('CALLBACK_CORE_GET_COMMUNITY_VIEW_CSSS', array());
     $this->addDynamicHelp('#tabDataLink', 'Public and Private Data hosted by the community.');
     $this->addDynamicHelp('#tabFeedLink', 'What\'s new?');
     $this->addDynamicHelp('#tabInfoLink', 'Description of the community.');
     $this->addDynamicHelp('#tabSharedLink', 'Data shared to the member of the community.');
     $this->view->extraHtml = Zend_Registry::get('notifier')->callback('CALLBACK_CORE_GET_COMMUNITY_VIEW_EXTRA_HTML', array('community' => $communityDao));
     $this->view->customTabs = Zend_Registry::get('notifier')->callback('CALLBACK_CORE_GET_COMMUNITY_VIEW_TABS', array('community' => $communityDao));
     $this->view->customManageActions = Zend_Registry::get('notifier')->callback('CALLBACK_CORE_GET_COMMUNITY_VIEW_ADMIN_ACTIONS', array('community' => $communityDao));
 }
Exemplo n.º 28
0
 /**
  * View a Item.
  *
  * @throws Zend_Exception on invalid itemId and incorrect access permission
  */
 public function viewAction()
 {
     $this->view->Date = $this->Component->Date;
     $itemId = $this->getParam('itemId');
     if (!isset($itemId) || !is_numeric($itemId)) {
         throw new Zend_Exception('itemId should be a number');
     }
     $itemDao = $this->Item->load($itemId);
     if ($itemDao === false) {
         throw new Zend_Exception("This item doesn't exist.", 404);
     }
     if (!$this->Item->policyCheck($itemDao, $this->userSession->Dao, MIDAS_POLICY_READ)) {
         throw new Zend_Exception('Read permission required', 403);
     }
     $this->view->isAdmin = $this->Item->policyCheck($itemDao, $this->userSession->Dao, MIDAS_POLICY_ADMIN);
     $this->view->isModerator = $this->Item->policyCheck($itemDao, $this->userSession->Dao, MIDAS_POLICY_WRITE);
     $itemRevision = $this->Item->getLastRevision($itemDao);
     if ($this->_request->isPost()) {
         $itemRevisionNumber = $this->getParam('itemrevision');
         if (isset($itemRevisionNumber)) {
             $metadataItemRevision = $this->Item->getRevision($itemDao, $itemRevisionNumber);
         } else {
             $metadataItemRevision = $itemRevision;
         }
         if ($metadataItemRevision === false) {
             throw new Zend_Exception('The item must have at least one revision to have metadata', MIDAS_INVALID_POLICY);
         }
         $deleteMetadata = $this->getParam('deleteMetadata');
         $editMetadata = $this->getParam('editMetadata');
         if (isset($deleteMetadata) && !empty($deleteMetadata) && $this->view->isModerator) {
             // delete metadata field
             $this->disableView();
             $this->disableLayout();
             $metadataId = $this->getParam('element');
             $this->ItemRevision->deleteMetadata($metadataItemRevision, $metadataId);
             echo JsonComponent::encode(array(true, $this->t('Changes saved')));
             return;
         }
         if (isset($editMetadata) && !empty($editMetadata) && $this->view->isModerator) {
             // add metadata field
             $metadatatype = $this->getParam('metadatatype');
             $element = $this->getParam('element');
             $qualifier = $this->getParam('qualifier');
             $value = $this->getParam('value');
             $updateMetadata = $this->getParam('updateMetadata');
             $metadataDao = $this->Metadata->getMetadata($metadatatype, $element, $qualifier);
             if ($metadataDao == false) {
                 $metadataDao = $this->Metadata->addMetadata($metadatatype, $element, $qualifier, '');
             }
             $metadataDao->setItemrevisionId($metadataItemRevision->getKey());
             $metadataValueExists = $this->Metadata->getMetadataValueExists($metadataDao);
             if ($updateMetadata || !$metadataValueExists) {
                 // if we are updating or no metadatavalue exists, then save it
                 // otherwise we are attempting to add a new value where one already
                 // exists, and we won't save in this case
                 $this->Metadata->addMetadataValue($metadataItemRevision, $metadatatype, $element, $qualifier, $value);
             }
         }
     }
     if ($this->logged && !$this->isTestingEnv()) {
         $cookieName = hash('sha1', MIDAS_ITEM_COOKIE_NAME . $this->userSession->Dao->getKey());
         /** @var Zend_Controller_Request_Http $request */
         $request = $this->getRequest();
         $cookieData = $request->getCookie($cookieName);
         $recentItems = array();
         if (isset($cookieData)) {
             $recentItems = unserialize($cookieData);
         }
         $tmp = array_reverse($recentItems);
         $i = 0;
         foreach ($tmp as $key => $t) {
             if ($t == $itemDao->getKey() || !is_numeric($t)) {
                 unset($tmp[$key]);
                 continue;
             }
             ++$i;
             if ($i > 4) {
                 unset($tmp[$key]);
             }
         }
         $recentItems = array_reverse($tmp);
         $recentItems[] = $itemDao->getKey();
         $date = new DateTime();
         $interval = new DateInterval('P1M');
         setcookie($cookieName, serialize($recentItems), $date->add($interval)->getTimestamp(), '/', $request->getHttpHost(), (int) Zend_Registry::get('configGlobal')->get('cookie_secure', 1) === 1, true);
     }
     $this->Item->incrementViewCount($itemDao);
     $itemDao->lastrevision = $itemRevision;
     $itemDao->revisions = $itemDao->getRevisions();
     // Display the good link if the item is pointing to a website
     $this->view->itemIsLink = false;
     if (isset($itemRevision) && $itemRevision !== false) {
         $bitstreams = $itemRevision->getBitstreams();
         if (count($bitstreams) == 1) {
             $bitstream = $bitstreams[0];
             if (preg_match('/^https?:\\/\\//', $bitstream->getPath())) {
                 $this->view->itemIsLink = true;
             }
         }
         $itemDao->creation = $this->Component->Date->formatDate(strtotime($itemRevision->getDate()));
     }
     // Add the metadata for each revision
     foreach ($itemDao->getRevisions() as $revision) {
         $revision->metadatavalues = $this->ItemRevision->getMetadata($revision);
     }
     $this->Component->Sortdao->field = 'revision';
     $this->Component->Sortdao->order = 'desc';
     usort($itemDao->revisions, array($this->Component->Sortdao, 'sortByNumber'));
     $this->view->itemDao = $itemDao;
     $this->view->itemSize = UtilityComponent::formatSize($itemDao->getSizebytes());
     $this->view->title .= ' - ' . $itemDao->getName();
     $this->view->metaDescription = substr($itemDao->getDescription(), 0, 160);
     $tmp = Zend_Registry::get('notifier')->callback('CALLBACK_VISUALIZE_CAN_VISUALIZE', array('item' => $itemDao));
     if (isset($tmp['visualize']) && $tmp['visualize'] == true) {
         $this->view->preview = true;
     } else {
         $this->view->preview = false;
     }
     $currentFolder = false;
     $parents = $itemDao->getFolders();
     if (count($parents) == 1) {
         $currentFolder = $parents[0];
     } elseif (isset($this->userSession->recentFolders)) {
         foreach ($this->userSession->recentFolders as $recent) {
             foreach ($parents as $parent) {
                 if ($parent->getKey() == $recent) {
                     $currentFolder = $parent;
                     break;
                 }
             }
         }
         if ($currentFolder === false && count($parents) > 0) {
             $currentFolder = $parents[0];
         }
     } elseif (count($parents) > 0) {
         $currentFolder = $parents[0];
     }
     $this->view->currentFolder = $currentFolder;
     $parent = $currentFolder;
     $breadcrumbs = array();
     while ($parent !== false) {
         if (strpos($parent->getName(), 'community') !== false && $this->Folder->getCommunity($parent) !== false) {
             $breadcrumbs[] = array('type' => 'community', 'object' => $this->Folder->getCommunity($parent));
         } elseif (strpos($parent->getName(), 'user') !== false && $this->Folder->getUser($parent) !== false) {
             $breadcrumbs[] = array('type' => 'user', 'object' => $this->Folder->getUser($parent));
         } else {
             $breadcrumbs[] = array('type' => 'folder', 'object' => $parent);
         }
         $parent = $parent->getParent();
     }
     $this->Component->Breadcrumb->setBreadcrumbHeader(array_reverse($breadcrumbs), $this->view);
     $folders = array();
     $parents = $itemDao->getFolders();
     foreach ($parents as $parent) {
         if ($this->Folder->policyCheck($parent, $this->userSession->Dao, MIDAS_POLICY_READ)) {
             $folders[] = $parent;
         }
     }
     $this->view->folders = $folders;
     $this->view->json['item'] = $itemDao->toArray();
     $this->view->json['item']['isAdmin'] = $this->view->isAdmin;
     $this->view->json['item']['isModerator'] = $this->view->isModerator;
     $this->view->json['item']['message']['delete'] = $this->t('Delete');
     $this->view->json['item']['message']['sharedItem'] = $this->t('This item is currrently shared by other folders and/or communities. Deletion will make it disappear in all these folders and/or communitites. ');
     $this->view->json['item']['message']['deleteMessage'] = $this->t('Do you really want to delete this item? It cannot be undone.');
     $this->view->json['item']['message']['deleteMetadataMessage'] = $this->t('Do you really want to delete this metadata? It cannot be undone.');
     $this->view->json['item']['message']['deleteItemrevisionMessage'] = $this->t('Do you really want to delete this revision? It cannot be undone.');
     $this->view->json['item']['message']['deleteBitstreamMessage'] = $this->t('Do you really want to delete this bitstream? It cannot be undone.');
     $this->view->json['item']['message']['duplicate'] = $this->t('Duplicate Item');
     $this->view->json['modules'] = Zend_Registry::get('notifier')->callback('CALLBACK_CORE_ITEM_VIEW_JSON', array('item' => $itemDao));
 }
Exemplo n.º 29
0
 /**
  * Markdown view helper.
  *
  * @param string $text Markdown or Markdown Extra text
  * @return string HTML text
  */
 public function markdown($text)
 {
     return UtilityComponent::markdown(htmlspecialchars($text, ENT_COMPAT, 'UTF-8'));
 }
Exemplo n.º 30
0
 /**
  * Return a temporary directory.
  *
  * @param string $subDirectory
  * @param bool $createDirectory
  * @return string
  */
 protected function getTempDirectory($subDirectory = 'misc', $createDirectory = true)
 {
     return UtilityComponent::getTempDirectory($subDirectory, $createDirectory);
 }