Esempio n. 1
0
 public static function CheckFilepath($FP)
 {
     if (\OC\Files\Filesystem::file_exists($FP)) {
         return true;
     }
     return false;
 }
Esempio n. 2
0
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  */
 public function Add()
 {
     \OCP\JSON::setContentTypeHeader('application/json');
     if (isset($_POST['FILE']) && strlen($_POST['FILE']) > 0 && Tools::CheckURL($_POST['FILE']) && isset($_POST['OPTIONS'])) {
         try {
             $Target = Tools::CleanString(substr($_POST['FILE'], strrpos($_POST['FILE'], '/') + 1));
             // If target file exists, create a new one
             if (\OC\Files\Filesystem::file_exists($this->DownloadsFolder . '/' . $Target)) {
                 $Target = time() . '_' . $Target;
             }
             // Create the target file if the downloader is Aria2
             if ($this->WhichDownloader == 0) {
                 \OC\Files\Filesystem::touch($this->DownloadsFolder . '/' . $Target);
             } else {
                 if (!\OC\Files\Filesystem::is_dir($this->DownloadsFolder)) {
                     \OC\Files\Filesystem::mkdir($this->DownloadsFolder);
                 }
             }
             // Build OPTIONS array
             $OPTIONS = array('dir' => $this->AbsoluteDownloadsFolder, 'out' => $Target, 'follow-torrent' => false);
             if (isset($_POST['OPTIONS']['FTPUser']) && strlen(trim($_POST['OPTIONS']['FTPUser'])) > 0 && isset($_POST['OPTIONS']['FTPPasswd']) && strlen(trim($_POST['OPTIONS']['FTPPasswd'])) > 0) {
                 $OPTIONS['ftp-user'] = $_POST['OPTIONS']['FTPUser'];
                 $OPTIONS['ftp-passwd'] = $_POST['OPTIONS']['FTPPasswd'];
             }
             if (isset($_POST['OPTIONS']['FTPPasv']) && strlen(trim($_POST['OPTIONS']['FTPPasv'])) > 0) {
                 $OPTIONS['ftp-pasv'] = strcmp($_POST['OPTIONS']['FTPPasv'], "true") == 0 ? true : false;
             }
             if (!$this->ProxyOnlyWithYTDL && !is_null($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) {
                 $OPTIONS['all-proxy'] = rtrim($this->ProxyAddress, '/') . ':' . $this->ProxyPort;
                 if (!is_null($this->ProxyUser) && !is_null($this->ProxyPasswd)) {
                     $OPTIONS['all-proxy-user'] = $this->ProxyUser;
                     $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd;
                 }
             }
             $AddURI = $this->WhichDownloader == 0 ? Aria2::AddUri(array($_POST['FILE']), array('Params' => $OPTIONS)) : CURL::AddUri($_POST['FILE'], $OPTIONS);
             if (isset($AddURI['result']) && !is_null($AddURI['result'])) {
                 $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES (?, ?, ?, ?, ?, ?)';
                 if ($this->DbType == 1) {
                     $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES (?, ?, ?, ?, ?, ?)';
                 }
                 $Query = \OCP\DB::prepare($SQL);
                 $Result = $Query->execute(array($this->CurrentUID, $AddURI['result'], $Target, strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), 1, time()));
                 sleep(1);
                 $Status = $this->WhichDownloader == 0 ? Aria2::TellStatus($AddURI['result']) : CURL::TellStatus($AddURI['result']);
                 $Progress = 0;
                 if ($Status['result']['totalLength'] > 0) {
                     $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength'];
                 }
                 $ProgressString = Tools::GetProgressString($Status['result']['completedLength'], $Status['result']['totalLength'], $Progress);
                 return new JSONResponse(array('ERROR' => false, 'MESSAGE' => (string) $this->L10N->t('Download started'), 'GID' => $AddURI['result'], 'PROGRESSVAL' => round($Progress * 100, 2) . '%', 'PROGRESS' => is_null($ProgressString) ? (string) $this->L10N->t('N/A') : $ProgressString, 'STATUS' => isset($Status['result']['status']) ? (string) $this->L10N->t(ucfirst($Status['result']['status'])) : (string) $this->L10N->t('N/A'), 'STATUSID' => Tools::GetDownloadStatusID($Status['result']['status']), 'SPEED' => isset($Status['result']['downloadSpeed']) ? Tools::FormatSizeUnits($Status['result']['downloadSpeed']) . '/s' : (string) $this->L10N->t('N/A'), 'FILENAME' => strlen($Target) > 40 ? substr($Target, 0, 40) . '...' : $Target, 'PROTO' => strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), 'ISTORRENT' => false));
             } else {
                 return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t($this->WhichDownloader == 0 ? 'Returned GID is null ! Is Aria2c running as a daemon ?' : 'An error occurred while running the CURL download')));
             }
         } catch (Exception $E) {
             return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage()));
         }
     } else {
         return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('Please check the URL you\'ve just provided')));
     }
 }
 /**
  * @NoAdminRequired
  *
  * @param string $path
  * @param string $pass
  */
 public function validatePath($path, $pass)
 {
     if (\OC\Files\Filesystem::file_exists($path)) {
         return "true";
     } else {
         return $path;
     }
 }
