Example #1
0
 /**
  * rename a file
  *
  * @param string $dir
  * @param string $oldname
  * @param string $newname
  * @return array
  */
 public function rename($dir, $oldname, $newname)
 {
     $result = array('success' => false, 'data' => NULL);
     // rename to non-existing folder is denied
     if (!$this->view->file_exists($dir)) {
         $result['data'] = array('message' => (string) $this->l10n->t('The target folder has been moved or deleted.', array($dir)), 'code' => 'targetnotfound');
         // rename to existing file is denied
     } else {
         if ($this->view->file_exists($dir . '/' . $newname)) {
             $result['data'] = array('message' => $this->l10n->t("The name %s is already used in the folder %s. Please choose a different name.", array($newname, $dir)));
         } else {
             if ($newname !== '.' and $this->view->rename($dir . '/' . $oldname, $dir . '/' . $newname)) {
                 // successful rename
                 $meta = $this->view->getFileInfo($dir . '/' . $newname);
                 $fileinfo = \OCA\Files\Helper::formatFileInfo($meta);
                 $result['success'] = true;
                 $result['data'] = $fileinfo;
             } else {
                 // rename failed
                 $result['data'] = array('message' => $this->l10n->t('%s could not be renamed', array($oldname)));
             }
         }
     }
     return $result;
 }
Example #2
0
 /**
  * rename a file
  *
  * @param string $dir
  * @param string $oldname
  * @param string $newname
  * @return array
  */
 public function rename($dir, $oldname, $newname)
 {
     $result = array('success' => false, 'data' => NULL);
     // rename to "/Shared" is denied
     if ($dir === '/' and $newname === 'Shared') {
         $result['data'] = array('message' => $this->l10n->t("Invalid folder name. Usage of 'Shared' is reserved."));
         // rename to existing file is denied
     } else {
         if ($this->view->file_exists($dir . '/' . $newname)) {
             $result['data'] = array('message' => $this->l10n->t("The name %s is already used in the folder %s. Please choose a different name.", array($newname, $dir)));
         } else {
             if ($newname !== '.' and !($dir === '/' and $oldname === 'Shared') and $this->view->rename($dir . '/' . $oldname, $dir . '/' . $newname)) {
                 // successful rename
                 $meta = $this->view->getFileInfo($dir . '/' . $newname);
                 if ($meta['mimetype'] === 'httpd/unix-directory') {
                     $meta['type'] = 'dir';
                 } else {
                     $meta['type'] = 'file';
                 }
                 $fileinfo = array('id' => $meta['fileid'], 'mime' => $meta['mimetype'], 'size' => $meta['size'], 'etag' => $meta['etag'], 'directory' => $dir, 'name' => $newname, 'isPreviewAvailable' => \OC::$server->getPreviewManager()->isMimeSupported($meta['mimetype']), 'icon' => \OCA\Files\Helper::determineIcon($meta));
                 $result['success'] = true;
                 $result['data'] = $fileinfo;
             } else {
                 // rename failed
                 $result['data'] = array('message' => $this->l10n->t('%s could not be renamed', array($oldname)));
             }
         }
     }
     return $result;
 }
Example #3
0
 public function testGetFilesByTagMultiple()
 {
     $tagName = 'MyTagName';
     $fileInfo1 = new FileInfo('/root.txt', $this->getMockBuilder('\\OC\\Files\\Storage\\Storage')->disableOriginalConstructor()->getMock(), '/var/www/root.txt', ['mtime' => 55, 'mimetype' => 'application/pdf', 'size' => 1234, 'etag' => 'MyEtag'], $this->getMockBuilder('\\OCP\\Files\\Mount\\IMountPoint')->disableOriginalConstructor()->getMock());
     $fileInfo2 = new FileInfo('/root.txt', $this->getMockBuilder('\\OC\\Files\\Storage\\Storage')->disableOriginalConstructor()->getMock(), '/var/www/some/sub.txt', ['mtime' => 999, 'mimetype' => 'application/binary', 'size' => 9876, 'etag' => 'SubEtag'], $this->getMockBuilder('\\OCP\\Files\\Mount\\IMountPoint')->disableOriginalConstructor()->getMock());
     $this->tagService->expects($this->once())->method('getFilesByTag')->with($this->equalTo([$tagName]))->will($this->returnValue([$fileInfo1, $fileInfo2]));
     $expected = new DataResponse(['files' => [['id' => null, 'parentId' => null, 'date' => \OCP\Util::formatDate(55), 'mtime' => 55000, 'icon' => \OCA\Files\Helper::determineIcon($fileInfo1), 'name' => 'root.txt', 'permissions' => null, 'mimetype' => 'application/pdf', 'size' => 1234, 'type' => 'file', 'etag' => 'MyEtag', 'path' => '/', 'tags' => [['MyTagName']]], ['id' => null, 'parentId' => null, 'date' => \OCP\Util::formatDate(999), 'mtime' => 999000, 'icon' => \OCA\Files\Helper::determineIcon($fileInfo2), 'name' => 'root.txt', 'permissions' => null, 'mimetype' => 'application/binary', 'size' => 9876, 'type' => 'file', 'etag' => 'SubEtag', 'path' => '/', 'tags' => [['MyTagName']]]]]);
     $this->assertEquals($expected, $this->apiController->getFilesByTag([$tagName]));
 }
