From d332b1d4a2e9382aaa8e8a11b6200efaadb18768 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 2 Jul 2013 11:13:22 +0200 Subject: implement preview loading after upload --- apps/files/js/filelist.js | 5 +++-- apps/files/js/files.js | 19 +++++++++++++------ 2 files changed, 16 insertions(+), 8 deletions(-) (limited to 'apps/files/js') diff --git a/apps/files/js/filelist.js b/apps/files/js/filelist.js index e19a35bbc5b..11bf028d93a 100644 --- a/apps/files/js/filelist.js +++ b/apps/files/js/filelist.js @@ -172,8 +172,9 @@ var FileList={ if (id != null) { tr.attr('data-id', id); } - getMimeIcon(mime,function(path){ - tr.find('td.filename').attr('style','background-image:url('+path+')'); + var path = $('#dir').val()+'/'+name; + getPreviewIcon(path, function(previewpath){ + tr.find('td.filename').attr('style','background-image:url('+previewpath+')'); }); tr.find('td.filename').draggable(dragOptions); }, diff --git a/apps/files/js/files.js b/apps/files/js/files.js index a79d34c9b23..224167b99c1 100644 --- a/apps/files/js/files.js +++ b/apps/files/js/files.js @@ -513,8 +513,9 @@ $(document).ready(function() { var tr=$('tr').filterAttr('data-file',name); tr.attr('data-mime',result.data.mime); tr.attr('data-id', result.data.id); - getMimeIcon(result.data.mime,function(path){ - tr.find('td.filename').attr('style','background-image:url('+path+')'); + var path = $('#dir').val()+'/'+name; + getPreviewIcon(path, function(previewpath){ + tr.find('td.filename').attr('style','background-image:url('+previewpath+')'); }); } else { OC.dialogs.alert(result.data.message, t('core', 'Error')); @@ -577,8 +578,9 @@ $(document).ready(function() { var tr=$('tr').filterAttr('data-file',localName); tr.data('mime',mime).data('id',id); tr.attr('data-id', id); - getMimeIcon(mime,function(path){ - tr.find('td.filename').attr('style','background-image:url('+path+')'); + var path = $('#dir').val()+'/'+localName; + getPreviewIcon(path, function(previewpath){ + tr.find('td.filename').attr('style','background-image:url('+previewpath+')'); }); }); eventSource.listen('error',function(error){ @@ -769,8 +771,9 @@ var createDragShadow = function(event){ if (elem.type === 'dir') { newtr.find('td.filename').attr('style','background-image:url('+OC.imagePath('core', 'filetypes/folder.png')+')'); } else { - getMimeIcon(elem.mime,function(path){ - newtr.find('td.filename').attr('style','background-image:url('+path+')'); + var path = $('#dir').val()+'/'+elem.name; + getPreviewIcon(path, function(previewpath){ + newtr.find('td.filename').attr('style','background-image:url('+previewpath+')'); }); } }); @@ -956,6 +959,10 @@ function getMimeIcon(mime, ready){ } getMimeIcon.cache={}; +function getPreviewIcon(path, ready){ + ready(OC.Router.generate('core_ajax_preview', {file:path, x:44, y:44})); +} + function getUniqueName(name){ if($('tr').filterAttr('data-file',name).length>0){ var parts=name.split('.'); -- cgit v1.2.3 From cf449d42e87b21dff0de35c394031c5fa28b56aa Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 10 Jul 2013 11:25:28 +0200 Subject: properly encode path --- apps/files/js/files.js | 2 +- apps/files_trashbin/lib/trash.php | 2 +- lib/helper.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'apps/files/js') diff --git a/apps/files/js/files.js b/apps/files/js/files.js index 224167b99c1..06d193bf8f3 100644 --- a/apps/files/js/files.js +++ b/apps/files/js/files.js @@ -960,7 +960,7 @@ function getMimeIcon(mime, ready){ getMimeIcon.cache={}; function getPreviewIcon(path, ready){ - ready(OC.Router.generate('core_ajax_preview', {file:path, x:44, y:44})); + ready(OC.Router.generate('core_ajax_preview', {file: encodeURIComponent(path), x:44, y:44})); } function getUniqueName(name){ diff --git a/apps/files_trashbin/lib/trash.php b/apps/files_trashbin/lib/trash.php index e82a597c61e..fb99fca5b3f 100644 --- a/apps/files_trashbin/lib/trash.php +++ b/apps/files_trashbin/lib/trash.php @@ -852,6 +852,6 @@ class Trashbin { } public static function preview_icon($path) { - return \OC_Helper::linkToRoute( 'core_ajax_trashbin_preview', array('x' => 44, 'y' => 44, 'file' => $path)); + return \OC_Helper::linkToRoute( 'core_ajax_trashbin_preview', array('x' => 44, 'y' => 44, 'file' => urlencode($path) )); } } diff --git a/lib/helper.php b/lib/helper.php index 0a8962a5312..326f2567f99 100644 --- a/lib/helper.php +++ b/lib/helper.php @@ -231,7 +231,7 @@ class OC_Helper { * Returns the path to the preview of the file. */ public static function previewIcon($path) { - return self::linkToRoute( 'core_ajax_preview', array('x' => 44, 'y' => 44, 'file' => $path)); + return self::linkToRoute( 'core_ajax_preview', array('x' => 44, 'y' => 44, 'file' => urlencode($path) )); } /** -- cgit v1.2.3 From ac6a3133eca86b853da838ae310534b76e9fb662 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 30 Jul 2013 12:29:12 +0200 Subject: style fixes --- apps/files/js/files.js | 2 +- apps/files/templates/part.list.php | 2 +- apps/files_sharing/public.php | 2 +- core/ajax/preview.php | 42 +++++ core/ajax/publicpreview.php | 92 +++++++++++ core/ajax/trashbinpreview.php | 46 ++++++ core/routes.php | 6 +- lib/helper.php | 2 +- lib/preview.php | 308 ++++++++----------------------------- lib/preview/images.php | 7 +- lib/preview/libreoffice-cl.php | 24 +-- lib/preview/movies.php | 22 +-- lib/preview/mp3.php | 22 +-- lib/preview/msoffice.php | 24 +-- lib/preview/office.php | 7 +- lib/preview/pdf.php | 8 +- lib/preview/txt.php | 15 +- lib/preview/unknown.php | 8 +- lib/template.php | 3 + lib/template/functions.php | 16 ++ 20 files changed, 349 insertions(+), 309 deletions(-) create mode 100644 core/ajax/preview.php create mode 100644 core/ajax/publicpreview.php create mode 100644 core/ajax/trashbinpreview.php (limited to 'apps/files/js') diff --git a/apps/files/js/files.js b/apps/files/js/files.js index 53c6de09dd0..8b66ed6747b 100644 --- a/apps/files/js/files.js +++ b/apps/files/js/files.js @@ -825,7 +825,7 @@ function getMimeIcon(mime, ready){ getMimeIcon.cache={}; function getPreviewIcon(path, ready){ - ready(OC.Router.generate('core_ajax_preview', {file: encodeURIComponent(path), x:44, y:44})); + ready(OC.Router.generate('core_ajax_preview', {file: encodeURIComponent(path), x:36, y:36})); } function getUniqueName(name){ diff --git a/apps/files/templates/part.list.php b/apps/files/templates/part.list.php index a957a94f332..ab1b91167db 100644 --- a/apps/files/templates/part.list.php +++ b/apps/files/templates/part.list.php @@ -3,7 +3,7 @@ $totaldirs = 0; $totalsize = 0; ?> 6 $totalsize += $file['size']; if ($file['type'] === 'dir') { $totaldirs++; diff --git a/apps/files_sharing/public.php b/apps/files_sharing/public.php index 284b7a30208..650fa6a7c27 100644 --- a/apps/files_sharing/public.php +++ b/apps/files_sharing/public.php @@ -196,7 +196,7 @@ if (isset($path)) { OCP\Util::linkToPublic('files') . $urlLinkIdentifiers . '&download&path='); $list->assign('isPublic', true); $list->assign('sharingtoken', $token); - $list->assign('sharingroot', ($path)); + $list->assign('sharingroot', $basePath); $breadcrumbNav = new OCP\Template('files', 'part.breadcrumb', ''); $breadcrumbNav->assign('breadcrumb', $breadcrumb); $breadcrumbNav->assign('baseURL', OCP\Util::linkToPublic('files') . $urlLinkIdentifiers . '&path='); diff --git a/core/ajax/preview.php b/core/ajax/preview.php new file mode 100644 index 00000000000..a9d127ffcc4 --- /dev/null +++ b/core/ajax/preview.php @@ -0,0 +1,42 @@ +setFile($file); + $preview->setMaxX($maxX); + $preview->setMaxY($maxY); + $preview->setScalingUp($scalingUp); + + $preview->show(); +}catch(\Exception $e) { + \OC_Response::setStatus(500); + \OC_Log::write('core', $e->getmessage(), \OC_Log::ERROR); + \OC\Preview::showErrorPreview(); + exit; +} \ No newline at end of file diff --git a/core/ajax/publicpreview.php b/core/ajax/publicpreview.php new file mode 100644 index 00000000000..aace24caa21 --- /dev/null +++ b/core/ajax/publicpreview.php @@ -0,0 +1,92 @@ +setFile($sharedFile); + $preview->setMaxX($maxX); + $preview->setMaxY($maxY); + $preview->setScalingUp($scalingUp); + + $preview->show(); +}catch(\Exception $e) { + \OC_Response::setStatus(500); + \OC_Log::write('core', $e->getmessage(), \OC_Log::ERROR); + \OC\Preview::showErrorPreview(); + exit; +} \ No newline at end of file diff --git a/core/ajax/trashbinpreview.php b/core/ajax/trashbinpreview.php new file mode 100644 index 00000000000..d018a57d37b --- /dev/null +++ b/core/ajax/trashbinpreview.php @@ -0,0 +1,46 @@ +setFile($file); + $preview->setMaxX($maxX); + $preview->setMaxY($maxY); + $preview->setScalingUp($scalingUp); + + $preview->showPreview(); +}catch(\Exception $e) { + \OC_Response::setStatus(500); + \OC_Log::write('core', $e->getmessage(), \OC_Log::ERROR); + \OC\Preview::showErrorPreview(); + exit; +} \ No newline at end of file diff --git a/core/routes.php b/core/routes.php index 41e82f8a73d..75cc4d511c0 100644 --- a/core/routes.php +++ b/core/routes.php @@ -43,11 +43,11 @@ $this->create('js_config', '/core/js/config.js') $this->create('core_ajax_routes', '/core/routes.json') ->action('OC_Router', 'JSRoutes'); $this->create('core_ajax_preview', '/core/preview.png') - ->action('OC\Preview', 'previewRouter'); + ->actionInclude('core/ajax/preview.php'); $this->create('core_ajax_trashbin_preview', '/core/trashbinpreview.png') - ->action('OC\Preview', 'trashbinPreviewRouter'); + ->actionInclude('core/ajax/trashbinpreview.php'); $this->create('core_ajax_public_preview', '/core/publicpreview.png') - ->action('OC\Preview', 'publicPreviewRouter'); + ->actionInclude('core/ajax/publicpreview.php'); OC::$CLASSPATH['OC_Core_LostPassword_Controller'] = 'core/lostpassword/controller.php'; $this->create('core_lostpassword_index', '/lostpassword/') ->get() diff --git a/lib/helper.php b/lib/helper.php index 460e5679b02..b74e4c4512e 100644 --- a/lib/helper.php +++ b/lib/helper.php @@ -233,7 +233,7 @@ class OC_Helper { return self::linkToRoute( 'core_ajax_preview', array('x' => 36, 'y' => 36, 'file' => urlencode($path) )); } - public static function publicPreview_icon( $path, $token ) { + public static function publicPreviewIcon( $path, $token ) { return self::linkToRoute( 'core_ajax_public_preview', array('x' => 36, 'y' => 36, 'file' => urlencode($path), 't' => $token)); } diff --git a/lib/preview.php b/lib/preview.php index 245ad64014e..9f4d20b4650 100755 --- a/lib/preview.php +++ b/lib/preview.php @@ -55,12 +55,12 @@ class Preview { * @param string $file The path to the file where you want a thumbnail from * @param int $maxX The maximum X size of the thumbnail. It can be smaller depending on the shape of the image * @param int $maxY The maximum Y size of the thumbnail. It can be smaller depending on the shape of the image - * @param bool $scalingup Disable/Enable upscaling of previews + * @param bool $scalingUp Disable/Enable upscaling of previews * @return mixed (bool / string) * false if thumbnail does not exist * path to thumbnail if thumbnail exists */ - public function __construct($user='', $root='/', $file='', $maxX=1, $maxY=1, $scalingup=true) { + public function __construct($user='', $root='/', $file='', $maxX=1, $maxY=1, $scalingUp=true) { //set config $this->configMaxX = \OC_Config::getValue('preview_max_x', null); $this->configMaxY = \OC_Config::getValue('preview_max_y', null); @@ -70,11 +70,11 @@ class Preview { $this->setFile($file); $this->setMaxX($maxX); $this->setMaxY($maxY); - $this->setScalingUp($scalingup); + $this->setScalingUp($scalingUp); //init fileviews if($user === ''){ - $user = OC_User::getUser(); + $user = \OC_User::getUser(); } $this->fileview = new \OC\Files\View('/' . $user . '/' . $root); $this->userview = new \OC\Files\View('/' . $user); @@ -120,7 +120,7 @@ class Preview { * @brief returns whether or not scalingup is enabled * @return bool */ - public function getScalingup() { + public function getScalingUp() { return $this->scalingup; } @@ -172,8 +172,8 @@ class Preview { * @return $this */ public function setMaxX($maxX=1) { - if($maxX === 0) { - throw new \Exception('Cannot set width of 0!'); + if($maxX <= 0) { + throw new \Exception('Cannot set width of 0 or smaller!'); } $configMaxX = $this->getConfigMaxX(); if(!is_null($configMaxX)) { @@ -192,8 +192,8 @@ class Preview { * @return $this */ public function setMaxY($maxY=1) { - if($maxY === 0) { - throw new \Exception('Cannot set height of 0!'); + if($maxY <= 0) { + throw new \Exception('Cannot set height of 0 or smaller!'); } $configMaxY = $this->getConfigMaxY(); if(!is_null($configMaxY)) { @@ -208,14 +208,14 @@ class Preview { /** * @brief set whether or not scalingup is enabled - * @param bool $scalingup + * @param bool $scalingUp * @return $this */ - public function setScalingup($scalingup) { + public function setScalingup($scalingUp) { if($this->getMaxScaleFactor() === 1) { - $scalingup = false; + $scalingUp = false; } - $this->scalingup = $scalingup; + $this->scalingup = $scalingUp; return $this; } @@ -245,12 +245,12 @@ class Preview { public function deletePreview() { $file = $this->getFile(); - $fileinfo = $this->fileview->getFileInfo($file); - $fileid = $fileinfo['fileid']; + $fileInfo = $this->fileview->getFileInfo($file); + $fileId = $fileInfo['fileid']; - $previewpath = $this->getThumbnailsFolder() . '/' . $fileid . '/' . $this->getMaxX() . '-' . $this->getMaxY() . '.png'; - $this->userview->unlink($previewpath); - return !$this->userview->file_exists($previewpath); + $previewPath = $this->getThumbnailsFolder() . '/' . $fileId . '/' . $this->getMaxX() . '-' . $this->getMaxY() . '.png'; + $this->userview->unlink($previewPath); + return !$this->userview->file_exists($previewPath); } /** @@ -260,13 +260,13 @@ class Preview { public function deleteAllPreviews() { $file = $this->getFile(); - $fileinfo = $this->fileview->getFileInfo($file); - $fileid = $fileinfo['fileid']; + $fileInfo = $this->fileview->getFileInfo($file); + $fileId = $fileInfo['fileid']; - $previewpath = $this->getThumbnailsFolder() . '/' . $fileid . '/'; - $this->userview->deleteAll($previewpath); - $this->userview->rmdir($previewpath); - return !$this->userview->is_dir($previewpath); + $previewPath = $this->getThumbnailsFolder() . '/' . $fileId . '/'; + $this->userview->deleteAll($previewPath); + $this->userview->rmdir($previewPath); + return !$this->userview->is_dir($previewPath); } /** @@ -279,45 +279,45 @@ class Preview { $file = $this->getFile(); $maxX = $this->getMaxX(); $maxY = $this->getMaxY(); - $scalingup = $this->getScalingup(); + $scalingUp = $this->getScalingUp(); $maxscalefactor = $this->getMaxScaleFactor(); - $fileinfo = $this->fileview->getFileInfo($file); - $fileid = $fileinfo['fileid']; + $fileInfo = $this->fileview->getFileInfo($file); + $fileId = $fileInfo['fileid']; - if(is_null($fileid)) { + if(is_null($fileId)) { return false; } - $previewpath = $this->getThumbnailsFolder() . '/' . $fileid . '/'; - if(!$this->userview->is_dir($previewpath)) { + $previewPath = $this->getThumbnailsFolder() . '/' . $fileId . '/'; + if(!$this->userview->is_dir($previewPath)) { return false; } //does a preview with the wanted height and width already exist? - if($this->userview->file_exists($previewpath . $maxX . '-' . $maxY . '.png')) { - return $previewpath . $maxX . '-' . $maxY . '.png'; + if($this->userview->file_exists($previewPath . $maxX . '-' . $maxY . '.png')) { + return $previewPath . $maxX . '-' . $maxY . '.png'; } - $wantedaspectratio = (float) ($maxX / $maxY); + $wantedAspectRatio = (float) ($maxX / $maxY); //array for usable cached thumbnails - $possiblethumbnails = array(); + $possibleThumbnails = array(); - $allthumbnails = $this->userview->getDirectoryContent($previewpath); - foreach($allthumbnails as $thumbnail) { + $allThumbnails = $this->userview->getDirectoryContent($previewPath); + foreach($allThumbnails as $thumbnail) { $name = rtrim($thumbnail['name'], '.png'); $size = explode('-', $name); $x = (int) $size[0]; $y = (int) $size[1]; - $aspectratio = (float) ($x / $y); - if($aspectratio !== $wantedaspectratio) { + $aspectRatio = (float) ($x / $y); + if($aspectRatio !== $wantedAspectRatio) { continue; } if($x < $maxX || $y < $maxY) { - if($scalingup) { + if($scalingUp) { $scalefactor = $maxX / $x; if($scalefactor > $maxscalefactor) { continue; @@ -326,28 +326,28 @@ class Preview { continue; } } - $possiblethumbnails[$x] = $thumbnail['path']; + $possibleThumbnails[$x] = $thumbnail['path']; } - if(count($possiblethumbnails) === 0) { + if(count($possibleThumbnails) === 0) { return false; } - if(count($possiblethumbnails) === 1) { - return current($possiblethumbnails); + if(count($possibleThumbnails) === 1) { + return current($possibleThumbnails); } - ksort($possiblethumbnails); + ksort($possibleThumbnails); - if(key(reset($possiblethumbnails)) > $maxX) { - return current(reset($possiblethumbnails)); + if(key(reset($possibleThumbnails)) > $maxX) { + return current(reset($possibleThumbnails)); } - if(key(end($possiblethumbnails)) < $maxX) { - return current(end($possiblethumbnails)); + if(key(end($possibleThumbnails)) < $maxX) { + return current(end($possibleThumbnails)); } - foreach($possiblethumbnails as $width => $path) { + foreach($possibleThumbnails as $width => $path) { if($width < $maxX) { continue; }else{ @@ -358,7 +358,7 @@ class Preview { /** * @brief return a preview of a file - * @return image + * @return \OC_Image */ public function getPreview() { if(!is_null($this->preview) && $this->preview->valid()){ @@ -369,10 +369,10 @@ class Preview { $file = $this->getFile(); $maxX = $this->getMaxX(); $maxY = $this->getMaxY(); - $scalingup = $this->getScalingup(); + $scalingUp = $this->getScalingUp(); - $fileinfo = $this->fileview->getFileInfo($file); - $fileid = $fileinfo['fileid']; + $fileInfo = $this->fileview->getFileInfo($file); + $fileId = $fileInfo['fileid']; $cached = $this->isCached(); @@ -386,12 +386,12 @@ class Preview { $mimetype = $this->fileview->getMimeType($file); $preview = null; - foreach(self::$providers as $supportedmimetype => $provider) { - if(!preg_match($supportedmimetype, $mimetype)) { + foreach(self::$providers as $supportedMimetype => $provider) { + if(!preg_match($supportedMimetype, $mimetype)) { continue; } - $preview = $provider->getThumbnail($file, $maxX, $maxY, $scalingup, $this->fileview); + $preview = $provider->getThumbnail($file, $maxX, $maxY, $scalingUp, $this->fileview); if(!($preview instanceof \OC_Image)) { continue; @@ -400,18 +400,18 @@ class Preview { $this->preview = $preview; $this->resizeAndCrop(); - $previewpath = $this->getThumbnailsFolder() . '/' . $fileid . '/'; - $cachepath = $previewpath . $maxX . '-' . $maxY . '.png'; + $previewPath = $this->getThumbnailsFolder() . '/' . $fileId . '/'; + $cachePath = $previewPath . $maxX . '-' . $maxY . '.png'; if($this->userview->is_dir($this->getThumbnailsFolder() . '/') === false) { $this->userview->mkdir($this->getThumbnailsFolder() . '/'); } - if($this->userview->is_dir($previewpath) === false) { - $this->userview->mkdir($previewpath); + if($this->userview->is_dir($previewPath) === false) { + $this->userview->mkdir($previewPath); } - $this->userview->file_put_contents($cachepath, $preview->data()); + $this->userview->file_put_contents($cachePath, $preview->data()); break; } @@ -447,13 +447,13 @@ class Preview { /** * @brief resize, crop and fix orientation - * @return image + * @return void */ private function resizeAndCrop() { $image = $this->preview; $x = $this->getMaxX(); $y = $this->getMaxY(); - $scalingup = $this->getScalingup(); + $scalingUp = $this->getScalingUp(); $maxscalefactor = $this->getMaxScaleFactor(); if(!($image instanceof \OC_Image)) { @@ -480,7 +480,7 @@ class Preview { $factor = $factorY; } - if($scalingup === false) { + if($scalingUp === false) { if($factor > 1) { $factor = 1; } @@ -583,182 +583,6 @@ class Preview { array_multisort($keys, SORT_DESC, self::$providers); } - /** - * @brief method that handles preview requests from users that are logged in - * @return void - */ - public static function previewRouter() { - \OC_Util::checkLoggedIn(); - - $file = array_key_exists('file', $_GET) ? (string) urldecode($_GET['file']) : ''; - $maxX = array_key_exists('x', $_GET) ? (int) $_GET['x'] : '36'; - $maxY = array_key_exists('y', $_GET) ? (int) $_GET['y'] : '36'; - $scalingup = array_key_exists('scalingup', $_GET) ? (bool) $_GET['scalingup'] : true; - - if($file === '') { - \OC_Response::setStatus(400); //400 Bad Request - \OC_Log::write('core-preview', 'No file parameter was passed', \OC_Log::DEBUG); - self::showErrorPreview(); - exit; - } - - if($maxX === 0 || $maxY === 0) { - \OC_Response::setStatus(400); //400 Bad Request - \OC_Log::write('core-preview', 'x and/or y set to 0', \OC_Log::DEBUG); - self::showErrorPreview(); - exit; - } - - try{ - $preview = new Preview(\OC_User::getUser(), 'files'); - $preview->setFile($file); - $preview->setMaxX($maxX); - $preview->setMaxY($maxY); - $preview->setScalingUp($scalingup); - - $preview->show(); - }catch(\Exception $e) { - \OC_Response::setStatus(500); - \OC_Log::write('core', $e->getmessage(), \OC_Log::ERROR); - self::showErrorPreview(); - exit; - } - } - - /** - * @brief method that handles preview requests from users that are not logged in / view shared folders that are public - * @return void - */ - public static function publicPreviewRouter() { - if(!\OC_App::isEnabled('files_sharing')){ - exit; - } - - $file = array_key_exists('file', $_GET) ? (string) urldecode($_GET['file']) : ''; - $maxX = array_key_exists('x', $_GET) ? (int) $_GET['x'] : '36'; - $maxY = array_key_exists('y', $_GET) ? (int) $_GET['y'] : '36'; - $scalingup = array_key_exists('scalingup', $_GET) ? (bool) $_GET['scalingup'] : true; - $token = array_key_exists('t', $_GET) ? (string) $_GET['t'] : ''; - - if($token === ''){ - \OC_Response::setStatus(400); //400 Bad Request - \OC_Log::write('core-preview', 'No token parameter was passed', \OC_Log::DEBUG); - self::showErrorPreview(); - exit; - } - - $linkedItem = \OCP\Share::getShareByToken($token); - if($linkedItem === false || ($linkedItem['item_type'] !== 'file' && $linkedItem['item_type'] !== 'folder')) { - \OC_Response::setStatus(404); - \OC_Log::write('core-preview', 'Passed token parameter is not valid', \OC_Log::DEBUG); - self::showErrorPreview(); - exit; - } - - if(!isset($linkedItem['uid_owner']) || !isset($linkedItem['file_source'])) { - \OC_Response::setStatus(500); - \OC_Log::write('core-preview', 'Passed token seems to be valid, but it does not contain all necessary information . ("' . $token . '")'); - self::showErrorPreview(); - exit; - } - - $userid = $linkedItem['uid_owner']; - \OC_Util::setupFS($userid); - - $pathid = $linkedItem['file_source']; - $path = \OC\Files\Filesystem::getPath($pathid); - $pathinfo = \OC\Files\Filesystem::getFileInfo($path); - $sharedfile = null; - - if($linkedItem['item_type'] === 'folder') { - $isvalid = \OC\Files\Filesystem::isValidPath($file); - if(!$isvalid) { - \OC_Response::setStatus(400); //400 Bad Request - \OC_Log::write('core-preview', 'Passed filename is not valid, might be malicious (file:"' . $file . '";ip:"' . $_SERVER['REMOTE_ADDR'] . '")', \OC_Log::WARN); - self::showErrorPreview(); - exit; - } - $sharedfile = \OC\Files\Filesystem::normalizePath($file); - } - - if($linkedItem['item_type'] === 'file') { - $parent = $pathinfo['parent']; - $path = \OC\Files\Filesystem::getPath($parent); - $sharedfile = $pathinfo['name']; - } - - $path = \OC\Files\Filesystem::normalizePath($path, false); - if(substr($path, 0, 1) === '/') { - $path = substr($path, 1); - } - - if($maxX === 0 || $maxY === 0) { - \OC_Response::setStatus(400); //400 Bad Request - \OC_Log::write('core-preview', 'x and/or y set to 0', \OC_Log::DEBUG); - self::showErrorPreview(); - exit; - } - - $root = 'files/' . $path; - - try{ - $preview = new Preview($userid, $root); - $preview->setFile($file); - $preview->setMaxX($maxX); - $preview->setMaxY($maxY); - $preview->setScalingUp($scalingup); - - $preview->show(); - }catch(\Exception $e) { - \OC_Response::setStatus(500); - \OC_Log::write('core', $e->getmessage(), \OC_Log::ERROR); - self::showErrorPreview(); - exit; - } - } - - public static function trashbinPreviewRouter() { - \OC_Util::checkLoggedIn(); - - if(!\OC_App::isEnabled('files_trashbin')){ - exit; - } - - $file = array_key_exists('file', $_GET) ? (string) urldecode($_GET['file']) : ''; - $maxX = array_key_exists('x', $_GET) ? (int) $_GET['x'] : '44'; - $maxY = array_key_exists('y', $_GET) ? (int) $_GET['y'] : '44'; - $scalingup = array_key_exists('scalingup', $_GET) ? (bool) $_GET['scalingup'] : true; - - if($file === '') { - \OC_Response::setStatus(400); //400 Bad Request - \OC_Log::write('core-preview', 'No file parameter was passed', \OC_Log::DEBUG); - self::showErrorPreview(); - exit; - } - - if($maxX === 0 || $maxY === 0) { - \OC_Response::setStatus(400); //400 Bad Request - \OC_Log::write('core-preview', 'x and/or y set to 0', \OC_Log::DEBUG); - self::showErrorPreview(); - exit; - } - - try{ - $preview = new Preview(\OC_User::getUser(), 'files_trashbin/files'); - $preview->setFile($file); - $preview->setMaxX($maxX); - $preview->setMaxY($maxY); - $preview->setScalingUp($scalingup); - - $preview->showPreview(); - }catch(\Exception $e) { - \OC_Response::setStatus(500); - \OC_Log::write('core', $e->getmessage(), \OC_Log::ERROR); - self::showErrorPreview(); - exit; - } - } - public static function post_write($args) { self::post_delete($args); } @@ -780,8 +604,8 @@ class Preview { //remove last element because it has the mimetype * $providers = array_slice(self::$providers, 0, -1); - foreach($providers as $supportedmimetype => $provider) { - if(preg_match($supportedmimetype, $mimetype)) { + foreach($providers as $supportedMimetype => $provider) { + if(preg_match($supportedMimetype, $mimetype)) { return true; } } diff --git a/lib/preview/images.php b/lib/preview/images.php index 987aa9aef0a..9aec967282d 100644 --- a/lib/preview/images.php +++ b/lib/preview/images.php @@ -16,10 +16,13 @@ class Image extends Provider { public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { //get fileinfo - $fileinfo = $fileview->getFileInfo($path); + $fileInfo = $fileview->getFileInfo($path); + if(!$fileInfo) { + return false; + } //check if file is encrypted - if($fileinfo['encrypted'] === true) { + if($fileInfo['encrypted'] === true) { $image = new \OC_Image(stream_get_contents($fileview->fopen($path, 'r'))); }else{ $image = new \OC_Image(); diff --git a/lib/preview/libreoffice-cl.php b/lib/preview/libreoffice-cl.php index 2749c4867e9..0f4ec3d0348 100644 --- a/lib/preview/libreoffice-cl.php +++ b/lib/preview/libreoffice-cl.php @@ -22,28 +22,30 @@ class Office extends Provider { return false; } - $abspath = $fileview->toTmpFile($path); + $absPath = $fileview->toTmpFile($path); - $tmpdir = get_temp_dir(); + $tmpDir = get_temp_dir(); - $exec = $this->cmd . ' --headless --nologo --nofirststartwizard --invisible --norestore -convert-to pdf -outdir ' . escapeshellarg($tmpdir) . ' ' . escapeshellarg($abspath); - $export = 'export HOME=/' . $tmpdir; + $exec = $this->cmd . ' --headless --nologo --nofirststartwizard --invisible --norestore -convert-to pdf -outdir ' . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath); + $export = 'export HOME=/' . $tmpDir; shell_exec($export . "\n" . $exec); //create imagick object from pdf try{ - $pdf = new \imagick($abspath . '.pdf' . '[0]'); + $pdf = new \imagick($absPath . '.pdf' . '[0]'); $pdf->setImageFormat('jpg'); - }catch(\Exception $e){ + }catch (\Exception $e) { + unlink($absPath); + unlink($absPath . '.pdf'); \OC_Log::write('core', $e->getmessage(), \OC_Log::ERROR); return false; } $image = new \OC_Image($pdf); - unlink($abspath); - unlink($abspath . '.pdf'); + unlink($absPath); + unlink($absPath . '.pdf'); return $image->valid() ? $image : false; } @@ -55,11 +57,13 @@ class Office extends Provider { $cmd = \OC_Config::getValue('preview_libreoffice_path', null); } - if($cmd === '' && shell_exec('libreoffice --headless --version')) { + $whichLibreOffice = shell_exec('which libreoffice'); + if($cmd === '' && !empty($whichLibreOffice)) { $cmd = 'libreoffice'; } - if($cmd === '' && shell_exec('openoffice --headless --version')) { + $whichOpenOffice = shell_exec('which openoffice'); + if($cmd === '' && !empty($whichOpenOffice)) { $cmd = 'openoffice'; } diff --git a/lib/preview/movies.php b/lib/preview/movies.php index 8531050d112..e2a1b8edddc 100644 --- a/lib/preview/movies.php +++ b/lib/preview/movies.php @@ -8,7 +8,11 @@ */ namespace OC\Preview; -if(!is_null(shell_exec('ffmpeg -version'))) { +$isShellExecEnabled = !in_array('shell_exec', explode(', ', ini_get('disable_functions'))); +$whichFFMPEG = shell_exec('which ffmpeg'); +$isFFMPEGAvailable = !empty($whichFFMPEG); + +if($isShellExecEnabled && $isFFMPEGAvailable) { class Movie extends Provider { @@ -17,23 +21,23 @@ if(!is_null(shell_exec('ffmpeg -version'))) { } public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { - $abspath = \OC_Helper::tmpFile(); - $tmppath = \OC_Helper::tmpFile(); + $absPath = \OC_Helper::tmpFile(); + $tmpPath = \OC_Helper::tmpFile(); $handle = $fileview->fopen($path, 'rb'); $firstmb = stream_get_contents($handle, 1048576); //1024 * 1024 = 1048576 - file_put_contents($abspath, $firstmb); + file_put_contents($absPath, $firstmb); - //$cmd = 'ffmpeg -y -i ' . escapeshellarg($abspath) . ' -f mjpeg -vframes 1 -ss 1 -s ' . escapeshellarg($maxX) . 'x' . escapeshellarg($maxY) . ' ' . $tmppath; - $cmd = 'ffmpeg -an -y -i ' . escapeshellarg($abspath) . ' -f mjpeg -vframes 1 -ss 1 ' . escapeshellarg($tmppath); + //$cmd = 'ffmpeg -y -i ' . escapeshellarg($absPath) . ' -f mjpeg -vframes 1 -ss 1 -s ' . escapeshellarg($maxX) . 'x' . escapeshellarg($maxY) . ' ' . $tmpPath; + $cmd = 'ffmpeg -an -y -i ' . escapeshellarg($absPath) . ' -f mjpeg -vframes 1 -ss 1 ' . escapeshellarg($tmpPath); shell_exec($cmd); - $image = new \OC_Image($tmppath); + $image = new \OC_Image($tmpPath); - unlink($abspath); - unlink($tmppath); + unlink($absPath); + unlink($tmpPath); return $image->valid() ? $image : false; } diff --git a/lib/preview/mp3.php b/lib/preview/mp3.php index 835ff529000..1eed566315c 100644 --- a/lib/preview/mp3.php +++ b/lib/preview/mp3.php @@ -18,19 +18,21 @@ class MP3 extends Provider { $getID3 = new \getID3(); - $tmppath = $fileview->toTmpFile($path); - - $tags = $getID3->analyze($tmppath); - \getid3_lib::CopyTagsToComments($tags); - $picture = @$tags['id3v2']['APIC'][0]['data']; - - unlink($tmppath); + $tmpPath = $fileview->toTmpFile($path); + + $tags = $getID3->analyze($tmpPath); + \getid3_lib::CopyTagsToComments($tags); + if(isset($tags['id3v2']['APIC'][0]['data'])) { + $picture = @$tags['id3v2']['APIC'][0]['data']; + unlink($tmpPath); + $image = new \OC_Image($picture); + return $image->valid() ? $image : $this->getNoCoverThumbnail(); + } - $image = new \OC_Image($picture); - return $image->valid() ? $image : $this->getNoCoverThumbnail($maxX, $maxY); + return $this->getNoCoverThumbnail(); } - public function getNoCoverThumbnail($maxX, $maxY) { + private function getNoCoverThumbnail() { $icon = \OC::$SERVERROOT . '/core/img/filetypes/audio.png'; if(!file_exists($icon)) { diff --git a/lib/preview/msoffice.php b/lib/preview/msoffice.php index ccf1d674c7a..e69ab0ab8cb 100644 --- a/lib/preview/msoffice.php +++ b/lib/preview/msoffice.php @@ -32,16 +32,16 @@ class DOCX extends Provider { public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { require_once('phpdocx/classes/TransformDoc.inc'); - $tmpdoc = $fileview->toTmpFile($path); + $tmpDoc = $fileview->toTmpFile($path); $transformdoc = new \TransformDoc(); - $transformdoc->setStrFile($tmpdoc); - $transformdoc->generatePDF($tmpdoc); + $transformdoc->setStrFile($tmpDoc); + $transformdoc->generatePDF($tmpDoc); - $pdf = new \imagick($tmpdoc . '[0]'); + $pdf = new \imagick($tmpDoc . '[0]'); $pdf->setImageFormat('jpg'); - unlink($tmpdoc); + unlink($tmpDoc); $image = new \OC_Image($pdf); @@ -62,23 +62,23 @@ class MSOfficeExcel extends Provider { require_once('PHPExcel/Classes/PHPExcel.php'); require_once('PHPExcel/Classes/PHPExcel/IOFactory.php'); - $abspath = $fileview->toTmpFile($path); - $tmppath = \OC_Helper::tmpFile(); + $absPath = $fileview->toTmpFile($path); + $tmpPath = \OC_Helper::tmpFile(); $rendererName = \PHPExcel_Settings::PDF_RENDERER_DOMPDF; $rendererLibraryPath = \OC::$THIRDPARTYROOT . '/3rdparty/dompdf'; \PHPExcel_Settings::setPdfRenderer($rendererName, $rendererLibraryPath); - $phpexcel = new \PHPExcel($abspath); + $phpexcel = new \PHPExcel($absPath); $excel = \PHPExcel_IOFactory::createWriter($phpexcel, 'PDF'); - $excel->save($tmppath); + $excel->save($tmpPath); - $pdf = new \imagick($tmppath . '[0]'); + $pdf = new \imagick($tmpPath . '[0]'); $pdf->setImageFormat('jpg'); - unlink($abspath); - unlink($tmppath); + unlink($absPath); + unlink($tmpPath); $image = new \OC_Image($pdf); diff --git a/lib/preview/office.php b/lib/preview/office.php index b6783bc5798..b93e1e57c8b 100644 --- a/lib/preview/office.php +++ b/lib/preview/office.php @@ -7,8 +7,13 @@ */ //both, libreoffice backend and php fallback, need imagick if (extension_loaded('imagick')) { + $isShellExecEnabled = !in_array('shell_exec', explode(', ', ini_get('disable_functions'))); + $whichLibreOffice = shell_exec('which libreoffice'); + $isLibreOfficeAvailable = !empty($whichLibreOffice); + $whichOpenOffice = shell_exec('which libreoffice'); + $isOpenOfficeAvailable = !empty($whichOpenOffice); //let's see if there is libreoffice or openoffice on this machine - if(shell_exec('libreoffice --headless --version') || shell_exec('openoffice --headless --version') || is_string(\OC_Config::getValue('preview_libreoffice_path', null))) { + if($isShellExecEnabled && ($isLibreOfficeAvailable || $isOpenOfficeAvailable || is_string(\OC_Config::getValue('preview_libreoffice_path', null)))) { require_once('libreoffice-cl.php'); }else{ //in case there isn't, use our fallback diff --git a/lib/preview/pdf.php b/lib/preview/pdf.php index 3eabd201156..723dc1d80d2 100644 --- a/lib/preview/pdf.php +++ b/lib/preview/pdf.php @@ -16,18 +16,18 @@ if (extension_loaded('imagick')) { } public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { - $tmppath = $fileview->toTmpFile($path); + $tmpPath = $fileview->toTmpFile($path); //create imagick object from pdf try{ - $pdf = new \imagick($tmppath . '[0]'); + $pdf = new \imagick($tmpPath . '[0]'); $pdf->setImageFormat('jpg'); - }catch(\Exception $e){ + }catch (\Exception $e) { \OC_Log::write('core', $e->getmessage(), \OC_Log::ERROR); return false; } - unlink($tmppath); + unlink($tmpPath); //new image object $image = new \OC_Image($pdf); diff --git a/lib/preview/txt.php b/lib/preview/txt.php index c7b8fabc6b0..89927fd580a 100644 --- a/lib/preview/txt.php +++ b/lib/preview/txt.php @@ -18,24 +18,23 @@ class TXT extends Provider { $content = stream_get_contents($content); $lines = preg_split("/\r\n|\n|\r/", $content); - $numoflines = count($lines); - $fontsize = 5; //5px - $linesize = ceil($fontsize * 1.25); + $fontSize = 5; //5px + $lineSize = ceil($fontSize * 1.25); $image = imagecreate($maxX, $maxY); - $imagecolor = imagecolorallocate($image, 255, 255, 255); - $textcolor = imagecolorallocate($image, 0, 0, 0); + imagecolorallocate($image, 255, 255, 255); + $textColor = imagecolorallocate($image, 0, 0, 0); foreach($lines as $index => $line) { $index = $index + 1; $x = (int) 1; - $y = (int) ($index * $linesize) - $fontsize; + $y = (int) ($index * $lineSize) - $fontSize; - imagestring($image, 1, $x, $y, $line, $textcolor); + imagestring($image, 1, $x, $y, $line, $textColor); - if(($index * $linesize) >= $maxY) { + if(($index * $lineSize) >= $maxY) { break; } } diff --git a/lib/preview/unknown.php b/lib/preview/unknown.php index a31b365722e..ba13ca35d66 100644 --- a/lib/preview/unknown.php +++ b/lib/preview/unknown.php @@ -20,7 +20,7 @@ class Unknown extends Provider { list($type, $subtype) = explode('/', $mimetype); } - $iconsroot = \OC::$SERVERROOT . '/core/img/filetypes/'; + $iconsRoot = \OC::$SERVERROOT . '/core/img/filetypes/'; if(isset($type)){ $icons = array($mimetype, $type, 'text'); @@ -30,10 +30,10 @@ class Unknown extends Provider { foreach($icons as $icon) { $icon = str_replace('/', '-', $icon); - $iconpath = $iconsroot . $icon . '.png'; + $iconPath = $iconsRoot . $icon . '.png'; - if(file_exists($iconpath)) { - return new \OC_Image($iconpath); + if(file_exists($iconPath)) { + return new \OC_Image($iconPath); } } return false; diff --git a/lib/template.php b/lib/template.php index caa1e667c61..9b2c1211e61 100644 --- a/lib/template.php +++ b/lib/template.php @@ -23,6 +23,9 @@ require_once __DIR__.'/template/functions.php'; +/** + * This class provides the templates for ownCloud. + */ class OC_Template extends \OC\Template\Base { private $renderas; // Create a full page? private $path; // The path to the template diff --git a/lib/template/functions.php b/lib/template/functions.php index a864614c9a1..842f28c90e0 100644 --- a/lib/template/functions.php +++ b/lib/template/functions.php @@ -47,6 +47,22 @@ function image_path( $app, $image ) { return OC_Helper::imagePath( $app, $image ); } +/** + * @brief make preview_icon available as a simple function + * Returns the path to the preview of the image. + * @param $path path of file + * @returns link to the preview + * + * For further information have a look at OC_Helper::previewIcon + */ +function preview_icon( $path ) { + return OC_Helper::previewIcon( $path ); +} + +function publicPreview_icon ( $path, $token ) { + return OC_Helper::publicPreviewIcon( $path, $token ); +} + /** * @brief make OC_Helper::mimetypeIcon available as a simple function * @param string $mimetype mimetype -- cgit v1.2.3 From e1927d5bee11b561a293a9488bd27d90c2c043e6 Mon Sep 17 00:00:00 2001 From: Jörn Friedrich Dreyer Date: Mon, 12 Aug 2013 12:33:22 +0200 Subject: fix whitespace, check selected files before starting upload --- apps/files/ajax/upload.php | 39 ++- apps/files/css/files.css | 41 +++ apps/files/js/file-upload.js | 710 +++++++++++++++++++++++++------------------ apps/files/js/filelist.js | 2 +- core/js/jquery.ocdialog.js | 3 + core/js/oc-dialogs.js | 134 +++++++- 6 files changed, 614 insertions(+), 315 deletions(-) (limited to 'apps/files/js') diff --git a/apps/files/ajax/upload.php b/apps/files/ajax/upload.php index dde5d3c50af..8d183bd1f9c 100644 --- a/apps/files/ajax/upload.php +++ b/apps/files/ajax/upload.php @@ -98,23 +98,46 @@ $result = array(); if (strpos($dir, '..') === false) { $fileCount = count($files['name']); for ($i = 0; $i < $fileCount; $i++) { - $target = OCP\Files::buildNotExistingFileName(stripslashes($dir), $files['name'][$i]); // $path needs to be normalized - this failed within drag'n'drop upload to a sub-folder - $target = \OC\Files\Filesystem::normalizePath($target); - if (is_uploaded_file($files['tmp_name'][$i]) and \OC\Files\Filesystem::fromTmpFile($files['tmp_name'][$i], $target)) { + if (isset($_POST['new_name'])) { + $newName = $_POST['new_name']; + } else { + $newName = $files['name'][$i]; + } + if (isset($_POST['replace']) && $_POST['replace'] == true) { + $replace = true; + } else { + $replace = false; + } + $target = \OC\Files\Filesystem::normalizePath(stripslashes($dir).$newName); + if ( ! $replace && \OC\Files\Filesystem::file_exists($target)) { $meta = \OC\Files\Filesystem::getFileInfo($target); - // updated max file size after upload - $storageStats = \OCA\files\lib\Helper::buildFileStorageStatistics($dir); - - $result[] = array('status' => 'success', + $result[] = array('status' => 'existserror', 'mime' => $meta['mimetype'], 'size' => $meta['size'], 'id' => $meta['fileid'], 'name' => basename($target), - 'originalname' => $files['name'][$i], + 'originalname' => $newName, 'uploadMaxFilesize' => $maxUploadFileSize, 'maxHumanFilesize' => $maxHumanFileSize ); + } else { + //$target = OCP\Files::buildNotExistingFileName(stripslashes($dir), $files['name'][$i]); + if (is_uploaded_file($files['tmp_name'][$i]) and \OC\Files\Filesystem::fromTmpFile($files['tmp_name'][$i], $target)) { + $meta = \OC\Files\Filesystem::getFileInfo($target); + // updated max file size after upload + $storageStats = \OCA\files\lib\Helper::buildFileStorageStatistics($dir); + + $result[] = array('status' => 'success', + 'mime' => $meta['mimetype'], + 'size' => $meta['size'], + 'id' => $meta['fileid'], + 'name' => basename($target), + 'originalname' => $newName, + 'uploadMaxFilesize' => $maxUploadFileSize, + 'maxHumanFilesize' => $maxHumanFileSize + ); + } } } OCP\JSON::encodedPrint($result); diff --git a/apps/files/css/files.css b/apps/files/css/files.css index 86fb0dc6046..acee8471aff 100644 --- a/apps/files/css/files.css +++ b/apps/files/css/files.css @@ -189,3 +189,44 @@ table.dragshadow td.size { text-align: center; margin-left: -200px; } + +.oc-dialog .fileexists .original .icon { + width: 64px; + height: 64px; + margin: 5px 5px 5px 0px; + background-repeat: no-repeat; + background-size: 64px 64px; + float: left; +} + +.oc-dialog .fileexists .replacement { + margin-top: 20px; +} + +.oc-dialog .fileexists .replacement .icon { + width: 64px; + height: 64px; + margin: 5px 5px 5px 0px; + background-repeat: no-repeat; + background-size: 64px 64px; + float: left; + clear: both; +} + +.oc-dialog .fileexists label[for="new-name"] { + margin-top: 20px; + display: block; +} +.oc-dialog .fileexists h3 { + font-weight: bold; +} + + +.oc-dialog .oc-dialog-buttonrow { + width:100%; + text-align:right; +} + +.oc-dialog .oc-dialog-buttonrow .cancel { + float:left; +} \ No newline at end of file diff --git a/apps/files/js/file-upload.js b/apps/files/js/file-upload.js index 942a07dfccc..71034a0b3f4 100644 --- a/apps/files/js/file-upload.js +++ b/apps/files/js/file-upload.js @@ -1,343 +1,445 @@ -$(document).ready(function() { - - file_upload_param = { - dropZone: $('#content'), // restrict dropZone to content div - //singleFileUploads is on by default, so the data.files array will always have length 1 - add: function(e, data) { - - if(data.files[0].type === '' && data.files[0].size == 4096) - { - data.textStatus = 'dirorzero'; - data.errorThrown = t('files','Unable to upload your file as it is a directory or has 0 bytes'); - var fu = $(this).data('blueimp-fileupload') || $(this).data('fileupload'); - fu._trigger('fail', e, data); - return true; //don't upload this file but go on with next in queue - } - - var totalSize=0; - $.each(data.originalFiles, function(i,file){ - totalSize+=file.size; - }); - - if(totalSize>$('#max_upload').val()){ - data.textStatus = 'notenoughspace'; - data.errorThrown = t('files','Not enough space available'); - var fu = $(this).data('blueimp-fileupload') || $(this).data('fileupload'); - fu._trigger('fail', e, data); - return false; //don't upload anything - } - - // start the actual file upload - var jqXHR = data.submit(); +OC.upload = { + _isProcessing:false, + isProcessing:function(){ + return this._isProcessing; + }, + _uploadQueue:[], + addUpload:function(data){ + this._uploadQueue.push(data); - // remember jqXHR to show warning to user when he navigates away but an upload is still in progress - if (typeof data.context !== 'undefined' && data.context.data('type') === 'dir') { - var dirName = data.context.data('file'); - if(typeof uploadingFiles[dirName] === 'undefined') { - uploadingFiles[dirName] = {}; + if ( ! OC.upload.isProcessing() ) { + OC.upload.startUpload(); } - uploadingFiles[dirName][data.files[0].name] = jqXHR; - } else { - uploadingFiles[data.files[0].name] = jqXHR; - } - - //show cancel button - if($('html.lte9').length === 0 && data.dataType !== 'iframe') { - $('#uploadprogresswrapper input.stop').show(); - } }, - /** - * called after the first add, does NOT have the data param - * @param e - */ - start: function(e) { - //IE < 10 does not fire the necessary events for the progress bar. - if($('html.lte9').length > 0) { - return; - } - $('#uploadprogressbar').progressbar({value:0}); - $('#uploadprogressbar').fadeIn(); + startUpload:function(){ + if (this._uploadQueue.length > 0) { + this._isProcessing = true; + this.nextUpload(); + return true; + } else { + return false; + } }, - fail: function(e, data) { - if (typeof data.textStatus !== 'undefined' && data.textStatus !== 'success' ) { - if (data.textStatus === 'abort') { - $('#notification').text(t('files', 'Upload cancelled.')); + nextUpload:function(){ + if (this._uploadQueue.length > 0) { + var data = this._uploadQueue.pop(); + var jqXHR = data.submit(); + + // remember jqXHR to show warning to user when he navigates away but an upload is still in progress + if (typeof data.context !== 'undefined' && data.context.data('type') === 'dir') { + var dirName = data.context.data('file'); + if(typeof uploadingFiles[dirName] === 'undefined') { + uploadingFiles[dirName] = {}; + } + uploadingFiles[dirName][data.files[0].name] = jqXHR; + } else { + uploadingFiles[data.files[0].name] = jqXHR; + } } else { - // HTTP connection problem - $('#notification').text(data.errorThrown); + //queue is empty, we are done + this._isProcessing = false; } - $('#notification').fadeIn(); - //hide notification after 5 sec - setTimeout(function() { - $('#notification').fadeOut(); - }, 5000); - } - delete uploadingFiles[data.files[0].name]; }, - progress: function(e, data) { - // TODO: show nice progress bar in file row + onCancel:function(data){ + //TODO cancel all uploads + Files.cancelUploads(); + this._uploadQueue = []; + this._isProcessing = false; + }, + onSkip:function(data){ + this.nextUpload(); }, - progressall: function(e, data) { - //IE < 10 does not fire the necessary events for the progress bar. - if($('html.lte9').length > 0) { - return; - } - var progress = (data.loaded/data.total)*100; - $('#uploadprogressbar').progressbar('value',progress); + onReplace:function(data){ + //TODO overwrite file + data.data.append('replace', true); + data.submit(); }, - /** - * called for every successful upload - * @param e - * @param data - */ - done:function(e, data) { - // handle different responses (json or body from iframe for ie) - var response; - if (typeof data.result === 'string') { - response = data.result; - } else { - //fetch response from iframe - response = data.result[0].body.innerText; - } - var result=$.parseJSON(response); + onRename:function(data, newName){ + //TODO rename file in filelist, stop spinner + data.data.append('new_name', newName); + data.submit(); + } +}; - if(typeof result[0] !== 'undefined' && result[0].status === 'success') { - var file = result[0]; - } else { - data.textStatus = 'servererror'; - data.errorThrown = t('files', result.data.message); - var fu = $(this).data('blueimp-fileupload') || $(this).data('fileupload'); - fu._trigger('fail', e, data); - } +$(document).ready(function() { - var filename = result[0].originalname; + var file_upload_param = { + dropZone: $('#content'), // restrict dropZone to content div + //singleFileUploads is on by default, so the data.files array will always have length 1 + add: function(e, data) { + var that = $(this); - // delete jqXHR reference - if (typeof data.context !== 'undefined' && data.context.data('type') === 'dir') { - var dirName = data.context.data('file'); - delete uploadingFiles[dirName][filename]; - if ($.assocArraySize(uploadingFiles[dirName]) == 0) { - delete uploadingFiles[dirName]; - } - } else { - delete uploadingFiles[filename]; - } + if (typeof data.originalFiles.checked === 'undefined') { + + var totalSize = 0; + $.each(data.originalFiles, function(i, file) { + totalSize += file.size; - }, - /** - * called after last upload - * @param e - * @param data - */ - stop: function(e, data) { - if(data.dataType !== 'iframe') { - $('#uploadprogresswrapper input.stop').hide(); - } + if (file.type === '' && file.size === 4096) { + data.textStatus = 'dirorzero'; + data.errorThrown = t('files', 'Unable to upload {filename} as it is a directory or has 0 bytes', + {filename: file.name} + ); + return false; + } + }); - //IE < 10 does not fire the necessary events for the progress bar. - if($('html.lte9').length > 0) { - return; - } + if (totalSize > $('#max_upload').val()) { + data.textStatus = 'notenoughspace'; + data.errorThrown = t('files', 'Not enough space available'); + } - $('#uploadprogressbar').progressbar('value',100); - $('#uploadprogressbar').fadeOut(); - } - } - var file_upload_handler = function() { - $('#file_upload_start').fileupload(file_upload_param); - }; + if (data.errorThrown) { + //don't upload anything + var fu = that.data('blueimp-fileupload') || that.data('fileupload'); + fu._trigger('fail', e, data); + return false; + } + + data.originalFiles.checked = true; // this will skip the checks on subsequent adds + } + + //TODO check filename already exists + /* + if ($('tr[data-file="'+data.files[0].name+'"][data-id]').length > 0) { + data.textStatus = 'alreadyexists'; + data.errorThrown = t('files', '{filename} already exists', + {filename: data.files[0].name} + ); + //TODO show "file already exists" dialog + var fu = that.data('blueimp-fileupload') || that.data('fileupload'); + fu._trigger('fail', e, data); + return false; + } + */ + //add files to queue + OC.upload.addUpload(data); + + //TODO refactor away: + //show cancel button + if($('html.lte9').length === 0 && data.dataType !== 'iframe') { + $('#uploadprogresswrapper input.stop').show(); + } + return true; + }, + /** + * called after the first add, does NOT have the data param + * @param e + */ + start: function(e) { + //IE < 10 does not fire the necessary events for the progress bar. + if($('html.lte9').length > 0) { + return true; + } + $('#uploadprogressbar').progressbar({value:0}); + $('#uploadprogressbar').fadeIn(); + }, + fail: function(e, data) { + if (typeof data.textStatus !== 'undefined' && data.textStatus !== 'success' ) { + if (data.textStatus === 'abort') { + $('#notification').text(t('files', 'Upload cancelled.')); + } else { + // HTTP connection problem + $('#notification').text(data.errorThrown); + } + $('#notification').fadeIn(); + //hide notification after 5 sec + setTimeout(function() { + $('#notification').fadeOut(); + }, 5000); + } + delete uploadingFiles[data.files[0].name]; + }, + progress: function(e, data) { + // TODO: show nice progress bar in file row + }, + progressall: function(e, data) { + //IE < 10 does not fire the necessary events for the progress bar. + if($('html.lte9').length > 0) { + return; + } + var progress = (data.loaded/data.total)*100; + $('#uploadprogressbar').progressbar('value', progress); + }, + /** + * called for every successful upload + * @param e + * @param data + */ + done:function(e, data) { + // handle different responses (json or body from iframe for ie) + var response; + if (typeof data.result === 'string') { + response = data.result; + } else { + //fetch response from iframe + response = data.result[0].body.innerText; + } + var result=$.parseJSON(response); + if(typeof result[0] !== 'undefined' && result[0].status === 'success') { + OC.upload.nextUpload(); + } else { + if (result[0].status === 'existserror') { + //TODO open dialog and retry with other name? + // get jqXHR reference + if (typeof data.context !== 'undefined' && data.context.data('type') === 'dir') { + var dirName = data.context.data('file'); + var jqXHR = uploadingFiles[dirName][filename]; + } else { + var jqXHR = uploadingFiles[filename]; + } + //filenames can only be changed on the server side + //TODO show "file already exists" dialog + //options: abort | skip | replace / rename + //TODO reset all-files flag? when done with selection? + var original = result[0]; + var replacement = data.files[0]; + OC.dialogs.fileexists(data, original, replacement, OC.upload); + } else { + data.textStatus = 'servererror'; + data.errorThrown = t('files', result.data.message); + var fu = $(this).data('blueimp-fileupload') || $(this).data('fileupload'); + fu._trigger('fail', e, data); + } + } - if ( document.getElementById('data-upload-form') ) { - $(file_upload_handler); - } - $.assocArraySize = function(obj) { - // http://stackoverflow.com/a/6700/11236 - var size = 0, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) size++; - } - return size; - }; + var filename = result[0].originalname; - // warn user not to leave the page while upload is in progress - $(window).bind('beforeunload', function(e) { - if ($.assocArraySize(uploadingFiles) > 0) - return t('files','File upload is in progress. Leaving the page now will cancel the upload.'); - }); + // delete jqXHR reference + if (typeof data.context !== 'undefined' && data.context.data('type') === 'dir') { + var dirName = data.context.data('file'); + delete uploadingFiles[dirName][filename]; + if ($.assocArraySize(uploadingFiles[dirName]) === 0) { + delete uploadingFiles[dirName]; + } + } else { + delete uploadingFiles[filename]; + } + + }, + /** + * called after last upload + * @param e + * @param data + */ + stop: function(e, data) { + if(data.dataType !== 'iframe') { + $('#uploadprogresswrapper input.stop').hide(); + } - //add multiply file upload attribute to all browsers except konqueror (which crashes when it's used) - if(navigator.userAgent.search(/konqueror/i)==-1){ - $('#file_upload_start').attr('multiple','multiple') - } + //IE < 10 does not fire the necessary events for the progress bar. + if($('html.lte9').length > 0) { + return; + } - //if the breadcrumb is to long, start by replacing foldernames with '...' except for the current folder - var crumb=$('div.crumb').first(); - while($('div.controls').height()>40 && crumb.next('div.crumb').length>0){ - crumb.children('a').text('...'); - crumb=crumb.next('div.crumb'); - } - //if that isn't enough, start removing items from the breacrumb except for the current folder and it's parent - var crumb=$('div.crumb').first(); - var next=crumb.next('div.crumb'); - while($('div.controls').height()>40 && next.next('div.crumb').length>0){ - crumb.remove(); - crumb=next; - next=crumb.next('div.crumb'); - } - //still not enough, start shorting down the current folder name - var crumb=$('div.crumb>a').last(); - while($('div.controls').height()>40 && crumb.text().length>6){ - var text=crumb.text() - text=text.substr(0,text.length-6)+'...'; - crumb.text(text); - } + $('#uploadprogressbar').progressbar('value', 100); + $('#uploadprogressbar').fadeOut(); + } + }; + + var file_upload_handler = function() { + $('#file_upload_start').fileupload(file_upload_param); + }; - $(document).click(function(){ - $('#new>ul').hide(); - $('#new').removeClass('active'); - $('#new li').each(function(i,element){ - if($(element).children('p').length==0){ - $(element).children('form').remove(); - $(element).append('

'+$(element).data('text')+'

'); - } + if ( document.getElementById('data-upload-form') ) { + $(file_upload_handler); + } + $.assocArraySize = function(obj) { + // http://stackoverflow.com/a/6700/11236 + var size = 0, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + size++; + } + } + return size; + }; + + // warn user not to leave the page while upload is in progress + $(window).bind('beforeunload', function(e) { + if ($.assocArraySize(uploadingFiles) > 0) { + return t('files', 'File upload is in progress. Leaving the page now will cancel the upload.'); + } }); - }); - $('#new li').click(function(){ - if($(this).children('p').length==0){ - return; + + //add multiply file upload attribute to all browsers except konqueror (which crashes when it's used) + if(navigator.userAgent.search(/konqueror/i) === -1) { + $('#file_upload_start').attr('multiple', 'multiple'); + } + + //if the breadcrumb is to long, start by replacing foldernames with '...' except for the current folder + var crumb = $('div.crumb').first(); + while($('div.controls').height() > 40 && crumb.next('div.crumb').length > 0) { + crumb.children('a').text('...'); + crumb = crumb.next('div.crumb'); + } + //if that isn't enough, start removing items from the breacrumb except for the current folder and it's parent + var crumb = $('div.crumb').first(); + var next = crumb.next('div.crumb'); + while($('div.controls').height() > 40 && next.next('div.crumb').length > 0) { + crumb.remove(); + crumb = next; + next = crumb.next('div.crumb'); } + //still not enough, start shorting down the current folder name + var crumb = $('div.crumb>a').last(); + while($('div.controls').height() > 40 && crumb.text().length > 6) { + var text = crumb.text(); + text = text.substr(0, text.length-6)+'...'; + crumb.text(text); + } + + $(document).click(function() { + $('#new>ul').hide(); + $('#new').removeClass('active'); + $('#new li').each(function(i, element) { + if($(element).children('p').length === 0) { + $(element).children('form').remove(); + $(element).append('

' + $(element).data('text') + '

'); + } + }); + }); + $('#new li').click(function() { + if($(this).children('p').length === 0) { + return; + } - $('#new li').each(function(i,element){ - if($(element).children('p').length==0){ - $(element).children('form').remove(); - $(element).append('

'+$(element).data('text')+'

'); - } + $('#new li').each(function(i, element) { + if($(element).children('p').length === 0) { + $(element).children('form').remove(); + $(element).append('

' + $(element).data('text') + '

'); + } }); - var type=$(this).data('type'); - var text=$(this).children('p').text(); - $(this).data('text',text); + var type = $(this).data('type'); + var text = $(this).children('p').text(); + $(this).data('text', text); $(this).children('p').remove(); - var form=$('
'); - var input=$(''); + var form = $('
'); + var input = $(''); form.append(input); $(this).append(form); input.focus(); - form.submit(function(event){ - event.stopPropagation(); - event.preventDefault(); - var newname=input.val(); - if(type == 'web' && newname.length == 0) { - OC.Notification.show(t('files', 'URL cannot be empty.')); - return false; - } else if (type != 'web' && !Files.isFileNameValid(newname)) { - return false; - } else if( type == 'folder' && $('#dir').val() == '/' && newname == 'Shared') { - OC.Notification.show(t('files','Invalid folder name. Usage of \'Shared\' is reserved by ownCloud')); - return false; - } - if (FileList.lastAction) { - FileList.lastAction(); - } - var name = getUniqueName(newname); - if (newname != name) { - FileList.checkName(name, newname, true); - var hidden = true; - } else { - var hidden = false; - } - switch(type){ - case 'file': - $.post( - OC.filePath('files','ajax','newfile.php'), - {dir:$('#dir').val(),filename:name}, - function(result){ - if (result.status == 'success') { - var date=new Date(); - FileList.addFile(name,0,date,false,hidden); - var tr=$('tr').filterAttr('data-file',name); - tr.attr('data-mime',result.data.mime); - tr.attr('data-id', result.data.id); - getMimeIcon(result.data.mime,function(path){ - tr.find('td.filename').attr('style','background-image:url('+path+')'); - }); - } else { - OC.dialogs.alert(result.data.message, t('core', 'Error')); - } - } - ); - break; - case 'folder': - $.post( - OC.filePath('files','ajax','newfolder.php'), - {dir:$('#dir').val(),foldername:name}, - function(result){ - if (result.status == 'success') { - var date=new Date(); - FileList.addDir(name,0,date,hidden); - var tr=$('tr').filterAttr('data-file',name); - tr.attr('data-id', result.data.id); - } else { - OC.dialogs.alert(result.data.message, t('core', 'Error')); - } - } - ); - break; - case 'web': - if(name.substr(0,8)!='https://' && name.substr(0,7)!='http://'){ - name='http://'+name; - } - var localName=name; - if(localName.substr(localName.length-1,1)=='/'){//strip / - localName=localName.substr(0,localName.length-1) + form.submit(function(event) { + event.stopPropagation(); + event.preventDefault(); + var newname=input.val(); + if(type === 'web' && newname.length === 0) { + OC.Notification.show(t('files', 'URL cannot be empty.')); + return false; + } else if (type !== 'web' && !Files.isFileNameValid(newname)) { + return false; + } else if( type === 'folder' && $('#dir').val() === '/' && newname === 'Shared') { + OC.Notification.show(t('files', 'Invalid folder name. Usage of \'Shared\' is reserved by ownCloud')); + return false; } - if(localName.indexOf('/')){//use last part of url - localName=localName.split('/').pop(); - } else { //or the domain - localName=(localName.match(/:\/\/(.[^\/]+)/)[1]).replace('www.',''); + if (FileList.lastAction) { + FileList.lastAction(); } - localName = getUniqueName(localName); - //IE < 10 does not fire the necessary events for the progress bar. - if($('html.lte9').length > 0) { + var name = getUniqueName(newname); + if (newname !== name) { + FileList.checkName(name, newname, true); + var hidden = true; } else { - $('#uploadprogressbar').progressbar({value:0}); - $('#uploadprogressbar').fadeIn(); + var hidden = false; } + switch(type) { + case 'file': + $.post( + OC.filePath('files', 'ajax', 'newfile.php'), + {dir:$('#dir').val(), filename:name}, + function(result) { + if (result.status === 'success') { + var date = new Date(); + FileList.addFile(name, 0, date, false, hidden); + var tr = $('tr').filterAttr('data-file', name); + tr.attr('data-mime', result.data.mime); + tr.attr('data-id', result.data.id); + getMimeIcon(result.data.mime, function(path) { + tr.find('td.filename').attr('style', 'background-image:url('+path+')'); + }); + } else { + OC.dialogs.alert(result.data.message, t('core', 'Error')); + } + } + ); + break; + case 'folder': + $.post( + OC.filePath('files', 'ajax', 'newfolder.php'), + {dir:$('#dir').val(), foldername:name}, + function(result) { + if (result.status === 'success') { + var date = new Date(); + FileList.addDir(name, 0, date, hidden); + var tr = $('tr').filterAttr('data-file', name); + tr.attr('data-id', result.data.id); + } else { + OC.dialogs.alert(result.data.message, t('core', 'Error')); + } + } + ); + break; + case 'web': + if (name.substr(0, 8) !== 'https://' && name.substr(0, 7) !== 'http://') { + name = 'http://' + name; + } + var localName = name; + if(localName.substr(localName.length-1, 1) === '/') { //strip / + localName = localName.substr(0, localName.length-1); + } + if (localName.indexOf('/')) { //use last part of url + localName = localName.split('/').pop(); + } else { //or the domain + localName = (localName.match(/:\/\/(.[^\/]+)/)[1]).replace('www.', ''); + } + localName = getUniqueName(localName); + //IE < 10 does not fire the necessary events for the progress bar. + if ($('html.lte9').length > 0) { + } else { + $('#uploadprogressbar').progressbar({value:0}); + $('#uploadprogressbar').fadeIn(); + } - var eventSource=new OC.EventSource(OC.filePath('files','ajax','newfile.php'),{dir:$('#dir').val(),source:name,filename:localName}); - eventSource.listen('progress',function(progress){ - //IE < 10 does not fire the necessary events for the progress bar. - if($('html.lte9').length > 0) { - } else { - $('#uploadprogressbar').progressbar('value',progress); - } - }); - eventSource.listen('success',function(data){ - var mime=data.mime; - var size=data.size; - var id=data.id; - $('#uploadprogressbar').fadeOut(); - var date=new Date(); - FileList.addFile(localName,size,date,false,hidden); - var tr=$('tr').filterAttr('data-file',localName); - tr.data('mime',mime).data('id',id); - tr.attr('data-id', id); - getMimeIcon(mime,function(path){ - tr.find('td.filename').attr('style','background-image:url('+path+')'); - }); - }); - eventSource.listen('error',function(error){ - $('#uploadprogressbar').fadeOut(); - alert(error); + var eventSource = new OC.EventSource( + OC.filePath('files', 'ajax', 'newfile.php'), + {dir:$('#dir').val(), source:name, filename:localName} + ); + eventSource.listen('progress', function(progress) { + //IE < 10 does not fire the necessary events for the progress bar. + if($('html.lte9').length > 0) { + } else { + $('#uploadprogressbar').progressbar('value', progress); + } + }); + eventSource.listen('success', function(data) { + var mime = data.mime; + var size = data.size; + var id = data.id; + $('#uploadprogressbar').fadeOut(); + var date = new Date(); + FileList.addFile(localName, size, date, false, hidden); + var tr = $('tr').filterAttr('data-file', localName); + tr.data('mime', mime).data('id', id); + tr.attr('data-id', id); + getMimeIcon(mime, function(path) { + tr.find('td.filename').attr('style', 'background-image:url(' + path + ')'); + }); + }); + eventSource.listen('error', function(error) { + $('#uploadprogressbar').fadeOut(); + alert(error); + }); + break; + } + var li = form.parent(); + form.remove(); + li.append('

' + li.data('text') + '

'); + $('#new>a').click(); }); - break; - } - var li=form.parent(); - form.remove(); - li.append('

'+li.data('text')+'

'); - $('#new>a').click(); + }); - }); + }); diff --git a/apps/files/js/filelist.js b/apps/files/js/filelist.js index b858e2580ee..bcc77e68ce6 100644 --- a/apps/files/js/filelist.js +++ b/apps/files/js/filelist.js @@ -308,7 +308,7 @@ var FileList={ html.attr('data-oldName', oldName); html.attr('data-newName', newName); html.attr('data-isNewFile', isNewFile); - OC.Notification.showHtml(html); + OC.Notification.showHtml(html); return true; } else { return false; diff --git a/core/js/jquery.ocdialog.js b/core/js/jquery.ocdialog.js index 7413927e3b2..52ff5633f9a 100644 --- a/core/js/jquery.ocdialog.js +++ b/core/js/jquery.ocdialog.js @@ -101,6 +101,9 @@ } $.each(value, function(idx, val) { var $button = $('