function thumb($path)
{
    $thumb_path = \OCP\Config::getSystemValue('datadirectory') . '/' . \OC_User::getUser() . '/reader';
    if (file_exists($thumb_path . $path)) {
        return new \OC_Image($thumb_path . $path);
    }
    if (!\OC\Files\Filesystem::file_exists($path)) {
        return false;
    }
}
Esempio n. 5
0
 /**
  * @brief remove all shares for a given file if the file was deleted
  *
  * @param string $path
  */
 private static function removeShare($path)
 {
     $fileSource = self::$toRemove[$path];
     if (!\OC\Files\Filesystem::file_exists($path)) {
         $query = \OC_DB::prepare('DELETE FROM `*PREFIX*share` WHERE `file_source`=?');
         try {
             \OC_DB::executeAudited($query, array($fileSource));
         } catch (\Exception $e) {
             \OCP\Util::writeLog('files_sharing', "can't remove share: " . $e->getMessage(), \OCP\Util::WARN);
         }
     }
     unset(self::$toRemove[$path]);
 }
 /**
  * @NoAdminRequired
  */
 public function savePersonal($savePath)
 {
     if (is_null($savePath)) {
         $savePath = '/';
     }
     $status = true;
     if (\OC\Files\Filesystem::file_exists($savePath) === false) {
         $status = \OC\Files\Filesystem::mkdir($savePath);
     }
     if ($status) {
         $this->appConfig->setUserValue($this->userId, 'save_path', $savePath);
         $response = array('status' => 'success', 'data' => array('message' => $this->l10n->t('Directory saved successfully.')));
     } else {
         $response = array('status' => 'error', 'data' => array('message' => $this->l10n->t('An error occurred while changing directory.')));
     }
     return $response;
 }
Esempio n. 7
0
 public function setUp()
 {
     parent::setUp();
     $this->userBackend = new \Test\Util\User\Dummy();
     \OC::$server->getUserManager()->registerBackend($this->userBackend);
     $this->ownerUid = $this->getUniqueID('owner_');
     $this->recipientUid = $this->getUniqueID('recipient_');
     $this->userBackend->createUser($this->ownerUid, '');
     $this->userBackend->createUser($this->recipientUid, '');
     $this->loginAsUser($this->ownerUid);
     Filesystem::mkdir('/foo');
     Filesystem::file_put_contents('/foo/bar.txt', 'asd');
     $fileId = Filesystem::getFileInfo('/foo/bar.txt')->getId();
     \OCP\Share::shareItem('file', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->recipientUid, 31);
     $this->loginAsUser($this->recipientUid);
     $this->assertTrue(Filesystem::file_exists('bar.txt'));
 }
Esempio n. 8
0
 public function __construct($AppName, IRequest $request, $UserId)
 {
     parent::__construct($AppName, $request);
     $this->userId = $UserId;
     $path = self::PROJECTKIT_PREFIX . DIRECTORY_SEPARATOR;
     if (isset($_GET['containerId'])) {
         $path .= self::PROJECT_PREFIX . (string) $_GET['containerId'] . DIRECTORY_SEPARATOR;
         if (isset($_GET['targetType']) && isset($_GET['targetId'])) {
             switch ($_GET['targetType']) {
                 case TargetType::TASK:
                     $path .= self::TASK_PREFIX;
                     break;
                 case TargetType::ISSUE:
                     $path .= self::ISSUE_PREFIX;
                     break;
                 default:
                     break;
             }
             $path .= (string) $_GET['targetId'] . DIRECTORY_SEPARATOR;
             $_SESSION['targetType'] = $_GET['targetType'];
         } elseif (!isset($_GET['targetType']) && !isset($_GET['targetId'])) {
             $_SESSION['targetType'] = TargetType::PROJECT;
         }
         //use session to save targetType
         $path = Filesystem::normalizePath($path);
         //Create folder for path
         if (!Filesystem::file_exists($path)) {
             try {
                 Filesystem::mkdir($path);
             } catch (\Exception $e) {
                 $result = ['success' => false, 'data' => ['message' => $e->getMessage()]];
                 \OCP\JSON::error($result);
                 exit;
             }
         }
         if (!isset($_GET['dir'])) {
             $params = array_merge($_GET, ["dir" => $path]);
             $url = $_SERVER['PHP_SELF'] . '?' . http_build_query($params);
             header('Location: ' . $url, true, 302);
             exit;
         }
     }
 }
Esempio n. 9
0
 /**
  * @medium
  */
 function testUnshareChildren()
 {
     $fileInfo2 = \OC\Files\Filesystem::getFileInfo($this->folder);
     $this->share(\OCP\Share::SHARE_TYPE_USER, $this->folder, self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2, \OCP\Constants::PERMISSION_ALL);
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     // one folder should be shared with the user
     $shares = $this->shareManager->getSharedWith(self::TEST_FILES_SHARING_API_USER2, \OCP\Share::SHARE_TYPE_USER);
     $this->assertCount(1, $shares);
     // move shared folder to 'localDir'
     \OC\Files\Filesystem::mkdir('localDir');
     $result = \OC\Files\Filesystem::rename($this->folder, '/localDir/' . $this->folder);
     $this->assertTrue($result);
     \OC\Files\Filesystem::unlink('localDir');
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     // after the parent directory was deleted the share should be unshared
     $shares = $this->shareManager->getSharedWith(self::TEST_FILES_SHARING_API_USER2, \OCP\Share::SHARE_TYPE_USER);
     $this->assertEmpty($shares);
     self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
     // the folder for the owner should still exists
     $this->assertTrue(\OC\Files\Filesystem::file_exists($this->folder));
 }
Esempio n. 10
0
 /**
  * @medium
  */
 function testpreUnlink()
 {
     $fileInfo2 = \OC\Files\Filesystem::getFileInfo($this->folder);
     $result = \OCP\Share::shareItem('folder', $fileInfo2->getId(), \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31);
     $this->assertTrue($result);
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     // one folder should be shared with the user
     $sharedFolders = \OCP\Share::getItemsSharedWith('folder');
     $this->assertSame(1, count($sharedFolders));
     // move shared folder to 'localDir'
     \OC\Files\Filesystem::mkdir('localDir');
     $result = \OC\Files\Filesystem::rename($this->folder, '/localDir/' . $this->folder);
     $this->assertTrue($result);
     \OC\Files\Filesystem::unlink('localDir');
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     // after the parent directory was deleted the share should be unshared
     $sharedFolders = \OCP\Share::getItemsSharedWith('folder');
     $this->assertTrue(empty($sharedFolders));
     self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
     // the folder for the owner should still exists
     $this->assertTrue(\OC\Files\Filesystem::file_exists($this->folder));
 }