Example #4
0
 /**
  * @dataProvider sortDataProvider
  */
 public function testSortByName($sort, $sortDescending, $expectedOrder)
 {
     $files = self::getTestFileList();
     $files = \OCA\Files\Helper::sortFiles($files, $sort, $sortDescending);
     $fileNames = array();
     foreach ($files as $fileInfo) {
         $fileNames[] = $fileInfo->getName();
     }
     $this->assertEquals($expectedOrder, $fileNames);
 }
Example #5
0
 /**
  * Retrieves the contents of a trash bin directory.
  * @param string $dir path to the directory inside the trashbin
  * or empty to retrieve the root of the trashbin
  * @return array of files
  */
 public static function getTrashFiles($dir)
 {
     $result = array();
     $user = \OCP\User::getUser();
     if ($dir && $dir !== '/') {
         $view = new \OC_Filesystemview('/' . $user . '/files_trashbin/files');
         $dirContent = $view->opendir($dir);
         if ($dirContent === false) {
             return null;
         }
         if (is_resource($dirContent)) {
             while (($entryName = readdir($dirContent)) !== false) {
                 if (!\OC\Files\Filesystem::isIgnoredDir($entryName)) {
                     $pos = strpos($dir . '/', '/', 1);
                     $tmp = substr($dir, 0, $pos);
                     $pos = strrpos($tmp, '.d');
                     $timestamp = substr($tmp, $pos + 2);
                     $result[] = array('id' => $entryName, 'timestamp' => $timestamp, 'mime' => $view->getMimeType($dir . '/' . $entryName), 'type' => $view->is_dir($dir . '/' . $entryName) ? 'dir' : 'file', 'location' => $dir);
                 }
             }
             closedir($dirContent);
         }
     } else {
         $query = \OC_DB::prepare('SELECT `id`,`location`,`timestamp`,`type`,`mime` FROM `*PREFIX*files_trash` WHERE `user` = ?');
         $result = $query->execute(array($user))->fetchAll();
     }
     $files = array();
     $id = 0;
     foreach ($result as $r) {
         $i = array();
         $i['id'] = $id++;
         $i['name'] = $r['id'];
         $i['date'] = \OCP\Util::formatDate($r['timestamp']);
         $i['timestamp'] = $r['timestamp'];
         $i['etag'] = $i['timestamp'];
         // dummy etag
         $i['mimetype'] = $r['mime'];
         $i['type'] = $r['type'];
         if ($i['type'] === 'file') {
             $fileinfo = pathinfo($r['id']);
             $i['basename'] = $fileinfo['filename'];
             $i['extension'] = isset($fileinfo['extension']) ? '.' . $fileinfo['extension'] : '';
         }
         $i['directory'] = $r['location'];
         if ($i['directory'] === '/') {
             $i['directory'] = '';
         }
         $i['permissions'] = \OCP\PERMISSION_READ;
         $i['isPreviewAvailable'] = \OC::$server->getPreviewManager()->isMimeSupported($r['mime']);
         $i['icon'] = \OCA\Files\Helper::determineIcon($i);
         $files[] = $i;
     }
     usort($files, array('\\OCA\\Files\\Helper', 'fileCmp'));
     return $files;
 }
Example #6
0
function determineIcon($file, $sharingRoot, $sharingToken)
{
    // for folders we simply reuse the files logic
    if ($file['type'] == 'dir') {
        return \OCA\Files\Helper::determineIcon($file);
    }
    $relativePath = substr($file['path'], 6);
    $relativePath = substr($relativePath, strlen($sharingRoot));
    if ($file['isPreviewAvailable']) {
        return OCP\publicPreview_icon($relativePath, $sharingToken) . '&c=' . $file['etag'];
    }
    return OCP\mimetype_icon($file['mimetype']);
}
Example #7
0
/**
 * @param \OCP\Files\FileInfo $dir
 * @param \OC\Files\View $view
 * @return array
 */
function getChildInfo($dir, $view)
{
    $children = $view->getDirectoryContent($dir->getPath());
    $result = array();
    foreach ($children as $child) {
        $formated = \OCA\Files\Helper::formatFileInfo($child);
        if ($child->getType() === 'dir') {
            $formated['children'] = getChildInfo($child, $view);
        }
        $formated['mtime'] = $formated['mtime'] / 1000;
        $result[] = $formated;
    }
    return $result;
}
Example #8
0
 /**
  * Format file infos for JSON
  * @param \OCP\Files\FileInfo[] $fileInfos file infos
  */
 public static function formatFileInfos($fileInfos)
 {
     $files = array();
     $id = 0;
     foreach ($fileInfos as $i) {
         $entry = \OCA\Files\Helper::formatFileInfo($i);
         $entry['id'] = $id++;
         $entry['etag'] = $entry['mtime'];
         // add fake etag, it is only needed to identify the preview image
         $entry['permissions'] = \OCP\Constants::PERMISSION_READ;
         $files[] = $entry;
     }
     return $files;
 }
