public static function outputFile($relPath, $filename = null) { $fullpath = self::getExportPath() . DIRECTORY_SEPARATOR . $relPath; if (tao_helpers_File::securityCheck($fullpath, true) && file_exists($fullpath)) { Context::getInstance()->getResponse()->setContentHeader(tao_helpers_File::getMimeType($fullpath)); $fileName = empty($filename) ? basename($fullpath) : $filename; header('Content-Disposition: attachment; fileName="' . $fileName . '"'); header("Content-Length: " . filesize($fullpath)); //Clean all levels of output buffering while (ob_get_level() > 0) { ob_end_clean(); } flush(); $fp = fopen($fullpath, "r"); if ($fp !== false) { while (!feof($fp)) { echo fread($fp, 65536); flush(); } fclose($fp); @unlink($fullpath); } else { common_Logger::e('Unable to open File to export' . $fullpath); } } else { common_Logger::e('Could not find File to export: ' . $fullpath); } }
/** * Import file entry point by using $this->service * Check POST method & get valid uploaded file */ public function import() { $fileUploadName = "qtiPackage"; if ($this->getRequestMethod() != Request::HTTP_POST) { throw new \common_exception_NotImplemented('Only post method is accepted to import Qti package.'); } if (tao_helpers_Http::hasUploadedFile($fileUploadName)) { $file = tao_helpers_Http::getUploadedFile($fileUploadName); $mimeType = tao_helpers_File::getMimeType($file['tmp_name']); if (!in_array($mimeType, self::$accepted_types)) { $this->returnFailure(new common_exception_BadRequest()); } else { $report = $this->service->importQtiTest($file['tmp_name']); if ($report->getType() === common_report_Report::TYPE_SUCCESS) { $data = array(); foreach ($report as $r) { $values = $r->getData(); $testid = $values->rdfsResource->getUri(); foreach ($values->items as $item) { $itemsid[] = $item->getUri(); } $data[] = array('testId' => $testid, 'testItems' => $itemsid); } return $this->returnSuccess($data); } else { return $this->returnFailure(new common_exception_InconsistentData($report->getMessage())); } } } else { return $this->returnFailure(new common_exception_BadRequest()); } }
public function getAsset() { $item = new \core_kernel_classes_Resource($this->getRequestParameter('id')); $assetPath = $this->getRequestParameter('asset'); $mimeType = \tao_helpers_File::getMimeType($assetPath, true); header('Content-Type: ' . $mimeType); $loader = new Loader($item); $content = $loader->getAssetContent($assetPath); echo $content; }
public static function buildFile(core_kernel_classes_Resource $test, $lang, $relPath, $filters = array()) { $file = null; $baseDir = self::getBaseDir($test); $path = $baseDir . ltrim($relPath, '/'); $mime = tao_helpers_File::getMimeType($path); if (count($filters) == 0 || in_array($mime, $filters)) { $file = array('name' => basename($path), 'mime' => $mime, 'size' => filesize($path), 'url' => _url('download', 'TestContent', 'taoQtiTest', array('uri' => $test->getUri(), 'lang' => $lang, 'path' => $relPath))); } return $file; }
/** * (non-PHPdoc) * @see \oat\tao\model\media\MediaBrowser::getFileInfo */ public function getFileInfo($link) { $file = null; $filename = basename($link); $dir = ltrim(dirname($link), '/'); $sysPath = $this->getSysPath($dir . '/' . $filename); $mime = tao_helpers_File::getMimeType($sysPath); if (file_exists($sysPath)) { $file = array('name' => basename($sysPath), 'mime' => $mime, 'size' => filesize($sysPath)); } return $file; }
/** * Create a media instance from a file, and define its class and language * * @param string $fileSource path to the file to create instance from * @param string $classUri parent to add the instance to * @param string $language language of the content * @param string $label label of the instance * @param string $mimeType mimeType of the file * @return string | bool $instanceUri or false on error */ public function createMediaInstance($fileSource, $classUri, $language, $label = null, $mimeType = null) { $clazz = new \core_kernel_classes_Class($classUri); //get the file MD5 $md5 = md5_file($fileSource); //create media instance $label = is_null($label) ? basename($fileSource) : $label; $fileManager = FileManager::getFileManagementModel(); $link = $fileManager->storeFile($fileSource, $label); if ($link !== false) { $mimeType = is_null($mimeType) ? \tao_helpers_File::getMimeType($fileSource) : $mimeType; $instance = $clazz->createInstanceWithProperties(array(RDFS_LABEL => $label, MEDIA_LINK => $link, MEDIA_LANGUAGE => $language, MEDIA_MD5 => $md5, MEDIA_MIME_TYPE => $mimeType, MEDIA_ALT_TEXT => $label)); if (common_ext_ExtensionsManager::singleton()->isEnabled('taoRevision')) { \common_Logger::i('Auto generating initial revision'); RevisionService::commit($instance, __('Initial import')); } return $instance->getUri(); } return false; }
/** * Short description of method evaluate * * @access public * @author Joel Bout, <*****@*****.**> * @param values * @return boolean */ public function evaluate($values) { $returnValue = (bool) false; $mimetype = ''; if (is_array($values)) { if (file_exists($values['uploaded_file'])) { $mimetype = tao_helpers_File::getMimeType($values['uploaded_file']); common_Logger::i($mimetype); } if (!empty($mimetype)) { if (in_array($mimetype, $this->options['mimetype'])) { $returnValue = true; } else { $this->message .= " " . implode(', ', $this->options['mimetype']) . " are expected but {$mimetype} detected"; } } else { common_Logger::i('mimetype empty'); } } return (bool) $returnValue; }
/** * Short description of method evaluate * * @access public * @author Joel Bout, <*****@*****.**> * @param values * @return boolean */ public function evaluate($values) { $returnValue = (bool) false; $mimetype = ''; if (is_array($values)) { if (file_exists($values['uploaded_file'])) { $mimetype = tao_helpers_File::getMimeType($values['uploaded_file']); common_Logger::d($mimetype); } if (!empty($mimetype)) { if (in_array($mimetype, $this->getOption('mimetype'))) { $returnValue = true; } else { $this->setMessage(__('%1$s expected but %2$s detected', implode(', ', $this->getOption('mimetype')), $mimetype)); } } else { common_Logger::i('mimetype empty'); } } return (bool) $returnValue; }
/** * Upload a file to the item directory * * @throws common_exception_MissingParameter */ public function upload() { //as upload may be called multiple times, we remove the session lock as soon as possible try { session_write_close(); if ($this->hasRequestParameter('uri')) { $itemUri = $this->getRequestParameter('uri'); $item = new core_kernel_classes_Resource($itemUri); } if ($this->hasRequestParameter('lang')) { $itemLang = $this->getRequestParameter('lang'); } if (!$this->hasRequestParameter('path')) { throw new common_exception_MissingParameter('path', __METHOD__); } if (!$this->hasRequestParameter('filters')) { throw new common_exception_MissingParameter('filters', __METHOD__); } $filters = explode(',', $this->getRequestParameter('filters')); $resolver = new ItemMediaResolver($item, $itemLang); $asset = $resolver->resolve($this->getRequestParameter('relPath')); $file = tao_helpers_Http::getUploadedFile('content'); $fileTmpName = $file['tmp_name'] . '_' . $file['name']; if (!tao_helpers_File::copy($file['tmp_name'], $fileTmpName)) { throw new common_exception_Error('impossible to copy ' . $file['tmp_name'] . ' to ' . $fileTmpName); } $mime = \tao_helpers_File::getMimeType($fileTmpName); if (in_array($mime, $filters)) { $filedata = $asset->getMediaSource()->add($fileTmpName, $file['name'], $asset->getMediaIdentifier()); } else { throw new \oat\tao\helpers\FileUploadException('The file you tried to upload is not valid'); } $this->returnJson($filedata); return; } catch (\oat\tao\model\accessControl\data\PermissionException $e) { $message = $e->getMessage(); } catch (\oat\tao\helpers\FileUploadException $e) { $message = $e->getMessage(); } catch (common_Exception $e) { common_Logger::w($e->getMessage()); $message = _('Unable to upload file'); } $this->returnJson(array('error' => $message)); }
/** * Sends file content to the client(browser or video/audio player in the browser), it serves images, video/audio files and any other type of file.<br /> * If the client asks for partial contents, then partial contents are served, if not, the whole file is send.<br /> * Works well with big files, without eating up memory. * @author "Martin for OAT <*****@*****.**>" * @param string $filename the file name * @param boolean $contenttype whether to add content type header or not * @param boolean $svgzSupport whether to add content encoding header or not * @throws common_exception_Error */ public static function returnFile($filename, $contenttype = true, $svgzSupport = false) { if (tao_helpers_File::securityCheck($filename, true)) { if (file_exists($filename)) { $mimeType = tao_helpers_File::getMimeType($filename, true); if ($contenttype) { header('Content-Type: ' . $mimeType); } $fp = fopen($filename, 'rb'); if ($fp === false) { header("HTTP/1.0 404 Not Found"); } else { $pathinfo = pathinfo($filename); if (isset($pathinfo['extension']) && $pathinfo['extension'] === 'svgz' && !$svgzSupport) { header('Content-Encoding: gzip'); } // session must be closed because, for example, video files might take a while to be sent to the client // and we need the client to be able to make other calls to the server during that time session_write_close(); $http416RequestRangeNotSatisfiable = 'HTTP/1.1 416 Requested Range Not Satisfiable'; $http206PartialContent = 'HTTP/1.1 206 Partial Content'; $http200OK = 'HTTP/1.1 200 OK'; $filesize = filesize($filename); $offset = 0; $length = $filesize; $useFpassthru = false; $partialContent = false; header('Accept-Ranges: bytes'); if (isset($_SERVER['HTTP_RANGE'])) { $partialContent = true; preg_match('/bytes=(\\d+)-(\\d+)?/', $_SERVER['HTTP_RANGE'], $matches); $offset = intval($matches[1]); if (!isset($matches[2])) { // no end position is given, so we serve the file from the start position to the end $useFpassthru = true; } else { $length = intval($matches[2]) - $offset; } } fseek($fp, $offset); if ($partialContent) { if ($offset < 0 || $offset > $filesize) { header($http416RequestRangeNotSatisfiable); } else { if ($useFpassthru) { // only a starting position is given header($http206PartialContent); header("Content-Length: " . ($filesize - $offset)); header('Content-Range: bytes ' . $offset . '-' . ($filesize - 1) . '/' . $filesize); if (ob_get_level() > 0) { ob_end_flush(); } fpassthru($fp); } else { // we are given a starting position and how many bytes the client asks for $endPosition = $offset + $length; if ($endPosition > $filesize) { header($http416RequestRangeNotSatisfiable); } else { header($http206PartialContent); header("Content-Length: " . $length); header('Content-Range: bytes ' . $offset . '-' . ($offset + $length - 1) . '/' . $filesize); // send 500KB per cycle $bytesPerCycle = 1024 * 1024 * 0.5; $currentPosition = $offset; if (ob_get_level() > 0) { ob_end_flush(); } // because the client might ask for the whole file, we split the serving into little pieces // this is also good in case someone with bad intentions tries to get the whole file many times // and eat up the server memory, we are not loading the whole file into the memory. while (!feof($fp)) { if ($currentPosition + $bytesPerCycle <= $endPosition) { $data = fread($fp, $bytesPerCycle); $currentPosition = $currentPosition + $bytesPerCycle; echo $data; } else { $data = fread($fp, $endPosition - $currentPosition); echo $data; } } } } } } else { // client does not want partial contents so we just serve the whole file header($http200OK); header("Content-Length: " . $filesize); if (ob_get_level() > 0) { ob_end_flush(); } fpassthru($fp); } fclose($fp); } } else { if (class_exists('common_Logger')) { common_Logger::w('File ' . $filename . ' not found'); } header("HTTP/1.0 404 Not Found"); } } else { throw new common_exception_Error('Security exception for path ' . $filename); } }
/** * Get, check and move the file uploaded (described in the posetedFile parameter) * * @param array $postedFile * @param string $folder * @return array $data */ protected function uploadFile($postedFile, $folder) { $returnValue = array(); if (isset($postedFile['tmp_name']) && isset($postedFile['name'])) { $tempFile = $postedFile['tmp_name']; $targetPath = tao_helpers_File::concat(array($this->rootFolder, $folder)); if (tao_helpers_File::securityCheck($targetPath)) { if (!file_exists($targetPath)) { mkdir($targetPath); } $targetFile = tao_helpers_File::concat(array($targetPath, uniqid() . '_' . $postedFile['name'])); if (move_uploaded_file($tempFile, $targetFile)) { $returnValue['uploaded'] = true; $data = $postedFile; $data['type'] = tao_helpers_File::getMimeType($targetFile); $data['uploaded_file'] = $targetFile; $returnValue['name'] = $postedFile['name']; $returnValue['uploaded_file'] = $targetFile; $returnValue['data'] = json_encode($data); } } } return $returnValue; }
/** * Download a resource file content * @param {String} uri Uri of the resource file */ public function downloadFile() { if ($this->hasRequestParameter('uri')) { $uri = tao_helpers_Uri::decode($this->getRequestParameter('uri')); $resource = new core_kernel_classes_Resource($uri); if (core_kernel_versioning_File::isVersionedFile($resource) || core_kernel_file_File::isFile($resource)) { $file = new core_kernel_file_File($uri); $fileName = $file->getOnePropertyValue(new core_kernel_classes_Property(PROPERTY_FILE_FILENAME)); $content = $file->getFileContent(); $size = strlen($content); $mimeType = tao_helpers_File::getMimeType($file->getAbsolutePath(), true); $this->setContentHeader($mimeType); header("Content-Length: {$size}"); header("Content-Disposition: attachment; filename=\"{$fileName}\""); header("Expires: 0"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); print $content; return; } else { throw new Exception('The resource (' . $uri . ') is not a valid file resource'); } } }
/** * Get details about file * * @param $path * @param $relPath * @return array * @throws \tao_models_classes_FileNotFoundException */ public function getFileInfo($path, $relPath) { if (file_exists($path)) { return array('name' => basename($path), 'uri' => $relPath, 'mime' => \tao_helpers_File::getMimeType($path), 'filePath' => $path, 'size' => filesize($path)); } throw new \tao_models_classes_FileNotFoundException($path); }
/** * * @param string $initialVersion * @return string $versionUpdatedTo */ public function update($initialVersion) { $currentVersion = $initialVersion; //migrate from 0.1 to 0.1.1 if ($currentVersion == '0.1') { // mediaSources set in 0.2 $currentVersion = '0.1.1'; } if ($currentVersion == '0.1.1') { FileManager::setFileManagementModel(new SimpleFileManagement()); // mediaSources unset in 0.2 $currentVersion = '0.1.2'; } if ($currentVersion == '0.1.2') { //add alt text to media manager $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'alt_text.rdf'; $adapter = new \tao_helpers_data_GenerisAdapterRdf(); if ($adapter->import($file)) { $currentVersion = '0.1.3'; } else { \common_Logger::w('Import failed for ' . $file); } } if ($currentVersion == '0.1.3') { OntologyUpdater::correctModelId(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'alt_text.rdf'); $currentVersion = '0.1.4'; } if ($currentVersion == '0.1.4') { //modify config files due to the new interfaces relation $tao = \common_ext_ExtensionsManager::singleton()->getExtensionById('tao'); $tao->unsetConfig('mediaManagementSources'); $tao->unsetConfig('mediaBrowserSources'); TaoMediaService::singleton()->addMediaSource(new MediaSource()); //modify links in item content $service = \taoItems_models_classes_ItemsService::singleton(); $items = $service->getAllByModel('http://www.tao.lu/Ontologies/TAOItem.rdf#QTI'); foreach ($items as $item) { $itemContent = $service->getItemContent($item); $itemContent = preg_replace_callback('/src="mediamanager\\/([^"]+)"/', function ($matches) { $mediaClass = MediaService::singleton()->getRootClass(); $medias = $mediaClass->searchInstances(array(MEDIA_LINK => $matches[1]), array('recursive' => true)); $media = array_pop($medias); $uri = ''; if (!is_null($media) && $media->exists()) { $uri = \tao_helpers_Uri::encode($media->getUri()); } return 'src="taomedia://mediamanager/' . $uri . '"'; }, $itemContent); $itemContent = preg_replace_callback('/src="local\\/([^"]+)"/', function ($matches) { return 'src="' . $matches[1] . '"'; }, $itemContent); $service->setItemContent($item, $itemContent); } $currentVersion = '0.2.0'; } if ($currentVersion === '0.2.0') { $accessService = \funcAcl_models_classes_AccessService::singleton(); //revoke access right to back office $backOffice = new \core_kernel_classes_Resource('http://www.tao.lu/Ontologies/TAO.rdf#BackOfficeRole'); $accessService->revokeExtensionAccess($backOffice, 'taoMediaManager'); //grant access right to media manager $mediaManager = new \core_kernel_classes_Resource('http://www.tao.lu/Ontologies/TAOMedia.rdf#MediaManagerRole'); $accessService->grantExtensionAccess($mediaManager, 'taoMediaManager'); $currentVersion = '0.2.1'; } if ($currentVersion === '0.2.1') { //include mediamanager into globalmanager $mediaManager = new \core_kernel_classes_Resource('http://www.tao.lu/Ontologies/TAOMedia.rdf#MediaManagerRole'); $globalManager = new \core_kernel_Classes_Resource('http://www.tao.lu/Ontologies/TAO.rdf#GlobalManagerRole'); \tao_models_classes_RoleService::singleton()->includeRole($globalManager, $mediaManager); $currentVersion = '0.2.2'; } if ($currentVersion === '0.2.2') { //copy file from /media to data/taoMediaManager/media and delete /media $dataPath = FILES_PATH . 'taoMediaManager' . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR; $dir = dirname(dirname(__DIR__)) . '/media'; if (file_exists($dir)) { if (\tao_helpers_File::copy($dir, $dataPath)) { $it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS); $files = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST); foreach ($files as $file) { if ($file->isDir()) { rmdir($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($dir); $currentVersion = '0.2.3'; } } else { $currentVersion = '0.2.3'; } } if ($currentVersion === '0.2.3') { $accessService = \funcAcl_models_classes_AccessService::singleton(); //grant access to item author $itemAuthor = new \core_kernel_classes_Resource('http://www.tao.lu/Ontologies/TAOItem.rdf#ItemAuthor'); $accessService->grantExtensionAccess($itemAuthor, 'taoMediaManager'); $currentVersion = '0.2.4'; } if ($currentVersion === '0.2.4') { $mediaClass = MediaService::singleton()->getRootClass(); $fileManager = FileManager::getFileManagementModel(); foreach ($mediaClass->getInstances(true) as $media) { $fileLink = $media->getUniquePropertyValue(new \core_kernel_classes_Property(MEDIA_LINK)); $fileLink = $fileLink instanceof \core_kernel_classes_Resource ? $fileLink->getUri() : (string) $fileLink; $filePath = $fileManager->retrieveFile($fileLink); $mimeType = \tao_helpers_File::getMimeType($filePath); $mimeType = $mimeType === 'application/xhtml+xml' ? 'application/qti+xml' : $mimeType; $media->setPropertyValue(new \core_kernel_classes_Property(MEDIA_MIME_TYPE), $mimeType); } $currentVersion = '0.2.5'; } if ($currentVersion === '0.2.5') { $fileManager = FileManager::getFileManagementModel(); $iterator = new \core_kernel_classes_ResourceIterator(array(MediaService::singleton()->getRootClass())); foreach ($iterator as $media) { $fileLink = $media->getUniquePropertyValue(new \core_kernel_classes_Property(MEDIA_LINK)); $fileLink = $fileLink instanceof \core_kernel_classes_Resource ? $fileLink->getUri() : (string) $fileLink; $filePath = $fileManager->retrieveFile($fileLink); try { SharedStimulusImporter::isValidSharedStimulus($filePath); $media->editPropertyValues(new \core_kernel_classes_Property(MEDIA_MIME_TYPE), 'application/qti+xml'); } catch (\Exception $e) { $mimeType = \tao_helpers_File::getMimeType($filePath); $media->editPropertyValues(new \core_kernel_classes_Property(MEDIA_MIME_TYPE), $mimeType); } } $currentVersion = '0.3.0'; } $this->skip('0.3.0', '0.5.1'); }
/** * Reconstruct PortableElement XML from PortableElementStorage data * * @param DOMDocument $dom * @param $nodeName * @param $typeIdentifierAttributeName * @param $ns * @param $portableElementsToExport * @param $portableAssetsToExport * @throws \common_Exception */ private function exportPortableAssets(DOMDocument $dom, $nodeName, $typeIdentifierAttributeName, $ns, $portableElementsToExport, $portableAssetsToExport) { $xpath = new DOMXPath($dom); // Get all portable element from qti.xml $portableElementNodes = $dom->getElementsByTagName($nodeName); for ($i = 0; $i < $portableElementNodes->length; $i++) { /** @var \DOMElement $currentPortableNode */ $currentPortableNode = $portableElementNodes->item($i); $identifier = $currentPortableNode->getAttribute($typeIdentifierAttributeName); if (!isset($portableElementsToExport[$identifier])) { throw new \common_Exception('Unable to find loaded portable element.'); } /** @var PortableElementObject $portableElement */ $portableElement = $portableElementsToExport[$identifier]; // Add hook and version as attributes if ($portableElement->hasRuntimeKey('hook')) { $currentPortableNode->setAttribute('hook', preg_replace('/^(.\\/)(.*)/', $portableElement->getTypeIdentifier() . "/\$2", $portableElement->getRuntimeKey('hook'))); } $currentPortableNode->setAttribute('version', $portableElement->getVersion()); // If asset files list is empty for current identifier skip if (!isset($portableAssetsToExport) || !isset($portableAssetsToExport[$portableElement->getTypeIdentifier()])) { continue; } /** @var \DOMElement $resourcesNode */ $resourcesNode = $currentPortableNode->getElementsByTagName('resources')->item(0); // Portable libraries $librariesNode = $dom->createElement($ns . ':libraries'); foreach ($portableElement->getRuntimeKey('libraries') as $library) { $libraryNode = $dom->createElement($ns . ':lib'); //the exported lib id must be adapted from a href mode to an amd name mode $libraryNode->setAttribute('id', preg_replace('/\\.js$/', '', $portableAssetsToExport[$portableElement->getTypeIdentifier()][$library])); $librariesNode->appendChild($libraryNode); } $oldLibrariesNode = $xpath->query('.//' . $ns . ':libraries', $resourcesNode); if ($oldLibrariesNode->length > 0) { $resourcesNode->removeChild($oldLibrariesNode->item(0)); } if ($librariesNode->hasChildNodes()) { $resourcesNode->appendChild($librariesNode); } // Portable stylesheets $stylesheetsNode = $dom->createElement($ns . ':stylesheets'); foreach ($portableElement->getRuntimeKey('stylesheets') as $stylesheet) { $stylesheetNode = $dom->createElement($ns . ':link'); $stylesheetNode->setAttribute('href', $portableAssetsToExport[$portableElement->getTypeIdentifier()][$stylesheet]); $stylesheetNode->setAttribute('type', 'text/css'); $info = pathinfo($stylesheet); $stylesheetNode->setAttribute('title', basename($stylesheet, '.' . $info['extension'])); $stylesheetsNode->appendChild($stylesheetNode); } $oldStylesheetsNode = $xpath->query('.//' . $ns . ':stylesheets', $resourcesNode); if ($oldStylesheetsNode->length > 0) { $resourcesNode->removeChild($oldStylesheetsNode->item(0)); } if ($stylesheetsNode->hasChildNodes()) { $resourcesNode->appendChild($stylesheetsNode); } // Portable mediaFiles $mediaFilesNode = $dom->createElement($ns . ':mediaFiles'); foreach ($portableElement->getRuntimeKey('mediaFiles') as $mediaFile) { $mediaFileNode = $dom->createElement($ns . ':file'); $mediaFileNode->setAttribute('src', $portableAssetsToExport[$portableElement->getTypeIdentifier()][$mediaFile]); $mediaFileNode->setAttribute('type', \tao_helpers_File::getMimeType($portableAssetsToExport[$portableElement->getTypeIdentifier()][$mediaFile])); $mediaFilesNode->appendChild($mediaFileNode); } $oldMediaFilesNode = $xpath->query('.//' . $ns . ':mediaFiles', $resourcesNode); if ($oldMediaFilesNode->length > 0) { $resourcesNode->removeChild($oldMediaFilesNode->item(0)); } if ($mediaFilesNode->hasChildNodes()) { $resourcesNode->appendChild($mediaFilesNode); } } unset($xpath); }
/** * Load an item external media * It prevents to get it direclty in the data folder that access is denied * @requiresRight uri READ * @deprecated */ public function getMediaResource() { if ($this->hasRequestParameter('path')) { $item = null; if ($this->hasRequestParameter('uri') && $this->hasRequestParameter('classUri')) { $item = $this->getCurrentInstance(); } else { if ($this->hasSessionAttribute('uri') && $this->hasSessionAttribute('classUri')) { $classUri = tao_helpers_Uri::decode($this->getSessionAttribute('classUri')); if ($this->getClassService()->isItemClass(new core_kernel_classes_Class($classUri))) { $item = new core_kernel_classes_Resource(tao_helpers_Uri::decode($this->getSessionAttribute('uri'))); } } } if (!is_null($item)) { $path = urldecode($this->getRequestParameter('path')); if (!tao_helpers_File::securityCheck($path)) { throw new Exception('Unauthorized path ' . $path); } if (preg_match('/(.)+\\/filemanager\\/views\\/data\\//i', $path)) { // check if the file is linked to the file manager $resource = preg_replace('/(.)+\\/filemanager\\/views\\/data\\//i', ROOT_PATH . '/filemanager/views/data/', $path); } else { // look in the item's dedicated folder. it should be a resource // that is local to the item, not it the file manager // $folder is the item's dedicated folder path, $path the path to the resource, relative to $folder $folder = $this->getClassService()->getItemFolder($item); $resource = tao_helpers_File::concat(array($folder, $path)); } if (file_exists($resource)) { $mimeType = tao_helpers_File::getMimeType($resource); //allow only images, video, flash (and css?) if (preg_match("/^(image|video|audio|application\\/x-shockwave-flash)/", $mimeType)) { header("Content-Type: {$mimeType}; charset utf-8"); print trim(file_get_contents($resource)); } } } } }
public function addItems($directory) { $qtiManifestParser = new \taoQtiTest_models_classes_ManifestParser($directory . 'imsmanifest.xml'); $itemTypes = array('imsqti_item_xmlv2p1', 'imsqti_apipitem_xmlv2p2', 'imsqti_apipitem_xmlv2p1'); $items = $qtiManifestParser->getResources(); $todo = array(); foreach ($items as $res) { if (in_array($res->getType(), $itemTypes)) { $this->addXml($directory . $res->getFile()); } foreach ($res->getAuxiliaryFiles() as $file) { $mime = \tao_helpers_File::getMimeType($directory . $file); $prefix = substr($mime, 0, strpos($mime, '/')); if ($prefix == 'image') { $this->replaceImage($directory . $file); } } } }
/** * Copy the test resources (e.g. images) that will be availabe at delivery time * in the public compilation directory. * */ protected function copyPublicResources() { $compiledDocDir = $this->getPrivateDirectory()->getPath(); $publicCompiledDocDir = $this->getPublicDirectory()->getPath(); foreach (tao_helpers_File::scandir($compiledDocDir, array('recursive' => true, 'only' => tao_helpers_File::$FILE, 'absolute' => true)) as $file) { $mime = tao_helpers_File::getMimeType($file, true); $pathinfo = pathinfo($file); // Exclude CSS files because already copied when dealing with rubric blocks. if (in_array($mime, self::getPublicMimeTypes()) === true && $pathinfo['extension'] !== 'php') { $file = str_replace($compiledDocDir, '', $file); common_Logger::t("Copying public resource '{$file}'..."); taoQtiTest_helpers_Utils::storeQtiResource($publicCompiledDocDir, $file, $compiledDocDir); } } }
die; } $config = (include $configPath); $compiledPath = $config['options']['path']; $secretPassphrase = $config['options']['secret']; $ttl = $config['options']['ttl']; $correctToken = md5($timestamp . $subPath . $secretPassphrase); if (time() - $timestamp > $ttl || $token != $correctToken) { header('HTTP/1.0 403 Forbidden'); die; } $path = array(); foreach (explode('/', $subPath . $file) as $ele) { $path[] = rawurldecode($ele); } $filename = $compiledPath . implode(DIRECTORY_SEPARATOR, $path); if (strpos($filename, '?')) { // A query string is provided with the file to be retrieved - clean up! $parts = explode('?', $filename); $filename = $parts[0]; } if (tao_helpers_File::securityCheck($filename, true)) { header('Content-Type: ' . tao_helpers_File::getMimeType($filename, true)); $fp = fopen($filename, 'rb'); if ($fp === false) { header("HTTP/1.0 404 Not Found"); } else { fpassthru($fp); } } exit;