Esempio n. 11
0
 /**
  * Tries to read the file $this->file, and to decode it as a KeePass 2.x
  * database, using the key $this->key. Returns true if the operation was
  * successful, or false otherwise. In case of success, the array
  * $this->entries will contain the resulting list of entries.
  *
  * @return boolean
  */
 public function tryLoad()
 {
     if ($this->loaded) {
         return $this->rawEntries != null;
     }
     $this->loaded = true;
     if (!\OC\Files\Filesystem::file_exists($this->file)) {
         KeePassPHP::raiseError("Impossible to read " . $this->file);
         return false;
     }
     KeePassPHP::printDebug("Attempting to load database from " . $this->file);
     $resReader = RessourceReader::openFile($this->file);
     if (!$resReader) {
         KeePassPHP::raiseError("Unable to open file " . $this->file);
         return false;
     }
     if (!$this->tryParse($resReader)) {
         KeePassPHP::printDebug("  ... attempt failed !");
         return false;
     }
     KeePassPHP::printDebug("  ... attempt succeeded !");
     return true;
 }
Esempio n. 12
0
 /**
  * return the content of a file or return a zip file containing multiple files
  *
  * @param string $dir
  * @param string $files ; separated list of files to download
  * @param boolean $only_header ; boolean to only send header of the request
  */
 public static function get($dir, $files, $only_header = false)
 {
     $xsendfile = false;
     if (isset($_SERVER['MOD_X_SENDFILE_ENABLED']) || isset($_SERVER['MOD_X_SENDFILE2_ENABLED']) || isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) {
         $xsendfile = true;
     }
     if (is_array($files) && count($files) === 1) {
         $files = $files[0];
     }
     if (is_array($files)) {
         $get_type = GET_TYPE::ZIP_FILES;
         $basename = basename($dir);
         if ($basename) {
             $name = $basename . '.zip';
         } else {
             $name = 'download.zip';
         }
         $filename = $dir . '/' . $name;
     } else {
         $filename = $dir . '/' . $files;
         if (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) {
             $get_type = GET_TYPE::ZIP_DIR;
             // downloading root ?
             if ($files === '') {
                 $name = 'download.zip';
             } else {
                 $name = $files . '.zip';
             }
         } else {
             $get_type = GET_TYPE::FILE;
             $name = $files;
         }
     }
     if ($get_type === GET_TYPE::FILE) {
         $zip = false;
         if ($xsendfile && OC_App::isEnabled('files_encryption')) {
             $xsendfile = false;
         }
     } else {
         $zip = new ZipStreamer(false);
     }
     OC_Util::obEnd();
     if ($zip or \OC\Files\Filesystem::isReadable($filename)) {
         self::sendHeaders($filename, $name, $zip);
     } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
         header("HTTP/1.0 404 Not Found");
         $tmpl = new OC_Template('', '404', 'guest');
         $tmpl->assign('file', $name);
         $tmpl->printPage();
     } else {
         header("HTTP/1.0 403 Forbidden");
         die('403 Forbidden');
     }
     if ($only_header) {
         return;
     }
     if ($zip) {
         $executionTime = intval(ini_get('max_execution_time'));
         set_time_limit(0);
         if ($get_type === GET_TYPE::ZIP_FILES) {
             foreach ($files as $file) {
                 $file = $dir . '/' . $file;
                 if (\OC\Files\Filesystem::is_file($file)) {
                     $fh = \OC\Files\Filesystem::fopen($file, 'r');
                     $zip->addFileFromStream($fh, basename($file));
                     fclose($fh);
                 } elseif (\OC\Files\Filesystem::is_dir($file)) {
                     self::zipAddDir($file, $zip);
                 }
             }
         } elseif ($get_type === GET_TYPE::ZIP_DIR) {
             $file = $dir . '/' . $files;
             self::zipAddDir($file, $zip);
         }
         $zip->finalize();
         set_time_limit($executionTime);
     } else {
         if ($xsendfile) {
             $view = \OC\Files\Filesystem::getView();
             /** @var $storage \OC\Files\Storage\Storage */
             list($storage) = $view->resolvePath($filename);
             if ($storage->isLocal()) {
                 self::addSendfileHeader($filename);
             } else {
                 \OC\Files\Filesystem::readfile($filename);
             }
         } else {
             \OC\Files\Filesystem::readfile($filename);
         }
     }
 }