Example #9
0
 /**
  * Format file infos for JSON
  * @param \OCP\Files\FileInfo[] $fileInfos file infos
  */
 public static function formatFileInfos($fileInfos)
 {
     $files = array();
     $id = 0;
     foreach ($fileInfos as $i) {
         $entry = \OCA\Files\Helper::formatFileInfo($i);
         $entry['id'] = $id++;
         $entry['etag'] = $entry['mtime'];
         // add fake etag, it is only needed to identify the preview image
         $entry['permissions'] = \OCP\Constants::PERMISSION_READ;
         if (\OCP\App::isEnabled('files_encryption')) {
             $entry['isPreviewAvailable'] = false;
         }
         $files[] = $entry;
     }
     return $files;
 }
Example #10
0
 /**
  * rename a file
  *
  * @param string $dir
  * @param string $oldname
  * @param string $newname
  * @return array
  */
 public function rename($dir, $oldname, $newname)
 {
     $result = array('success' => false, 'data' => NULL);
     try {
         // check if the new name is conform to file name restrictions
         $this->view->verifyPath($dir, $newname);
     } catch (\OCP\Files\InvalidPathException $ex) {
         $result['data'] = array('message' => $this->l10n->t($ex->getMessage()), 'code' => 'invalidname');
         return $result;
     }
     $normalizedOldPath = \OC\Files\Filesystem::normalizePath($dir . '/' . $oldname);
     $normalizedNewPath = \OC\Files\Filesystem::normalizePath($dir . '/' . $newname);
     // rename to non-existing folder is denied
     if (!$this->view->file_exists($normalizedOldPath)) {
         $result['data'] = array('message' => $this->l10n->t('%s could not be renamed as it has been deleted', array($oldname)), 'code' => 'sourcenotfound', 'oldname' => $oldname, 'newname' => $newname);
     } else {
         if (!$this->view->file_exists($dir)) {
             $result['data'] = array('message' => (string) $this->l10n->t('The target folder has been moved or deleted.', array($dir)), 'code' => 'targetnotfound');
             // rename to existing file is denied
         } else {
             if ($this->view->file_exists($normalizedNewPath)) {
                 $result['data'] = array('message' => $this->l10n->t("The name %s is already used in the folder %s. Please choose a different name.", array($newname, $dir)));
             } else {
                 if ($newname !== '.' and $this->view->rename($normalizedOldPath, $normalizedNewPath)) {
                     // successful rename
                     $meta = $this->view->getFileInfo($normalizedNewPath);
                     $meta = \OCA\Files\Helper::populateTags(array($meta));
                     $fileInfo = \OCA\Files\Helper::formatFileInfo(current($meta));
                     $fileInfo['path'] = dirname($normalizedNewPath);
                     $result['success'] = true;
                     $result['data'] = $fileInfo;
                 } else {
                     // rename failed
                     $result['data'] = array('message' => $this->l10n->t('%s could not be renamed', array($oldname)));
                 }
             }
         }
     }
     return $result;
 }
Example #11
0
 /**
  * Retrieves the contents of the given directory and
  * returns it as a sorted array.
  * @param string $dir path to the directory
  * @return array of files
  */
 public static function getFiles($dir)
 {
     $content = \OC\Files\Filesystem::getDirectoryContent($dir);
     $files = array();
     foreach ($content as $i) {
         $i['date'] = \OCP\Util::formatDate($i['mtime']);
         if ($i['type'] === 'file') {
             $fileinfo = pathinfo($i['name']);
             $i['basename'] = $fileinfo['filename'];
             if (!empty($fileinfo['extension'])) {
                 $i['extension'] = '.' . $fileinfo['extension'];
             } else {
                 $i['extension'] = '';
             }
         }
         $i['directory'] = $dir;
         $i['isPreviewAvailable'] = \OC::$server->getPreviewManager()->isMimeSupported($i['mimetype']);
         $i['icon'] = \OCA\Files\Helper::determineIcon($i);
         $files[] = $i;
     }
     usort($files, array('\\OCA\\Files\\Helper', 'fileCmp'));
     return $files;
 }
Example #12
0
 /**
  * Formats the file info to be returned as JSON to the client.
  *
  * @param \OCP\Files\FileInfo $i
  * @return array formatted file info
  */
 public static function formatFileInfo(FileInfo $i)
 {
     $entry = parent::formatFileInfo($i);
     preg_match('/(?<container>project-\\d+)/', $i->getPath(), $container);
     preg_match('/(?<target>task-(?<targetId>\\d+))/', $i->getPath(), $task);
     preg_match('/(?<target>issue-(?<targetId>\\d+))/', $i->getPath(), $issue);
     if (!is_null($container)) {
         if (isset($_SESSION['targetType'])) {
             $entry['container'] = $_SESSION['targetType'];
         }
         $entry['path'] .= PageController::PROJECTKIT_PREFIX . DIRECTORY_SEPARATOR . $container[0] . DIRECTORY_SEPARATOR;
         if (!empty($task)) {
             $entry['path'] .= $task['target'];
             $entry['targetType'] = TargetType::TASK;
             $entry['targetId'] = $task['targetId'];
         }
         if (!empty($issue)) {
             $entry['path'] .= $issue['target'];
             $entry['targetType'] = TargetType::ISSUE;
             $entry['targetId'] = $issue['targetId'];
         }
     }
     return $entry;
 }
