public function createTaggableObject(array $taggableObjectData) { if (!isset($taggableObjectData[self::OBJECTDATA_KEY_PATH])) { throw new EyeInvalidArgumentException('Given $taggableObjectData is not valid (missing "' . self::OBJECTDATA_KEY_PATH . '" key).'); } return FSI::getFile($taggableObjectData[self::OBJECTDATA_KEY_PATH]); }
public static function createLink($params) { $structure = array(); $structure['url'] = $params[0]; $structure['width'] = $params[1]; $structure['height'] = $params[2]; $structure['icon'] = str_replace('eyeos/extern/', 'index.php?extern=', $params[5]); $structure['openInNewWindow'] = $params[6]; $structure['type'] = 'web'; $linkName = utf8_basename($params[3]); $info = pathinfo($linkName); if (!isset($info['extension']) || $info['extension'] != 'lnk') { $linkName .= '.lnk'; } $path = $params[4]; $text = json_encode($structure); $linkName = str_replace('?', '_', $linkName); $linkName = str_replace('#', '_', $linkName); $newFile = FSI::getFile($path . '/' . $linkName); $newFile->createNewFile(); $newFile->putContents($text); $currentUser = ProcManager::getInstance()->getCurrentProcess()->getLoginContext()->getEyeosUser(); $settings = MetaManager::getInstance()->retrieveMeta($currentUser); //TODO: better message? $message = new ClientBusMessage('file', 'uploadComplete', self::getFileInfo($newFile, $settings)); ClientMessageBusController::getInstance()->queueMessage($message); }
public static function getLinkInformation($params) { $link = $params[0]; $file = FSI::getFile($link); $content = json_decode($file->getContents()); return $content; }
public static function Convert($from, $format = '') { //first, get the original file $myFile = FSI::getFile($from); $myFile->checkReadPermission(); if ($myFile instanceof EyeLocalFile) { $fileNameOriginal = $from; } else { $myRealFile = $myFile->getRealFile(); $fileNameOriginal = AdvancedPathLib::getPhpLocalHackPath($myRealFile->getPath()); } $hash = md5(md5_file($fileNameOriginal) . '/' . $format); $to = 'home:///'; //then, check the destination file $myFileDest = FSI::getFile($to); $myFileDest->checkWritePermission(); $myRealFile = $myFileDest->getRealFile(); $fileNameDestination = AdvancedPathLib::getPhpLocalHackPath($myRealFile->getPath()); $conversionCache = $fileNameDestination . '/.office/' . $hash . '/' . $hash; if (!file_exists($fileNameDestination . '/.office/')) { mkdir($fileNameDestination . '/.office/'); } if (file_exists($conversionCache)) { return $conversionCache; } else { if (!is_dir($fileNameDestination . '/.office/' . $hash)) { mkdir($fileNameDestination . '/.office/' . $hash); } $fileNameDestination = $conversionCache; } $fileNameReturn = $fileNameDestination; /* * If isset format do conversion, otherwise just copy original file to */ if ($format != '') { $fileNameOriginal = escapeshellarg($fileNameOriginal); $fileNameDestination = escapeshellarg($fileNameDestination); $format = escapeshellarg($format); //some legacy applications do not use the filter writer_pdf_Export, just pdf if ($format == 'pdf') { $format = 'writer_pdf_Export'; } if (!@fsockopen('127.0.0.1', '2002', $errno, $errstr, 3)) { shell_exec('nohup soffice "-accept=socket,host=localhost,port=2002;urp;" >/dev/null 2>/dev/null &'); //shell_exec with soffice forked to avoid soffice to be killed //at the end of the php execution, cannot be synchronous. sleep(4); } $cmd = 'python ' . EYE_ROOT . '/' . SYSTEM_DIR . '/' . FRAMEWORKS_DIR . '/Converter/ooo2any.py --extension eyeos --format ' . $format; $cmd .= ' --destination ' . $fileNameDestination . ' ' . $fileNameOriginal; shell_exec('LANG=en_US.utf-8;' . $cmd); } else { // Just copy file to new destination copy($fileNameOriginal, $fileNameDestination); } return $fileNameReturn; }
public function createFile(IUrlFile $file) { try { $myFile = FSI::getFile($file->getPath()); $myFile->checkReadPermission(); $this->getProvider()->createFile($file); return $file; } catch (Exception $e) { self::$Logger->error('Error while creating UrlFile: ' . $file); throw $e; } }
public function putContents($path, $content) { try { $node = FSI::getFile($path); $bytes = $node->getRealFile()->putContents($content); if ($bytes > 0) { return true; } } catch (Exception $e) { } return false; }
public static function __run(AppExecutionContext $context, MMapResponse $response) { $currentUser = $context->getProcess()->getLoginContext()->getEyeosUser(); $groups = UMManager::getInstance()->getAllGroupsByPrincipal($currentUser); $isAdmin = 0; if ($currentUser->getPrimaryGroupId() == 'eyeID_EyeosGroup_root' || $currentUser->getPrimaryGroupId() == 'eyeID_EyeosGroup_admin') { $isAdmin = 1; } else { foreach ($groups as $group) { if ($group->getId() == 'eyeID_EyeosGroup_admin') { $isAdmin = 1; } } } $context->getArgs()->offsetSet(0, $isAdmin); //get the applications $myApplicationsManager = new EyeosApplicationsManager(); $applications = $myApplicationsManager->getAllApplications(); $return = array(); foreach ($applications as $appDesc) { $appMeta = $appDesc->getMeta(); $systemParameters = $appMeta->get('eyeos.application.systemParameters'); $currentApplicationGroup = 'eyeID_EyeosGroup_' . $systemParameters['group']; $currentUserGroup = ProcManager::getInstance()->getCurrentProcess()->getLoginContext()->getEyeosUser()->getPrimaryGroupId(); if ($currentUserGroup == 'eyeID_EyeosGroup_users' && $currentApplicationGroup == 'eyeID_EyeosGroup_users' || $currentUserGroup != 'eyeID_EyeosGroup_users') { $sysParams = $appMeta->get('eyeos.application.systemParameters'); $imagePath = $appMeta->get('eyeos.application.iconUrl'); $imageIsValid = true; $imagePath = str_replace('48x48', '22x22', $imagePath); $imagePath = str_replace('64x64', '22x22', $imagePath); try { $file = FSI::getFile($imagePath); } catch (Exception $e) { $imageIsValid = false; } if ($imageIsValid && !$file->isReadable()) { $imageIsValid = false; } if (!$imageIsValid) { $imagePath = 'sys:///extern/images/22x22/apps/preferences-desktop-default-applications.png'; } $return[] = array('name' => $appDesc->getName(), 'displayName' => $appMeta->get('eyeos.application.name') !== null ? $appMeta->get('eyeos.application.name') : $appDesc->getName(), 'app' => $appDesc->getName(), 'shortDescription' => $appMeta->get('eyeos.application.description'), 'image' => FSI::toExternalUrl($imagePath), 'favorite' => $myApplicationsManager->isApplicationFavorite($appDesc) ? 1 : 0, 'lists' => $appMeta->get('eyeos.application.category'), 'listable' => $sysParams['listable'] == 'true' ? 1 : 0); } } $context->getArgs()->offsetSet(1, $return); }
/** * @param string $path * @param SimpleXMLElement $xmlConf * @return AbstractFile */ public static function getRealFile($path, $xmlParams = null, $params = null) { $moutpointDescriptors = MountpointsManager::getInstance()->getMountpointDescriptorsList($path); $mountedPath = null; $realPath = AdvancedPathLib::getCanonicalURL($path); foreach ($moutpointDescriptors as $moutpointDescriptor) { $mountpointPath = $moutpointDescriptor->getMountpointPath(); if (utf8_strpos($realPath, $mountpointPath) === 0) { $mountedPath = $moutpointDescriptor->getTargetPath(); $mountedPath .= '/' . utf8_substr($realPath, utf8_strlen($mountpointPath)); } } if ($mountedPath !== null) { return FSI::getFile($mountedPath, $params); } return null; }
public function processRequest(MMapRequest $request, MMapResponse $response) { $urlName = $request->getGET('download'); if (is_array($urlName)) { exit; } $urlShare = new UrlShare(); $urlShare->setName($urlName); $urlShareController = UrlShareController::getInstance(); $urlShare = current($urlShareController->searchUrl($urlShare)); if ($urlShare) { if ($urlShare->getExpirationDate() < time()) { self::renderErrorMessage($response, 'Url Expired'); return; } $file = new UrlFile(); $file->setId($urlShare->getFileId()); $urlShareController->readFile($file); if ($file) { $fileName = basename($file->getPath()); $currentFile = FSI::getFile($file->getPath()); $size = $currentFile->getSize(); $unim = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); $c = 0; while ($size >= 1024) { $c++; $size = $size / 1024; } $size = number_format($size, $c ? 2 : 0, ',', '.') . ' ' . $unim[$c]; if ($request->issetGET('wrongPassword')) { $wrongPassword = $request->getGET('wrongPassword'); } else { $wrongPassword = 0; } Kernel::exitSystemMode(); self::renderFoundFile($fileName, $size, $urlName, $response, $urlShare->getPassword(), $wrongPassword); } else { self::renderErrorMessage($response, 'File not available'); } } else { self::renderErrorMessage($response, 'File not available'); } }
public static function getFile($params) { $hash = utf8_basename($params[0]); $num = utf8_basename(intval($params[1])); $thubnail = $params[2]; $to = 'home:///'; //then, check the destination file $myFileDest = FSI::getFile($to); $myFileDest->checkWritePermission(); $myRealFile = $myFileDest->getRealFile(); $fileNameDestination = AdvancedPathLib::getPhpLocalHackPath($myRealFile->getPath()); header('Content-Type: image/jpeg'); if (!$thubnail) { readfile($fileNameDestination . '/.office/' . $hash . '/' . $hash . '-' . $num . '.jpg'); } else { session_write_close(); require_once 'system/Frameworks/Applications/Executables/EyeosModules/FileSystemExecModule.php'; FileSystemExecModule::getScaledImage(array('maxWidth' => '150', 'path' => $fileNameDestination . '/.office/' . $hash . '/' . $hash . '-' . $num . '.jpg')); } exit; }
public static function download($path) { $myFile = FSI::getFile($path); $myFile->checkReadPermission(); $len = $myFile->getSize(); $filename = $myFile->getName(); $mimetype = $myFile->getMimeType(); $filename = str_replace("\n", "", $filename); $filename = str_replace("\r", "", $filename); header('Content-Length: ' . $len); header('Content-Type: ' . $mimetype); header('Accept-Ranges: bytes'); header('X-Pad: avoid browser bug'); header('Content-Disposition: attachment; filename="' . $filename . '"'); $currentProc = ProcManager::getInstance()->getCurrentProcess(); ProcManager::getInstance()->kill($currentProc); $myRealFile = $myFile->getRealFile(); $fileNameDestination = AdvancedPathLib::getPhpLocalHackPath($myRealFile->getPath()); session_write_close(); readFile($fileNameDestination); exit; }
private function cleanCloud($cloud, $user) { $oauthManager = new OAuthManager(); $apiManager = new ApiManager(); $token = new Token(); $token->setCloudspaceName($cloud); $token->setUserID($user->getId()); $path = ''; if ($oauthManager->deleteToken($token)) { if ($apiManager->deleteMetadataUser($user->getId(), $cloud)) { unset($_SESSION['request_token_' . $cloud . '_v2']); unset($_SESSION['access_token_' . $cloud . '_v2']); $pathOrg = "home://~" . $user->getName() . "/Cloudspaces/" . $cloud; $pathDest = "home://~" . $user->getName() . "/Cloudspaces/." . $cloud; $folderToRename1 = FSI::getFile($pathOrg); $folderToRename2 = FSI::getFile($pathDest); shell_exec('mv ' . AdvancedPathLib::getPhpLocalHackPath($folderToRename1->getRealFile()->getAbsolutePath()) . ' ' . AdvancedPathLib::getPhpLocalHackPath($folderToRename2->getRealFile()->getAbsolutePath())); $path = AdvancedPathLib::getPhpLocalHackPath($folderToRename2->getRealFile()->getAbsolutePath()); } } return $path; }
/** * Modify the path of the file to the output folder * @param string $fileName original path of the file */ private function CreateOutputPath($fileName) { if (!isset($fileName) || !is_string($fileName)) { throw new EyeInvalidArgumentException('Missing or invalid param $fileName'); } //Home of the user $to = 'home:///'; //then, check the destination file $myFileDest = FSI::getFile($to); $myFileDest->checkWritePermission(); $myRealFile = $myFileDest->getRealFile(); $fileNameDestination = AdvancedPathLib::getPhpLocalHackPath($myRealFile->getPath()); if (!file_exists($fileNameDestination . '/.office/')) { mkdir($fileNameDestination . '/.office/'); } if (!file_exists($fileNameDestination . '/.office/.media/')) { mkdir($fileNameDestination . '/.office/.media/'); } $this->outputPath = $fileNameDestination . '/.office/.media/'; }
/** * TODO: Will need to be moved/merged to/with FileSystemExecModule */ public static function rename($params) { $currentUser = ProcManager::getInstance()->getCurrentProcess()->getLoginContext()->getEyeosUser(); $settings = MetaManager::getInstance()->retrieveMeta($currentUser); $fileToRename = FSI::getFile($params[0]); $i = 1; $nameForCheck = $params[2]; $renamed = FSI::getFile($params[1] . '/' . $params[2]); while ($renamed->exists()) { $name = explode(".", $params[2]); $extension = (string) $name[count($name) - 1]; $futureName = array($name[0], $i); $nameForCheck = implode(' ', $futureName); if (!$fileToRename->isDirectory()) { $nameForCheck .= '.' . $extension; } $i++; $renamed = FSI::getFile($params[1] . '/' . $nameForCheck); } $fileToRename->renameTo($nameForCheck); self::updateUrlShare($params[0], $renamed->getPath()); $return = self::getFileInfo($fileToRename, $settings); return $return; }
/** * @param array( * 'filePath' => filePath, * ['userId' => userId], * ['userName' => userName] * ) */ public function setAvatarPicture($params) { if (!isset($params['filePath']) || !is_string($params['filePath'])) { throw new EyeInvalidArgumentException('Missing or invalid $params[\'filePath\'].'); } if (isset($params['userId']) && is_string($params['userId'])) { $user = UMManager::getInstance()->getUserById($params['userId']); } else { if (isset($params['userName']) && is_string($params['userName'])) { $user = UMManager::getInstance()->getUserByName($params['userName']); } else { $user = ProcManager::getInstance()->getCurrentProcess()->getLoginContext()->getEyeosUser(); } } $file = FSI::getFile($params['filePath']); if (!$file->isReadable()) { throw new EyeIOException('Unable to read file at ' . $params['filePath'] . '.'); } $extension = $file->getExtension() ? '.' . $file->getExtension() : ''; $destFile = FSI::getFile('user-conf://~' . $user->getName() . '/public/avatarpic' . $extension); $file->copyTo($destFile); // Update settings (metadata) $settings = MetaManager::getInstance()->retrieveMeta($user); $settings->set('eyeos.user.picture.url', $destFile->getAbsolutePath()); MetaManager::getInstance()->storeMeta($user, $settings); }
/** * Get the first image of a video * @param Array $params = ( * path => string Path of the file * ) * @return fill the response with the image */ public static function getVideoPoster($params) { if ($params === null || !is_array($params)) { throw new EyeInvalidArgumentException('Missing or invalid $params'); } if (!isset($params['path']) || !is_string($params['path'])) { throw new EyeInvalidArgumentException('Missing or invalid $params[\'path\']'); } $myFile = FSI::getFile($params['path']); if (method_exists($myFile, 'getRealFile')) { $fileName = AdvancedPathLib::getPhpLocalHackPath($myFile->getRealFile()->getAbsolutePath()); } else { $fileName = $params['path']; } Logger::getLogger('Mobile - files.php')->debug('$fileName: ' . $fileName); try { $MediaConverter = new MediaConverter(); $fileName = $MediaConverter->Convert($fileName, 'JPG'); } catch (Exception $e) { Logger::getLogger('Mobile - files.php')->debug('$MediaConverter error: ' . $e); } $size = filesize($fileName); $data = file_get_contents($fileName); $response = MMapManager::getCurrentResponse(); $response->getHeaders()->append('Content-Type: image/jpeg'); $response->getHeaders()->append('Content-Length: ' . $size); $response->getHeaders()->append('Accept-Ranges: bytes'); // $response->getHeaders()->append('Expires: 0'); // $response->getHeaders()->append('Pragma: public'); // $response->getHeaders()->append('Content-Disposition: inline'); // $response->getHeaders()->append('Content-Transfer-Encoding: binary'); // $response->getHeaders()->append('Cache-Control: must-revalidate, post-check=0, pre-check=0'); // $response->getHeaders()->append('X-Pad: avoid browser bug'); $response->setBody($data); }
public static function submitFile($path) { try { if (!isset($_FILES['Filedata'])) { echo '<div style="font-size:20px;font-family:Helvetica, Arial, Verdana, Sans, FreeSans;margin-top:80px;margin-right:15px;"><center> <img style="position:relative;top:15px"src="index.php?extern=/images/48x48/actions/dialog-close.png" />Error uploading files</center>'; exit; } $Logger = Logger::getLogger('application.upload'); foreach ($_FILES['Filedata']['name'] as $k => $v) { if (!empty($v)) { $filename = $_FILES['Filedata']['name'][$k]; if (!isset($_POST['UPLOAD_IDENTIFIER'])) { $filename = utf8_encode($filename); } $tmpPath = $_FILES['Filedata']['tmp_name'][$k]; $Logger->debug("Filename: " . $filename); if (!is_uploaded_file($tmpPath)) { throw new EyeFileNotFoundException('Uploaded file not found at "' . $tmpPath . '".'); } $request = MMapManager::getCurrentRequest(); $destPath = $path; $filename = str_replace('?', '_', $filename); $filename = str_replace('#', '_', $filename); $tmp = pathinfo($filename); if (isset($tmp['extension']) && "lnk" == $tmp['extension']) { throw new EyeFileNotFoundException('This file cannot be uploaded (file type banned)'); } /* if ( '?' == $filename{0} ) { $filename{0} = "_"; } */ $destFile = FSI::getFile($destPath . '/' . $filename); //The uploaded file is necessarily on the local filesystem and we want to avoid any //permission check through EyeLocalFile, so we use LocalFile directly $tmpFile = new LocalFile($tmpPath); $num = 1; $extension = AdvancedPathLib::pathinfo($filename, PATHINFO_EXTENSION); $filename = AdvancedPathLib::pathinfo($filename, PATHINFO_FILENAME); $Logger->debug("CLASS: " . get_class($destFile)); $Logger->debug("Exists: " . $destFile->exists()); //exit(); while ($destFile->exists()) { $newBasename = $filename . ' (' . $num++ . ')' . ($extension ? '.' . $extension : ''); $destFile = FSI::getFile($destPath . '/' . $newBasename); } $destFile->checkWritePermission(); $tmpFile->moveTo($destFile); $currentUser = ProcManager::getInstance()->getCurrentProcess()->getLoginContext()->getEyeosUser(); $settings = MetaManager::getInstance()->retrieveMeta($currentUser); $message = new ClientBusMessage('file', 'uploadComplete', self::getFileInfo($destFile, $settings)); ClientMessageBusController::getInstance()->queueMessage($message); $event = new FileEvent($destFile); $destFile->fireEvent('fileWritten', $event); } } register_shutdown_function('endRequestUpload'); } catch (EyeException $e) { echo '<div style="font-size:20px;font-family:Helvetica, Arial, Verdana, Sans, FreeSans;margin-top:80px;margin-right:15px;"><center> <img style="position:relative;top:15px"src="index.php?extern=/images/48x48/actions/dialog-close.png" />Error uploading files: ' . $e->getMessage() . '</center>'; exit; } }
public static function __run(AppExecutionContext $context, MMapResponse $response) { $args = $context->getArgs(); if (!isset($args[0]) || !is_string($args[0])) { throw new EyeMissingArgumentException('Missing filename to open.'); } try { $file = FSI::getFile($args[0]); } catch (Exception $e) { throw new EyeInvalidArgumentException('args[0] must be a valid path to a file.', 0, $e); } $appName = false; if ($file->isDirectory()) { $appName = 'files'; } else { $extension = utf8_strtolower($file->getExtension()); // TODO: Currently hard-coded here but in the future associations will be read from a DB. // We must have general entries, common to all the users of the system, that will be used // as default, and then user-customized entries with a higher priority on the general ones. switch ($extension) { // // VIEWER // case 'jpg': case 'gif': case 'jpeg': case 'png': case 'htm': case 'html': case 'flv': case 'm4a': case 'mp3': $appName = 'viewer'; break; // // EDITOR // // // EDITOR // case 'txt': case 'xml': case 'ini': case 'js': case 'sql': case 'log': $appName = 'femto'; break; } } // Association found: execute matching application if ($appName) { $myProcess = ProcManager::getInstance()->getCurrentProcess(); // prepare context and execute application $currentAppDesc = new EyeosApplicationDescriptor($appName); $appContext = new AppExecutionContext(); $appContext->setParentProcess($myProcess); $appContext->setApplicationDescriptor($currentAppDesc); $appContext->setArgs(clone $args); MMapGetApp::getInstance()->processRequest(MMapManager::getCurrentRequest(), $response, $appContext); // Kill our process $context->setExecuteJavascript(false); ProcManager::getInstance()->kill($myProcess); return; } // Otherwise, show the OpenWith dialog }
public function getAvatarPicture($params) { $userId = $params[0]; $user = UMManager::getInstance()->getUserById($params['userId']); $settings = MetaManager::getInstance()->retrieveMeta($user); $file = null; if ($settings->get('eyeos.user.picture.url') !== null) { $file = FSI::getFile($settings->get('eyeos.user.picture.url')); } if ($file === null || !$file->isReadable()) { $file = FSI::getFile('sys:///extern/images/empty_profile.png'); } $response = MMapManager::getCurrentResponse(); $bodyrenderer = new FileReaderBodyRenderer($file->getInputStream()); // Set headers $response->getHeaders()->append('Content-Type: ' . mime_content_type($file->getName())); $response->getHeaders()->append('Content-Length: ' . $file->getSize()); $response->getHeaders()->append('Accept-Ranges: bytes'); $response->getHeaders()->append('X-Pad: avoid browser bug'); $response->setBodyRenderer($bodyrenderer); }
public function testRenameTo() { /**** existing home file ****/ $this->assertFalse(is_file($this->fixture_metafile1_path)); $meta = new VirtualFileMetaData(); $meta->set('myDummyMetaValue', 'someValueHere'); $this->fixture_file1->setMeta($meta); $this->assertTrue(is_file($this->fixture_metafile1_path)); $this->assertTrue(is_file($this->fixture_file1_path)); $targetPath = USERS_PATH . '/john/' . USERS_FILES_DIR . '/myHomeFile_renamed.ext'; $this->assertFalse(is_file($targetPath)); $this->assertEquals('someValueHere', $this->fixture_file1->getMeta()->get('myDummyMetaValue')); $originalContent = file_get_contents($this->fixture_file1_path); $this->assertTrue($this->fixture_file1->renameTo('myHomeFile_renamed.ext')); $this->assertFalse(is_file($this->fixture_file1_path)); $this->assertTrue(is_file($targetPath)); $targetFile = FSI::getFile('home://~john/myHomeFile_renamed.ext'); $this->assertFalse(is_file($this->fixture_metafile1_path)); $this->assertTrue(is_file(USERS_PATH . '/john/' . USERS_METAFILES_DIR . '/' . USERS_FILES_DIR . '/myHomeFile_renamed.ext.xml')); $this->assertEquals('someValueHere', $targetFile->getMeta()->get('myDummyMetaValue')); $this->assertEquals($originalContent, file_get_contents($targetPath)); $this->tearDown(); $this->setUp(); /**** non-existing home file ****/ unlink($this->fixture_file1_path); $this->assertFalse(is_file($this->fixture_file1_path)); try { $this->fixture_file1->renameTo('test'); $this->fail(); } catch (EyeFileNotFoundException $e) { // normal situation } /**** home dir ****/ $meta = new VirtualFileMetaData(); $meta->set('myDummyMetaValue', 'someValueHere'); $this->fixture_dir1->setMeta($meta); $this->assertTrue(is_dir($this->fixture_dir1_path)); $targetPath = USERS_PATH . '/john/' . USERS_FILES_DIR . '/myHomeDir_renamed'; $this->assertFalse(is_dir($targetPath)); $this->assertEquals('someValueHere', $this->fixture_dir1->getMeta()->get('myDummyMetaValue')); $oldDir = clone $this->fixture_dir1; $this->assertTrue($this->fixture_dir1->renameTo('myHomeDir_renamed')); $this->assertFalse(is_dir($this->fixture_dir1_path)); $this->assertTrue(is_dir($targetPath)); $targetFile = FSI::getFile('home://~john/myHomeDir_renamed'); $this->assertNull($oldDir->getMeta()); $this->assertEquals('someValueHere', $targetFile->getMeta()->get('myDummyMetaValue')); /**** sys file ****/ $this->assertTrue(is_file($this->fixture_file2_path)); $targetPath = EYEOS_TESTS_TMP_PATH . '/mySysFile_renamed.ext'; $this->assertFalse(is_file($targetPath)); $originalContent = file_get_contents($this->fixture_file2_path); //as normal user => fails try { $this->fixture_file2->renameTo('mySysFile_renamed.ext'); $this->fail(); } catch (EyeAccessControlException $e) { } //as root => succeeds self::logInAsRoot(); $this->assertTrue($this->fixture_file2->renameTo('mySysFile_renamed.ext')); self::logInAsJohn(); $this->assertFalse(is_file($this->fixture_file2_path)); $this->assertTrue(is_file($targetPath)); $targetFile = FSI::getFile('sys:///tests/tmp/mySysFile_renamed.ext'); $this->assertEquals($originalContent, file_get_contents($targetPath)); /**** sys dir ****/ $this->assertTrue(is_dir($this->fixture_dir2_path)); $targetPath = EYEOS_TESTS_TMP_PATH . '/mySysDir_renamed'; $this->assertFalse(is_dir($targetPath)); //as normal user => fails try { $this->fixture_dir2->renameTo('mySysDir_renamed'); $this->fail(); } catch (EyeAccessControlException $e) { } //as root => succeeds self::logInAsRoot(); $this->assertTrue($this->fixture_dir2->renameTo('mySysDir_renamed')); self::logInAsJohn(); $this->assertFalse(is_dir($this->fixture_dir2_path)); $this->assertTrue(is_dir($targetPath)); $targetFile = FSI::getFile('home://~john/mySysDir_renamed'); }
public static function getFileVersionData($params) { if (isset($params['cloud']) && isset($_SESSION['access_token_' . $params['cloud'] . '_v2'])) { $cloud = $params['cloud']; $user = ProcManager::getInstance()->getCurrentProcess()->getLoginContext()->getEyeosUser()->getId(); $id = $params['id']; $version = $params['version']; $file = FSI::getFile($params['path']); $apiManager = new ApiManager(); $path = AdvancedPathLib::getPhpLocalHackPath($file->getRealFile()->getAbsolutePath()); $token = $_SESSION['access_token_' . $cloud . '_v2']; $resourceUrl = null; if (isset($params['resource_url'])) { $token = new stdClass(); $resourceUrl = $params['resource_url']; $token->key = $params['access_token_key']; $token->secret = $params['access_token_secret']; } $result = $apiManager->getFileVersionData($cloud, $token, $id, $version, $path, $user, $resourceUrl); if ($result) { if (isset($result['error']) && $result['error'] == 403) { $denied = self::permissionDeniedCloud($cloud); $result['path'] = $denied['path']; } } } else { $result['error'] = -1; $result['description'] = "Access token not exists"; } return $result; }
public function testNotifyShareableObjectUpdated() { /**** Change shareable object internal properties ****/ $dir = FSI::getFile('home://~john/myDir'); $dir->mkdir(); $targetFile = FSI::getFile('home://~john/myDir/myMovedFile.ext'); $this->assertEquals(0, count($this->fixture->getAllShareInfo())); $perms = new SharePermission('read,write'); $this->fixture->addCollaborator($this->collaborator1, $perms); $perms = new SharePermission('read'); $this->fixture->addCollaborator($this->collaborator2, $perms); $perms = new SharePermission('write'); $this->fixture->addCollaborator($this->collaborator3, $perms); // preconditions $this->assertEquals(3, count($this->fixture->getAllShareInfo())); $this->assertFalse($targetFile->exists()); $this->assertEquals(0, count($targetFile->getAllShareInfo())); $this->fixture->moveTo($targetFile); // postconditions + preconditions for next operation $this->assertTrue($targetFile->exists()); $this->assertEquals(3, count($targetFile->getAllShareInfo())); $this->assertEquals(0, count($this->fixture->getAllShareInfo())); $targetFile->renameTo('myRenamedFile.ext'); // postconditions $this->assertTrue($targetFile->exists()); $this->assertEquals('myRenamedFile.ext', $targetFile->getName()); $this->assertEquals(3, count($targetFile->getAllShareInfo())); $this->tearDown(); $this->setUp(); /**** Change shareable object's owner ****/ $this->assertEquals(0, count($this->fixture->getAllShareInfo())); $perms = new SharePermission('read,write'); $this->fixture->addCollaborator($this->collaborator1, $perms); $perms = new SharePermission('read'); $this->fixture->addCollaborator($this->collaborator2, $perms); // preconditions $this->assertEquals(2, count($this->fixture->getAllShareInfo())); $this->assertEquals(2, count(SharingManager::getInstance()->getAllShareInfoFromOwner($this->owner))); $this->assertEquals(0, count(SharingManager::getInstance()->getAllShareInfoFromOwner($this->collaborator1))); $this->assertEquals(0, count(SharingManager::getInstance()->getAllShareInfoFromOwner($this->collaborator2))); $this->fixture->chown($this->collaborator1); // postconditions + preconditions for next operation $this->assertEquals(2, count($this->fixture->getAllShareInfo())); $this->assertEquals(0, count(SharingManager::getInstance()->getAllShareInfoFromOwner($this->owner))); $this->assertEquals(2, count(SharingManager::getInstance()->getAllShareInfoFromOwner($this->collaborator1))); $this->assertEquals(0, count(SharingManager::getInstance()->getAllShareInfoFromOwner($this->collaborator2))); $this->assertEquals(0, count(SharingManager::getInstance()->getAllShareInfoFromCollaborator($this->collaborator2, $this->owner))); $this->assertEquals(1, count(SharingManager::getInstance()->getAllShareInfoFromCollaborator($this->owner, $this->collaborator1))); $this->assertEquals(1, count(SharingManager::getInstance()->getAllShareInfoFromCollaborator($this->collaborator2, $this->collaborator1))); //needed to be able to change a file's owner $this->loginAsRoot(); try { $this->fixture->chown($this->collaborator2); } catch (Exception $e) { $this->loginAsJohn(); throw $e; } $this->loginAsJohn(); // postconditions $this->assertEquals(2, count($this->fixture->getAllShareInfo())); $this->assertEquals(0, count(SharingManager::getInstance()->getAllShareInfoFromOwner($this->owner))); $this->assertEquals(0, count(SharingManager::getInstance()->getAllShareInfoFromCollaborator($this->collaborator2, $this->owner))); $this->assertEquals(1, count(SharingManager::getInstance()->getAllShareInfoFromCollaborator($this->owner, $this->collaborator2))); $this->assertEquals(1, count(SharingManager::getInstance()->getAllShareInfoFromCollaborator($this->collaborator1, $this->collaborator2))); $this->assertEquals(0, count(SharingManager::getInstance()->getAllShareInfoFromCollaborator($this->collaborator2, $this->collaborator1))); }
public static function fileExport(array $params) { $destinationFile = $params[0]; $originalFile = $params[1]; $format = $params[2]; if ($format == 'PDF') { $extension = 'pdf'; $format = 'writer_pdf_Export'; } elseif ($format == 'Doc') { $extension = 'doc'; $format = 'MS Word 97'; } elseif ($format == 'Open Office') { $extension = 'odt'; $format = 'writer8'; } elseif ($format == 'HTML') { $extension = 'html'; $format = 'HTML (StarWriter)'; } elseif ($format == 'RTF') { $extension = 'rtf'; $format = 'Rich Text Format'; } elseif ($format == 'TXT') { $extension = 'txt'; $format = 'Text (encoded)'; } $destinationFile .= '.' . $extension; $file = FSI::getFile($originalFile); $memory = MemoryManager::getInstance(); $file->checkReadPermission(); $to = 'home:///'; //then, check the destination file $myFileDest = FSI::getFile($to); $myFileDest->checkWritePermission(); $myRealFile = $myFileDest->getRealFile(); $partName = '.office/' . uniqid(time()) . '_conversion/'; $fileNameDestination = AdvancedPathLib::getPhpLocalHackPath($myRealFile->getPath()) . '/' . $partName; mkdir($fileNameDestination); $myRealFile = $file->getRealFile(); $originalFile = AdvancedPathLib::getPhpLocalHackPath($myRealFile->getPath()); $cmd = 'unzip -d ' . escapeshellarg($fileNameDestination) . ' ' . escapeshellarg($originalFile); shell_exec($cmd); $myConverter = new Converter(); $fileName = $myConverter->Convert($to . $partName . '/document.html', $format); shell_exec('rm -rf ' . escapeshellarg($fileNameDestination)); if (!file_exists($fileName)) { return false; } $content = file_get_contents($fileName); $newFile = FSI::getFile($destinationFile); $newFile->createNewFile(true); $newFile->putContents($content); return $destinationFile; }
public static function viewTempImg($params) { $parts = explode('_', $params); $filepath = 'home:///'; $myFile = FSI::getFile($filepath); $myFile->checkWritePermission(); $myRealFile = $myFile->getRealFile(); $fileNameDestination = AdvancedPathLib::getPhpLocalHackPath($myRealFile->getPath()); $fileNameDestination .= '/.office/' . utf8_basename($parts[0]) . '/' . utf8_basename($params); $info = pathinfo($fileNameDestination); $myExt = strtolower($info['extension']); $response = MMapManager::getCurrentResponse(); header('Content-Type: image/' . $myExt); header('Content-Length: ' . filesize($fileNameDestination)); header('Accept-Ranges: bytes'); header('X-Pad: avoid browser bug'); readfile($fileNameDestination); exit; }
public function listFiles($pattern = '*', $flags = AdvancedPathLib::GLOB_NORMAL) { $files = array(); $urlParts = $this->getURLComponents(); $isRoot = false; if (!isset($urlParts['principalname'])) { $isRoot = true; } // ROOT (workgroup://): list the workgroups the current user is member of if ($isRoot) { $UM = UMManager::getInstance(); $currentUser = ProcManager::getInstance()->getCurrentProcess()->getLoginContext()->getEyeosUser(); // Retrieve all user/workgroup assignations with current user $refAssignation = $UM->getNewUserWorkgroupAssignationInstance(); $refAssignation->setUserId($currentUser->getId()); $assignations = $UM->getAllUserWorkgroupAssignations($refAssignation); // Build an array(workgroupId => workgroupName) only with workgroups the user is MEMBER of $workgroups = array(); foreach ($assignations as &$assignation) { $status = $assignation->getStatus(); if ($status === WorkgroupConstants::STATUS_MEMBER) { $workgroups[] = $UM->getWorkgroupById($assignation->getWorkgroupId())->getName(); } } sort($workgroups); foreach ($workgroups as $workgroupName) { $files[] = FSI::getFile(self::URL_SCHEME_WORKGROUPFILES . '://' . self::URL_LOCATOR_CHAR . $workgroupName . '/'); } } else { $files = parent::listFiles($pattern, $flags); } return $files; }
public static function renameFile($params) { $number = 1; $source = FSI::getFile($params[0]); $target = FSI::getFile($params[1]); if ($target->exists()) { return "duplicated"; } $source->moveTo($target); }
/** * Return the scaled version of image. * * @param Array $params = ( * maxHeight => integer, Max Height of output image * maxWidth => integer, Max Width of output image * path => string Path of input image * ) */ public static function getScaledImage($params) { if ($params === null || !is_array($params)) { throw new EyeInvalidArgumentException('Missing or invalid $params'); } if (!isset($params['path']) || !is_string($params['path'])) { throw new EyeInvalidArgumentException('Missing or invalid $params[\'path\']'); } $path = $params['path']; $maxHeight = isset($params['maxHeight']) ? intval($params['maxHeight']) : null; $maxWidth = isset($params['maxWidth']) ? intval($params['maxWidth']) : null; $response = MMapManager::getCurrentResponse(); $myFile = FSI::getFile($params['path']); if (method_exists($myFile, 'getRealFile')) { $fileName = AdvancedPathLib::getPhpLocalHackPath($myFile->getRealFile()->getAbsolutePath()); } else { $fileName = $params['path']; } $info = GetImageSize($fileName); $width = $info[0]; $height = $info[1]; $mime = $info['mime']; //Calculate new dimensions $newDimensions = self::calculateDimensions(array('height' => $height, 'width' => $width, 'maxHeight' => $maxHeight, 'maxWidth' => $maxWidth)); $newHeight = $newDimensions['height']; $newWidth = $newDimensions['width']; if ($newHeight == $height && $newWidth == $width) { //No resize is necessary $imageData = $myFile->getContents(); } else { // What sort of image? $type = substr(strrchr($mime, '/'), 1); switch ($type) { case 'jpeg': $image_create_func = 'ImageCreateFromJPEG'; $image_save_func = 'ImageJPEG'; $new_image_ext = 'jpg'; break; case 'png': $image_create_func = 'ImageCreateFromPNG'; $image_save_func = 'ImagePNG'; $new_image_ext = 'png'; break; case 'bmp': $image_create_func = 'ImageCreateFromBMP'; $image_save_func = 'ImageBMP'; $new_image_ext = 'bmp'; break; case 'gif': $image_create_func = 'ImageCreateFromGIF'; $image_save_func = 'ImageGIF'; $new_image_ext = 'gif'; break; case 'vnd.wap.wbmp': $image_create_func = 'ImageCreateFromWBMP'; $image_save_func = 'ImageWBMP'; $new_image_ext = 'bmp'; break; case 'xbm': $image_create_func = 'ImageCreateFromXBM'; $image_save_func = 'ImageXBM'; $new_image_ext = 'xbm'; break; default: $image_create_func = 'ImageCreateFromJPEG'; $image_save_func = 'ImageJPEG'; $new_image_ext = 'jpg'; } // Create blank image with new dimensions $imageData = ImageCreateTrueColor($newWidth, $newHeight); $originalImage = $image_create_func($fileName); ImageCopyResampled($imageData, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); $image_save_func($imageData); } $imagevariable = ob_get_contents(); ob_end_clean(); header('Content-Type:' . $mime); header('Content-Length: ' . strlen($imagevariable)); header('Accept-Ranges: bytes'); header('X-Pad: avoid browser bug'); echo $imagevariable; exit; }
/** * @param array( * 'filePath' => filePath, * 'workgroupId' => workgroupId * ) */ public function setWorkgroupPicture($params) { if (!isset($params['filePath']) || !is_string($params['filePath'])) { throw new EyeInvalidArgumentException('Missing or invalid $params[\'filePath\'].'); } if (!isset($params['workgroupId']) || !is_string($params['workgroupId'])) { throw new EyeInvalidArgumentException('Missing or invalid $params[\'workgroupId\'].'); } $workgroup = UMManager::getInstance()->getWorkgroupById($params['workgroupId']); $file = FSI::getFile($params['filePath']); if (!$file->isReadable()) { throw new EyeIOException('Unable to read file at ' . $params['filePath'] . '.'); } $extension = $file->getExtension() ? '.' . $file->getExtension() : ''; $destFile = FSI::getFile('workgroup-conf://~' . $workgroup->getName() . '/public/avatarpic' . $extension); $file->copyTo($destFile); // Update settings (metadata) $settings = MetaManager::getInstance()->retrieveMeta($workgroup); $settings->set('eyeos.workgroup.picture.url', $destFile->getAbsolutePath()); MetaManager::getInstance()->storeMeta($workgroup, $settings); }
/** * @return bool TRUE if the file has been successfully renamed, FALSE otherwise */ public function renameTo($newName) { if ($this->realFile === null) { throw new EyeUnsupportedOperationException(__METHOD__ . ' on ' . $this->path); } if (!$this->exists()) { throw new EyeFileNotFoundException($this->path . ' does not exist.'); } if ($this->isRoot()) { throw new EyeUnsupportedOperationException('Cannot rename the root folder.'); } $oldName = $this->getName(); $oldPath = $this->getAbsolutePath(); $this->getParentFile()->checkWritePermission(); $newFile = FSI::getFile(dirname($oldPath) . '/' . $newName); $newFile->checkWritePermission(); try { if ($this->realFile->renameTo($newName)) { //change internal name in URL $urlParts = $this->getURLComponents(); $dirname = dirname($urlParts['path']); $urlParts['path'] = $dirname . '/' . $newName; $this->path = AdvancedPathLib::buildUrl($urlParts); //Update URL components cache $this->urlParts = $urlParts; //update metadata MetaManager::getInstance()->updateMeta($this, array('oldName' => $oldName)); $oldFile = FSI::getFile($oldPath); //notify listeners $this->fireEvent('fileRenamed', new FileEvent($oldFile, $this)); return true; } } catch (EyeFileNotFoundException $e) { throw new EyeFileNotFoundException($this->path . ' does not exist.', 0, $e); } catch (EyeException $e) { throw new EyeIOException('Unable to rename file ' . $this->path . '.', 0, $e); } throw new EyeIOException('Unable to rename file ' . $this->path . '.'); }
public function testSearchFileRecollPlugin() { $query = "filename:*foo* filename:*lol* type:pdf OR type:xml AND ext:html OR ext:xml"; $searchQuery = new SearchQuery(); $searchQuery->setQueryString($this->query); $searchQuery->setQueryTokens($this->tokens); // we want to check if the SearchManager is well working, // means if it is able to load all the required library. $searchManager = new SearchManager(); $searchManager->search($searchQuery); // we also want to check if the parsing process // gives us a well formatted string. $recollPlugin = new SearchFileRecollPlugin(); $recollPlugin->search($searchQuery); $this->assertEquals($query, $recollPlugin->getSearchQuery()); // FileSearchListener::fileCreated() $this->assertFalse(is_file($this->fixture_file_path)); $this->assertTrue($this->fixture_file->createNewFile()); $this->assertTrue(is_file($this->fixture_file_path)); $searchQuery->setQueryString('testFile'); $searchQuery->setQueryTokens(null); $recollPlugin->resetSearchQuery(); $recollPlugin->search($searchQuery); $results = $recollPlugin->getResults(); $this->assertEquals($results[0]['name'], 'testFile.txt'); // FileSearchListener::fileDeleted() $this->assertTrue(is_file($this->fixture_file_path)); $this->assertTrue($this->fixture_file->delete()); $this->assertFalse(is_file($this->fixture_file_path)); $searchQuery->setQueryString('testFile'); $searchQuery->setQueryTokens(null); $recollPlugin->resetSearchQuery(); $recollPlugin->search($searchQuery); $results = $recollPlugin->getResults(); $this->assertTrue(empty($results)); // FileSearchListener::directoryCreated() $this->assertFalse(is_dir($this->fixture_dir_path)); $this->assertTrue($this->fixture_dir->mkdir()); $this->assertTrue(is_dir($this->fixture_dir_path)); $searchQuery->setQueryString('testDir'); $searchQuery->setQueryTokens(null); $recollPlugin->resetSearchQuery(); $recollPlugin->search($searchQuery); $results = $recollPlugin->getResults(); $this->assertEquals($results[0]['name'], 'testDir'); // FileSearchListener::fileMoved() $this->assertFalse(is_file($this->fixture_file_path)); $this->assertTrue($this->fixture_file->createNewFile()); $this->assertTrue(is_file($this->fixture_file_path)); $newFile = FSI::getFile('home://~fakeUser/testDir/testFile2.txt'); $this->assertTrue($this->fixture_file->moveTo($newFile)); $this->assertTrue(is_file($this->fixture_newFile_path)); $this->assertFalse(is_file($this->fixture_file_path)); $searchQuery->setQueryString('testFile2'); $searchQuery->setQueryTokens(null); $recollPlugin->resetSearchQuery(); $recollPlugin->search($searchQuery); $results = $recollPlugin->getResults(); $this->assertEquals($results[0]['name'], 'testFile2.txt'); $searchQuery->setQueryString('testFile'); $searchQuery->setQueryTokens(null); $recollPlugin->resetSearchQuery(); $recollPlugin->search($searchQuery); $results = $recollPlugin->getResults(); $this->assertNotEquals($results[0]['name'], 'testFile.txt'); $newFile->delete(); // FileSearchListener::fileRenamed() $this->assertFalse(is_file($this->fixture_file_path)); $this->assertTrue($this->fixture_file->createNewFile()); $this->assertTrue(is_file($this->fixture_file_path)); $this->assertTrue($this->fixture_file->renameTo('testFileRenamed.txt')); $searchQuery->setQueryString('testFile'); $searchQuery->setQueryTokens(null); $recollPlugin->resetSearchQuery(); $recollPlugin->search($searchQuery); $results = $recollPlugin->getResults(); $this->assertNotEquals($results[0]['name'], 'testFile.txt'); $this->assertEquals($results[0]['name'], 'testFileRenamed.txt'); // FileSearchListener::fileWritten() $this->fixture_file->putContents('take it easy!'); // TODO: check if the content's file is up to date. }