Esempio n. 13
0
$l10n = \OC::$server->getL10N('files');
$result = array('success' => false, 'data' => NULL);
try {
    \OC\Files\Filesystem::getView()->verifyPath($dir, $fileName);
} catch (\OCP\Files\InvalidPathException $ex) {
    $result['data'] = ['message' => $ex->getMessage()];
    OCP\JSON::error($result);
    return;
}
if (!\OC\Files\Filesystem::file_exists($dir . '/')) {
    $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) {
Esempio n. 14
0
 /**
  * test expiration of files older then the max storage time defined for the trash
  * in this test we delete a shared file and check if both trash bins, the one from
  * the owner of the file and the one from the user who deleted the file get expired
  * correctly
  */
 public function testExpireOldFilesShared()
 {
     $currentTime = time();
     $folder = "trashTest-" . $currentTime . '/';
     $expiredDate = $currentTime - 3 * 24 * 60 * 60;
     // create some files
     \OC\Files\Filesystem::mkdir($folder);
     \OC\Files\Filesystem::file_put_contents($folder . 'user1-1.txt', 'file1');
     \OC\Files\Filesystem::file_put_contents($folder . 'user1-2.txt', 'file2');
     \OC\Files\Filesystem::file_put_contents($folder . 'user1-3.txt', 'file3');
     \OC\Files\Filesystem::file_put_contents($folder . 'user1-4.txt', 'file4');
     //share user1-4.txt with user2
     $fileInfo = \OC\Files\Filesystem::getFileInfo($folder);
     $result = \OCP\Share::shareItem('folder', $fileInfo->getId(), \OCP\Share::SHARE_TYPE_USER, self::TEST_TRASHBIN_USER2, 31);
     $this->assertTrue($result);
     // delete them so that they end up in the trash bin
     \OC\Files\Filesystem::unlink($folder . 'user1-1.txt');
     \OC\Files\Filesystem::unlink($folder . 'user1-2.txt');
     \OC\Files\Filesystem::unlink($folder . 'user1-3.txt');
     $filesInTrash = OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'name');
     $this->assertSame(3, count($filesInTrash));
     // every second file will get a date in the past so that it will get expired
     $this->manipulateDeleteTime($filesInTrash, $this->trashRoot1, $expiredDate);
     // login as user2
     self::loginHelper(self::TEST_TRASHBIN_USER2);
     $this->assertTrue(\OC\Files\Filesystem::file_exists($folder . "user1-4.txt"));
     // create some files
     \OC\Files\Filesystem::file_put_contents('user2-1.txt', 'file1');
     \OC\Files\Filesystem::file_put_contents('user2-2.txt', 'file2');
     // delete them so that they end up in the trash bin
     \OC\Files\Filesystem::unlink('user2-1.txt');
     \OC\Files\Filesystem::unlink('user2-2.txt');
     $filesInTrashUser2 = OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER2, 'name');
     $this->assertSame(2, count($filesInTrashUser2));
     // every second file will get a date in the past so that it will get expired
     $this->manipulateDeleteTime($filesInTrashUser2, $this->trashRoot2, $expiredDate);
     \OC\Files\Filesystem::unlink($folder . 'user1-4.txt');
     $this->runCommands();
     $filesInTrashUser2AfterDelete = OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER2);
     // user2-1.txt should have been expired
     $this->verifyArray($filesInTrashUser2AfterDelete, array('user2-2.txt', 'user1-4.txt'));
     self::loginHelper(self::TEST_TRASHBIN_USER1);
     // user1-1.txt and user1-3.txt should have been expired
     $filesInTrashUser1AfterDelete = OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1);
     $this->verifyArray($filesInTrashUser1AfterDelete, array('user1-2.txt', 'user1-4.txt'));
 }
Esempio n. 15
0
 public function file_assemble($path)
 {
     $absolutePath = \OC\Files\Filesystem::normalizePath(\OC\Files\Filesystem::getView()->getAbsolutePath($path));
     $data = '';
     // use file_put_contents as method because that best matches what this function does
     if (OC_FileProxy::runPreProxies('file_put_contents', $absolutePath, $data) && \OC\Files\Filesystem::isValidPath($path)) {
         $path = \OC\Files\Filesystem::getView()->getRelativePath($absolutePath);
         $exists = \OC\Files\Filesystem::file_exists($path);
         $run = true;
         if (!$exists) {
             OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array(\OC\Files\Filesystem::signal_param_path => $path, \OC\Files\Filesystem::signal_param_run => &$run));
         }
         OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array(\OC\Files\Filesystem::signal_param_path => $path, \OC\Files\Filesystem::signal_param_run => &$run));
         if (!$run) {
             return false;
         }
         $target = \OC\Files\Filesystem::fopen($path, 'w');
         if ($target) {
             $count = $this->assemble($target);
             fclose($target);
             if (!$exists) {
                 OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(\OC\Files\Filesystem::signal_param_path => $path));
             }
             OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(\OC\Files\Filesystem::signal_param_path => $path));
             OC_FileProxy::runPostProxies('file_put_contents', $absolutePath, $count);
             return $count > 0;
         } else {
             return false;
         }
     }
 }