Example #13
0
 /**
  * @param OCP\Files\FileInfo[] $files
  * @param string $trashRoot
  * @param integer $expireDate
  */
 private function manipulateDeleteTime($files, $trashRoot, $expireDate)
 {
     $counter = 0;
     foreach ($files as &$file) {
         // modify every second file
         $counter = ($counter + 1) % 2;
         if ($counter === 1) {
             $source = $trashRoot . '/files/' . $file['name'] . '.d' . $file['mtime'];
             $target = \OC\Files\Filesystem::normalizePath($trashRoot . '/files/' . $file['name'] . '.d' . $expireDate);
             $this->rootView->rename($source, $target);
             $file['mtime'] = $expireDate;
         }
     }
     return \OCA\Files\Helper::sortFiles($files, 'mtime');
 }
 /**
  * @NoAdminRequired
  */
 public function create()
 {
     $mimetype = $this->request->post['mimetype'];
     $filename = $this->request->post['filename'];
     $dir = $this->request->post['dir'];
     $view = new View('/' . $this->uid . '/files');
     if (!$dir) {
         $dir = '/';
     }
     $basename = $this->l10n->t('New Document.odt');
     switch ($mimetype) {
         case 'application/vnd.oasis.opendocument.spreadsheet':
             $basename = $this->l10n->t('New Spreadsheet.ods');
             break;
         case 'application/vnd.oasis.opendocument.presentation':
             $basename = $this->l10n->t('New Presentation.odp');
             break;
         default:
             // to be safe
             $mimetype = 'application/vnd.oasis.opendocument.text';
             break;
     }
     if (!$filename) {
         $path = Helper::getNewFileName($view, $dir . '/' . $basename);
     } else {
         $path = $dir . '/' . $filename;
     }
     $content = '';
     if (class_exists('\\OC\\Files\\Type\\TemplateManager')) {
         $manager = \OC_Helper::getFileTemplateManager();
         $content = $manager->getTemplate($mimetype);
     }
     if (!$content) {
         $content = file_get_contents(dirname(__DIR__) . self::ODT_TEMPLATE_PATH);
     }
     $discovery_parsed = null;
     try {
         $discovery = $this->getDiscovery();
         $loadEntities = libxml_disable_entity_loader(true);
         $discovery_parsed = simplexml_load_string($discovery);
         libxml_disable_entity_loader($loadEntities);
         if ($discovery_parsed === false) {
             $this->cache->remove('discovery.xml');
             $wopiRemote = $this->appConfig->getAppValue('wopi_url');
             return array('status' => 'error', 'message' => $this->l10n->t('Collabora Online: discovery.xml from "%s" is not a well-formed XML string.', array($wopiRemote)), 'hint' => $this->l10n->t('Please contact the "%s" administrator.', array($wopiRemote)));
         }
     } catch (ResponseException $e) {
         return array('status' => 'error', 'message' => $e->getMessage(), 'hint' => $e->getHint());
     }
     if ($content && $view->file_put_contents($path, $content)) {
         $info = $view->getFileInfo($path);
         $ret = $this->getWopiSrcUrl($discovery_parsed, $mimetype);
         $response = array('status' => 'success', 'fileid' => $info['fileid'], 'urlsrc' => $ret['urlsrc'], 'action' => $ret['action'], 'lolang' => $this->settings->getUserValue($this->uid, 'core', 'lang', 'en'), 'data' => \OCA\Files\Helper::formatFileInfo($info));
     } else {
         $response = array('status' => 'error', 'message' => (string) $this->l10n->t('Can\'t create document'));
     }
     return $response;
 }
