public function workgroupDeleted(UMEvent $e) { if ($e->getSource() instanceof AbstractEyeosWorkgroup) { $workgroupDirPath = UMManager::getEyeosWorkgroupDirectory($e->getSource()->getName()); AdvancedPathLib::rmdirs($workgroupDirPath); } }
/** * @param string $internalUrl * @return mixed The URL to access the target file from outside, if available, or FALSE. */ public static function toExternalUrl($internalUrl) { $currentProc = ProcManager::getInstance()->getCurrentProcess(); if ($currentProc) { $checknum = $currentProc->getChecknum(); } else { $checknum = -1; } $urlParts = AdvancedPathLib::parse_url($internalUrl); if ($urlParts === false) { return $internalUrl; } if ($urlParts['scheme'] === EyeosAbstractVirtualFile::URL_SCHEME_SYSTEM) { // EXTERN try { $externPath = AdvancedPathLib::resolvePath($urlParts['path'], '/extern', AdvancedPathLib::OS_UNIX | AdvancedPathLib::RESOLVEPATH_RETURN_REFDIR_RELATIVE); return 'index.php?extern=' . $externPath; } catch (Exception $e) { } // APPS try { $appPath = AdvancedPathLib::resolvePath($urlParts['path'], '/apps', AdvancedPathLib::OS_UNIX | AdvancedPathLib::RESOLVEPATH_RETURN_REFDIR_RELATIVE); $appName = utf8_substr($appPath, 1, utf8_strpos($appPath, '/', 1)); $appFile = utf8_substr($appPath, utf8_strlen($appName) + 1); return 'index.php?checknum=' . $checknum . '&appName=' . $appName . '&appFile=' . $appFile; } catch (Exception $e) { } return $internalUrl; } //TODO return $internalUrl; }
/** * @param string $path * @return bool */ public function checkPath($path) { $urlParts = AdvancedPathLib::parse_url($path); if (strtolower($urlParts['scheme']) == 'file') { return true; } return false; }
/** * @param string $path * @return bool */ public function checkPath($path) { $urlParts = AdvancedPathLib::parse_url($path); if (in_array(strtolower($urlParts['scheme']), self::$handledSchemes)) { return true; } return false; }
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; }
function __ooFiles_loadSubFiles($subFilesDir) { $subClassesFiles = scandir($subFilesDir); foreach ($subClassesFiles as $currentSubClassFile) { if (is_file($subFilesDir . '/' . $currentSubClassFile)) { require_once $subFilesDir . '/' . $currentSubClassFile; $subClassFilename = AdvancedPathLib::pathinfo($currentSubClassFile, PATHINFO_FILENAME); if (is_dir($subFilesDir . '/' . $subClassFilename)) { __ooFiles_loadSubFiles($subFilesDir . '/' . $subClassFilename); } } } }
public function testChown() { if (AdvancedPathLib::getCurrentOS() == AdvancedPathLib::OS_WINDOWS) { $this->markTestSkipped('chown() is not available on Windows.'); } // // Unable to check that without running phpunit as 'root' // /*chmod(TESTS_FSI_LOCALFILE_TMP_PATH . '/myFile.ext', 0777); $this->assertNotEquals(1001, fileowner(TESTS_FSI_LOCALFILE_TMP_PATH . '/myFile.ext')); $this->assertTrue($this->fixture_file->chown(1001)); clearstatcache(); $this->assertEquals(1001, fileowner(TESTS_FSI_LOCALFILE_TMP_PATH . '/myFile.ext'));*/ }
/** * @param string $path The path to the file (MUST BE A VALID URL) * @param mixed $params Additional arguments (could be useful for derivated classes) * @throws EyeInvalidArgumentException * @throws EyeMissingArgumentException * @throws EyeNullPointerException */ public function __construct($path, $params = null) { try { $urlParts = AdvancedPathLib::parse_url($path); if ($urlParts['scheme'] != self::URL_SCHEME_SYSTEM) { throw new EyeInvalidArgumentException($urlParts['scheme'] . ' is not a valid scheme for system file, expecting ' . self::URL_SCHEME_SYSTEM . '.'); } } catch (EyeException $e) { throw new EyeInvalidArgumentException($path . ' is not a valid path value.', 0, $e); } try { parent::__construct($path, $params); } catch (EyeException $e) { throw new EyeException('Unable to create ' . __CLASS__, 0, $e); } }
/** * @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; }
/** * @param mixed $object * @param String $params * @return boolean * @throws EyeException * @throws EyeErrorException */ public function deleteMeta($object, $params) { if (!$object instanceof EyeUserFile) { throw new EyeInvalidArgumentException('$object must be an EyeUserFile.'); } $meta = $this->retrieveMeta($object, $params); if ($meta !== null) { SecurityManager::getInstance()->checkPermission($meta, new MetaDataPermission('delete', null, $object)); } $urlParts = $object->getURLComponents(); if ($urlParts['path'] == '/') { $realpath = $this->getUserMetaFilesPath($urlParts['principalname']) . '/' . USERS_FILES_DIR; } else { $realpath = $this->getUserMetaFilesPath($urlParts['principalname']) . '/' . USERS_FILES_DIR . $urlParts['path']; } if (is_dir($realpath)) { AdvancedPathLib::rmdirs($realpath); } return @unlink($realpath . USERS_METAFILES_EXTENSION); }
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; }
/** * @param IFile $file * @param bool $foldersFirst * @return int A negative value if the current file should be placed before $file, * zero (0) if they are equals, a positive value otherwise. */ public function compareTo(IFile $file, $foldersFirst = false) { if ($foldersFirst) { $isDirThis = $this->isDirectory(); $isDirFile = $file->isDirectory(); if ($isDirThis && !$isDirFile) { return -1; } else { if ($isDirFile && !$isDirThis) { return 1; } } } $urlParts = $file->getURLComponents(); $urlParts['path'] = $file->getPathFromRoot(); //needed to resolve the path (if relative) $absolutePathFile = AdvancedPathLib::buildURL($urlParts); $urlParts = $this->getURLComponents(); $urlParts['path'] = $this->getPathFromRoot(); //needed to resolve the path (if relative) $absolutePathThis = AdvancedPathLib::buildURL($urlParts); return utf8_strcasecmp($absolutePathThis, $absolutePathFile); }
/** * @param string $path The path to the file * @param mixed $params Additional arguments (could be useful for derivated classes) */ public function __construct($path, $params = null) { $urlParts = AdvancedPathLib::parse_url($path); //DSN if (!isset($params['PDOFile::dsn'])) { throw new EyeInvalidArgumentException('Missing DSN (key "dsn") in $params for database connection.'); } $this->connectionData['dsn'] = $params['dsn']; //TABLE NAME if (!isset($params['PDOFile::tableName'])) { throw new EyeInvalidArgumentException('Missing table name (key "tableName") in $params for database connection.'); } $this->connectionData['tableName'] = $params['tableName']; //USER if (isset($params['PDOFile::user'])) { $this->connectionData['user'] = $params['PDOFile::user']; } //PASSWORD if (isset($params['PDOFile::password'])) { $this->connectionData['password'] = $params['PDOFile::password']; } $this->path = $path; }
/** * TODO * * @param mixed $object * @param IPermission $permission * @param LoginContext $context * @return bool TRUE if the handler performed the permission check successfully, FALSE otherwise. * * @throws EyeInvalidArgumentException * @throws EyeUnexpectedValueException * @throws EyeAccessControlException */ public function checkPermission($object, IPermission $permission, LoginContext $context) { if (!$object instanceof EyeosApplicationDescriptor) { throw new EyeInvalidArgumentException('$object must be an EyeosApplicationDescriptor.'); } try { $eyeosUser = $context->getEyeosUser(); } catch (EyeNullPointerException $e) { $this->failureException = new EyeHandlerFailureException('No eyeos user found in login context.'); return false; } $meta = $object->getMeta(); if ($meta === null) { throw new EyeNullPointerException('$meta cannot be null.'); } $sysParams = $meta->get('eyeos.application.systemParameters'); // Extract owner, group and permissions from application's metadata try { $owner = UMManager::getInstance()->getUserByName($sysParams['owner']); } catch (EyeNoSuchPrincipalException $e) { $this->failureException = new EyeHandlerFailureException('Unknown owner "' . $owner . '".'); return false; } try { $group = UMManager::getInstance()->getGroupByName($sysParams['group']); } catch (EyeNoSuchPrincipalException $e) { $this->failureException = new EyeHandlerFailureException('Unknown group "' . $group . '".'); return false; } try { $perms = AdvancedPathLib::permsToOctal($sysParams['permissions']); } catch (Exception $e) { $this->failureException = new EyeHandlerFailureException('"' . $perms . '" is not a valid octal UNIX permission for application ' . $object->getName() . '.'); return false; } // Loop on actions (but here we currently know the action "execute" only) $accessGranted = false; $actionText = ''; foreach ($permission->getActions() as $action) { if ($action == 'execute') { $ref = 0100; $actionText = 'Execution'; } else { // the given action is not supported by this handler $this->failureException = new EyeHandlerFailureException('Unknown action received: ' . $action . '.'); return false; } //owner if ($eyeosUser->getId() == $owner->getId()) { if ($ref & $perms) { $accessGranted = true; continue; } else { throw new EyeAccessControlException($actionText . ' access denied to user ' . $eyeosUser->getName() . ' for application ' . $object->getName() . ' (insufficient permissions).'); } } else { $ref = $ref >> 3; //group if ($context->getSubject()->getPrincipals()->contains($group)) { if ($ref & $perms) { $accessGranted = true; continue; } else { throw new EyeAccessControlException($actionText . ' access denied to user ' . $eyeosUser->getName() . ' for application ' . $object->getName() . ' (insufficient permissions).'); } } else { $ref = $ref >> 3; //others if ($ref & $perms) { $accessGranted = true; continue; } else { throw new EyeAccessControlException($actionText . ' access denied to user ' . $eyeosUser->getName() . ' for application ' . $object->getName() . ' (insufficient permissions).'); } } } } if (self::$Logger->isInfoEnabled()) { self::$Logger->info('Access granted to user ' . $eyeosUser->getName() . ' for actions "' . $permission->getActionsAsString() . '" on application ' . $object->getName() . '.'); } return true; }
public static function updateDb(AbstractEyeosUser $user) { if (AdvancedPathLib::getCurrentOS() == AdvancedPathLib::OS_WINDOWS) { return; } $userRecollDirPath = UMManager::getInstance()->getEyeosUserDirectory($user) . '/' . USERS_CONF_DIR . '/' . FRAMEWORK_SEARCH_RECOLL_DIR; shell_exec(realpath(FRAMEWORK_SEARCH_UTILS_PATH) . '/updateDB.pl ' . escapeshellarg(realpath($userRecollDirPath))); }
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 testMkdir() { /**** non-existing home dir ****/ $this->assertFalse(is_dir(USERS_PATH . '/john/' . USERS_FILES_DIR . '/myHomeDirZ')); $file = FSI::getFile('home://~john/myHomeDirZ'); $this->assertNull($file->getMeta()); $this->assertTrue($file->mkdir()); $this->assertTrue(is_dir(USERS_PATH . '/john/' . USERS_FILES_DIR . '/myHomeDirZ')); //check metadata $meta = $file->getMeta(); $this->assertNotNull($meta); $this->assertEquals('john', $meta->get(EyeosAbstractVirtualFile::METADATA_KEY_OWNER)); $this->assertEquals('users', $meta->get(EyeosAbstractVirtualFile::METADATA_KEY_GROUP)); $this->assertEquals(AdvancedPathLib::permsToUnix(0777 & ~$file->getUMask()), $meta->get(EyeosAbstractVirtualFile::METADATA_KEY_PERMISSIONS)); $file->delete(); /**** non-existing home dir (mode = 0751) ****/ $this->assertFalse(is_dir(USERS_PATH . '/john/' . USERS_FILES_DIR . '/myHomeDirZ')); $file = FSI::getFile('home://~john/myHomeDirZ'); $this->assertNull($file->getMeta()); $this->assertTrue($file->mkdir(0751)); $this->assertTrue(is_dir(USERS_PATH . '/john/' . USERS_FILES_DIR . '/myHomeDirZ')); //check metadata ( => rights !) $meta = $file->getMeta(); $this->assertNotNull($meta); $this->assertEquals('john', $meta->get(EyeosAbstractVirtualFile::METADATA_KEY_OWNER)); $this->assertEquals('users', $meta->get(EyeosAbstractVirtualFile::METADATA_KEY_GROUP)); $this->assertEquals(AdvancedPathLib::permsToUnix(0751), $meta->get(EyeosAbstractVirtualFile::METADATA_KEY_PERMISSIONS)); $file->delete(); /**** existing home dir ****/ $this->assertTrue(is_dir($this->fixture_dir1_path)); try { $this->fixture_dir1->mkdir(); $this->fail(); } catch (EyeIOException $e) { // normal situation } $this->assertTrue(is_dir($this->fixture_dir1_path)); //TODO: test sys files when metadata will be implemented for them }
/** * * @param string $referenceUrl * @param string $requestedUrl * @param bool $requestedUrlIsDir * @return bool */ protected static function impliesUrl($referenceUrl, $requestedUrl) { $refUrlParts = AdvancedPathLib::parse_url($referenceUrl); $requestedUrlParts = AdvancedPathLib::parse_url($requestedUrl); // schemes must match if ($refUrlParts['scheme'] != $requestedUrlParts['scheme']) { return false; } // hosts must match (except if reference host is "*") // TODO: add ability to provide a partial host (e.g. "*.eyeos.org") if (isset($refUrlParts['host'])) { if ($refUrlParts['host'] != self::WILD_CHAR) { if (!isset($requestedUrlParts['host']) || $refUrlParts['host'] != $requestedUrlParts['host']) { return false; } } } // initialize reference URL $referenceIsDirectory = false; $referenceIsRecursive = false; $refCanonicalPath = AdvancedPathLib::getCanonicalPath($refUrlParts['path']); //var_dump('$refCanonicalPath: ' . $refCanonicalPath); // analyze reference URL (directory? recursive?) $length = utf8_strlen($refCanonicalPath); $lastChar = $length > 0 ? utf8_substr($refCanonicalPath, -1) : 0; $lastCharButOneIdx = $length > 0 ? utf8_substr($refCanonicalPath, -2, 1) : 0; if ($lastChar == self::RECURSIVE_CHAR && $lastCharButOneIdx == '/') { $referenceIsDirectory = true; $referenceIsRecursive = true; $refCanonicalPath = utf8_substr($refCanonicalPath, 0, -1); } elseif ($lastChar == self::WILD_CHAR && $lastCharButOneIdx == '/') { $referenceIsDirectory = true; $referenceIsRecursive = utf8_substr($refCanonicalPath, 0, -1); } // initialize requested URL $canonicalPath = AdvancedPathLib::getCanonicalPath($requestedUrlParts['path']); //var_dump($canonicalPath . ' ### ' . $refCanonicalPath); //var_dump('refIsDir: ' . ($referenceIsDirectory ? 'true' : 'false')); //var_dump('refIsRecursive: ' . ($referenceIsRecursive ? 'true' : 'false')); // check implication $implies = false; if ($referenceIsDirectory) { if ($referenceIsRecursive) { $implies = utf8_strlen($canonicalPath) > utf8_strlen($refCanonicalPath) && ($canonicalPath == $refCanonicalPath || utf8_strpos($canonicalPath, $refCanonicalPath) === 0); } else { $lastSeparatorIdx = utf8_strrpos($canonicalPath, '/'); if ($lastSeparatorIdx === false) { $implies = false; } else { $implies = utf8_strlen($refCanonicalPath) == $lastSeparatorIdx + 1 && utf8_substr($refCanonicalPath, 0, $lastSeparatorIdx + 1) == utf8_substr($canonicalPath, 0, $lastSeparatorIdx + 1); } } } else { $implies = $refCanonicalPath == $canonicalPath; } //var_dump('$implies= ' . ($implies? 'true' : 'false')); return $implies; }
/** * @return int The number of bytes written to the file. * @param mixed $data THe data to be written to the file. * @param int $flags FILE_APPEND | LOCK_EX (FILE_TEXT | FILE_BINARY only for PHP 6) * @throws EyeBadMethodCallException * @throws EyeIOException */ public function putContents($data, $flags = 0) { if (!is_integer($flags)) { throw new EyeInvalidArgumentException('Expecting an integer value for $flags. Given: "' . $flags . '" (' . gettype($flags) . ').'); } $opts = array('ftp' => array('overwrite' => true)); $context = stream_context_create($opts); try { $this->destroyConnection(); $bytesAdded = file_put_contents($this->path, $data, $flags, $context); } catch (Exception $e) { throw new EyeIOException('Error occured during data transfer to file ' . AdvancedPathLib::getURLForDisplay($this->path) . '.', 0, $e); } catch (ErrorException $e) { throw new EyeIOException('Error occured during data transfer to file ' . AdvancedPathLib::getURLForDisplay($this->path) . '.', 0, $e); } if ($bytesAdded === false) { throw new EyeIOException('Unable to write data to file ' . AdvancedPathLib::getURLForDisplay($this->path) . '.'); } if ($flags & FILE_APPEND) { $this->statsCache['size'] += $bytesAdded; } else { $this->statsCache['size'] = $bytesAdded; } $this->statsCache['isDirectory'] = false; return $bytesAdded; }
function __shutdown_test() { try { // We need to be root to delete test principals $myUManager = UMManager::getInstance(); $subject = new Subject(); $loginContext = new LoginContext('init', $subject); $subject->getPrivateCredentials()->append(new EyeosPasswordCredential('root', 'root')); $loginContext->login(); // we need a fake shutdown process $procManager = ProcManager::getInstance(); $myProcess = new Process('shutdown'); $procManager->execute($myProcess); $procManager->setProcessLoginContext($myProcess->getPid(), $loginContext); // clean deletion of users foreach (UMManager::getInstance()->getAllUsers() as $user) { UMManager::getInstance()->deletePrincipal($user); } AdvancedPathLib::rmdirs(USERS_PATH, true); } catch (Exception $e) { echo 'Uncaught exception on shutdown!' . "\n"; ExceptionStackUtil::printStackTrace($e, false); } }
/** * 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/'; }
/** * 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; }
/** * 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); }
/** * TODO: Will need to be moved/merged to/with FileSystemExecModule */ public static function createNewFile($params) { $currentUser = ProcManager::getInstance()->getCurrentProcess()->getLoginContext()->getEyeosUser(); $settings = MetaManager::getInstance()->retrieveMeta($currentUser); $newFile = FSI::getFile($params[0]); $name = explode(".", $newFile->getName()); $extension = (string) $name[count($name) - 1]; if ($newFile->exists()) { $name = explode(".", $newFile->getName()); $path = str_replace($newFile->getName(), '', $newFile->getPath()); $extension = (string) $name[count($name) - 1]; $theName = substr($newFile->getName(), 0, strlen($newFile->getName()) - strlen($extension) - 1); $futureName = array($theName, 1); $nameForCheck = implode(' ', $futureName); $nameForCheck .= '.' . $extension; $newFile = FSI::getFile($path . "/" . $nameForCheck); while ($newFile->exists()) { $futureName[1] += 1; $nameForCheck = implode(' ', $futureName); $nameForCheck .= '.' . $extension; $newFile = FSI::getFile($path . "/" . $nameForCheck); } } if ($extension == 'edoc') { $rand = md5(uniqid(time())); mkdir('/tmp/' . $rand); $uniqid = uniqid(); shell_exec('touch /tmp/' . $rand . '/document.html'); file_put_contents('/tmp/' . $rand . '/duid', $uniqid); $myFile = FSI::getFile($params[0] . '_tmp'); $myFile->checkWritePermission(); $myRealFile = $myFile->getRealFile(); $fileNameOriginal = AdvancedPathLib::getPhpLocalHackPath($myRealFile->getPath()); //this is REALLY annoying to be forced to do this, but zip command line util is a mess $oldDir = getcwd(); chdir('/tmp/' . $rand); $cmd = 'zip -r ' . escapeshellarg($fileNameOriginal) . ' ./'; shell_exec($cmd); //we return into the normal directory...this is ugly chdir($oldDir); AdvancedPathLib::rmdirs('/tmp/' . $rand); // creating a fake file trought FSI, so we can have our nice xml :) $newFile->createNewFile(true); $newFile->putContents($myFile->getContents()); unlink($fileNameOriginal); // FIXME!!!!! } else { $newFile->createNewFile(); } return self::getFileInfo($newFile, $settings); }
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; } }
/** * Resolves a given $path into given $referenceDirPath if possible. * <b>WARNING:</b> * <ul> * <li>This function is not to be used on URL as (file://..., ftp://..., etc.), only *simple* paths (/my/simple/path).</li> * <li>This function may output incorrect results on Windows platforms when $path is located on a different drive letter * from $referenceDirPath.</li> * </ul> * * @param string $path The path of a file to resolve<br /> * (e.g. "/Documents/Images/..",<br /> * or "./users/john/files/Documents/Images/..",<br /> * or "/home/john/eyeos/users/john/files/Documents/Images/..",<br /> * or "C:\My Documents\john\eyeos\users\john\files\Documents\Images\..") * @param string $referenceDirPath The path of the directory used as a reference for resolution * @param int $flags * OS_WINDOWS: Set it to force resolution assuming a Windows filesystem.<br /> * OS_UNIX: Set it to force resolution assuming a UNIX filesystem. <br /> * RESOLVEPATH_RETURN_REFDIR_RELATIVE: Set it to get a resolved path from current PHP directory (getcwd) * (e.g. "./users/john/files/Documents"), * or don't to get a resolved path in the reference folder (e.g. "/Documents")<br /> * RESOLVEPATH_NOT_LOCALHOST: Set it to resolve the given path as a normal file on the filesystem, * or don't to resolve it according to the reference path only.<br /> * @return mixed The resolved path or FALSE if the given path is not in the reference directory or if an error occured * @throws InvalidArgumentException */ public static function resolvePath($path, $referenceDirPath, $flags = self::NONE) { if ($flags & self::OS_WINDOWS) { $isWindows = true; } elseif ($flags & self::OS_UNIX) { $isWindows = false; } else { $isWindows = self::isCurrentOS(self::OS_WINDOWS); } $path = AdvancedPathLib::unifyPath($path); $resolveOnLocalHost = !($flags & self::RESOLVEPATH_NOT_LOCALHOST); //both following var are used in the next different parts to analyze its structure, but we initialize them //now to avoid multiple calls to self::realpath() $absolutePath = self::realpath($path, $resolveOnLocalHost); $absolutePathReferenceDir = self::realpath($referenceDirPath, $resolveOnLocalHost); //$path is a relative path to the current PHP dir // -OR- $path is a full absolute path if (stripos($path, './') === 0 || $path == $absolutePath) { //designated path is NOT in the reference directory => ERROR if (stripos($absolutePath, $absolutePathReferenceDir) !== 0) { throw new InvalidArgumentException('Unable to process paths resolution: ' . $path . ' is not located in ' . $referenceDirPath . '.'); } $path = $absolutePath; } //$path is an absolute path // UN*X: /home/john/eyeos/eyeos/users/john/files/Documents // WIN: C:\My Documents\john\eyeos\eyeos\users\john\files\Documents if (stripos($path, $absolutePathReferenceDir) === 0) { $relativePath = utf8_substr($absolutePath, utf8_strlen($absolutePathReferenceDir)); $path = $relativePath; } //$path is a relative path if (stripos($path, $referenceDirPath) === 0) { $relativePath = utf8_substr($path, utf8_strlen($referenceDirPath)); $path = $relativePath; } if ($isWindows) { //$path starts with a Windows drive letter but referenceDir doesn't => ERROR if (preg_match('/^([a-z]{1}):/i', $path)) { throw new InvalidArgumentException('Unable to process paths resolution: ' . $path . ' starts with a Windows drive letter but ' . $referenceDirPath . ' does not.'); } } //designated path is NOT in the reference directory => ERROR if (stripos(self::realpath($referenceDirPath . self::dirname($path)), $absolutePathReferenceDir) === false) { throw new InvalidArgumentException('Unable to process paths resolution: ' . $path . ' is not located in ' . $referenceDirPath . '.'); } $resolvedPath = ''; if ($flags & self::RESOLVEPATH_RETURN_REFDIR_RELATIVE) { $resolvedPath = '/' . utf8_substr(self::realpath($referenceDirPath . '/' . $path), utf8_strlen(self::unifyPath($absolutePathReferenceDir . '/'))); } else { $resolvedPath = '.' . utf8_substr(self::realpath($referenceDirPath . '/' . $path), utf8_strlen(self::realpath('.'))); } return $resolvedPath; }
public static function createFile($params) { $number = 1; $newfile = FSI::getFile($params[0]); $info = pathinfo($params[0]); while ($newfile->exists()) { $newfile = FSI::getFile($info['dirname'] . '/' . $info['filename'] . ' ' . $number . '.' . $info['extension']); $number++; } if (strtoupper($info['extension']) == 'EDOC') { $rand = md5(uniqid(time())); mkdir('/tmp/' . $rand); $uniqid = uniqid(); shell_exec('touch /tmp/' . $rand . '/document.html'); file_put_contents('/tmp/' . $rand . '/duid', $uniqid); $myFile = FSI::getFile($params[0] . '_tmp'); $myFile->checkWritePermission(); $myRealFile = $myFile->getRealFile(); $fileNameOriginal = AdvancedPathLib::getPhpLocalHackPath($myRealFile->getPath()); //this is REALLY annoying to be forced to do this, but zip command line util is a mess $oldDir = getcwd(); chdir('/tmp/' . $rand); $cmd = 'zip -r ' . escapeshellarg($fileNameOriginal) . ' ./'; shell_exec($cmd); //we return into the normal directory...this is ugly chdir($oldDir); AdvancedPathLib::rmdirs('/tmp/' . $rand); // creating a fake file trought FSI, so we can have our nice xml :) $newfile->createNewFile(true); $newfile->putContents($myFile->getContents()); unlink($fileNameOriginal); // FIXME!!!!! } else { $newfile->createNewFile(); } $return = array('class' => get_class($newfile), 'type' => $newfile->isDirectory() ? 'folder' : ($newfile->isLink() ? 'link' : 'file'), 'extension' => utf8_strtoupper($newfile->getExtension()), 'size' => $newfile->isDirectory() ? 0 : $newfile->getSize(), 'permissions' => $newfile->getPermissions(false), 'owner' => $newfile->getOwner(), 'group' => $newfile->getGroup(), 'absolutepath' => $newfile->getAbsolutePath(), 'meta' => $newfile->getMeta()->getAll()); if ($return['extension'] == 'LNK') { $return['content'] = $newfile->getContents(); } $return['name'] = $newfile->getName() != '/' ? $newfile->getName() : $return['absolutepath']; if ($newfile instanceof EyeosAbstractVirtualFile) { $return['virtual'] = 'true'; } else { $return['virtual'] = 'false'; } return $return; }
public function setUp() { if (self::$InitProcessToRestore === null) { self::$InitProcessToRestore = ProcManager::getInstance()->getCurrentProcess(); } if (!self::$ClassSetUpRun) { $this->tearDown(); $this->owner = UMManager::getInstance()->getUserByName('john'); $this->group = UMManager::getGroupByName(SERVICE_UM_DEFAULTUSERSGROUP); //create group "wonderland" $this->secGroup = UMManager::getInstance()->getNewGroupInstance(); $this->secGroup->setName('wonderland'); UMManager::getInstance()->createGroup($this->secGroup); //create user "alice" $this->collaborator1 = UMManager::getInstance()->getNewUserInstance(); $this->collaborator1->setName('alice'); $this->collaborator1->setPassword('alice', true); $this->collaborator1->setPrimaryGroupId($this->secGroup->getId()); UMManager::getInstance()->createUser($this->collaborator1); //create user "bob" $this->collaborator2 = UMManager::getInstance()->getNewUserInstance(); $this->collaborator2->setName('bob'); $this->collaborator2->setPassword('bob', true); $this->collaborator2->setPrimaryGroupId($this->secGroup->getId()); UMManager::getInstance()->createUser($this->collaborator2); //create user "charlie" $this->collaborator3 = UMManager::getInstance()->getNewUserInstance(); $this->collaborator3->setName('charlie'); $this->collaborator3->setPassword('charlie', true); $this->collaborator3->setPrimaryGroupId($this->secGroup->getId()); UMManager::getInstance()->createUser($this->collaborator3); $proc = new Process('example'); $loginContext = new LoginContext('example', new Subject()); $proc->setLoginContext($loginContext); ProcManager::getInstance()->execute($proc); self::$MyProcPid = $proc->getPid(); $this->loginAsJohn(); self::$ClassSetUpRun = true; } else { $this->owner = UMManager::getInstance()->getUserByName('john'); $this->collaborator1 = UMManager::getInstance()->getUserByName('alice'); $this->collaborator2 = UMManager::getInstance()->getUserByName('bob'); $this->collaborator3 = UMManager::getInstance()->getUserByName('charlie'); } AdvancedPathLib::rmdirs(USERS_PATH . '/john/' . USERS_FILES_DIR, true); AdvancedPathLib::rmdirs(USERS_PATH . '/john/' . USERS_METAFILES_DIR, true); $this->fixture = FSI::getFile('home://~john/myFile.ext'); $this->loginAsRoot(); try { $this->fixture->delete(); } catch (Exception $e) { } $this->loginAsJohn(); $this->fixture->createNewFile(true); $conf = SharingManager::getConfiguration('SharingManager'); $providerClassName = (string) $conf->providerClassName[0]; if ($providerClassName == 'DefaultSQLiteShareInfoProvider') { if (is_file(USERS_PATH . '/' . $this->owner->getName() . '/' . USERS_CONF_DIR . '/' . USERS_SHARE_DIR . '/shares.db')) { unlink(USERS_PATH . '/' . $this->owner->getName() . '/' . USERS_CONF_DIR . '/' . USERS_SHARE_DIR . '/shares.db'); } if (is_file(USERS_PATH . '/' . $this->collaborator1->getName() . '/' . USERS_CONF_DIR . '/' . USERS_SHARE_DIR . '/shares.db')) { unlink(USERS_PATH . '/' . $this->collaborator1->getName() . '/' . USERS_CONF_DIR . '/' . USERS_SHARE_DIR . '/shares.db'); } if (is_file(USERS_PATH . '/' . $this->collaborator2->getName() . '/' . USERS_CONF_DIR . '/' . USERS_SHARE_DIR . '/shares.db')) { unlink(USERS_PATH . '/' . $this->collaborator2->getName() . '/' . USERS_CONF_DIR . '/' . USERS_SHARE_DIR . '/shares.db'); } if (is_file(USERS_PATH . '/' . $this->collaborator3->getName() . '/' . USERS_CONF_DIR . '/' . USERS_SHARE_DIR . '/shares.db')) { unlink(USERS_PATH . '/' . $this->collaborator3->getName() . '/' . USERS_CONF_DIR . '/' . USERS_SHARE_DIR . '/shares.db'); } } else { if ($providerClassName == 'DefaultMySQLShareInfoProvider') { try { require_once SERVICE_SHARING_SHARINGMANAGERS_PROVIDERS_PATH . '/DefaultMySQLShareInfoProvider.php'; $dao = StorageManager::getInstance()->getHandler(SQL_DAOHANDLER); $dao->send('TRUNCATE TABLE ' . DefaultMySQLShareInfoProvider::SHAREINFO_TABLE_NAME); $dao->send('TRUNCATE TABLE ShareableVirtualFilesHandler'); } catch (PDOException $e) { } } } }
/** * @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 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; }