Esempio n. 16
0
 public function testRenameSharedFile()
 {
     \OC\Files\Filesystem::file_put_contents("test.txt", "test file");
     $fileInfo = \OC\Files\Filesystem::getFileInfo('test.txt');
     $t1 = time();
     // second version is two weeks older, this way we make sure that no
     // version will be expired
     $t2 = $t1 - 60 * 60 * 24 * 14;
     $this->rootView->mkdir(self::USERS_VERSIONS_ROOT);
     // create some versions
     $v1 = self::USERS_VERSIONS_ROOT . '/test.txt.v' . $t1;
     $v2 = self::USERS_VERSIONS_ROOT . '/test.txt.v' . $t2;
     // the renamed versions should not exist! Because we only moved the mount point!
     $v1Renamed = self::USERS_VERSIONS_ROOT . '/test2.txt.v' . $t1;
     $v2Renamed = self::USERS_VERSIONS_ROOT . '/test2.txt.v' . $t2;
     $this->rootView->file_put_contents($v1, 'version1');
     $this->rootView->file_put_contents($v2, 'version2');
     \OCP\Share::shareItem('file', $fileInfo['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_VERSIONS_USER2, \OCP\Constants::PERMISSION_ALL);
     self::loginHelper(self::TEST_VERSIONS_USER2);
     $this->assertTrue(\OC\Files\Filesystem::file_exists('test.txt'));
     // execute rename hook of versions app
     \OC\Files\Filesystem::rename('test.txt', 'test2.txt');
     self::loginHelper(self::TEST_VERSIONS_USER);
     $this->runCommands();
     $this->assertTrue($this->rootView->file_exists($v1));
     $this->assertTrue($this->rootView->file_exists($v2));
     $this->assertFalse($this->rootView->file_exists($v1Renamed));
     $this->assertFalse($this->rootView->file_exists($v2Renamed));
 }
Esempio n. 17
0
 /**
  * Expire versions which exceed the quota
  *
  * @param string $filename
  * @return bool|int|null
  */
 public static function expire($filename)
 {
     $config = \OC::$server->getConfig();
     $expiration = self::getExpiration();
     if ($config->getSystemValue('files_versions', Storage::DEFAULTENABLED) == 'true' && $expiration->isEnabled()) {
         if (!Filesystem::file_exists($filename)) {
             return false;
         }
         list($uid, $filename) = self::getUidAndFilename($filename);
         if (empty($filename)) {
             // file maybe renamed or deleted
             return false;
         }
         $versionsFileview = new View('/' . $uid . '/files_versions');
         // get available disk space for user
         $user = \OC::$server->getUserManager()->get($uid);
         $softQuota = true;
         $quota = $user->getQuota();
         if ($quota === null || $quota === 'none') {
             $quota = Filesystem::free_space('/');
             $softQuota = false;
         } else {
             $quota = \OCP\Util::computerFileSize($quota);
         }
         // make sure that we have the current size of the version history
         $versionsSize = self::getVersionsSize($uid);
         // calculate available space for version history
         // subtract size of files and current versions size from quota
         if ($quota >= 0) {
             if ($softQuota) {
                 $files_view = new View('/' . $uid . '/files');
                 $rootInfo = $files_view->getFileInfo('/', false);
                 $free = $quota - $rootInfo['size'];
                 // remaining free space for user
                 if ($free > 0) {
                     $availableSpace = $free * self::DEFAULTMAXSIZE / 100 - $versionsSize;
                     // how much space can be used for versions
                 } else {
                     $availableSpace = $free - $versionsSize;
                 }
             } else {
                 $availableSpace = $quota;
             }
         } else {
             $availableSpace = PHP_INT_MAX;
         }
         $allVersions = Storage::getVersions($uid, $filename);
         $time = time();
         list($toDelete, $sizeOfDeletedVersions) = self::getExpireList($time, $allVersions, $availableSpace <= 0);
         $availableSpace = $availableSpace + $sizeOfDeletedVersions;
         $versionsSize = $versionsSize - $sizeOfDeletedVersions;
         // if still not enough free space we rearrange the versions from all files
         if ($availableSpace <= 0) {
             $result = Storage::getAllVersions($uid);
             $allVersions = $result['all'];
             foreach ($result['by_file'] as $versions) {
                 list($toDeleteNew, $size) = self::getExpireList($time, $versions, $availableSpace <= 0);
                 $toDelete = array_merge($toDelete, $toDeleteNew);
                 $sizeOfDeletedVersions += $size;
             }
             $availableSpace = $availableSpace + $sizeOfDeletedVersions;
             $versionsSize = $versionsSize - $sizeOfDeletedVersions;
         }
         foreach ($toDelete as $key => $path) {
             \OC_Hook::emit('\\OCP\\Versions', 'preDelete', array('path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
             self::deleteVersion($versionsFileview, $path);
             \OC_Hook::emit('\\OCP\\Versions', 'delete', array('path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
             unset($allVersions[$key]);
             // update array with the versions we keep
             \OCP\Util::writeLog('files_versions', "Expire: " . $path, \OCP\Util::DEBUG);
         }
         // Check if enough space is available after versions are rearranged.
         // If not we delete the oldest versions until we meet the size limit for versions,
         // but always keep the two latest versions
         $numOfVersions = count($allVersions) - 2;
         $i = 0;
         // sort oldest first and make sure that we start at the first element
         ksort($allVersions);
         reset($allVersions);
         while ($availableSpace < 0 && $i < $numOfVersions) {
             $version = current($allVersions);
             \OC_Hook::emit('\\OCP\\Versions', 'preDelete', array('path' => $version['path'] . '.v' . $version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
             self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
             \OC_Hook::emit('\\OCP\\Versions', 'delete', array('path' => $version['path'] . '.v' . $version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
             \OCP\Util::writeLog('files_versions', 'running out of space! Delete oldest version: ' . $version['path'] . '.v' . $version['version'], \OCP\Util::DEBUG);
             $versionsSize -= $version['size'];
             $availableSpace += $version['size'];
             next($allVersions);
             $i++;
         }
         return $versionsSize;
         // finally return the new size of the version history
     }
     return false;
 }
Esempio n. 18
0
 /**
  * get default share folder
  *
  * @return string
  */
 public static function getShareFolder()
 {
     $shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
     $shareFolder = Filesystem::normalizePath($shareFolder);
     if (!Filesystem::file_exists($shareFolder)) {
         $dir = '';
         $subdirs = explode('/', $shareFolder);
         foreach ($subdirs as $subdir) {
             $dir = $dir . '/' . $subdir;
             if (!Filesystem::is_dir($dir)) {
                 Filesystem::mkdir($dir);
             }
         }
     }
     return $shareFolder;
 }
Esempio n. 19
0
 if (isset($_POST['resolution']) && $_POST['resolution'] === 'autorename') {
     // append a number in brackets like 'filename (2).ext'
     $target = OCP\Files::buildNotExistingFileName(stripslashes($dir . $relativePath), $files['name'][$i]);
 } else {
     $target = \OC\Files\Filesystem::normalizePath(stripslashes($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);
 if (!\OC\Files\Filesystem::file_exists($target) || isset($_POST['resolution']) && $_POST['resolution'] === 'replace') {
     // upload and overwrite file
     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 = $l->t('The target folder has been moved or deleted.');
                 $errorCode = 'targetnotfound';
             } else {
                 $data = \OCA\Files\Helper::formatFileInfo($meta);
                 $data['status'] = 'success';
                 $data['originalname'] = $files['tmp_name'][$i];
                 $data['uploadMaxFilesize'] = $maxUploadFileSize;
                 $data['maxHumanFilesize'] = $maxHumanFileSize;
Esempio n. 20
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)));
}
Esempio n. 21
0
 /**
  * share file with a group if a user renames the file the filename should not change
  * for the other users
  */
 function testMoveGroupShare()
 {
     \OC_Group::createGroup('testGroup');
     \OC_Group::addToGroup(self::TEST_FILES_SHARING_API_USER1, 'testGroup');
     \OC_Group::addToGroup(self::TEST_FILES_SHARING_API_USER2, 'testGroup');
     \OC_Group::addToGroup(self::TEST_FILES_SHARING_API_USER3, 'testGroup');
     $fileinfo = $this->view->getFileInfo($this->filename);
     $result = \OCP\Share::shareItem('file', $fileinfo['fileid'], \OCP\Share::SHARE_TYPE_GROUP, "testGroup", 31);
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
     \OC\Files\Filesystem::rename($this->filename, "newFileName");
     $this->assertTrue(\OC\Files\Filesystem::file_exists('newFileName'));
     $this->assertFalse(\OC\Files\Filesystem::file_exists($this->filename));
     self::loginHelper(self::TEST_FILES_SHARING_API_USER3);
     $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
     $this->assertFalse(\OC\Files\Filesystem::file_exists("newFileName"));
     self::loginHelper(self::TEST_FILES_SHARING_API_USER3);
     $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
     $this->assertFalse(\OC\Files\Filesystem::file_exists("newFileName"));
     //cleanup
     \OCP\Share::unshare('file', $fileinfo['fileid'], \OCP\Share::SHARE_TYPE_GROUP, 'testGroup');
     \OC_Group::removeFromGroup(self::TEST_FILES_SHARING_API_USER1, 'testGroup');
     \OC_Group::removeFromGroup(self::TEST_FILES_SHARING_API_USER2, 'testGroup');
     \OC_Group::removeFromGroup(self::TEST_FILES_SHARING_API_USER3, 'testGroup');
 }
Esempio n. 22
0
<?php

OCP\JSON::checkLoggedIn();
OCP\JSON::callCheck();
\OC::$server->getSession()->close();
// Get data
$dir = isset($_POST['dir']) ? (string) $_POST['dir'] : '';
$file = isset($_POST['file']) ? (string) $_POST['file'] : '';
$target = isset($_POST['target']) ? rawurldecode((string) $_POST['target']) : '';
$l = \OC::$server->getL10N('files');
if (\OC\Files\Filesystem::file_exists($target . '/' . $file)) {
    OCP\JSON::error(array("data" => array("message" => $l->t("Could not move %s - File with this name already exists", array($file)))));
    exit;
}
if ($target != '' || strtolower($file) != 'shared') {
    $targetFile = \OC\Files\Filesystem::normalizePath($target . '/' . $file);
    $sourceFile = \OC\Files\Filesystem::normalizePath($dir . '/' . $file);
    try {
        if (\OC\Files\Filesystem::rename($sourceFile, $targetFile)) {
            OCP\JSON::success(array("data" => array("dir" => $dir, "files" => $file)));
        } else {
            OCP\JSON::error(array("data" => array("message" => $l->t("Could not move %s", array($file)))));
        }
    } catch (\OCP\Files\NotPermittedException $e) {
        OCP\JSON::error(array("data" => array("message" => $l->t("Permission denied"))));
    } catch (\Exception $e) {
        OCP\JSON::error(array("data" => array("message" => $e->getMessage())));
    }
} else {
    OCP\JSON::error(array("data" => array("message" => $l->t("Could not move %s", array($file)))));
}
Esempio n. 23
0
\OC::$session->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::isDeletable($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)));
}
Esempio n. 24
0
 public function testShareWithDifferentShareFolder()
 {
     $fileinfo = $this->view->getFileInfo($this->filename);
     $folderinfo = $this->view->getFileInfo($this->folder);
     $fileShare = \OCP\Share::shareItem('file', $fileinfo['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31);
     $this->assertTrue($fileShare);
     \OCA\Files_Sharing\Helper::setShareFolder('/Shared/subfolder');
     $folderShare = \OCP\Share::shareItem('folder', $folderinfo['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31);
     $this->assertTrue($folderShare);
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
     $this->assertTrue(\OC\Files\Filesystem::file_exists('/Shared/subfolder/' . $this->folder));
     //cleanup
     \OC::$server->getConfig()->deleteSystemValue('share_folder');
 }
Esempio n. 25
0
 public function testShareWithDifferentShareFolder()
 {
     $fileinfo = $this->view->getFileInfo($this->filename);
     $folderinfo = $this->view->getFileInfo($this->folder);
     $share = $this->share(\OCP\Share::SHARE_TYPE_USER, $this->filename, self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE);
     \OCA\Files_Sharing\Helper::setShareFolder('/Shared/subfolder');
     $share = $this->share(\OCP\Share::SHARE_TYPE_USER, $this->folder, self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2, \OCP\Constants::PERMISSION_ALL);
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
     $this->assertTrue(\OC\Files\Filesystem::file_exists('/Shared/subfolder/' . $this->folder));
     //cleanup
     \OC::$server->getConfig()->deleteSystemValue('share_folder');
 }
Esempio n. 26
0
 public function testGetPathByIdShareSubFolder()
 {
     self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
     \OC\Files\Filesystem::mkdir('foo');
     \OC\Files\Filesystem::mkdir('foo/bar');
     \OC\Files\Filesystem::touch('foo/bar/test.txt', 'bar');
     $folderInfo = \OC\Files\Filesystem::getFileInfo('foo');
     $fileInfo = \OC\Files\Filesystem::getFileInfo('foo/bar/test.txt');
     \OCP\Share::shareItem('folder', $folderInfo->getId(), \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, \OCP\PERMISSION_ALL);
     \OC_Util::tearDownFS();
     self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
     $this->assertTrue(\OC\Files\Filesystem::file_exists('/foo'));
     list($sharedStorage) = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/foo');
     /**
      * @var \OC\Files\Storage\Shared $sharedStorage
      */
     $sharedCache = $sharedStorage->getCache();
     $this->assertEquals('', $sharedCache->getPathById($folderInfo->getId()));
     $this->assertEquals('bar/test.txt', $sharedCache->getPathById($fileInfo->getId()));
 }
Esempio n. 27
0
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/
// Check if we are a user
OCP\User::checkLoggedIn();
$filename = $_GET["file"];
if (!\OC\Files\Filesystem::file_exists($filename)) {
    header("HTTP/1.0 404 Not Found");
    $tmpl = new OCP\Template('', '404', 'guest');
    $tmpl->assign('file', $filename);
    $tmpl->printPage();
    exit;
}
$ftype = \OC\Files\Filesystem::getMimeType($filename);
header('Content-Type:' . $ftype);
if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
    header('Content-Disposition: attachment; filename="' . rawurlencode(basename($filename)) . '"');
} else {
    header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode(basename($filename)) . '; filename="' . rawurlencode(basename($filename)) . '"');
}
OCP\Response::disableCaching();
header('Content-Length: ' . \OC\Files\Filesystem::filesize($filename));
Esempio n. 28
0
 /**
  * @param View $view
  * @param string $name
  * @param string $dir
  * @param boolean $onlyHeader
  */
 private static function getSingleFile($view, $dir, $name, $onlyHeader)
 {
     $filename = $dir . '/' . $name;
     OC_Util::obEnd();
     $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
     if (\OC\Files\Filesystem::isReadable($filename)) {
         self::sendHeaders($filename, $name);
     } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
         header("HTTP/1.0 404 Not Found");
         $tmpl = new OC_Template('', '404', 'guest');
         $tmpl->printPage();
         exit;
     } else {
         header("HTTP/1.0 403 Forbidden");
         die('403 Forbidden');
     }
     if ($onlyHeader) {
         return;
     }
     $view->readfile($filename);
 }
Esempio n. 29
0
 /**
  * return the content of a file or return a zip file containing multiple files
  *
  * @param string $dir
  * @param string $files ; separated list of files to download
  * @param boolean $only_header ; boolean to only send header of the request
  */
 public static function get($dir, $files, $only_header = false)
 {
     $view = \OC\Files\Filesystem::getView();
     $xsendfile = false;
     if (\OC::$server->getLockingProvider() instanceof NoopLockingProvider) {
         if (isset($_SERVER['MOD_X_SENDFILE_ENABLED']) || isset($_SERVER['MOD_X_SENDFILE2_ENABLED']) || isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) {
             $xsendfile = true;
         }
     }
     if (is_array($files) && count($files) === 1) {
         $files = $files[0];
     }
     if (is_array($files)) {
         $get_type = self::ZIP_FILES;
         $basename = basename($dir);
         if ($basename) {
             $name = $basename . '.zip';
         } else {
             $name = 'download.zip';
         }
         $filename = $dir . '/' . $name;
     } else {
         $filename = $dir . '/' . $files;
         if (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) {
             $get_type = self::ZIP_DIR;
             // downloading root ?
             if ($files === '') {
                 $name = 'download.zip';
             } else {
                 $name = $files . '.zip';
             }
         } else {
             $get_type = self::FILE;
             $name = $files;
         }
     }
     if ($get_type === self::FILE) {
         $zip = false;
         if ($xsendfile && \OC::$server->getEncryptionManager()->isEnabled()) {
             $xsendfile = false;
         }
     } else {
         $zip = new ZipStreamer(false);
     }
     OC_Util::obEnd();
     try {
         if ($get_type === self::FILE) {
             $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
         }
         if ($zip or \OC\Files\Filesystem::isReadable($filename)) {
             self::sendHeaders($filename, $name, $zip);
         } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
             header("HTTP/1.0 404 Not Found");
             $tmpl = new OC_Template('', '404', 'guest');
             $tmpl->printPage();
             exit;
         } else {
             header("HTTP/1.0 403 Forbidden");
             die('403 Forbidden');
         }
         if ($only_header) {
             return;
         }
         if ($zip) {
             $executionTime = intval(ini_get('max_execution_time'));
             set_time_limit(0);
             if ($get_type === self::ZIP_FILES) {
                 foreach ($files as $file) {
                     $file = $dir . '/' . $file;
                     if (\OC\Files\Filesystem::is_file($file)) {
                         $fh = \OC\Files\Filesystem::fopen($file, 'r');
                         $zip->addFileFromStream($fh, basename($file));
                         fclose($fh);
                     } elseif (\OC\Files\Filesystem::is_dir($file)) {
                         self::zipAddDir($file, $zip);
                     }
                 }
             } elseif ($get_type === self::ZIP_DIR) {
                 $file = $dir . '/' . $files;
                 self::zipAddDir($file, $zip);
             }
             $zip->finalize();
             set_time_limit($executionTime);
         } else {
             if ($xsendfile) {
                 /** @var $storage \OC\Files\Storage\Storage */
                 list($storage) = $view->resolvePath($filename);
                 if ($storage->isLocal()) {
                     self::addSendfileHeader($filename);
                 } else {
                     \OC\Files\Filesystem::readfile($filename);
                 }
             } else {
                 \OC\Files\Filesystem::readfile($filename);
             }
         }
         if ($get_type === self::FILE) {
             $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
         }
     } catch (\OCP\Lock\LockedException $ex) {
         $l = \OC::$server->getL10N('core');
         $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
         \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
     } catch (\Exception $ex) {
         $l = \OC::$server->getL10N('core');
         $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
         \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
     }
 }
Esempio n. 30
0
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  */
 public function Add()
 {
     \OCP\JSON::setContentTypeHeader('application/json');
     if (isset($_POST['FILE']) && strlen($_POST['FILE']) > 0 && Tools::CheckURL($_POST['FILE']) && isset($_POST['OPTIONS'])) {
         try {
             if (!$this->AllowProtocolYT && !\OC_User::isAdminUser($this->CurrentUID)) {
                 throw new \Exception((string) $this->L10N->t('You are not allowed to use the YouTube protocol'));
             }
             $YouTube = new YouTube($this->YTDLBinary, $_POST['FILE']);
             if (!is_null($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) {
                 $YouTube->SetProxy($this->ProxyAddress, $this->ProxyPort);
             }
             if (isset($_POST['OPTIONS']['YTForceIPv4']) && strcmp($_POST['OPTIONS']['YTForceIPv4'], 'false') == 0) {
                 $YouTube->SetForceIPv4(false);
             }
             // Extract Audio YES
             if (isset($_POST['OPTIONS']['YTExtractAudio']) && strcmp($_POST['OPTIONS']['YTExtractAudio'], 'true') == 0) {
                 $VideoData = $YouTube->GetVideoData(true);
                 if (!isset($VideoData['AUDIO']) || !isset($VideoData['FULLNAME'])) {
                     return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('Unable to retrieve true YouTube audio URL')));
                 }
                 $DL = array('URL' => $VideoData['AUDIO'], 'FILENAME' => Tools::CleanString($VideoData['FULLNAME']), 'TYPE' => 'YT Audio');
             } else {
                 $VideoData = $YouTube->GetVideoData();
                 if (!isset($VideoData['VIDEO']) || !isset($VideoData['FULLNAME'])) {
                     return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('Unable to retrieve true YouTube video URL')));
                 }
                 $DL = array('URL' => $VideoData['VIDEO'], 'FILENAME' => Tools::CleanString($VideoData['FULLNAME']), 'TYPE' => 'YT Video');
             }
             // If target file exists, create a new one
             if (\OC\Files\Filesystem::file_exists($this->DownloadsFolder . '/' . $DL['FILENAME'])) {
                 $DL['FILENAME'] = time() . '_' . $DL['FILENAME'];
             }
             // Create the target file if the downloader is ARIA2
             if ($this->WhichDownloader == 0) {
                 \OC\Files\Filesystem::touch($this->DownloadsFolder . '/' . $DL['FILENAME']);
             } else {
                 if (!\OC\Files\Filesystem::is_dir($this->DownloadsFolder)) {
                     \OC\Files\Filesystem::mkdir($this->DownloadsFolder);
                 }
             }
             $OPTIONS = array('dir' => $this->AbsoluteDownloadsFolder, 'out' => $DL['FILENAME']);
             if (!is_null($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) {
                 $OPTIONS['all-proxy'] = rtrim($this->ProxyAddress, '/') . ':' . $this->ProxyPort;
                 if (!is_null($this->ProxyUser) && !is_null($this->ProxyPasswd)) {
                     $OPTIONS['all-proxy-user'] = $this->ProxyUser;
                     $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd;
                 }
             }
             if (!is_null($this->MaxDownloadSpeed) && $this->MaxDownloadSpeed > 0) {
                 $OPTIONS['max-download-limit'] = $this->MaxDownloadSpeed . 'K';
             }
             $AddURI = $this->WhichDownloader == 0 ? Aria2::AddUri(array($DL['URL']), array('Params' => $OPTIONS)) : CURL::AddUri($DL['URL'], $OPTIONS);
             if (isset($AddURI['result']) && !is_null($AddURI['result'])) {
                 $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES (?, ?, ?, ?, ?, ?)';
                 if ($this->DbType == 1) {
                     $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES (?, ?, ?, ?, ?, ?)';
                 }
                 $Query = \OCP\DB::prepare($SQL);
                 $Result = $Query->execute(array($this->CurrentUID, $AddURI['result'], $DL['FILENAME'], $DL['TYPE'], 1, time()));
                 sleep(1);
                 $Status = Aria2::TellStatus($AddURI['result']);
                 $Progress = 0;
                 if ($Status['result']['totalLength'] > 0) {
                     $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength'];
                 }
                 $ProgressString = Tools::GetProgressString($Status['result']['completedLength'], $Status['result']['totalLength'], $Progress);
                 return new JSONResponse(array('ERROR' => false, 'MESSAGE' => (string) $this->L10N->t('Download started'), 'GID' => $AddURI['result'], 'PROGRESSVAL' => round($Progress * 100, 2) . '%', 'PROGRESS' => is_null($ProgressString) ? (string) $this->L10N->t('N/A') : $ProgressString, 'STATUS' => isset($Status['result']['status']) ? (string) $this->L10N->t(ucfirst($Status['result']['status'])) : (string) $this->L10N->t('N/A'), 'STATUSID' => Tools::GetDownloadStatusID($Status['result']['status']), 'SPEED' => isset($Status['result']['downloadSpeed']) ? Tools::FormatSizeUnits($Status['result']['downloadSpeed']) . '/s' : (string) $this->L10N->t('N/A'), 'FILENAME' => strlen($DL['FILENAME']) > 40 ? substr($DL['FILENAME'], 0, 40) . '...' : $DL['FILENAME'], 'PROTO' => $DL['TYPE'], 'ISTORRENT' => false));
             } else {
                 return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('Returned GID is null ! Is Aria2c running as a daemon ?')));
             }
         } catch (Exception $E) {
             return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage()));
         }
     } else {
         return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('Please check the URL you\'ve just provided')));
     }
 }