Example #15
0
                        $data['directory'] = $returnedDir;
                        $result[] = $data;
                    }
                } else {
                    $error = $l->t('Upload failed. Could not find uploaded file');
                }
            } catch (Exception $ex) {
                $error = $ex->getMessage();
            }
        } else {
            // file already exists
            $meta = \OC\Files\Filesystem::getFileInfo($target);
            if ($meta === false) {
                $error = $l->t('Upload failed. Could not get file info.');
            } else {
                $data = \OCA\Files\Helper::formatFileInfo($meta);
                $data['permissions'] = $data['permissions'] & $allowedPermissions;
                $data['status'] = 'existserror';
                $data['originalname'] = $files['tmp_name'][$i];
                $data['uploadMaxFilesize'] = $maxUploadFileSize;
                $data['maxHumanFilesize'] = $maxHumanFileSize;
                $data['permissions'] = $meta['permissions'] & $allowedPermissions;
                $data['directory'] = $returnedDir;
                $result[] = $data;
            }
        }
    }
} else {
    $error = $l->t('Invalid directory.');
}
if ($error === false) {
Example #16
0
 /**
  * Formats the file info to be returned as JSON to the client.
  *
  * @param \OCP\Files\FileInfo $i
  * @return array formatted file info
  */
 public static function formatFileInfo(FileInfo $i)
 {
     $entry = array();
     $entry['id'] = $i['fileid'];
     $entry['parentId'] = $i['parent'];
     $entry['date'] = \OCP\Util::formatDate($i['mtime']);
     $entry['mtime'] = $i['mtime'] * 1000;
     // only pick out the needed attributes
     $entry['icon'] = \OCA\Files\Helper::determineIcon($i);
     if (\OC::$server->getPreviewManager()->isAvailable($i)) {
         $entry['isPreviewAvailable'] = true;
     }
     $entry['name'] = $i->getName();
     $entry['permissions'] = $i['permissions'];
     $entry['mimetype'] = $i['mimetype'];
     $entry['size'] = $i['size'];
     $entry['type'] = $i['type'];
     $entry['etag'] = $i['etag'];
     if (isset($i['tags'])) {
         $entry['tags'] = $i['tags'];
     }
     if (isset($i['displayname_owner'])) {
         $entry['shareOwner'] = $i['displayname_owner'];
     }
     if (isset($i['is_share_mount_point'])) {
         $entry['isShareMountPoint'] = $i['is_share_mount_point'];
     }
     $mountType = null;
     if ($i->isShared()) {
         $mountType = 'shared';
     } else {
         if ($i->isMounted()) {
             $mountType = 'external';
         }
     }
     if ($mountType !== null) {
         if ($i->getInternalPath() === '') {
             $mountType .= '-root';
         }
         $entry['mountType'] = $mountType;
     }
     if (isset($i['extraData'])) {
         $entry['extraData'] = $i['extraData'];
     }
     return $entry;
 }
Example #17
0
\OC::$server->getSession()->close();
// Get data
$dir = stripslashes($_POST["dir"]);
$allFiles = isset($_POST["allfiles"]) ? $_POST["allfiles"] : false;
// delete all files in dir ?
if ($allFiles === 'true') {
    $files = array();
    $fileList = \OC\Files\Filesystem::getDirectoryContent($dir);
    foreach ($fileList as $fileInfo) {
        $files[] = $fileInfo['name'];
    }
} else {
    $files = isset($_POST["file"]) ? $_POST["file"] : $_POST["files"];
    $files = json_decode($files);
}
$filesWithError = '';
$success = true;
//Now delete
foreach ($files as $file) {
    if (\OC\Files\Filesystem::file_exists($dir . '/' . $file) && !\OC\Files\Filesystem::unlink($dir . '/' . $file)) {
        $filesWithError .= $file . "\n";
        $success = false;
    }
}
// get array with updated storage stats (e.g. max file size) after upload
$storageStats = \OCA\Files\Helper::buildFileStorageStatistics($dir);
if ($success) {
    OCP\JSON::success(array("data" => array_merge(array("dir" => $dir, "files" => $files), $storageStats)));
} else {
    OCP\JSON::error(array("data" => array_merge(array("message" => "Could not delete:\n" . $filesWithError), $storageStats)));
}
Example #18
0
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  * @return TemplateResponse
  */
 public function read($id)
 {
     $attachements_info = [];
     $message = $this->connect->messages()->getById((int) $id);
     $parent = $this->connect->messages()->getById((int) $message['rid']);
     if (!empty($message['attachements'])) {
         $attach = [];
         try {
             $attach = json_decode($message['attachements'], true);
         } catch (\Exception $e) {
             var_dump('Exception: ' . $e->getMessage());
         }
         foreach ($attach as $at) {
             $file = $this->connect->files()->getInfoById($at);
             $fileInfo = false;
             $filePath = str_replace('files/', '', $file['path']);
             try {
                 $fileInfo = \OC\Files\Filesystem::getFileInfo($filePath);
             } catch (\Exception $e) {
             }
             //var_dump($file);
             if (!$fileInfo) {
                 $itemSource = \OCP\Share::getItemSharedWithBySource('file', $at);
                 if (is_array($itemSource) && !empty($itemSource)) {
                     $fileInfo = \OC\Files\Filesystem::getFileInfo($itemSource['file_target']);
                     $filePath = $itemSource['file_target'];
                 }
             }
             if (!$fileInfo) {
                 continue;
             }
             $icon = '/core/img/filetypes/image.svg';
             // \OCA\Files\Helper::determineIcon($fileInfo);
             $attachements_info[] = ['preview' => $icon, 'link' => "/remote.php/webdav/{$filePath}", 'file' => $file, 'info' => \OCA\Files\Helper::formatFileInfo($fileInfo)];
         }
     }
     Helper::cookies('goto_message', $message['rid'] == 0 ? $message['id'] : $parent['id'], 0, '/');
     $data = ['menu' => 'all', 'content' => 'read', 'message' => $message, 'parent' => $parent, 'attachements_info' => $attachements_info];
     return new TemplateResponse($this->appName, 'main', $data);
 }
Example #19
0
$data = \OCA\Files_Sharing\Helper::setupFromToken($token, $relativePath, $password);
$linkItem = $data['linkItem'];
// Load the files
$dir = $data['realPath'];
$dir = \OC\Files\Filesystem::normalizePath($dir);
if (!\OC\Files\Filesystem::is_dir($dir . '/')) {
    \OC_Response::setStatus(\OC_Response::STATUS_NOT_FOUND);
    \OCP\JSON::error(array('success' => false));
    exit;
}
$data = array();
// make filelist
$files = \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection);
$formattedFiles = array();
foreach ($files as $file) {
    $entry = \OCA\Files\Helper::formatFileInfo($file);
    unset($entry['directory']);
    // for now
    $entry['permissions'] = \OCP\PERMISSION_READ;
    $formattedFiles[] = $entry;
}
$data['directory'] = $relativePath;
$data['files'] = $formattedFiles;
$data['dirToken'] = $linkItem['token'];
$permissions = $linkItem['permissions'];
// if globally disabled
if (OC_Appconfig::getValue('core', 'shareapi_allow_public_upload', 'yes') === 'no') {
    // only allow reading
    $permissions = \OCP\PERMISSION_READ;
}
$data['permissions'] = $permissions;
Example #20
0
OCP\JSON::checkLoggedIn();
\OC::$session->close();
$l = OC_L10N::get('files');
// Load the files
$dir = isset($_GET['dir']) ? $_GET['dir'] : '';
$dir = \OC\Files\Filesystem::normalizePath($dir);
try {
    $dirInfo = \OC\Files\Filesystem::getFileInfo($dir);
    if (!$dirInfo || !$dirInfo->getType() === 'dir') {
        header("HTTP/1.0 404 Not Found");
        exit;
    }
    $data = array();
    $baseUrl = OCP\Util::linkTo('files', 'index.php') . '?dir=';
    $permissions = $dirInfo->getPermissions();
    $sortAttribute = isset($_GET['sort']) ? $_GET['sort'] : 'name';
    $sortDirection = isset($_GET['sortdirection']) ? $_GET['sortdirection'] === 'desc' : false;
    // make filelist
    $files = \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection);
    $data['directory'] = $dir;
    $data['files'] = \OCA\Files\Helper::formatFileInfos($files);
    $data['permissions'] = $permissions;
    OCP\JSON::success(array('data' => $data));
} catch (\OCP\Files\StorageNotAvailableException $e) {
    OCP\JSON::error(array('data' => array('exception' => '\\OCP\\Files\\StorageNotAvailableException', 'message' => $l->t('Storage not available'))));
} catch (\OCP\Files\StorageInvalidException $e) {
    OCP\JSON::error(array('data' => array('exception' => '\\OCP\\Files\\StorageInvalidException', 'message' => $l->t('Storage invalid'))));
} catch (\Exception $e) {
    OCP\JSON::error(array('data' => array('exception' => '\\Exception', 'message' => $l->t('Unknown error'))));
}
Example #21
0
// Init owncloud
OCP\JSON::checkLoggedIn();
// Load the files
$dir = isset($_GET['dir']) ? (string) $_GET['dir'] : '';
$dir = \OC\Files\Filesystem::normalizePath($dir);
if (!\OC\Files\Filesystem::is_dir($dir . '/')) {
    header("HTTP/1.0 404 Not Found");
    exit;
}
$doBreadcrumb = isset($_GET['breadcrumb']);
$data = array();
$baseUrl = OCP\Util::linkTo('files', 'index.php') . '?dir=';
$permissions = \OCA\Files\Helper::getDirPermissions($dir);
// Make breadcrumb
if ($doBreadcrumb) {
    $breadcrumb = \OCA\Files\Helper::makeBreadcrumb($dir);
    $breadcrumbNav = new OCP\Template('files', 'part.breadcrumb', '');
    $breadcrumbNav->assign('breadcrumb', $breadcrumb, false);
    $breadcrumbNav->assign('baseURL', $baseUrl);
    $data['breadcrumb'] = $breadcrumbNav->fetchPage();
}
// make filelist
$files = \OCA\Files\Helper::getFiles($dir);
$list = new OCP\Template("files", "part.list", "");
$list->assign('files', $files, false);
$list->assign('baseURL', $baseUrl, false);
$list->assign('downloadURL', OCP\Util::linkToRoute('download', array('file' => '/')));
$list->assign('isPublic', false);
$data['files'] = $list->fetchPage();
$data['permissions'] = $permissions;
OCP\JSON::success(array('data' => $data));
Example #22
0
    }
    $freeSpace = \OC\Files\Filesystem::free_space($dir);
    $needUpgrade = false;
}
// Make breadcrumb
$breadcrumb = \OCA\Files\Helper::makeBreadcrumb($dir);
// make breadcrumb und filelist markup
$list = new OCP\Template('files', 'part.list', '');
$list->assign('files', $files);
$list->assign('baseURL', OCP\Util::linkTo('files', 'index.php') . '?dir=');
$list->assign('downloadURL', OCP\Util::linkToRoute('download', array('file' => '/')));
$list->assign('isPublic', false);
$breadcrumbNav = new OCP\Template('files', 'part.breadcrumb', '');
$breadcrumbNav->assign('breadcrumb', $breadcrumb);
$breadcrumbNav->assign('baseURL', OCP\Util::linkTo('files', 'index.php') . '?dir=');
$permissions = \OCA\Files\Helper::getDirPermissions($dir);
if ($needUpgrade) {
    OCP\Util::addscript('files', 'upgrade');
    $tmpl = new OCP\Template('files', 'upgrade', 'user');
    $tmpl->printPage();
} else {
    // information about storage capacities
    $storageInfo = OC_Helper::getStorageInfo($dir);
    $maxUploadFilesize = OCP\Util::maxUploadFilesize($dir);
    $publicUploadEnabled = \OC_Appconfig::getValue('core', 'shareapi_allow_public_upload', 'yes');
    // if the encryption app is disabled, than everything is fine (INIT_SUCCESSFUL status code)
    $encryptionInitStatus = 2;
    if (OC_App::isEnabled('files_encryption')) {
        $session = new \OCA\Encryption\Session(new \OC\Files\View('/'));
        $encryptionInitStatus = $session->getInitialized();
    }
Example #23
0
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  */
 public function UploadFiles()
 {
     \OCP\JSON::setContentTypeHeader('text/plain');
     if (!$this->AllowProtocolBT && !\OC_User::isAdminUser($this->CurrentUID)) {
         return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('You are not allowed to use the BitTorrent protocol')));
     }
     if (!isset($_FILES['files'])) {
         return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('Error while uploading torrent file')));
     } else {
         if (!isset($_FILES['files']['name'][0])) {
             throw new \Exception('Unable to find the uploaded file');
         }
         $Target = rtrim($this->TorrentsFolder, '/') . '/' . $_FILES['files']['name'][0];
         try {
             if (is_uploaded_file($_FILES['files']['tmp_name'][0]) && \OC\Files\Filesystem::fromTmpFile($_FILES['files']['tmp_name'][0], $Target)) {
                 $StorageStats = \OCA\Files\Helper::buildFileStorageStatistics($this->TorrentsFolder);
                 if (\OC\Files\Filesystem::getFileInfo($Target) !== false) {
                     return new JSONResponse(array('ERROR' => false, 'MESSAGE' => (string) $this->L10N->t('Upload OK')));
                 }
             } else {
                 return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('Error while uploading torrent file')));
             }
         } catch (Exception $E) {
             return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage()));
         }
     }
 }
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  * @SSOCORS
  */
 public function upload($dir = '/')
 {
     \OC::$server->getSession()->close();
     // Firefox and Konqueror tries to download application/json for me.  --Arthur
     \OCP\JSON::setContentTypeHeader('text/plain');
     // If a directory token is sent along check if public upload is permitted.
     // If not, check the login.
     // If no token is sent along, rely on login only
     $allowedPermissions = \OCP\Constants::PERMISSION_ALL;
     $errorCode = null;
     if (\OC\Files\Filesystem::file_exists($dir) === false) {
         return new DataResponse(array('data' => array_merge(array('message' => 'Invalid directory.')), 'status' => 'error'));
     }
     // get array with current storage stats (e.g. max file size)
     $storageStats = \OCA\Files\Helper::buildFileStorageStatistics($dir);
     $files = $this->request->getUploadedFile('files');
     if (!isset($files)) {
         return new DataResponse(array('data' => array_merge(array('message' => 'No file was uploaded. Unknown error'), $storageStats), 'status' => 'error'));
     }
     foreach ($files['error'] as $error) {
         if ($error != 0) {
             $errors = array(UPLOAD_ERR_OK => 'There is no error, the file uploaded with success', UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini: ' . ini_get('upload_max_filesize'), UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded', UPLOAD_ERR_NO_FILE => 'No file was uploaded', UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder', UPLOAD_ERR_CANT_WRITE => 'Failed to write to disk');
             $errorMessage = $errors[$error];
             \OC::$server->getLogger()->alert("Upload error: {$error} - {$errorMessage}", array('app' => 'files'));
             return new DataResponse(array('data' => array_merge(array('message' => $errorMessage), $storageStats), 'status' => 'error'));
         }
     }
     $error = false;
     $maxUploadFileSize = $storageStats['uploadMaxFilesize'];
     $maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize);
     $totalSize = 0;
     foreach ($files['size'] as $size) {
         $totalSize += $size;
     }
     if ($maxUploadFileSize >= 0 and $totalSize > $maxUploadFileSize) {
         return new DataResponse(array('data' => array('message' => 'Not enough storage available', 'uploadMaxFilesize' => $maxUploadFileSize, '   maxHumanFilesize' => $maxHumanFileSize), 'status' => 'error'));
     }
     $result = array();
     $fileCount = count($files['name']);
     for ($i = 0; $i < $fileCount; $i++) {
         // target directory for when uploading folders
         $relativePath = '';
         $target = \OC\Files\Filesystem::normalizePath($dir . $relativePath . '/' . $files['name'][$i]);
         // relative dir to return to the client
         if (isset($publicDirectory)) {
             // path relative to the public root
             $returnedDir = $publicDirectory . $relativePath;
         } else {
             // full path
             $returnedDir = $dir . $relativePath;
         }
         $returnedDir = \OC\Files\Filesystem::normalizePath($returnedDir);
         $exists = \OC\Files\Filesystem::file_exists($target);
         if ($exists) {
             $target = \OCP\Files::buildNotExistingFileName($dir . $relativePath, $files['name'][$i]);
         }
         try {
             if (is_uploaded_file($files['tmp_name'][$i]) and \OC\Files\Filesystem::fromTmpFile($files['tmp_name'][$i], $target)) {
                 // updated max file size after upload
                 $storageStats = \OCA\Files\Helper::buildFileStorageStatistics($dir);
                 $meta = \OC\Files\Filesystem::getFileInfo($target);
                 if ($meta === false) {
                     $error = 'The target folder has been moved or deleted.';
                     $errorCode = 'targetnotfound';
                 } else {
                     $data = \OCA\Files\Helper::formatFileInfo($meta);
                     $data['originalname'] = $files['name'][$i];
                     $data['uploadMaxFilesize'] = $maxUploadFileSize;
                     $data['maxHumanFilesize'] = $maxHumanFileSize;
                     $data['permissions'] = $meta['permissions'] & $allowedPermissions;
                     $data['directory'] = $returnedDir;
                     $result[] = $data;
                 }
             } else {
                 $error = 'Upload failed. Could not find uploaded file';
             }
         } catch (Exception $ex) {
             $error = $ex->getMessage();
         }
     }
     if ($error === false) {
         $result = \OCP\JSON::encode($result);
         return new DataResponse(array('data' => $result, 'status' => 'success'));
     } else {
         return new DataResponse(array('data' => array_merge(array('message' => $error, 'code' => $errorCode), $storageStats), 'status' => 'error'));
     }
 }
Example #25
0
    $result['data'] = array('message' => (string) $l10n->t('The target folder has been moved or deleted.'), 'code' => 'targetnotfound');
    OCP\JSON::error($result);
    exit;
}
$target = $dir . '/' . $fileName;
if (\OC\Files\Filesystem::file_exists($target)) {
    $result['data'] = array('message' => (string) $l10n->t('The name %s is already used in the folder %s. Please choose a different name.', array($fileName, $dir)));
    OCP\JSON::error($result);
    exit;
}
$success = false;
$templateManager = OC_Helper::getFileTemplateManager();
$mimeType = OC_Helper::getMimetypeDetector()->detectPath($target);
$content = $templateManager->getTemplate($mimeType);
try {
    if ($content) {
        $success = \OC\Files\Filesystem::file_put_contents($target, $content);
    } else {
        $success = \OC\Files\Filesystem::touch($target);
    }
} catch (\Exception $e) {
    $result = ['success' => false, 'data' => ['message' => $e->getMessage()]];
    OCP\JSON::error($result);
    exit;
}
if ($success) {
    $meta = \OC\Files\Filesystem::getFileInfo($target);
    OCP\JSON::success(array('data' => \OCA\Files\Helper::formatFileInfo($meta)));
    return;
}
OCP\JSON::error(array('data' => array('message' => $l10n->t('Error when creating the file'))));
Example #26
0
 /**
  * Returns a list of all files tagged with the given tag.
  *
  * @NoAdminRequired
  *
  * @param array|string $tagName tag name to filter by
  * @return DataResponse
  */
 public function getFilesByTag($tagName)
 {
     $files = array();
     $fileInfos = $this->tagService->getFilesByTag($tagName);
     foreach ($fileInfos as &$fileInfo) {
         $file = \OCA\Files\Helper::formatFileInfo($fileInfo);
         $parts = explode('/', dirname($fileInfo->getPath()), 4);
         if (isset($parts[3])) {
             $file['path'] = '/' . $parts[3];
         } else {
             $file['path'] = '/';
         }
         $file['tags'] = [$tagName];
         $files[] = $file;
     }
     return new DataResponse(['files' => $files]);
 }
Example #27
0
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  */
 public function ListTorrentFiles()
 {
     \OCP\JSON::setContentTypeHeader('application/json');
     try {
         if (!\OC\Files\Filesystem::is_dir($this->TorrentsFolder)) {
             \OC\Files\Filesystem::mkdir($this->TorrentsFolder);
         }
         $this->TorrentsFolder = \OC\Files\Filesystem::normalizePath($this->TorrentsFolder);
         $Files = \OCA\Files\Helper::getFiles($this->TorrentsFolder, 'name', 'desc');
         $Files = \OCA\Files\Helper::formatFileInfos($Files);
         return new JSONResponse(array('ERROR' => false, 'FILES' => $Files));
     } catch (Exception $E) {
         return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage()));
     }
 }
Example #28
0
<?php

$dir = '/';
if (isset($_GET['dir'])) {
    $dir = $_GET['dir'];
}
OCP\JSON::checkLoggedIn();
\OC::$server->getSession()->close();
// send back json
OCP\JSON::success(array('data' => \OCA\Files\Helper::buildFileStorageStatistics($dir)));
Example #29
0
 public function getlogo()
 {
     $userfiles = \OCA\Files\Helper::getFiles('ProjectLogo');
     foreach ($userfiles as $f => $file) {
         $userfiles[$f] = \OCA\Files\Helper::formatFileInfo($file);
         $userfiles[$f]['mtime'] = $userfiles[$f]['mtime'] / 1000;
     }
     $params = ['user' => $this->userId, 'files' => $userfiles, 'error' => null, 'errorinfo' => ''];
     return new DataResponse($params);
 }
 public function getfolderfiles($folderid)
 {
     $files = $this->connect->files();
     $path = $files->getFolderPath($folderid, $this->userId);
     //$userfiles = \OCA\Files\Helper::getFiles('../'.$path);
     $userfiles = \OCA\Files\Helper::getFiles('/' . $path);
     foreach ($userfiles as $f => $file) {
         $userfiles[$f] = \OCA\Files\Helper::formatFileInfo($file);
         $userfiles[$f]['mtime'] = $userfiles[$f]['mtime'] / 1000;
     }
     $params = array('files' => $userfiles, 'folder' => $userfiles, 'requesttoken' => !\OC_Util::isCallRegistered() ? '' : \OC_Util::callRegister());
     $view = Helper::renderPartial($this->appName, 'api.folderfiles', $params);
     //$view = "User files!";
     $params = array('user' => $this->userId, 'files' => $userfiles, 'view' => $view, 'requesttoken' => !\OC_Util::isCallRegistered() ? '' : \OC_Util::callRegister());
     return new DataResponse($params);
 }