aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--apps/calendar/js/loader.js2
-rw-r--r--apps/calendar/lib/share_backend.php44
-rw-r--r--apps/contacts/appinfo/app.php2
-rw-r--r--apps/contacts/css/contacts.css3
-rw-r--r--apps/contacts/js/loader.js4
-rw-r--r--apps/contacts/lib/addressbook.php2
-rw-r--r--apps/contacts/lib/app.php34
-rw-r--r--apps/contacts/lib/share.php77
-rw-r--r--apps/contacts/templates/part.chooseaddressbook.rowfields.php3
-rw-r--r--apps/files/index.php2
-rw-r--r--apps/files/js/fileactions.js54
-rw-r--r--apps/files/js/files.js35
-rwxr-xr-xapps/files/share.php38
-rw-r--r--apps/files/templates/index.php10
-rw-r--r--apps/files/templates/part.list.php3
-rw-r--r--apps/files_archive/js/archive.js4
-rw-r--r--apps/files_archive/lib/storage.php4
-rw-r--r--apps/files_external/lib/amazons3.php4
-rwxr-xr-xapps/files_external/lib/dropbox.php4
-rw-r--r--apps/files_external/lib/dropboxtest.php71
-rw-r--r--apps/files_external/lib/google.php4
-rw-r--r--apps/files_external/lib/googletest.php8
-rw-r--r--apps/files_external/lib/streamwrapper.php4
-rw-r--r--apps/files_external/lib/swift.php4
-rw-r--r--apps/files_external/lib/webdav.php4
-rw-r--r--apps/files_external/tests/test.php7
-rw-r--r--apps/files_imageviewer/js/lightbox.js2
-rw-r--r--apps/files_pdfviewer/js/viewer.js2
-rw-r--r--apps/files_sharing/appinfo/app.php6
-rw-r--r--apps/files_sharing/css/sharing.css14
-rw-r--r--apps/files_sharing/lib/share/file.php101
-rw-r--r--apps/files_sharing/lib/share/folder.php75
-rw-r--r--apps/files_sharing/sharedstorage.php487
-rwxr-xr-xapps/files_sharing/sharetest.php7
-rwxr-xr-xapps/files_sharing/templates/get.php11
-rw-r--r--apps/files_texteditor/js/editor.js16
-rw-r--r--apps/files_versions/appinfo/api.php36
-rw-r--r--apps/files_versions/js/versions.js2
-rw-r--r--apps/gallery/appinfo/app.php3
-rw-r--r--apps/gallery/lib/share.php42
-rw-r--r--apps/media/js/loader.js4
-rw-r--r--apps/media/lib/share/album.php0
-rw-r--r--apps/media/lib/share/artist.php65
-rw-r--r--apps/media/lib/share/song.php65
-rw-r--r--core/ajax/share.php107
-rw-r--r--core/js/share.js385
-rw-r--r--lib/filecache.php8
-rw-r--r--lib/files.php39
-rw-r--r--lib/filestorage.php7
-rw-r--r--lib/filestorage/common.php13
-rw-r--r--lib/filestorage/local.php8
-rw-r--r--lib/filesystem.php21
-rw-r--r--lib/filesystemview.php29
-rw-r--r--lib/group.php8
-rw-r--r--lib/group/backend.php2
-rw-r--r--lib/group/database.php12
-rw-r--r--lib/group/interface.php2
-rw-r--r--lib/public/share.php844
-rw-r--r--lib/public/user.php2
-rw-r--r--lib/user.php12
-rw-r--r--lib/user/backend.php2
-rw-r--r--lib/user/database.php13
-rw-r--r--lib/user/interface.php2
-rw-r--r--tests/lib/share/backend.php66
-rw-r--r--tests/lib/share/share.php161
65 files changed, 2681 insertions, 431 deletions
diff --git a/apps/calendar/js/loader.js b/apps/calendar/js/loader.js
index b28d19ab00e..253abafc427 100644
--- a/apps/calendar/js/loader.js
+++ b/apps/calendar/js/loader.js
@@ -173,7 +173,7 @@ Calendar_Import={
}
$(document).ready(function(){
if(typeof FileActions !== 'undefined'){
- FileActions.register('text/calendar','importCalendar', '', Calendar_Import.Dialog.open);
+ FileActions.register('text/calendar','importCalendar', FileActions.PERMISSION_READ, '', Calendar_Import.Dialog.open);
FileActions.setDefault('text/calendar','importCalendar');
};
});
diff --git a/apps/calendar/lib/share_backend.php b/apps/calendar/lib/share_backend.php
new file mode 100644
index 00000000000..f937c0d1c34
--- /dev/null
+++ b/apps/calendar/lib/share_backend.php
@@ -0,0 +1,44 @@
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+class OC_Share_Backend_Calendar extends OCP\Share_Backend {
+
+ public function getSource($item, $uid) {
+ $query = OCP\DB::prepare('SELECT id FROM *PREFIX*calendar_calendars WHERE userid = ? AND displayname = ? LIMIT 1');
+ return $query->execute(array($uid, $item))->fetchAll();
+ }
+
+ public function generateTarget($item, $uid) {
+
+ }
+
+ public function getItems($sources) {
+
+ }
+
+}
+
+class OC_Share_Backend_Event extends OCP\Share_Backend {
+
+}
+
+
+?> \ No newline at end of file
diff --git a/apps/contacts/appinfo/app.php b/apps/contacts/appinfo/app.php
index cbbbbc79e58..74660a2e2b8 100644
--- a/apps/contacts/appinfo/app.php
+++ b/apps/contacts/appinfo/app.php
@@ -3,6 +3,7 @@ OC::$CLASSPATH['OC_Contacts_App'] = 'apps/contacts/lib/app.php';
OC::$CLASSPATH['OC_Contacts_Addressbook'] = 'apps/contacts/lib/addressbook.php';
OC::$CLASSPATH['OC_Contacts_VCard'] = 'apps/contacts/lib/vcard.php';
OC::$CLASSPATH['OC_Contacts_Hooks'] = 'apps/contacts/lib/hooks.php';
+OC::$CLASSPATH['OC_Contacts_Share'] = 'apps/contacts/lib/share.php';
OC::$CLASSPATH['OC_Connector_Sabre_CardDAV'] = 'apps/contacts/lib/connector_sabre.php';
OC::$CLASSPATH['Sabre_CardDAV_VCFExportPlugin'] = 'apps/contacts/lib/VCFExportPlugin.php';
OC::$CLASSPATH['OC_Search_Provider_Contacts'] = 'apps/contacts/lib/search.php';
@@ -22,3 +23,4 @@ OCP\App::addNavigationEntry( array(
OCP\App::registerPersonal('contacts', 'settings');
OCP\Util::addscript('contacts', 'loader');
OC_Search::registerProvider('OC_Search_Provider_Contacts');
+OCP\Share::registerBackend('addressbook', 'OC_Contacts_Share');
diff --git a/apps/contacts/css/contacts.css b/apps/contacts/css/contacts.css
index ddae27da211..5a9e9cb9fe3 100644
--- a/apps/contacts/css/contacts.css
+++ b/apps/contacts/css/contacts.css
@@ -50,11 +50,12 @@ label:hover, dt:hover { color: #333; }
.float { float: left; }
.svg { border: inherit; background: inherit; }
.listactions { height: 1em; width:60px; float: left; clear: right; }
-.add,.edit,.delete,.mail, .globe, .upload, .download, .cloud { cursor: pointer; width: 20px; height: 20px; margin: 0; float: left; position:relative; opacity: 0.1; }
+.add,.edit,.delete,.mail, .globe, .upload, .download, .cloud, .share { cursor: pointer; width: 20px; height: 20px; margin: 0; float: left; position:relative; opacity: 0.1; }
.add:hover,.edit:hover,.delete:hover,.mail:hover, .globe:hover, .upload:hover, .download:hover .cloud:hover { opacity: 1.0 }
.add { background:url('%webroot%/core/img/actions/add.svg') no-repeat center; clear: both; }
.delete { background:url('%webroot%/core/img/actions/delete.svg') no-repeat center; }
.edit { background:url('%webroot%/core/img/actions/rename.svg') no-repeat center; }
+.share { background:url('%webroot%/core/img/actions/share.svg') no-repeat center; }
.mail { background:url('%webroot%/core/img/actions/mail.svg') no-repeat center; }
.upload { background:url('%webroot%/core/img/actions/upload.svg') no-repeat center; }
.download { background:url('%webroot%/core/img/actions/download.svg') no-repeat center; }
diff --git a/apps/contacts/js/loader.js b/apps/contacts/js/loader.js
index 5bca0ab7237..3b1f4070485 100644
--- a/apps/contacts/js/loader.js
+++ b/apps/contacts/js/loader.js
@@ -78,9 +78,9 @@ Contacts_Import={
}
$(document).ready(function(){
if(typeof FileActions !== 'undefined'){
- FileActions.register('text/vcard','importaddressbook', '', Contacts_Import.importdialog);
+ FileActions.register('text/vcard','importaddressbook', FileActions.PERMISSION_READ, '', Contacts_Import.importdialog);
FileActions.setDefault('text/vcard','importaddressbook');
- FileActions.register('text/x-vcard','importaddressbook', '', Contacts_Import.importdialog);
+ FileActions.register('text/x-vcard','importaddressbook', FileActions.PERMISSION_READ, '', Contacts_Import.importdialog);
FileActions.setDefault('text/x-vcard','importaddressbook');
};
}); \ No newline at end of file
diff --git a/apps/contacts/lib/addressbook.php b/apps/contacts/lib/addressbook.php
index eb61b6dbced..6e082c5e2e9 100644
--- a/apps/contacts/lib/addressbook.php
+++ b/apps/contacts/lib/addressbook.php
@@ -64,10 +64,10 @@ class OC_Contacts_Addressbook {
while( $row = $result->fetchRow()) {
$addressbooks[] = $row;
}
+ $addressbooks = array_merge($addressbooks, OCP\Share::getItemsSharedWith('addressbook', OC_Contacts_Share::FORMAT_ADDRESSBOOKS));
if(!$active && !count($addressbooks)) {
self::addDefault($uid);
}
-
return $addressbooks;
}
diff --git a/apps/contacts/lib/app.php b/apps/contacts/lib/app.php
index 67dfe8f640f..74464aa718b 100644
--- a/apps/contacts/lib/app.php
+++ b/apps/contacts/lib/app.php
@@ -23,32 +23,16 @@ class OC_Contacts_App {
public static function getAddressbook($id) {
$addressbook = OC_Contacts_Addressbook::find( $id );
- if($addressbook === false || $addressbook['userid'] != OCP\USER::getUser()) {
- if ($addressbook === false) {
- OCP\Util::writeLog('contacts',
- 'Addressbook not found: '. $id,
- OCP\Util::ERROR);
- OCP\JSON::error(
- array(
- 'data' => array(
- 'message' => self::$l10n->t('Addressbook not found.')
- )
- )
- );
- }
- else {
- OCP\Util::writeLog('contacts',
- 'Addressbook('.$id.') is not from '.OCP\USER::getUser(),
- OCP\Util::ERROR);
- OCP\JSON::error(
- array(
- 'data' => array(
- 'message' => self::$l10n->t('This is not your addressbook.')
- )
- )
- );
+ if ($addressbook === false) {
+ OCP\Util::writeLog('contacts', 'Addressbook not found: '. $id, OCP\Util::ERROR);
+ OCP\JSON::error(array('data' => array( 'message' => self::$l10n->t('Addressbook not found.'))));
+ } else if ($addressbook['userid'] != OCP\USER::getUser()) {
+ if ($shared = OCP\Share::getItemSharedWithBySource('addressbook', $id)) {
+ $addressbook['displayname'] = $shared['item_target'];
+ } else {
+ OCP\Util::writeLog('contacts', 'Addressbook('.$id.') is not from '.OCP\USER::getUser(), OCP\Util::ERROR);
+ OCP\JSON::error(array('data' => array( 'message' => self::$l10n->t('This is not your addressbook.'))));
}
- exit();
}
return $addressbook;
}
diff --git a/apps/contacts/lib/share.php b/apps/contacts/lib/share.php
new file mode 100644
index 00000000000..7aec5339577
--- /dev/null
+++ b/apps/contacts/lib/share.php
@@ -0,0 +1,77 @@
+<?php
+/**
+ * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl>
+ * This file is licensed under the Affero General Public License version 3 or
+ * later.
+ * See the COPYING-README file.
+ */
+
+class OC_Contacts_Share extends OCP\Share_Backend {
+ const FORMAT_ADDRESSBOOKS = 1;
+ /**
+ * @brief Get the source of the item to be stored in the database
+ * @param string Item
+ * @param string Owner of the item
+ * @return mixed|array|false Source
+ *
+ * Return an array if the item is file dependent, the array needs two keys: 'item' and 'file'
+ * Return false if the item does not exist for the user
+ *
+ * The formatItems() function will translate the source returned back into the item
+ */
+ public function getSource($item, $uid) {
+ $addressbook = OC_Contacts_Addressbook::find( $item );
+ if( $addressbook === false || $addressbook['userid'] != $uid) {
+ return false;
+ }
+ return $item;
+ }
+
+ /**
+ * @brief Get a unique name of the item for the specified user
+ * @param string Item
+ * @param string|false User the item is being shared with
+ * @param array|null List of similar item names already existing as shared items
+ * @return string Target name
+ *
+ * This function needs to verify that the user does not already have an item with this name.
+ * If it does generate a new name e.g. name_#
+ */
+ public function generateTarget($item, $uid, $exclude = null) {
+ $addressbook = OC_Contacts_Addressbook::find( $item );
+ $user_addressbooks = array();
+ foreach(OC_Contacts_Addressbook::all($uid) as $user_addressbook) {
+ $user_addressbooks[] = $user_addressbook['displayname'];
+ }
+ $name = $addressbook['userid']."'s ".$addressbook['displayname'];
+ $suffix = '';
+ while (in_array($name.$suffix, $user_addressbooks)) {
+ $suffix++;
+ }
+
+ return $name.$suffix;
+ }
+
+ /**
+ * @brief Converts the shared item sources back into the item in the specified format
+ * @param array Shared items
+ * @param int Format
+ * @return ?
+ *
+ * The items array is a 3-dimensional array with the item_source as the first key and the share id as the second key to an array with the share info.
+ * The key/value pairs included in the share info depend on the function originally called:
+ * If called by getItem(s)Shared: id, item_type, item, item_source, share_type, share_with, permissions, stime, file_source
+ * If called by getItem(s)SharedWith: id, item_type, item, item_source, item_target, share_type, share_with, permissions, stime, file_source, file_target
+ * This function allows the backend to control the output of shared items with custom formats.
+ * It is only called through calls to the public getItem(s)Shared(With) functions.
+ */
+ public function formatItems($items, $format, $parameters = null) {
+ $addressbooks = array();
+ foreach ($items as $item) {
+ $addressbook = OC_Contacts_Addressbook::find($item['item_source']);
+ $addressbook['displayname'] = $item['item_target'];
+ $addressbooks[] = $addressbook;
+ }
+ return $addressbooks;
+ }
+}
diff --git a/apps/contacts/templates/part.chooseaddressbook.rowfields.php b/apps/contacts/templates/part.chooseaddressbook.rowfields.php
index 2988bb44c5f..c0a3ba68cdf 100644
--- a/apps/contacts/templates/part.chooseaddressbook.rowfields.php
+++ b/apps/contacts/templates/part.chooseaddressbook.rowfields.php
@@ -14,5 +14,8 @@
<a title="<?php echo $l->t("Edit"); ?>" class="svg action edit" onclick="Contacts.UI.Addressbooks.editAddressbook(this, <?php echo $_['addressbook']["id"]; ?>);"></a>
</td>
<td width="20px">
+ <a title="<?php echo $l->t("Share"); ?>" class="svg action share" data-item-type="addressbook" data-item="<?php echo $_['addressbook']['id']; ?>" />
+</td>
+<td width="20px">
<a onclick="Contacts.UI.Addressbooks.deleteAddressbook(this, <?php echo $_['addressbook']["id"]; ?>);" title="<?php echo $l->t("Delete"); ?>" class="svg action delete"></a>
</td>
diff --git a/apps/files/index.php b/apps/files/index.php
index 79bed8e357e..225e2d7ac13 100644
--- a/apps/files/index.php
+++ b/apps/files/index.php
@@ -93,7 +93,7 @@ $tmpl = new OCP\Template( 'files', 'index', 'user' );
$tmpl->assign( 'fileList', $list->fetchPage(), false );
$tmpl->assign( 'breadcrumb', $breadcrumbNav->fetchPage(), false );
$tmpl->assign( 'dir', $dir);
-$tmpl->assign( 'readonly', !OC_Filesystem::is_writable($dir.'/'));
+$tmpl->assign( 'isCreatable', OC_Filesystem::isCreatable($dir.'/'));
$tmpl->assign( 'files', $files );
$tmpl->assign( 'uploadMaxFilesize', $maxUploadFilesize);
$tmpl->assign( 'uploadMaxHumanFilesize', OCP\Util::humanFileSize($maxUploadFilesize));
diff --git a/apps/files/js/fileactions.js b/apps/files/js/fileactions.js
index b6f4d0b0896..39e848cec80 100644
--- a/apps/files/js/fileactions.js
+++ b/apps/files/js/fileactions.js
@@ -1,19 +1,28 @@
FileActions={
+ PERMISSION_CREATE:4,
+ PERMISSION_READ:1,
+ PERMISSION_UPDATE:2,
+ PERMISSION_DELETE:8,
+ PERMISSION_SHARE:16,
actions:{},
defaults:{},
icons:{},
currentFile:null,
- register:function(mime,name,icon,action){
+ register:function(mime,name,permissions,icon,action){
if(!FileActions.actions[mime]){
FileActions.actions[mime]={};
}
- FileActions.actions[mime][name]=action;
+ if (!FileActions.actions[mime][name]) {
+ FileActions.actions[mime][name] = {};
+ }
+ FileActions.actions[mime][name]['action'] = action;
+ FileActions.actions[mime][name]['permissions'] = permissions;
FileActions.icons[name]=icon;
},
setDefault:function(mime,name){
FileActions.defaults[mime]=name;
},
- get:function(mime,type){
+ get:function(mime,type,permissions){
var actions={};
if(FileActions.actions.all){
actions=$.extend( actions, FileActions.actions.all )
@@ -32,9 +41,15 @@ FileActions={
actions=$.extend( actions, FileActions.actions[type] )
}
}
- return actions;
+ var filteredActions = {};
+ $.each(actions, function(name, action) {
+ if (action.permissions & permissions) {
+ filteredActions[name] = action.action;
+ }
+ });
+ return filteredActions;
},
- getDefault:function(mime,type){
+ getDefault:function(mime,type,permissions){
if(mime){
var mimePart=mime.substr(0,mime.indexOf('/'));
}
@@ -48,22 +63,20 @@ FileActions={
}else{
name=FileActions.defaults.all;
}
- var actions=this.get(mime,type);
+ var actions=this.get(mime,type,permissions);
return actions[name];
},
- display:function(parent, filename, type){
+ display:function(parent){
FileActions.currentFile=parent;
$('#fileList span.fileactions, #fileList td.date a.action').remove();
- var actions=FileActions.get(FileActions.getCurrentMimeType(),FileActions.getCurrentType());
+ var actions=FileActions.get(FileActions.getCurrentMimeType(),FileActions.getCurrentType(), FileActions.getCurrentPermissions());
var file=FileActions.getCurrentFile();
if($('tr').filterAttr('data-file',file).data('renaming')){
return;
}
parent.children('a.name').append('<span class="fileactions" />');
- var defaultAction=FileActions.getDefault(FileActions.getCurrentMimeType(),FileActions.getCurrentType());
+ var defaultAction=FileActions.getDefault(FileActions.getCurrentMimeType(),FileActions.getCurrentType(), FileActions.getCurrentPermissions());
for(name in actions){
- // no rename and share action for the 'Shared' dir
- if((name=='Rename' || name =='Share') && type=='dir' && filename=='Shared') { continue; }
if((name=='Download' || actions[name]!=defaultAction) && name!='Delete'){
var img=FileActions.icons[name];
if(img.call){
@@ -86,16 +99,12 @@ FileActions={
parent.find('a.name>span.fileactions').append(element);
}
}
- if(actions['Delete'] && (type!='dir' || filename != 'Shared')){ // no delete action for the 'Shared' dir
+ if(actions['Delete']){
var img=FileActions.icons['Delete'];
if(img.call){
img=img(file);
}
- if ($('#dir').val().indexOf('Shared') != -1) {
- var html='<a href="#" original-title="' + t('files', 'Unshare') + '" class="action delete" style="display:none" />';
- } else {
- var html='<a href="#" original-title="' + t('files', 'Delete') + '" class="action delete" style="display:none" />';
- }
+ var html='<a href="#" original-title="' + t('files', 'Delete') + '" class="action delete" style="display:none" />';
var element=$(html);
if(img){
element.append($('<img src="'+img+'"/>'));
@@ -131,6 +140,9 @@ FileActions={
},
getCurrentType:function(){
return FileActions.currentFile.parent().attr('data-type');
+ },
+ getCurrentPermissions:function() {
+ return FileActions.currentFile.parent().data('permissions');
}
}
@@ -140,12 +152,12 @@ $(document).ready(function(){
} else {
var downloadScope = 'file';
}
- FileActions.register(downloadScope,'Download',function(){return OC.imagePath('core','actions/download')},function(filename){
+ FileActions.register(downloadScope,'Download', FileActions.PERMISSION_READ, function(){return OC.imagePath('core','actions/download')},function(filename){
window.location=OC.filePath('files', 'ajax', 'download.php') + encodeURIComponent('?files='+encodeURIComponent(filename)+'&dir='+encodeURIComponent($('#dir').val()));
});
});
-FileActions.register('all','Delete',function(){return OC.imagePath('core','actions/delete')},function(filename){
+FileActions.register('all','Delete', FileActions.PERMISSION_DELETE, function(){return OC.imagePath('core','actions/delete')},function(filename){
if(Files.cancelUpload(filename)) {
if(filename.substr){
filename=[filename];
@@ -163,11 +175,11 @@ FileActions.register('all','Delete',function(){return OC.imagePath('core','actio
$('.tipsy').remove();
});
-FileActions.register('all','Rename',function(){return OC.imagePath('core','actions/rename')},function(filename){
+FileActions.register('all','Rename', FileActions.PERMISSION_UPDATE, function(){return OC.imagePath('core','actions/rename')},function(filename){
FileList.rename(filename);
});
-FileActions.register('dir','Open','',function(filename){
+FileActions.register('dir','Open', FileActions.PERMISSION_READ, '', function(filename){
window.location=OC.linkTo('files', 'index.php') + '&dir='+encodeURIComponent($('#dir').val()).replace(/%2F/g, '/')+'/'+encodeURIComponent(filename);
});
diff --git a/apps/files/js/files.js b/apps/files/js/files.js
index a4e2361feeb..daa250c9bd4 100644
--- a/apps/files/js/files.js
+++ b/apps/files/js/files.js
@@ -56,7 +56,7 @@ $(document).ready(function() {
// Sets the file-action buttons behaviour :
$('tr').live('mouseenter',function(event) {
- FileActions.display($(this).children('td.filename'), $(this).attr('data-file'), $(this).attr('data-type'));
+ FileActions.display($(this).children('td.filename'));
});
$('tr').live('mouseleave',function(event) {
FileActions.hide();
@@ -106,7 +106,8 @@ $(document).ready(function() {
if(!renaming && !FileList.isLoading(filename)){
var mime=$(this).parent().parent().data('mime');
var type=$(this).parent().parent().data('type');
- var action=FileActions.getDefault(mime,type);
+ var permissions = $(this).parent().parent().data('permissions');
+ var action=FileActions.getDefault(mime,type, permissions);
if(action){
action(filename);
}
@@ -462,14 +463,18 @@ $(document).ready(function() {
$.post(
OC.filePath('files','ajax','newfile.php'),
{dir:$('#dir').val(),filename:name,content:" \n"},
- function(data){
- var date=new Date();
- FileList.addFile(name,0,date);
- var tr=$('tr').filterAttr('data-file',name);
- tr.data('mime','text/plain');
- getMimeIcon('text/plain',function(path){
- tr.find('td.filename').attr('style','background-image:url('+path+')');
- });
+ function(result){
+ if (result.status == 'success') {
+ var date=new Date();
+ FileList.addFile(name,0,date);
+ var tr=$('tr').filterAttr('data-file',name);
+ tr.data('mime','text/plain');
+ getMimeIcon('text/plain',function(path){
+ tr.find('td.filename').attr('style','background-image:url('+path+')');
+ });
+ } else {
+ OC.dialogs.alert(result.data.message, 'Error');
+ }
}
);
break;
@@ -477,9 +482,13 @@ $(document).ready(function() {
$.post(
OC.filePath('files','ajax','newfolder.php'),
{dir:$('#dir').val(),foldername:name},
- function(data){
- var date=new Date();
- FileList.addDir(name,0,date);
+ function(result){
+ if (result.status == 'success') {
+ var date=new Date();
+ FileList.addDir(name,0,date);
+ } else {
+ OC.dialogs.alert(result.data.message, 'Error');
+ }
}
);
break;
diff --git a/apps/files/share.php b/apps/files/share.php
new file mode 100755
index 00000000000..4f7c1f55fcf
--- /dev/null
+++ b/apps/files/share.php
@@ -0,0 +1,38 @@
+<?php
+
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+class OC_Share_Backend_Files extends OCP\Share_Backend {
+
+ public function getSource($item, $uid) {
+ return $item;
+ }
+}
+
+class OC_Share_Backend_Folders extends OC_Share_Backend_Files {
+
+ public function share($
+ public function getDirectoryContent($folder) {
+
+ }
+}
+
+?> \ No newline at end of file
diff --git a/apps/files/templates/index.php b/apps/files/templates/index.php
index 44000171a17..bcf683ae4a8 100644
--- a/apps/files/templates/index.php
+++ b/apps/files/templates/index.php
@@ -1,8 +1,8 @@
<!--[if IE 8]><style>input[type="checkbox"]{padding:0;}table td{position:static !important;}</style><![endif]-->
<div id="controls">
<?php echo($_['breadcrumb']); ?>
- <?php if (!isset($_['readonly']) || !$_['readonly']):?>
- <div class="actions <?php if (isset($_['files']) and ! $_['readonly'] and count($_['files'])==0):?>emptyfolder<?php endif; ?>">
+ <?php if ($_['isCreatable']):?>
+ <div class="actions <?php if (isset($_['files']) and count($_['files'])==0):?>emptyfolder<?php endif; ?>">
<div id='new' class='button'>
<a><?php echo $l->t('New');?></a>
<ul class="popup popupTop">
@@ -35,7 +35,7 @@
</div>
<div id='notification'></div>
-<?php if (isset($_['files']) and ! $_['readonly'] and count($_['files'])==0):?>
+<?php if (isset($_['files']) and $_['isCreatable'] and count($_['files'])==0):?>
<div id="emptyfolder"><?php echo $l->t('Nothing in here. Upload something!')?></div>
<?php endif; ?>
@@ -43,7 +43,7 @@
<thead>
<tr>
<th id='headerName'>
- <?php if(!isset($_['readonly']) || !$_['readonly']) { ?><input type="checkbox" id="select_all" /><?php } ?>
+ <input type="checkbox" id="select_all" />
<span class='name'><?php echo $l->t( 'Name' ); ?></span>
<span class='selectedActions'>
<!-- <a href="" class="share"><img class='svg' alt="Share" src="<?php echo OCP\image_path("core", "actions/share.svg"); ?>" /> <?php echo $l->t('Share')?></a> -->
@@ -56,7 +56,7 @@
<th id="headerDate"><span id="modified"><?php echo $l->t( 'Modified' ); ?></span><span class="selectedActions"><a href="" class="delete"><?php echo $l->t('Delete')?> <img class="svg" alt="<?php echo $l->t('Delete')?>" src="<?php echo OCP\image_path("core", "actions/delete.svg"); ?>" /></a></span></th>
</tr>
</thead>
- <tbody id="fileList" data-readonly="<?php echo $_['readonly'];?>">
+ <tbody id="fileList">
<?php echo($_['fileList']); ?>
</tbody>
</table>
diff --git a/apps/files/templates/part.list.php b/apps/files/templates/part.list.php
index 4506630c16d..6667b5488af 100644
--- a/apps/files/templates/part.list.php
+++ b/apps/files/templates/part.list.php
@@ -1,5 +1,4 @@
<?php foreach($_['files'] as $file):
- $write = ($file['writable']) ? 'true' : 'false';
$simple_file_size = OCP\simple_file_size($file['size']);
$simple_size_color = intval(200-$file['size']/(1024*1024)*2); // the bigger the file, the darker the shade of grey; megabytes*2
if($simple_size_color<0) $simple_size_color = 0;
@@ -10,7 +9,7 @@
$name = str_replace('%2F','/', $name);
$directory = str_replace('+','%20',urlencode($file['directory']));
$directory = str_replace('%2F','/', $directory); ?>
- <tr data-file="<?php echo $name;?>" data-type="<?php echo ($file['type'] == 'dir')?'dir':'file'?>" data-mime="<?php echo $file['mimetype']?>" data-size='<?php echo $file['size'];?>' data-write='<?php echo $write;?>'>
+ <tr data-file="<?php echo $name;?>" data-type="<?php echo ($file['type'] == 'dir')?'dir':'file'?>" data-mime="<?php echo $file['mimetype']?>" data-size='<?php echo $file['size'];?>' data-permissions='<?php echo $file['permissions']; ?>'>
<td class="filename svg" style="background-image:url(<?php if($file['type'] == 'dir') echo OCP\mimetype_icon('dir'); else echo OCP\mimetype_icon($file['mimetype']); ?>)">
<?php if(!isset($_['readonly']) || !$_['readonly']) { ?><input type="checkbox" /><?php } ?>
<a class="name" href="<?php if($file['type'] == 'dir') echo $_['baseURL'].$directory.'/'.$name; else echo $_['downloadURL'].$directory.'/'.$name; ?>" title="">
diff --git a/apps/files_archive/js/archive.js b/apps/files_archive/js/archive.js
index 9fb9853e299..6bcbe092662 100644
--- a/apps/files_archive/js/archive.js
+++ b/apps/files_archive/js/archive.js
@@ -7,11 +7,11 @@
$(document).ready(function() {
if(typeof FileActions!=='undefined'){
- FileActions.register('application/zip','Open','',function(filename){
+ FileActions.register('application/zip','Open', FileActions.PERMISSION_READ, '',function(filename){
window.location=OC.linkTo('files', 'index.php')+'&dir='+encodeURIComponent($('#dir').val()).replace(/%2F/g, '/')+'/'+encodeURIComponent(filename);
});
FileActions.setDefault('application/zip','Open');
- FileActions.register('application/x-gzip','Open','',function(filename){
+ FileActions.register('application/x-gzip','Open', FileActions.PERMISSION_READ, '',function(filename){
window.location=OC.linkTo('files', 'index.php')+'&dir='+encodeURIComponent($('#dir').val()).replace(/%2F/g, '/')+'/'+encodeURIComponent(filename);
});
FileActions.setDefault('application/x-gzip','Open');
diff --git a/apps/files_archive/lib/storage.php b/apps/files_archive/lib/storage.php
index 86761663611..0723ae08ccf 100644
--- a/apps/files_archive/lib/storage.php
+++ b/apps/files_archive/lib/storage.php
@@ -78,10 +78,10 @@ class OC_Filestorage_Archive extends OC_Filestorage_Common{
return $this->archive->fileExists($path.'/')?'dir':'file';
}
}
- public function is_readable($path){
+ public function isReadable($path){
return is_readable($this->path);
}
- public function is_writable($path){
+ public function isUpdatable($path){
return is_writable($this->path);
}
public function file_exists($path){
diff --git a/apps/files_external/lib/amazons3.php b/apps/files_external/lib/amazons3.php
index 9feb490dac0..3c2e3330175 100644
--- a/apps/files_external/lib/amazons3.php
+++ b/apps/files_external/lib/amazons3.php
@@ -134,12 +134,12 @@ class OC_Filestorage_AmazonS3 extends OC_Filestorage_Common {
return false;
}
- public function is_readable($path) {
+ public function isReadable($path) {
// TODO Check acl and determine who grantee is
return true;
}
- public function is_writable($path) {
+ public function isUpdatable($path) {
// TODO Check acl and determine who grantee is
return true;
}
diff --git a/apps/files_external/lib/dropbox.php b/apps/files_external/lib/dropbox.php
index c849db38433..15446ff0bc3 100755
--- a/apps/files_external/lib/dropbox.php
+++ b/apps/files_external/lib/dropbox.php
@@ -118,11 +118,11 @@ class OC_Filestorage_Dropbox extends OC_Filestorage_Common {
return false;
}
- public function is_readable($path) {
+ public function isReadable($path) {
return $this->file_exists($path);
}
- public function is_writable($path) {
+ public function isUpdatable($path) {
return $this->file_exists($path);
}
diff --git a/apps/files_external/lib/dropboxtest.php b/apps/files_external/lib/dropboxtest.php
new file mode 100644
index 00000000000..686549e16b8
--- /dev/null
+++ b/apps/files_external/lib/dropboxtest.php
@@ -0,0 +1,71 @@
+<?php
+
+require_once 'dropbox.php';
+// $oauth = new Dropbox_OAuth_Curl('526ar3qlrtzmv65', '3bbn0wo5lzgpjty');
+$dropbox = new OC_Filestorage_Dropbox(array('app_key' => '526ar3qlrtzmv65', 'app_secret' => '3bbn0wo5lzgpjty', 'token' => 'a3ben02jb1y538a', 'token_secret' => 'x60h3fsky21r1b0'));
+$dropbox->rename('/652072main_2012-2897_full (1).jpg', '/test.jpg');
+// $dropbox->test();
+// print_r($dropbox->mkdir('Again'));
+
+// GET&https%3A%2F%2Fapi.dropbox.com%2F1%2Fmetadata%2Fdropbox%2FownCloud&list%3D0%26
+
+// uzpi8oo2rbax1po
+// th9uoso3xxny3ca
+//Step 3: Acquiring access tokens Array ( [token] => 37my637p88ng967 [token_secret] => t49fmgp3omucnnr )
+//The user is authenticated You should really save the oauth tokens somewhere, so the first steps will no longer be needed Array ( [token] => 37my637p88ng967 [token_secret] => t49fmgp3omucnnr )
+
+// For convenience, definitely not required
+// header('Content-Type: text/plain');
+
+// // We need to start a session
+// session_start();
+
+// There are multiple steps in this workflow, we keep a 'state number' here
+// if (isset($_SESSION['state'])) {
+// $state = 2;
+// } else {
+// $state = 1;
+// }
+//
+// switch($state) {
+//
+// /* In this phase we grab the initial request tokens
+// and redirect the user to the 'authorize' page hosted
+// on dropbox */
+// case 1 :
+// echo "Step 1: Acquire request tokens\n";
+// $tokens = $oauth->getRequestToken();
+// print_r($tokens);
+//
+// // Note that if you want the user to automatically redirect back, you can
+// // add the 'callback' argument to getAuthorizeUrl.
+// echo "Step 2: You must now redirect the user to:\n";
+// echo $oauth->getAuthorizeUrl() . "\n";
+// $_SESSION['state'] = 2;
+// $_SESSION['oauth_tokens'] = $tokens;
+// die();
+//
+// /* In this phase, the user just came back from authorizing
+// and we're going to fetch the real access tokens */
+// case 2 :
+// echo "Step 3: Acquiring access tokens\n";
+// $oauth->setToken($_SESSION['oauth_tokens']);
+// $tokens = $oauth->getAccessToken();
+// print_r($tokens);
+// $_SESSION['state'] = 3;
+// $_SESSION['oauth_tokens'] = $tokens;
+// // There is no break here, intentional
+//
+// /* This part gets called if the authentication process
+// already succeeded. We can use our stored tokens and the api
+// should work. Store these tokens somewhere, like a database */
+// case 3 :
+// echo "The user is authenticated\n";
+// echo "You should really save the oauth tokens somewhere, so the first steps will no longer be needed\n";
+// print_r($_SESSION['oauth_tokens']);
+// $oauth->setToken($_SESSION['oauth_tokens']);
+// break;
+//
+// }
+
+?> \ No newline at end of file
diff --git a/apps/files_external/lib/google.php b/apps/files_external/lib/google.php
index 2ad85d09d5f..02c52ffe04c 100644
--- a/apps/files_external/lib/google.php
+++ b/apps/files_external/lib/google.php
@@ -280,11 +280,11 @@ class OC_Filestorage_Google extends OC_Filestorage_Common {
return false;
}
- public function is_readable($path) {
+ public function isReadable($path) {
return true;
}
- public function is_writable($path) {
+ public function isUpdatable($path) {
if ($path == '' || $path == '/') {
return true;
} else if ($entry = $this->getResource($path)) {
diff --git a/apps/files_external/lib/googletest.php b/apps/files_external/lib/googletest.php
new file mode 100644
index 00000000000..a80af6a0978
--- /dev/null
+++ b/apps/files_external/lib/googletest.php
@@ -0,0 +1,8 @@
+<?php
+
+require_once 'google.php';
+
+// $drive = new OC_Filestorage_Google(array('token' => '4/7nZMlRLlAEeXdY0AeH-eHNCL0YaK', 'token_secret' => 'NqO5VMGUVkwFtOYqHsex4257'));
+// $drive = new OC_Filestorage_Google(array('token' => '1/4Xo84YtTxL2MkQst-Ti3nqF1Isy70NUHDRk-BwsLMf4', 'token_secret' => 'jYnyJ_4-ITNxlX9f9RDNoRW-'));
+// var_export($drive->getFeed('https://docs.google.com/feeds/metadata/default', 'GET'));
+
diff --git a/apps/files_external/lib/streamwrapper.php b/apps/files_external/lib/streamwrapper.php
index 7d56445361e..467c5a5b845 100644
--- a/apps/files_external/lib/streamwrapper.php
+++ b/apps/files_external/lib/streamwrapper.php
@@ -32,11 +32,11 @@ abstract class OC_FileStorage_StreamWrapper extends OC_Filestorage_Common{
return filetype($this->constructUrl($path));
}
- public function is_readable($path){
+ public function isReadable($path){
return true;//not properly supported
}
- public function is_writable($path){
+ public function isUpdatable($path){
return true;//not properly supported
}
diff --git a/apps/files_external/lib/swift.php b/apps/files_external/lib/swift.php
index 58b95a6ae01..94ccde1ff8f 100644
--- a/apps/files_external/lib/swift.php
+++ b/apps/files_external/lib/swift.php
@@ -353,11 +353,11 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
}
}
- public function is_readable($path){
+ public function isReadable($path){
return true;
}
- public function is_writable($path){
+ public function isUpdatable($path){
return true;
}
diff --git a/apps/files_external/lib/webdav.php b/apps/files_external/lib/webdav.php
index 84d64b65193..e3f73c5c0a7 100644
--- a/apps/files_external/lib/webdav.php
+++ b/apps/files_external/lib/webdav.php
@@ -104,11 +104,11 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
}
}
- public function is_readable($path){
+ public function isReadable($path){
return true;//not properly supported
}
- public function is_writable($path){
+ public function isUpdatable($path){
return true;//not properly supported
}
diff --git a/apps/files_external/tests/test.php b/apps/files_external/tests/test.php
new file mode 100644
index 00000000000..bd24404f3b9
--- /dev/null
+++ b/apps/files_external/tests/test.php
@@ -0,0 +1,7 @@
+<?php
+require_once 'files_external/lib/config.php';
+echo "<pre>";
+print_r(OC_Mount_Config::getSystemMountPoints());
+echo "</pre>";
+// OC_Mount_Config::addMountPoint('Photos', 'OC_Filestorage_SWIFT', array('host' => 'gapinthecloud.com', 'user' => 'Gap', 'token' => '23423afdasFJEW22', 'secure' => 'true', 'root' => ''), OC_Mount_Config::MOUNT_TYPE_GROUP, 'admin', false);
+?>
diff --git a/apps/files_imageviewer/js/lightbox.js b/apps/files_imageviewer/js/lightbox.js
index 31f08456d22..ff12d808bc8 100644
--- a/apps/files_imageviewer/js/lightbox.js
+++ b/apps/files_imageviewer/js/lightbox.js
@@ -1,6 +1,6 @@
$(document).ready(function() {
if(typeof FileActions!=='undefined'){
- FileActions.register('image','View','',function(filename){
+ FileActions.register('image','View', FileActions.PERMISSION_READ, '',function(filename){
viewImage($('#dir').val(),filename);
});
FileActions.setDefault('image','View');
diff --git a/apps/files_pdfviewer/js/viewer.js b/apps/files_pdfviewer/js/viewer.js
index 2c9cbb9b431..29db2ea7f24 100644
--- a/apps/files_pdfviewer/js/viewer.js
+++ b/apps/files_pdfviewer/js/viewer.js
@@ -40,7 +40,7 @@ $(document).ready(function(){
if(location.href.indexOf("files")!=-1) {
PDFJS.workerSrc = OC.filePath('files_pdfviewer','js','pdfjs/build/pdf.js');
if(typeof FileActions!=='undefined'){
- FileActions.register('application/pdf','Edit','',function(filename){
+ FileActions.register('application/pdf','Edit', FileActions.PERMISSION_READ, '',function(filename){
showPDFviewer($('#dir').val(),filename);
});
FileActions.setDefault('application/pdf','Edit');
diff --git a/apps/files_sharing/appinfo/app.php b/apps/files_sharing/appinfo/app.php
index bbb753d5e69..7495a5bbe6c 100644
--- a/apps/files_sharing/appinfo/app.php
+++ b/apps/files_sharing/appinfo/app.php
@@ -1,6 +1,8 @@
<?php
OC::$CLASSPATH['OC_Share'] = "apps/files_sharing/lib_share.php";
+OC::$CLASSPATH['OC_Share_Backend_File'] = "apps/files_sharing/lib/share/file.php";
+OC::$CLASSPATH['OC_Share_Backend_Folder'] = 'apps/files_sharing/lib/share/folder.php';
OC::$CLASSPATH['OC_Filestorage_Shared'] = "apps/files_sharing/sharedstorage.php";
OCP\App::registerAdmin('files_sharing', 'settings');
@@ -17,8 +19,10 @@ OCP\Util::connectHook('OC_User', 'post_removeFromGroup', 'OC_Share', 'removeFrom
$dir = isset($_GET['dir']) ? $_GET['dir'] : '/';
if ($dir != '/Shared' || OCP\Config::getAppValue('files_sharing', 'resharing', 'yes') == 'yes') {
- OCP\Util::addscript("files_sharing", "share");
+ OCP\Util::addScript('core', 'share');
}
OCP\Util::addscript("3rdparty", "chosen/chosen.jquery.min");
OCP\Util::addStyle( 'files_sharing', 'sharing' );
OCP\Util::addStyle("3rdparty", "chosen/chosen");
+OCP\Share::registerBackend('file', 'OC_Share_Backend_File');
+OCP\Share::registerBackend('folder', 'OC_Share_Backend_Folder', 'file');
diff --git a/apps/files_sharing/css/sharing.css b/apps/files_sharing/css/sharing.css
index d4fcf79ee98..f1d6faa6b0d 100644
--- a/apps/files_sharing/css/sharing.css
+++ b/apps/files_sharing/css/sharing.css
@@ -6,10 +6,12 @@
-moz-box-shadow:0 1px 1px #777; -webkit-box-shadow:0 1px 1px #777; box-shadow:0 1px 1px #777;
-moz-border-radius-bottomleft:1em; -webkit-border-bottom-left-radius:1em; border-bottom-left-radius:1em;
-moz-border-radius-bottomright:1em; -webkit-border-bottom-right-radius:1em; border-bottom-right-radius:1em; }
-#sharedWithList { padding:0.5em; list-style-type: none; }
-#privateLink { border-top:1px solid #ddd; padding-top:0.5em; }
-a.unshare { float:right; display:inline; margin:0 .5em; padding:.3em .3em 0 .3em !important; opacity:.5; }
+#shareWithList { padding:0.5em; list-style-type: none; }
+#shareWithList li { padding-top:0.1em; }
+#dropdown label { font-weight:normal; }
+#dropdown input[type="checkbox"] { margin:0 0.2em 0 0.5em; }
+a.showCruds { display:inline; opacity:.5; }
+a.showCruds:hover { opacity:1; }
+a.unshare { float:right; display:inline; padding:.3em 0 0 .3em !important; opacity:.5; }
a.unshare:hover { opacity:1; }
-#share_with { width: 16em; }
-#privateLink label, .edit { font-weight:normal; }
-#share_with_chzn { display: block; }
+#privateLink { border-top:1px solid #ddd; padding-top:0.5em; } \ No newline at end of file
diff --git a/apps/files_sharing/lib/share/file.php b/apps/files_sharing/lib/share/file.php
new file mode 100644
index 00000000000..dd63539cdfe
--- /dev/null
+++ b/apps/files_sharing/lib/share/file.php
@@ -0,0 +1,101 @@
+
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+class OC_Share_Backend_File extends OCP\Share_Backend {
+
+ const FORMAT_SHARED_STORAGE = 0;
+ const FORMAT_FILE_APP = 1;
+ const FORMAT_FILE_APP_ROOT = 2;
+ const FORMAT_OPENDIR = 3;
+
+ public function getSource($item, $uid) {
+ if (OC_Filesystem::file_exists($item)) {
+ return array('item' => null, 'file' => $item);
+ }
+ return false;
+ }
+
+ public function generateTarget($item, $uid, $exclude = null) {
+ // TODO Make sure target path doesn't exist already
+ return '/Shared'.$item;
+ }
+
+ public function formatItems($items, $format, $parameters = null) {
+ if ($format == self::FORMAT_OPENDIR) {
+ $files = array();
+ foreach ($items as $file) {
+ $files[] = basename($file['file_target']);
+ }
+ return $files;
+ } else if ($format == self::FORMAT_SHARED_STORAGE) {
+ $id = $items[key($items)]['file_source'];
+ $query = OCP\DB::prepare('SELECT path FROM *PREFIX*fscache WHERE id = ?');
+ $result = $query->execute(array($id))->fetchAll();
+ if (isset($result[0]['path'])) {
+ return array('path' => $result[0]['path'], 'permissions' => $items[key($items)]['permissions']);
+ }
+ return false;
+ } else {
+ $shares = array();
+ $ids = array();
+ foreach ($items as $item) {
+ $shares[$item['file_source']] = $item;
+ $ids[] = $item['file_source'];
+ }
+ $ids = "'".implode("','", $ids)."'";
+ if ($format == self::FORMAT_FILE_APP) {
+ $query = OCP\DB::prepare('SELECT id, path, name, ctime, mtime, mimetype, size, encrypted, versioned, writable FROM *PREFIX*fscache WHERE id IN ('.$ids.')');
+ $result = $query->execute();
+ $files = array();
+ while ($file = $result->fetchRow()) {
+ // Set target path
+ $file['path'] = $shares[$file['id']]['file_target'];
+ $file['name'] = basename($file['path']);
+ $file['directory'] = $parameters['folder'];
+ $file['type'] = ($file['mimetype'] == 'httpd/unix-directory') ? 'dir' : 'file';
+ $permissions = $shares[$file['id']]['permissions'];
+ if ($file['type'] == 'file') {
+ // Remove Create permission if type is file
+ $permissions &= ~OCP\Share::PERMISSION_CREATE;
+ }
+ $file['permissions'] = $permissions;
+ $files[] = $file;
+ }
+ return $files;
+ } else if ($format == self::FORMAT_FILE_APP_ROOT) {
+ $query = OCP\DB::prepare('SELECT id, path, name, ctime, mtime, mimetype, size, encrypted, versioned, writable FROM *PREFIX*fscache WHERE id IN ('.$ids.')');
+ $result = $query->execute();
+ $mtime = 0;
+ $size = 0;
+ while ($file = $result->fetchRow()) {
+ if ($file['mtime'] > $mtime) {
+ $mtime = $file['mtime'];
+ }
+ $size += $file['size'];
+ }
+ return array(0 => array('name' => 'Shared', 'mtime' => $mtime, 'mimetype' => 'httpd/unix-directory', 'size' => $size, 'writable' => false, 'type' => 'dir', 'directory' => '', 'permissions' => OCP\Share::PERMISSION_READ));
+ }
+ }
+ return array();
+ }
+
+} \ No newline at end of file
diff --git a/apps/files_sharing/lib/share/folder.php b/apps/files_sharing/lib/share/folder.php
new file mode 100644
index 00000000000..a43ce2b2caf
--- /dev/null
+++ b/apps/files_sharing/lib/share/folder.php
@@ -0,0 +1,75 @@
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+class OC_Share_Backend_Folder extends OC_Share_Backend_File {
+
+ public function inCollection($collections, $item) {
+ // TODO
+ }
+
+ public function getChildrenSources($item) {
+ return OC_FileCache::getFolderContent($item);
+ }
+
+ public function formatItems($items, $format, $parameters = null) {
+ if ($format == self::FORMAT_FILE_APP && isset($parameters['folder'])) {
+ $folder = $items[key($items)];
+ $query = OCP\DB::prepare('SELECT path FROM *PREFIX*fscache WHERE id = ?');
+ $result = $query->execute(array($folder['file_source']))->fetchRow();
+ if (isset($result['path'])) {
+ if (isset($parameters['mimetype_filter'])) {
+ $mimetype_filter = $parameters['mimetype_filter'];
+ } else {
+ $mimetype_filter = '';
+ }
+ $pos = strpos($result['path'], $folder['item']);
+ $path = substr($result['path'], $pos).substr($parameters['folder'], strlen($folder['file_target']));
+ $root = substr($result['path'], 0, $pos);
+ $files = OC_FileCache::getFolderContent($path, $root, $mimetype_filter);
+ foreach ($files as &$file) {
+ $file['directory'] = $parameters['folder'];
+ $file['type'] = ($file['mimetype'] == 'httpd/unix-directory') ? 'dir' : 'file';
+ $permissions = $folder['permissions'];
+ if ($file['type'] == 'file') {
+ // Remove Create permission if type is file
+ $permissions &= ~OCP\Share::PERMISSION_CREATE;
+ }
+ $file['permissions'] = $permissions;
+ }
+ return $files;
+ }
+ }/* else if ($format == self::FORMAT_OPENDIR_ROOT) {
+ $query = OCP\DB::prepare('SELECT name FROM *PREFIX*fscache WHERE id IN ('.$ids.')');
+ $result = $query->execute();
+ $files = array();
+ while ($file = $result->fetchRow()) {
+ // Set target path
+ $files[] = basename($shares[$file['id']]['item_target']);
+ }
+ return $files;
+ }*/
+ return array();
+ }
+
+}
+
+
+?> \ No newline at end of file
diff --git a/apps/files_sharing/sharedstorage.php b/apps/files_sharing/sharedstorage.php
index fc0d272b54e..2071942b062 100644
--- a/apps/files_sharing/sharedstorage.php
+++ b/apps/files_sharing/sharedstorage.php
@@ -3,7 +3,7 @@
* ownCloud
*
* @author Michael Gapczynski
- * @copyright 2011 Michael Gapczynski GapczynskiM@gmail.com
+ * @copyright 2011 Michael Gapczynski mtgap@owncloud.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
@@ -20,213 +20,217 @@
*
*/
-require_once( 'lib_share.php' );
-
/**
* Convert target path to source path and pass the function call to the correct storage provider
*/
class OC_Filestorage_Shared extends OC_Filestorage_Common {
- private $datadir;
- private $sourcePaths = array();
+ private $sharedFolder;
+ private $files = array();
public function __construct($arguments) {
- $this->datadir = $arguments['datadir'];
- $this->datadir .= "/";
+ $this->sharedFolder = $arguments['sharedFolder'];
}
-
- public function getInternalPath($path) {
+
+ /**
+ * @brief Get the source file path and the permissions granted for a shared file
+ * @param string Shared target file path
+ * @return Returns array with the keys path and permissions or false if not found
+ */
+ private function getFile($target) {
+ $target = $this->sharedFolder.'/'.$target;
+ $target = rtrim($target, '/');
+ if (isset($this->files[$target])) {
+ return $this->files[$target];
+ } else {
+ $pos = strpos($target, '/', 8);
+ // Get shared folder name
+ if ($pos !== false) {
+ $folder = substr($target, 0, $pos);
+ if (isset($this->files[$folder])) {
+ $file = $this->files[$folder];
+ } else {
+ $file = OCP\Share::getItemSharedWith('file', $folder, OC_Share_Backend_File::FORMAT_SHARED_STORAGE);
+ }
+ if ($file) {
+ $this->files[$target]['path'] = $file['path'].substr($target, strlen($folder));
+ $this->files[$target]['permissions'] = $file['permissions'];
+ return $this->files[$target];
+ }
+ } else {
+ $file = OCP\Share::getItemSharedWith('file', $target, OC_Share_Backend_File::FORMAT_SHARED_STORAGE);
+ if ($file) {
+ $this->files[$target] = $file;
+ return $this->files[$target];
+ }
+ }
+ OCP\Util::writeLog('files_sharing', 'File source not found for: '.$target, OCP\Util::ERROR);
+ return false;
+ }
+ }
+
+ /**
+ * @brief Get the source file path for a shared file
+ * @param string Shared target file path
+ * @return Returns source file path or false if not found
+ */
+ private function getSourcePath($target) {
+ $file = $this->getFile($target);
+ if (isset($file['path'])) {
+ return $file['path'];
+ }
+ return false;
+ }
+
+ /**
+ * @brief Get the permissions granted for a shared file
+ * @param string Shared target file path
+ * @return Returns CRUDS permissions granted or false if not found
+ */
+ private function getPermissions($target) {
+ $file = $this->getFile($target);
+ if (isset($file['permissions'])) {
+ return $file['permissions'];
+ }
+ return false;
+ }
+
+ /**
+ * @brief Get the internal path to pass to the storage filesystem call
+ * @param string Source file path
+ * @return Source file path with mount point stripped out
+ */
+ private function getInternalPath($path) {
$mountPoint = OC_Filesystem::getMountPoint($path);
$internalPath = substr($path, strlen($mountPoint));
return $internalPath;
}
- public function getSource($target) {
- $target = $this->datadir.$target;
- if (array_key_exists($target, $this->sourcePaths)) {
- return $this->sourcePaths[$target];
- } else {
- $source = OC_Share::getSource($target);
- $this->sourcePaths[$target] = $source;
- return $source;
- }
- }
-
public function mkdir($path) {
- if ($path == "" || $path == "/" || !$this->is_writable($path)) {
+ if ($path == '' || $path == '/' || !$this->isCreatable(dirname($path))) {
return false;
- } else {
- $source = $this->getSource($path);
- if ($source) {
- $storage = OC_Filesystem::getStorage($source);
- return $storage->mkdir($this->getInternalPath($source));
- }
+ } else if ($source = $this->getSourcePath($path)) {
+ $storage = OC_Filesystem::getStorage($source);
+ return $storage->mkdir($this->getInternalPath($source));
}
+ return false;
}
public function rmdir($path) {
- // The folder will be removed from the database, but won't be deleted from the owner's filesystem
- OC_Share::unshareFromMySelf($this->datadir.$path);
+ if (($source = $this->getSourcePath($path)) && $this->isDeletable($path)) {
+ $storage = OC_Filesystem::getStorage($source);
+ return $storage->rmdir($this->getInternalPath($source));
+ }
+ return false;
}
public function opendir($path) {
- if ($path == "" || $path == "/") {
- $path = $this->datadir.$path;
- $sharedItems = OC_Share::getItemsInFolder($path);
- $files = array();
- foreach ($sharedItems as $item) {
- // If item is in the root of the shared storage provider and the item exists add it to the fakedirs
- if (dirname($item['target'])."/" == $path && $this->file_exists(basename($item['target']))) {
- $files[] = basename($item['target']);
- }
- }
- OC_FakeDirStream::$dirs['shared'.$path] = $files;
- return opendir('fakedir://shared'.$path);
- } else {
- $source = $this->getSource($path);
- if ($source) {
- $storage = OC_Filesystem::getStorage($source);
- $dh = $storage->opendir($this->getInternalPath($source));
- $modifiedItems = OC_Share::getItemsInFolder($source);
- if ($modifiedItems && $dh) {
- $sources = array();
- $targets = array();
- // Remove any duplicate or trailing '/'
- $path = preg_replace('{(/)\1+}', "/", $path);
- $targetFolder = rtrim($this->datadir.$path, "/");
- foreach ($modifiedItems as $item) {
- // If the item is in the current directory and the item exists add it to the arrays
- if (dirname($item['target']) == $targetFolder && $this->file_exists($path."/".basename($item['target']))) {
- // If the item was unshared from self, add it it to the arrays
- if ($item['permissions'] == OC_Share::UNSHARED) {
- $sources[] = basename($item['source']);
- $targets[] = "";
- } else {
- $sources[] = basename($item['source']);
- $targets[] = basename($item['target']);
- }
- }
- }
- // Don't waste time if there aren't any modified items in the current directory
- if (empty($sources)) {
- return $dh;
- } else {
- global $FAKEDIRS;
- $files = array();
- while (($filename = readdir($dh)) !== false) {
- if ($filename != "." && $filename != "..") {
- // If the file isn't in the sources array it isn't modified and can be added as is
- if (!in_array($filename, $sources)) {
- $files[] = $filename;
- // The file has a different name than the source and is added to the fakedirs
- } else {
- $target = $targets[array_search($filename, $sources)];
- // Don't add the file if it was unshared from self by the user
- if ($target != "") {
- $files[] = $target;
- }
- }
- }
- }
- $FAKEDIRS['shared'] = $files;
- return opendir('fakedir://shared');
- }
- } else {
- return $dh;
- }
- }
+ if ($path == '' || $path == '/') {
+ $files = OCP\Share::getItemsSharedWith('file', OC_Share_Backend_Folder::FORMAT_OPENDIR);
+ OC_FakeDirStream::$dirs['shared'] = $files;
+ return opendir('fakedir://shared');
+ } else if ($source = $this->getSourcePath($path)) {
+ $storage = OC_Filesystem::getStorage($source);
+ return $storage->opendir($this->getInternalPath($source));
}
+ return false;
}
-
+
public function is_dir($path) {
- if ($path == "" || $path == "/") {
+ if ($path == '' || $path == '/') {
return true;
- } else {
- $source = $this->getSource($path);
- if ($source) {
- $storage = OC_Filesystem::getStorage($source);
- return $storage->is_dir($this->getInternalPath($source));
- }
+ } else if ($source = $this->getSourcePath($path)) {
+ $storage = OC_Filesystem::getStorage($source);
+ return $storage->is_dir($this->getInternalPath($source));
}
+ return false;
}
-
+
public function is_file($path) {
- $source = $this->getSource($path);
- if ($source) {
+ if ($source = $this->getSourcePath($path)) {
$storage = OC_Filesystem::getStorage($source);
return $storage->is_file($this->getInternalPath($source));
}
+ return false;
}
-
- // TODO fill in other components of array
+
public function stat($path) {
- if ($path == "" || $path == "/") {
- $stat["size"] = $this->filesize($path);
- $stat["mtime"] = $this->filemtime($path);
- $stat["ctime"] = $this->filectime($path);
+ if ($path == '' || $path == '/') {
+ $stat['size'] = $this->filesize($path);
+ $stat['mtime'] = $this->filemtime($path);
+ $stat['ctime'] = $this->filectime($path);
return $stat;
- } else {
- $source = $this->getSource($path);
- if ($source) {
- $storage = OC_Filesystem::getStorage($source);
- return $storage->stat($this->getInternalPath($source));
- }
+ } else if ($source = $this->getSourcePath($path)) {
+ $storage = OC_Filesystem::getStorage($source);
+ return $storage->stat($this->getInternalPath($source));
}
+ return false;
}
-
+
public function filetype($path) {
- if ($path == "" || $path == "/") {
- return "dir";
- } else {
- $source = $this->getSource($path);
- if ($source) {
- $storage = OC_Filesystem::getStorage($source);
- return $storage->filetype($this->getInternalPath($source));
- }
+ if ($path == '' || $path == '/') {
+ return 'dir';
+ } else if ($source = $this->getSourcePath($path)) {
+ $storage = OC_Filesystem::getStorage($source);
+ return $storage->filetype($this->getInternalPath($source));
}
-
+ return false;
}
-
+
public function filesize($path) {
- if ($path == "" || $path == "/" || $this->is_dir($path)) {
+ if ($path == '' || $path == '/' || $this->is_dir($path)) {
return 0;
- } else {
- $source = $this->getSource($path);
- if ($source) {
- $storage = OC_Filesystem::getStorage($source);
- return $storage->filesize($this->getInternalPath($source));
- }
+ } else if ($source = $this->getSourcePath($path)) {
+ $storage = OC_Filesystem::getStorage($source);
+ return $storage->filesize($this->getInternalPath($source));
}
+ return false;
}
- public function is_readable($path) {
- return true;
+ public function isCreatable($path) {
+ if ($path == '') {
+ return false;
+ }
+ return ($this->getPermissions($path) & OCP\Share::PERMISSION_CREATE);
}
-
- public function is_writable($path) {
- if($path == "" || $path == "/"){
+
+ public function isReadable($path) {
+ return $this->file_exists($path);
+ }
+
+ public function isUpdatable($path) {
+ if ($path == '') {
return false;
- }elseif (OC_Share::getPermissions($this->datadir.$path) & OC_Share::WRITE) {
- return true;
- } else {
+ }
+ return ($this->getPermissions($path) & OCP\Share::PERMISSION_UPDATE);
+ }
+
+ public function isDeletable($path) {
+ if ($path == '') {
return false;
}
+ return ($this->getPermissions($path) & OCP\Share::PERMISSION_DELETE);
}
-
+
+ public function isSharable($path) {
+ if ($path == '') {
+ return false;
+ }
+ return ($this->getPermissions($path) & OCP\Share::PERMISSION_SHARE);
+ }
+
public function file_exists($path) {
- if ($path == "" || $path == "/") {
+ if ($path == '' || $path == '/') {
return true;
- } else {
- $source = $this->getSource($path);
- if ($source) {
- $storage = OC_Filesystem::getStorage($source);
- return $storage->file_exists($this->getInternalPath($source));
- }
+ } else if ($source = $this->getSourcePath($path)) {
+ $storage = OC_Filesystem::getStorage($source);
+ return $storage->file_exists($this->getInternalPath($source));
}
+ return false;
}
public function filectime($path) {
- if ($path == "" || $path == "/") {
+ if ($path == '' || $path == '/') {
$ctime = 0;
if ($dh = $this->opendir($path)) {
while (($filename = readdir($dh)) !== false) {
@@ -238,7 +242,7 @@ class OC_Filestorage_Shared extends OC_Filestorage_Common {
}
return $ctime;
} else {
- $source = $this->getSource($path);
+ $source = $this->getSourcePath($path);
if ($source) {
$storage = OC_Filesystem::getStorage($source);
return $storage->filectime($this->getInternalPath($source));
@@ -247,7 +251,7 @@ class OC_Filestorage_Shared extends OC_Filestorage_Common {
}
public function filemtime($path) {
- if ($path == "" || $path == "/") {
+ if ($path == '' || $path == '/') {
$mtime = 0;
if ($dh = $this->opendir($path)) {
while (($filename = readdir($dh)) !== false) {
@@ -259,7 +263,7 @@ class OC_Filestorage_Shared extends OC_Filestorage_Common {
}
return $mtime;
} else {
- $source = $this->getSource($path);
+ $source = $this->getSourcePath($path);
if ($source) {
$storage = OC_Filesystem::getStorage($source);
return $storage->filemtime($this->getInternalPath($source));
@@ -268,10 +272,10 @@ class OC_Filestorage_Shared extends OC_Filestorage_Common {
}
public function file_get_contents($path) {
- $source = $this->getSource($path);
+ $source = $this->getSourcePath($path);
if ($source) {
$info = array(
- 'target' => $this->datadir.$path,
+ 'target' => $this->sharedFolder.$path,
'source' => $source,
);
OCP\Util::emitHook('OC_Filestorage_Shared', 'file_get_contents', $info);
@@ -282,10 +286,10 @@ class OC_Filestorage_Shared extends OC_Filestorage_Common {
public function file_put_contents($path, $data) {
if ($this->is_writable($path)) {
- $source = $this->getSource($path);
+ $source = $this->getSourcePath($path);
if ($source) {
$info = array(
- 'target' => $this->datadir.$path,
+ 'target' => $this->sharedFolder.$path,
'source' => $source,
);
OCP\Util::emitHook('OC_Filestorage_Shared', 'file_put_contents', $info);
@@ -297,78 +301,50 @@ class OC_Filestorage_Shared extends OC_Filestorage_Common {
}
public function unlink($path) {
- // The item will be removed from the database, but won't be touched on the owner's filesystem
- $target = $this->datadir.$path;
- // Check if the item is inside a shared folder
- if (OC_Share::getParentFolders($target)) {
- // If entry for item already exists
- if (OC_Share::getItem($target)) {
- OC_Share::unshareFromMySelf($target, false);
- } else {
- OC_Share::pullOutOfFolder($target, $target);
- OC_Share::unshareFromMySelf($target, false);
- }
- // Delete the database entry
- } else {
- OC_Share::unshareFromMySelf($target);
+ // Delete the file if DELETE permission is granted
+ if (($source = $this->getSourcePath($path)) && $this->isDeletable($path)) {
+ $storage = OC_Filesystem::getStorage($source);
+ return $storage->unlink($this->getInternalPath($source));
}
- return true;
+ return false;
}
public function rename($path1, $path2) {
- $oldTarget = $this->datadir.$path1;
- $newTarget = $this->datadir.$path2;
- // Check if the item is inside a shared folder
- if ($folders = OC_Share::getParentFolders($oldTarget)) {
- $root1 = substr($path1, 0, strpos($path1, "/"));
- $root2 = substr($path1, 0, strpos($path2, "/"));
- // Prevent items from being moved into different shared folders until versioning (cut and paste) and prevent items going into 'Shared'
- if ($root1 !== $root2) {
- return false;
- // Check if both paths have write permission
- } else if ($this->is_writable($path1) && $this->is_writable($path2)) {
- $oldSource = $this->getSource($path1);
- $newSource = $folders['source'].substr($newTarget, strlen($folders['target']));
- if ($oldSource) {
- $storage = OC_Filesystem::getStorage($oldSource);
+ if ($oldSource = $this->getSourcePath($path1)) {
+ $root1 = substr($path1, 0, strpos($path1, '/'));
+ $root2 = substr($path2, 0, strpos($path2, '/'));
+ // Moving/renaming is only allowed within the same shared folder
+ if ($root1 == $root2) {
+ $storage = OC_Filesystem::getStorage($oldSource);
+ $newSource = substr($oldSource, 0, strpos($oldSource, $root1)).$path2;
+ if (dirname($path1) == dirname($path2)) {
+ // Rename the file if UPDATE permission is granted
+ if ($this->isUpdatable($path1)) {
+ return $storage->rename($this->getInternalPath($oldSource), $this->getInternalPath($newSource));
+ }
+ // Move the file if DELETE and CREATE permissions are granted
+ } else if ($this->isDeletable($path1) && $this->isCreatable(dirname($path2))) {
return $storage->rename($this->getInternalPath($oldSource), $this->getInternalPath($newSource));
}
- // If the user doesn't have write permission, items can only be renamed and not moved
- } else if (dirname($path1) !== dirname($path2)) {
- return false;
- // The item will be renamed in the database, but won't be touched on the owner's filesystem
- } else {
- OC_Share::pullOutOfFolder($oldTarget, $newTarget);
- // If this is a folder being renamed, call setTarget in case there are any database entries inside the folder
- if (self::is_dir($path1)) {
- OC_Share::setTarget($oldTarget, $newTarget);
- }
}
- } else {
- OC_Share::setTarget($oldTarget, $newTarget);
}
- return true;
+ return false;
}
public function copy($path1, $path2) {
- if ($path2 == "" || $path2 == "/") {
- // TODO Construct new shared item or should this not be allowed?
- } else {
- if ($this->is_writable($path2)) {
- $tmpFile = $this->toTmpFile($path1);
- $result = $this->fromTmpFile($tmpFile, $path2);
- return $result;
- } else {
- return false;
- }
+ // Copy the file if CREATE permission is granted
+ if (($source = $this->getSourcePath($path1)) && $this->isCreatable(dirname($path2))) {
+ $source = $this->fopen($path1, 'r');
+ $target = $this->fopen($path2, 'w');
+ return OC_Helper::streamCopy($source, $target);
}
+ return true;
}
-
+
public function fopen($path, $mode) {
- $source = $this->getSource($path);
- if ($source) {
+ if ($source = $this->getSourcePath($path)) {
$info = array(
- 'target' => $this->datadir.$path,
+ 'target' => $this->sharedFolder.$path,
'source' => $source,
'mode' => $mode,
);
@@ -376,95 +352,46 @@ class OC_Filestorage_Shared extends OC_Filestorage_Common {
$storage = OC_Filesystem::getStorage($source);
return $storage->fopen($this->getInternalPath($source), $mode);
}
+ return false;
}
-
- public function toTmpFile($path) {
- $source = $this->getSource($path);
- if ($source) {
- $storage = OC_Filesystem::getStorage($source);
- return $storage->toTmpFile($this->getInternalPath($source));
- }
- }
-
- public function fromTmpFile($tmpFile, $path) {
- if ($this->is_writable($path)) {
- $source = $this->getSource($path);
- if ($source) {
- $storage = OC_Filesystem::getStorage($source);
- $result = $storage->fromTmpFile($tmpFile, $this->getInternalPath($source));
- return $result;
- }
- } else {
- return false;
- }
- }
-
+
public function getMimeType($path) {
- if ($path == "" || $path == "/") {
+ if ($path == '' || $path == '/') {
return 'httpd/unix-directory';
}
- $source = $this->getSource($path);
- if ($source) {
+ if ($source = $this->getSourcePath($path)) {
$storage = OC_Filesystem::getStorage($source);
return $storage->getMimeType($this->getInternalPath($source));
}
+ return false;
}
-
- public function hash($type, $path, $raw = false) {
- $source = $this->getSource($path);
- if ($source) {
- $storage = OC_Filesystem::getStorage($source);
- return $storage->hash($type, $this->getInternalPath($source), $raw);
- }
- }
-
+
public function free_space($path) {
- $source = $this->getSource($path);
+ $source = $this->getSourcePath($path);
if ($source) {
$storage = OC_Filesystem::getStorage($source);
return $storage->free_space($this->getInternalPath($source));
}
}
-
- public function search($query) {
- return $this->searchInDir($query);
- }
-
- protected function searchInDir($query, $path = "") {
- $files = array();
- if ($dh = $this->opendir($path)) {
- while (($filename = readdir($dh)) !== false) {
- if ($filename != "." && $filename != "..") {
- if (strstr(strtolower($filename), strtolower($query))) {
- $files[] = $path."/".$filename;
- }
- if ($this->is_dir($path."/".$filename)) {
- $files = array_merge($files, $this->searchInDir($query, $path."/".$filename));
- }
- }
- }
- }
- return $files;
- }
public function getLocalFile($path) {
- $source = $this->getSource($path);
- if ($source) {
+ if ($source = $this->getSourcePath($path)) {
$storage = OC_Filesystem::getStorage($source);
return $storage->getLocalFile($this->getInternalPath($source));
}
+ return false;
}
- public function touch($path, $mtime=null){
- $source = $this->getSource($path);
- if ($source) {
+ public function touch($path, $mtime = null) {
+ if ($source = $this->getSourcePath($path)) {
$storage = OC_Filesystem::getStorage($source);
- return $storage->touch($this->getInternalPath($source),$mtime);
+ return $storage->touch($this->getInternalPath($source), $mtime);
}
+ return false;
}
public static function setup($options) {
$user_dir = $options['user_dir'];
- OC_Filesystem::mount('OC_Filestorage_Shared', array('datadir' => $user_dir.'/Shared'), $user_dir.'/Shared/');
+ OC_Filesystem::mount('OC_Filestorage_Shared', array('sharedFolder' => '/Shared'), $user_dir.'/Shared/');
}
/**
@@ -474,6 +401,6 @@ class OC_Filestorage_Shared extends OC_Filestorage_Common {
*/
public function hasUpdated($path,$time){
//TODO
- return $this->filemtime($path)>$time;
+ return false;
}
}
diff --git a/apps/files_sharing/sharetest.php b/apps/files_sharing/sharetest.php
new file mode 100755
index 00000000000..bcff10ca0ec
--- /dev/null
+++ b/apps/files_sharing/sharetest.php
@@ -0,0 +1,7 @@
+<?php
+
+
+OCP\Share::setPermissions('file', '/01 - Genesis.mp3', OCP\Share::SHARE_TYPE_USER, 'Genie2', OCP\Share::PERMISSION_READ | OCP\Share::PERMISSION_UPDATE);
+
+
+?> \ No newline at end of file
diff --git a/apps/files_sharing/templates/get.php b/apps/files_sharing/templates/get.php
new file mode 100755
index 00000000000..57275f07a3d
--- /dev/null
+++ b/apps/files_sharing/templates/get.php
@@ -0,0 +1,11 @@
+<table>
+ <thead>
+ <tr>
+ <th id="headerSize"><?php echo $l->t( 'Size' ); ?></th>
+ <th id="headerDate"><span id="modified"><?php echo $l->t( 'Modified' ); ?></span><span class="selectedActions"><a href="" class="delete"><?php echo $l->t('Delete all')?> <img class="svg" alt="<?php echo $l->t('Delete')?>" src="<?php echo OCP\image_path("core", "actions/delete.svg"); ?>" /></a></span></th>
+ </tr>
+ </thead>
+ <tbody id="fileList" data-readonly="<?php echo $_['readonly'];?>">
+ <?php echo($_['fileList']); ?>
+ </tbody>
+</table> \ No newline at end of file
diff --git a/apps/files_texteditor/js/editor.js b/apps/files_texteditor/js/editor.js
index 70bb74a9101..3784ea1032f 100644
--- a/apps/files_texteditor/js/editor.js
+++ b/apps/files_texteditor/js/editor.js
@@ -222,9 +222,17 @@ function showFileEditor(dir,filename){
}
});
// Add the ctrl+s event
- window.aceEditor.commands.addCommand({ name: "save", bindKey: { win: "Ctrl-S", mac: "Command-S", sender: "editor" }, exec: function(){
+ window.aceEditor.commands.addCommand({
+ name: "save",
+ bindKey: {
+ win: "Ctrl-S",
+ mac: "Command-S",
+ sender: "editor"
+ },
+ exec: function(){
doFileSave();
- } });
+ }
+ });
});
} else {
// Failed to get the file.
@@ -297,11 +305,11 @@ $(window).resize(function() {
var is_editor_shown = false;
$(document).ready(function(){
if(typeof FileActions!=='undefined'){
- FileActions.register('text','Edit','',function(filename){
+ FileActions.register('text','Edit', FileActions.PERMISSION_READ, '',function(filename){
showFileEditor($('#dir').val(),filename);
});
FileActions.setDefault('text','Edit');
- FileActions.register('application/xml','Edit','',function(filename){
+ FileActions.register('application/xml','Edit', FileActions.PERMISSION_READ, '',function(filename){
showFileEditor($('#dir').val(),filename);
});
FileActions.setDefault('application/xml','Edit');
diff --git a/apps/files_versions/appinfo/api.php b/apps/files_versions/appinfo/api.php
new file mode 100644
index 00000000000..a7386bc2c9f
--- /dev/null
+++ b/apps/files_versions/appinfo/api.php
@@ -0,0 +1,36 @@
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+return array(
+ 'list' => array('method' => 'GET', 'class' => 'Storage', 'function' => 'getVersions',
+ 'parameters' => array(
+ 'file' => array('required' => true, 'type' => 'string')
+ )
+ ),
+ 'revert' => array('method' => 'POST', 'class' => 'Storage', 'function' => 'rollback',
+ 'parameters' => array(
+ 'file' => array('required' => true, 'type' => 'string'),
+ 'time' => array('required' => true, 'type' => 'int')
+ )
+ )
+);
+
+?> \ No newline at end of file
diff --git a/apps/files_versions/js/versions.js b/apps/files_versions/js/versions.js
index a090fde446e..c5c1553f1a8 100644
--- a/apps/files_versions/js/versions.js
+++ b/apps/files_versions/js/versions.js
@@ -11,7 +11,7 @@ $(document).ready(function() {
$(document).ready(function(){
if (typeof FileActions !== 'undefined') {
// Add history button to files/index.php
- FileActions.register('file','History',function(){return OC.imagePath('core','actions/history')},function(filename){
+ FileActions.register('file','History', FileActions.PERMISSION_UPDATE, function(){return OC.imagePath('core','actions/history')},function(filename){
if (scanFiles.scanning){return;}//workaround to prevent additional http request block scanning feedback
diff --git a/apps/gallery/appinfo/app.php b/apps/gallery/appinfo/app.php
index df3b68ef736..9efb4346c3e 100644
--- a/apps/gallery/appinfo/app.php
+++ b/apps/gallery/appinfo/app.php
@@ -28,6 +28,9 @@ OC::$CLASSPATH['OC_Gallery_Sharing'] = 'gallery/lib/sharing.php';
OC::$CLASSPATH['OC_Gallery_Hooks_Handlers'] = 'gallery/lib/hooks_handlers.php';
OC::$CLASSPATH['Pictures_Managers'] = 'gallery/lib/managers.php';
OC::$CLASSPATH['Pictures_Tiles'] = 'gallery/lib/tiles.php';
+OC::$CLASSPATH['OC_Share_Backend_Photo'] = 'gallery/lib/share.php';
+
+OCP\Share::registerBackend('photo', new OC_Share_Backend_Photo());
$l = OC_L10N::get('gallery');
diff --git a/apps/gallery/lib/share.php b/apps/gallery/lib/share.php
new file mode 100644
index 00000000000..6f3db45375f
--- /dev/null
+++ b/apps/gallery/lib/share.php
@@ -0,0 +1,42 @@
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+class OC_Share_Backend_Photo extends OCP\Share_Backend {
+
+ public $dependsOn = 'file';
+ public $supportedFileExtensions = array('jpg', 'png', 'gif');
+
+ public function getSource($item, $uid) {
+ return array('item' => 'blah.jpg', 'file' => $item);
+ }
+
+ public function generateTarget($item, $uid, $exclude = null) {
+ // TODO Make sure target path doesn't exist already
+ return $item;
+ }
+
+ public function formatItems($items, $format, $parameters = null) {
+
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/apps/media/js/loader.js b/apps/media/js/loader.js
index 393f8ba914e..ffe9c1cdd61 100644
--- a/apps/media/js/loader.js
+++ b/apps/media/js/loader.js
@@ -45,8 +45,8 @@ $(document).ready(function() {
// FileActions.register('application/ogg','Add to playlist','',addAudio);
if(typeof FileActions!=='undefined'){
- FileActions.register('audio','Play','',playAudio);
- FileActions.register('application/ogg','','Play',playAudio);
+ FileActions.register('audio','Play', FileActions.PERMISSION_READ, '',playAudio);
+ FileActions.register('application/ogg', FileActions.PERMISSION_READ, '','Play',playAudio);
FileActions.setDefault('audio','Play');
FileActions.setDefault('application/ogg','Play');
}
diff --git a/apps/media/lib/share/album.php b/apps/media/lib/share/album.php
new file mode 100644
index 00000000000..e69de29bb2d
--- /dev/null
+++ b/apps/media/lib/share/album.php
diff --git a/apps/media/lib/share/artist.php b/apps/media/lib/share/artist.php
new file mode 100644
index 00000000000..7218fa1a279
--- /dev/null
+++ b/apps/media/lib/share/artist.php
@@ -0,0 +1,65 @@
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+class OC_Share_Backend_Artist extends OCP\Share_Backend {
+
+ public function getSource($item, $uid) {
+ $query = OCP\DB::prepare('SELECT artist_id FROM *PREFIX*media_artists WHERE artist_id = ? AND song_user = ?');
+ $result = $query->execute(array($item, $uid))->fetchRow();
+ if (is_array($result)) {
+ return array('item' => $item, 'file' => $result['song_path']);
+ }
+ return false;
+ }
+
+ public function generateTarget($item, $uid, $exclude = null) {
+ // TODO Make sure target path doesn't exist already
+ return '/Shared'.$item;
+ }
+
+ public function formatItems($items, $format) {
+ $ids = array();
+ foreach ($items as $id => $info) {
+ $ids[] = $id;
+ }
+ $ids = "'".implode("','", $ids)."'";
+ switch ($format) {
+ case self::FORMAT_SOURCE_PATH:
+ $query = OCP\DB::prepare('SELECT path FROM *PREFIX*fscache WHERE id IN ('.$ids.')');
+ return $query->execute()->fetchAll();
+ case self::FORMAT_FILE_APP:
+ $query = OCP\DB::prepare('SELECT id, path, name, ctime, mtime, mimetype, size, encrypted, versioned, writable FROM *PREFIX*fscache WHERE id IN ('.$ids.')');
+ $result = $query->execute();
+ $files = array();
+ while ($file = $result->fetchRow()) {
+ // Set target path
+ $file['path'] = $items[$file['id']]['item_target'];
+ $file['name'] = basename($file['path']);
+ // TODO Set permissions: $file['writable']
+ $files[] = $file;
+ }
+ return $files;
+ }
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/apps/media/lib/share/song.php b/apps/media/lib/share/song.php
new file mode 100644
index 00000000000..fc69975f353
--- /dev/null
+++ b/apps/media/lib/share/song.php
@@ -0,0 +1,65 @@
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+class OC_Share_Backend_Song extends OCP\Share_Backend {
+
+ public function getSource($item, $uid) {
+ $query = OCP\DB::prepare('SELECT song_path FROM *PREFIX*media_songs WHERE song_id = ? AND song_user = ?');
+ $result = $query->execute(array($item, $uid))->fetchRow();
+ if (is_array($result)) {
+ return array('item' => $item, 'file' => $result['song_path']);
+ }
+ return false;
+ }
+
+ public function generateTarget($item, $uid, $exclude = null) {
+ // TODO Make sure target path doesn't exist already
+ return '/Shared'.$item;
+ }
+
+ public function formatItems($items, $format) {
+ $ids = array();
+ foreach ($items as $id => $info) {
+ $ids[] = $id;
+ }
+ $ids = "'".implode("','", $ids)."'";
+ switch ($format) {
+ case self::FORMAT_SOURCE_PATH:
+ $query = OCP\DB::prepare('SELECT path FROM *PREFIX*fscache WHERE id IN ('.$ids.')');
+ return $query->execute()->fetchAll();
+ case self::FORMAT_FILE_APP:
+ $query = OCP\DB::prepare('SELECT id, path, name, ctime, mtime, mimetype, size, encrypted, versioned, writable FROM *PREFIX*fscache WHERE id IN ('.$ids.')');
+ $result = $query->execute();
+ $files = array();
+ while ($file = $result->fetchRow()) {
+ // Set target path
+ $file['path'] = $items[$file['id']]['item_target'];
+ $file['name'] = basename($file['path']);
+ // TODO Set permissions: $file['writable']
+ $files[] = $file;
+ }
+ return $files;
+ }
+ }
+
+}
+
+?> \ No newline at end of file
diff --git a/core/ajax/share.php b/core/ajax/share.php
new file mode 100644
index 00000000000..c613baa7f5e
--- /dev/null
+++ b/core/ajax/share.php
@@ -0,0 +1,107 @@
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+require_once '../../lib/base.php';
+
+OC_JSON::checkLoggedIn();
+if (isset($_POST['action']) && isset($_POST['itemType']) && isset($_POST['item'])) {
+ switch ($_POST['action']) {
+ case 'share':
+ if (isset($_POST['shareType']) && isset($_POST['shareWith']) && isset($_POST['permissions'])) {
+ $return = OCP\Share::share($_POST['itemType'], $_POST['item'], $_POST['shareType'], $_POST['shareWith'], $_POST['permissions']);
+ // TODO May need to return private link
+ ($return) ? OC_JSON::success() : OC_JSON::error();
+ }
+ break;
+ case 'unshare':
+ if (isset($_POST['shareType']) && isset($_POST['shareWith'])) {
+ $return = OCP\Share::unshare($_POST['itemType'], $_POST['item'], $_POST['shareType'], $_POST['shareWith']);
+ ($return) ? OC_JSON::success() : OC_JSON::error();
+ }
+ break;
+ case 'setTarget':
+ if (isset($_POST['newTarget'])) {
+ $return = OCP\Share::setTarget($_POST['itemType'], $_POST['item'], $_POST['newTarget']);
+ ($return) ? OC_JSON::success() : OC_JSON::error();
+ }
+ break;
+ case 'setPermissions':
+ if (isset($_POST['shareType']) && isset($_POST['shareWith']) && isset($_POST['permissions'])) {
+ $return = OCP\Share::setPermissions($_POST['itemType'], $_POST['item'], $_POST['shareType'], $_POST['shareWith'], $_POST['permissions']);
+ ($return) ? OC_JSON::success() : OC_JSON::error();
+ }
+ break;
+ }
+} else if (isset($_GET['fetch'])) {
+ switch ($_GET['fetch']) {
+ case 'getItemsSharedStatuses':
+ if (isset($_GET['itemType'])) {
+ $return = OCP\Share::getItemsShared($_GET['itemType'], OCP\Share::FORMAT_STATUSES);
+ ($return) ? OC_JSON::success(array('data' => $return)) : OC_JSON::error();
+ }
+ break;
+ case 'getItem':
+ // TODO Check if the item was shared to the current user
+ if (isset($_GET['itemType']) && isset($_GET['item'])) {
+ $return = OCP\Share::getItemShared($_GET['itemType'], $_GET['item']);
+ ($return) ? OC_JSON::success(array('data' => $return)) : OC_JSON::error();
+ }
+ break;
+ case 'getShareWith':
+ if (isset($_GET['search'])) {
+ // TODO Include contacts
+ $shareWith = array();
+ $count = 0;
+ $users = array();
+ $limit = 0;
+ $offset = 0;
+ while ($count < 4 && count($users) == $limit) {
+ $limit = 4 - $count;
+ $users = OC_User::getUsers($_GET['search'], $limit, $offset);
+ $offset += $limit;
+ foreach ($users as $user) {
+ if ((!isset($_GET['itemShares'][OCP\Share::SHARE_TYPE_USER]) || !in_array($user, $_GET['itemShares'][OCP\Share::SHARE_TYPE_USER])) && $user != OC_User::getUser()) {
+ $shareWith[] = array('label' => $user, 'value' => array('shareType' => OCP\Share::SHARE_TYPE_USER, 'shareWith' => $user));
+ $count++;
+ }
+ }
+ }
+ $count = 0;
+ $groups = array();
+ $limit = 0;
+ $offset = 0;
+ while ($count < 4 && count($groups) == $limit) {
+ $limit = 4 - $count;
+ $groups = OC_Group::getGroups($_GET['search'], $limit, $offset);
+ $offset += $limit;
+ foreach ($groups as $group) {
+ if (!isset($_GET['itemShares'][OCP\Share::SHARE_TYPE_GROUP]) || !in_array($group, $_GET['itemShares'][OCP\Share::SHARE_TYPE_GROUP])) {
+ $shareWith[] = array('label' => $group.' (group)', 'value' => array('shareType' => OCP\Share::SHARE_TYPE_GROUP, 'shareWith' => $group));
+ $count++;
+ }
+ }
+ }
+ OC_JSON::success(array('data' => $shareWith));
+ }
+ break;
+ }
+}
+
+?> \ No newline at end of file
diff --git a/core/js/share.js b/core/js/share.js
new file mode 100644
index 00000000000..2d6bc653fa7
--- /dev/null
+++ b/core/js/share.js
@@ -0,0 +1,385 @@
+OC.Share={
+ SHARE_TYPE_USER:0,
+ SHARE_TYPE_GROUP:1,
+ SHARE_TYPE_PRIVATE_LINK:3,
+ SHARE_TYPE_EMAIL:4,
+ PERMISSION_CREATE:4,
+ PERMISSION_READ:1,
+ PERMISSION_UPDATE:2,
+ PERMISSION_DELETE:8,
+ PERMISSION_SHARE:16,
+ itemShares:[],
+ statuses:[],
+ loadIcons:function(itemType) {
+ // Load all share icons
+ $.get(OC.filePath('core', 'ajax', 'share.php'), { fetch: 'getItemsSharedStatuses', itemType: itemType }, function(result) {
+ if (result && result.status === 'success') {
+ $.each(result.data, function(item, hasPrivateLink) {
+ // Private links override shared in terms of icon display
+ if (itemType == 'file') {
+ OC.Share.statuses[item] = hasPrivateLink;
+ } else {
+ if (hasPrivateLink) {
+ $('.share').find('[data-item="'+item+'"]').attr('src', OC.imagePath('core', 'actions/public'));
+ } else {
+ $('.share').find('[data-item="'+item+'"]').attr('src', OC.imagePath('core', 'actions/shared'));
+ }
+ }
+ });
+ }
+ });
+ },
+ loadItem:function(itemType, item) {
+ var data = '';
+ $.ajax({type: 'GET', url: OC.filePath('core', 'ajax', 'share.php'), data: { fetch: 'getItem', itemType: itemType, item: item }, async: false, success: function(result) {
+ if (result && result.status === 'success') {
+ data = result.data;
+ } else {
+ data = false;
+ }
+ }});
+ return data;
+ },
+ share:function(itemType, item, shareType, shareWith, permissions, callback) {
+ $.post(OC.filePath('core', 'ajax', 'share.php'), { action: 'share', itemType: itemType, item: item, shareType: shareType, shareWith: shareWith, permissions: permissions }, function(result) {
+ if (result && result.status === 'success') {
+ if (callback) {
+ callback(result.data);
+ }
+ } else {
+ OC.dialogs.alert('Error', 'Error while sharing');
+ }
+ });
+ },
+ unshare:function(itemType, item, shareType, shareWith, callback) {
+ $.post(OC.filePath('core', 'ajax', 'share.php'), { action: 'unshare', itemType: itemType, item: item, shareType: shareType, shareWith: shareWith }, function(result) {
+ if (result && result.status === 'success') {
+ if (callback) {
+ callback();
+ }
+ } else {
+ OC.dialogs.alert('Error', 'Error while unsharing');
+ }
+ });
+ },
+ setPermissions:function(itemType, item, shareType, shareWith, permissions) {
+ $.post(OC.filePath('core', 'ajax', 'share.php'), { action: 'setPermissions', itemType: itemType, item: item, shareType: shareType, shareWith: shareWith, permissions: permissions }, function(result) {
+ if (!result || result.status !== 'success') {
+ OC.dialogs.alert('Error', 'Error while changing permissions');
+ }
+ });
+ },
+ showDropDown:function(itemType, item, appendTo, privateLink, possiblePermissions) {
+ var html = '<div id="dropdown" class="drop" data-item-type="'+itemType+'" data-item="'+item+'">';
+ // TODO replace with autocomplete textbox
+ html += '<input id="shareWith" type="text" placeholder="Share with" style="width:90%;"/>';
+ html += '<ul id="shareWithList">';
+ html += '</ul>';
+ if (privateLink) {
+ html += '<div id="privateLink">';
+ html += '<input type="checkbox" name="privateLinkCheckbox" id="privateLinkCheckbox" value="1" /><label for="privateLinkCheckbox">Share with private link</label>';
+ html += '<br />';
+ html += '<input id="privateLinkText" style="display:none; width:90%;" readonly="readonly" />';
+ html += '</div>';
+ }
+ html += '</div>';
+ $(html).appendTo(appendTo);
+ var data = OC.Share.loadItem(itemType, item);
+ if (data) {
+ $.each(data, function(index, share) {
+ if (share.share_type == OC.Share.SHARE_TYPE_PRIVATE_LINK) {
+ OC.Share.showPrivateLink(item, share.share_with);
+ } else {
+ OC.Share.addShareWith(share.share_type, share.share_with, share.permissions, possiblePermissions);
+
+ }
+ });
+ }
+ $('#shareWith').autocomplete({minLength: 2, source: function(search, response) {
+// if (cache[search.term]) {
+// response(cache[search.term]);
+// } else {
+ $.get(OC.filePath('core', 'ajax', 'share.php'), { fetch: 'getShareWith', search: search.term, itemShares: OC.Share.itemShares }, function(result) {
+ if (result.status == 'success' && result.data.length > 0) {
+ response(result.data);
+ } else {
+ // Suggest sharing via email if valid email address
+ var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
+ if (pattern.test(search.term)) {
+ response([{label: 'Share via email: '+search.term, value: {shareType: OC.Share.SHARE_TYPE_EMAIL, shareWith: search.term}}]);
+ } else {
+ response(['No people found']);
+ }
+ }
+ });
+// }
+ }, select: function(event, selected) {
+ var shareType = selected.item.value.shareType;
+ var shareWith = selected.item.value.shareWith;
+ $(this).val(shareWith);
+ // Default permissions are Read and Share
+ var permissions = OC.Share.PERMISSION_READ | OC.Share.PERMISSION_SHARE;
+ OC.Share.share($('#dropdown').data('item-type'), $('#dropdown').data('item'), shareType, shareWith, permissions, function() {
+ OC.Share.addShareWith(shareType, shareWith, permissions, possiblePermissions);
+ $('#shareWith').val('');
+ });
+ return false;
+ }
+ });
+ $('#dropdown').show('blind');
+ $('#shareWith').focus();
+ },
+ hideDropDown:function(callback) {
+ $('#dropdown').hide('blind', function() {
+ $('#dropdown').remove();
+ if (callback) {
+ callback.call();
+ }
+ });
+ },
+ addShareWith:function(shareType, shareWith, permissions, possiblePermissions) {
+ if (!OC.Share.itemShares[shareType]) {
+ OC.Share.itemShares[shareType] = [];
+ }
+ OC.Share.itemShares[shareType].push(shareWith);
+ var editChecked = createChecked = updateChecked = deleteChecked = shareChecked = '';
+ if (permissions & OC.Share.PERMISSION_CREATE) {
+ createChecked = 'checked="checked"';
+ editChecked = 'checked="checked"';
+ }
+ if (permissions & OC.Share.PERMISSION_UPDATE) {
+ updateChecked = 'checked="checked"';
+ editChecked = 'checked="checked"';
+ }
+ if (permissions & OC.Share.PERMISSION_DELETE) {
+ deleteChecked = 'checked="checked"';
+ editChecked = 'checked="checked"';
+ }
+ if (permissions & OC.Share.PERMISSION_SHARE) {
+ shareChecked = 'checked="checked"';
+ }
+ var html = '<li data-share-type="'+shareType+'" data-share-with="'+shareWith+'">';
+ html += shareWith;
+ if (possiblePermissions & OC.Share.PERMISSION_CREATE || possiblePermissions & OC.Share.PERMISSION_UPDATE || possiblePermissions & OC.Share.PERMISSION_DELETE) {
+ html += '<label><input type="checkbox" name="edit" class="permissions" '+editChecked+' />can edit</label>';
+ }
+ html += '<a href="#" class="showCruds" style="display:none;"><img class="svg" alt="Unshare" src="'+OC.imagePath('core', 'actions/triangle-s')+'"/></a>';
+ html += '<a href="#" class="unshare" style="display:none;"><img class="svg" alt="Unshare" src="'+OC.imagePath('core', 'actions/delete')+'"/></a>';
+ html += '<div class="cruds" style="display:none;">';
+ if (possiblePermissions & OC.Share.PERMISSION_CREATE) {
+ html += '<label><input type="checkbox" name="create" class="permissions" '+createChecked+' data-permissions="'+OC.Share.PERMISSION_CREATE+'" />create</label>';
+ }
+ if (possiblePermissions & OC.Share.PERMISSION_UPDATE) {
+ html += '<label><input type="checkbox" name="update" class="permissions" '+updateChecked+' data-permissions="'+OC.Share.PERMISSION_UPDATE+'" />update</label>';
+ }
+ if (possiblePermissions & OC.Share.PERMISSION_DELETE) {
+ html += '<label><input type="checkbox" name="delete" class="permissions" '+deleteChecked+' data-permissions="'+OC.Share.PERMISSION_DELETE+'" />delete</label>';
+ }
+ if (possiblePermissions & OC.Share.PERMISSION_SHARE) {
+ html += '<label><input type="checkbox" name="share" class="permissions" '+shareChecked+' data-permissions="'+OC.Share.PERMISSION_SHARE+'" />share</label>';
+ }
+ html += '</div>';
+ html += '</li>';
+ $(html).appendTo('#shareWithList');
+
+ },
+ showPrivateLink:function(item, token) {
+ $('#privateLinkCheckbox').attr('checked', true);
+ var link = parent.location.protocol+'//'+location.host+OC.linkTo('', 'public.php')+'?service=files&token='+token;
+ if (token.indexOf('&path=') == -1) {
+ link += '&file=' + encodeURIComponent(item).replace(/%2F/g, '/');
+ } else {
+ // Disable checkbox if inside a shared parent folder
+ $('#privateLinkCheckbox').attr('disabled', 'true');
+ }
+ $('#privateLinkText').val(link);
+ $('#privateLinkText').show('blind', function() {
+ $('#privateLinkText').after('<br id="emailBreak" />');
+ $('#email').show();
+ $('#emailButton').show();
+ });
+ },
+ hidePrivateLink:function() {
+ $('#privateLinkText').hide('blind');
+ $('#emailBreak').remove();
+ $('#email').hide();
+ $('#emailButton').hide();
+ },
+ emailPrivateLink:function() {
+ var link = $('#privateLinkText').val();
+ var file = link.substr(link.lastIndexOf('/') + 1).replace(/%20/g, ' ');
+ $.post(OC.filePath('files_sharing', 'ajax', 'email.php'), { toaddress: $('#email').val(), link: link, file: file } );
+ $('#email').css('font-weight', 'bold');
+ $('#email').animate({ fontWeight: 'normal' }, 2000, function() {
+ $(this).val('');
+ }).val('Email sent');
+ },
+ dirname:function(path) {
+ return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
+ }
+}
+
+$(document).ready(function() {
+
+ $('.share').live('click', function() {
+ if ($(this).data('item-type') !== undefined && $(this).data('item') !== undefined) {
+ var privateLink = false;
+ if ($(this).data('private-link') !== undefined && $(this).data('private-link') == true) {
+ privateLink = true;
+ }
+ OC.Share.showDropDown($(this).data('item-type'), $(this).data('item'), $(this).parent().parent(), privateLink, $(this).data('possible-permissions'));
+ }
+ });
+
+ if (typeof FileActions !== 'undefined') {
+
+ OC.Share.loadIcons('file');
+ FileActions.register('all', 'Share', FileActions.PERMISSION_SHARE, function(filename) {
+ // Return the correct sharing icon
+ if (scanFiles.scanning) { return; } // workaround to prevent additional http request block scanning feedback
+ var item = $('#dir').val() + '/' + filename;
+ // Check if status is in cache
+ if (OC.Share.statuses[item] === true) {
+ return OC.imagePath('core', 'actions/public');
+ } else if (OC.Share.statuses[item] === false) {
+ return OC.imagePath('core', 'actions/shared');
+ } else {
+ var last = '';
+ var path = OC.Share.dirname(item);
+ // Search for possible parent folders that are shared
+ while (path != last) {
+ if (OC.Share.statuses[path] === true) {
+ return OC.imagePath('core', 'actions/public');
+ } else if (OC.Share.statuses[path] === false) {
+ return OC.imagePath('core', 'actions/shared');
+ }
+ last = path;
+ path = OC.Share.dirname(path);
+ }
+ return OC.imagePath('core', 'actions/share');
+ }
+ }, function(filename) {
+ var item = $('#dir').val() + '/' + filename;
+ if ($('tr').filterAttr('data-file', filename).data('type') == 'dir') {
+ var itemType = 'folder';
+ var possiblePermissions = OC.Share.PERMISSION_CREATE | OC.Share.PERMISSION_UPDATE | OC.Share.PERMISSION_DELETE | OC.Share.PERMISSION_SHARE;
+ } else {
+ var itemType = 'file';
+ var possiblePermissions = OC.Share.PERMISSION_UPDATE | OC.Share.PERMISSION_DELETE | OC.Share.PERMISSION_SHARE;
+ }
+ var appendTo = $('tr').filterAttr('data-file', filename).find('td.filename');
+ // Check if drop down is already visible for a different file
+ if (($('#dropdown').length > 0)) {
+ if (item != $('#dropdown').data('item')) {
+ OC.Share.hideDropDown(function () {
+ $('tr').removeClass('mouseOver');
+ $('tr').filterAttr('data-file', filename).addClass('mouseOver');
+ OC.Share.showDropDown(itemType, item, appendTo, true, possiblePermissions);
+ });
+ }
+ } else {
+ $('tr').filterAttr('data-file',filename).addClass('mouseOver');
+ OC.Share.showDropDown(itemType, item, appendTo, true, possiblePermissions);
+ }
+ });
+ }
+
+// $(this).click(function(event) {
+// if (!($(event.target).hasClass('drop')) && $(event.target).parents().index($('#dropdown')) == -1) {
+// if ($('#dropdown').is(':visible')) {
+// OC.Share.hideDropDown(function() {
+// $('tr').removeClass('mouseOver');
+// });
+// }
+// }
+// });
+
+ $('#shareWithList li').live('mouseenter', function(event) {
+ // Show permissions and unshare button
+ $(':hidden', this).filter(':not(.cruds)').show();
+ });
+
+ $('#shareWithList li').live('mouseleave', function(event) {
+ // Hide permissions and unshare button
+ if (!$('.cruds', this).is(':visible')) {
+ $('a', this).hide();
+ if (!$('input[name="edit"]', this).is(':checked')) {
+ $('input:[type=checkbox]', this).hide();
+ $('label', this).hide();
+ }
+ } else {
+ $('a.unshare', this).hide();
+ }
+ });
+
+ $('.showCruds').live('click', function() {
+ $(this).parent().find('.cruds').toggle();
+ });
+
+ $('.unshare').live('click', function() {
+ var li = $(this).parent();
+ OC.Share.unshare($('#dropdown').data('item-type'), $('#dropdown').data('item'), $(li).data('share-type'), $(li).data('share-with'), function() {
+ $(li).remove();
+ });
+ });
+
+ $('.permissions').live('change', function() {
+ if ($(this).attr('name') == 'edit') {
+ var li = $(this).parent().parent()
+ var checkboxes = $('.permissions', li);
+ var checked = $(this).is(':checked');
+ // Check/uncheck Create, Update, and Delete checkboxes if Edit is checked/unck
+ $(checkboxes).filter('input[name="create"]').attr('checked', checked);
+ $(checkboxes).filter('input[name="update"]').attr('checked', checked);
+ $(checkboxes).filter('input[name="delete"]').attr('checked', checked);
+ } else {
+ var li = $(this).parent().parent().parent();
+ var checkboxes = $('.permissions', li);
+ // Uncheck Edit if Create, Update, and Delete are not checked
+ if (!$(this).is(':checked') && !$(checkboxes).filter('input[name="create"]').is(':checked') && !$(checkboxes).filter('input[name="update"]').is(':checked') && !$(checkboxes).filter('input[name="delete"]').is(':checked')) {
+ $(checkboxes).filter('input[name="edit"]').attr('checked', false);
+ // Check Edit if Create, Update, or Delete is checked
+ } else if (($(this).attr('name') == 'create' || $(this).attr('name') == 'update' || $(this).attr('name') == 'delete')) {
+ $(checkboxes).filter('input[name="edit"]').attr('checked', true);
+ }
+ }
+ var permissions = OC.Share.PERMISSION_READ;
+ $(checkboxes).filter(':not(input[name="edit"])').filter(':checked').each(function(index, checkbox) {
+ permissions |= $(checkbox).data('permissions');
+ });
+ OC.Share.setPermissions($('#dropdown').data('item-type'), $('#dropdown').data('item'), $(li).data('share-type'), $(li).data('share-with'), permissions);
+ });
+
+ $('#privateLinkCheckbox').live('change', function() {
+ var itemType = $('#dropdown').data('item-type');
+ var item = $('#dropdown').data('item');
+ if (this.checked) {
+ // Create a private link
+ OC.Share.share(itemType, item, OC.Share.SHARE_TYPE_PRIVATE_LINK, 0, 0, function(token) {
+ OC.Share.showPrivateLink(item, 'foo');
+ // Change icon
+ OC.Share.icons[item] = OC.imagePath('core', 'actions/public');
+ });
+ } else {
+ // Delete private link
+ OC.Share.unshare(item, 'public', function() {
+ OC.Share.hidePrivateLink();
+ // Change icon
+ if (OC.Share.itemUsers || OC.Share.itemGroups) {
+ OC.Share.icons[item] = OC.imagePath('core', 'actions/shared');
+ } else {
+ OC.Share.icons[item] = OC.imagePath('core', 'actions/share');
+ }
+ });
+ }
+ });
+
+ $('#privateLinkText').live('click', function() {
+ $(this).focus();
+ $(this).select();
+ });
+
+ $('#emailPrivateLink').live('submit', function() {
+ OC.Share.emailPrivateLink();
+ });
+});
diff --git a/lib/filecache.php b/lib/filecache.php
index 22f7427ae42..8211637d141 100644
--- a/lib/filecache.php
+++ b/lib/filecache.php
@@ -350,6 +350,10 @@ class OC_FileCache{
$eventSource->send('scanning',array('file'=>$path,'count'=>$count));
}
$lastSend=$count;
+ // NOTE: Ugly hack to prevent shared files from going into the cache (the source already exists somewhere in the cache)
+ if (substr($path, 0, 7) == '/Shared') {
+ return;
+ }
if($root===false){
$view=OC_Filesystem::getView();
}else{
@@ -387,6 +391,10 @@ class OC_FileCache{
* @return int size of the scanned file
*/
public static function scanFile($path,$root=false){
+ // NOTE: Ugly hack to prevent shared files from going into the cache (the source already exists somewhere in the cache)
+ if (substr($path, 0, 7) == '/Shared') {
+ return;
+ }
if($root===false){
$view=OC_Filesystem::getView();
}else{
diff --git a/lib/files.php b/lib/files.php
index d5bebb7e549..fee71b777b3 100644
--- a/lib/files.php
+++ b/lib/files.php
@@ -33,10 +33,38 @@ class OC_Files {
* @param dir $directory path under datadirectory
*/
public static function getDirectoryContent($directory, $mimetype_filter = ''){
- $files=OC_FileCache::getFolderContent($directory, false, $mimetype_filter);
- foreach($files as &$file){
- $file['directory']=$directory;
- $file['type']=($file['mimetype']=='httpd/unix-directory')?'dir':'file';
+ $files = array();
+ if (substr($directory, 0, 7) == '/Shared') {
+ if ($directory == '/Shared') {
+ $files = OCP\Share::getItemsSharedWith('file', OC_Share_Backend_File::FORMAT_FILE_APP, array('folder' => $directory, 'mimetype_filter' => $mimetype_filter));
+ } else {
+ $pos = strpos($directory, '/', 8);
+ // Get shared folder name
+ if ($pos !== false) {
+ $itemTarget = substr($directory, 0, $pos);
+ } else {
+ $itemTarget = $directory;
+ }
+ $files = OCP\Share::getItemSharedWith('folder', $itemTarget, OC_Share_Backend_File::FORMAT_FILE_APP, array('folder' => $directory, 'mimetype_filter' => $mimetype_filter));
+ }
+ } else {
+ $files = OC_FileCache::getFolderContent($directory, false, $mimetype_filter);
+ foreach ($files as &$file) {
+ $file['directory'] = $directory;
+ $file['type'] = ($file['mimetype'] == 'httpd/unix-directory') ? 'dir' : 'file';
+ $permissions = OCP\Share::PERMISSION_READ | OCP\Share::PERMISSION_SHARE;
+ if ($file['type'] == 'dir' && $file['writable']) {
+ $permissions |= OCP\Share::PERMISSION_CREATE;
+ }
+ if ($file['writable']) {
+ $permissions |= OCP\Share::PERMISSION_UPDATE | OCP\Share::PERMISSION_DELETE;
+ }
+ $file['permissions'] = $permissions;
+ }
+ if ($directory == '') {
+ // Add 'Shared' folder
+ $files = array_merge($files, OCP\Share::getItemsSharedWith('file', OC_Share_Backend_File::FORMAT_FILE_APP_ROOT));
+ }
}
usort($files, "fileCmp");//TODO: remove this once ajax is merged
return $files;
@@ -104,8 +132,7 @@ class OC_Files {
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($filename));
}else{
- $fileData=OC_FileCache::get($filename);
- header('Content-Type: ' . $fileData['mimetype']);
+ header('Content-Type: '.OC_Filesystem::getMimeType($filename));
}
}elseif($zip or !OC_Filesystem::file_exists($filename)){
header("HTTP/1.0 404 Not Found");
diff --git a/lib/filestorage.php b/lib/filestorage.php
index fd4ad36530e..5d864b5d7bb 100644
--- a/lib/filestorage.php
+++ b/lib/filestorage.php
@@ -33,8 +33,11 @@ abstract class OC_Filestorage{
abstract public function stat($path);
abstract public function filetype($path);
abstract public function filesize($path);
- abstract public function is_readable($path);
- abstract public function is_writable($path);
+ abstract public function isCreatable($path);
+ abstract public function isReadable($path);
+ abstract public function isUpdatable($path);
+ abstract public function isDeletable($path);
+ abstract public function isSharable($path);
abstract public function file_exists($path);
abstract public function filectime($path);
abstract public function filemtime($path);
diff --git a/lib/filestorage/common.php b/lib/filestorage/common.php
index c77df38e6b1..00c76796c57 100644
--- a/lib/filestorage/common.php
+++ b/lib/filestorage/common.php
@@ -54,8 +54,17 @@ abstract class OC_Filestorage_Common extends OC_Filestorage {
return $stat['size'];
}
}
-// abstract public function is_readable($path);
-// abstract public function is_writable($path);
+ public function isCreatable($path) {
+ return $this->isUpdatable($path);
+ }
+// abstract public function isReadable($path);
+// abstract public function isUpdatable($path);
+ public function isDeletable($path) {
+ return $this->isUpdatable($path);
+ }
+ public function isSharable($path) {
+ return $this->isReadable($path);
+ }
// abstract public function file_exists($path);
public function filectime($path) {
$stat = $this->stat($path);
diff --git a/lib/filestorage/local.php b/lib/filestorage/local.php
index d60f32b15be..94b3147b73b 100644
--- a/lib/filestorage/local.php
+++ b/lib/filestorage/local.php
@@ -45,10 +45,10 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
return filesize($this->datadir.$path);
}
}
- public function is_readable($path){
+ public function isReadable($path){
return is_readable($this->datadir.$path);
}
- public function is_writable($path){
+ public function isUpdatable($path){
return is_writable($this->datadir.$path);
}
public function file_exists($path){
@@ -85,7 +85,7 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
return $this->delTree($path);
}
public function rename($path1,$path2){
- if (!$this->is_writable($path1)) {
+ if (!$this->isUpdatable($path1)) {
OC_Log::write('core','unable to rename, file is not writable : '.$path1,OC_Log::ERROR);
return false;
}
@@ -128,7 +128,7 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
}
public function getMimeType($path){
- if($this->is_readable($path)){
+ if($this->isReadable($path)){
return OC_Helper::getMimeType($this->datadir.$path);
}else{
return false;
diff --git a/lib/filesystem.php b/lib/filesystem.php
index 47626c05ae2..72d3711e9a2 100644
--- a/lib/filesystem.php
+++ b/lib/filesystem.php
@@ -406,12 +406,33 @@ class OC_Filesystem{
static public function readfile($path){
return self::$defaultInstance->readfile($path);
}
+ /**
+ * @deprecated Replaced by isReadable() as part of CRUDS
+ */
static public function is_readable($path){
return self::$defaultInstance->is_readable($path);
}
+ /**
+ * @deprecated Replaced by isCreatable(), isUpdatable(), isDeletable() as part of CRUDS
+ */
static public function is_writable($path){
return self::$defaultInstance->is_writable($path);
}
+ static public function isCreatable($path) {
+ return self::$defaultInstance->isCreatable($path);
+ }
+ static public function isReadable($path) {
+ return self::$defaultInstance->isReadable($path);
+ }
+ static public function isUpdatable($path) {
+ return self::$defaultInstance->isUpdatable($path);
+ }
+ static public function isDeletable($path) {
+ return self::$defaultInstance->isDeletable($path);
+ }
+ static public function isSharable($path) {
+ return self::$defaultInstance->isSharable($path);
+ }
static public function file_exists($path){
return self::$defaultInstance->file_exists($path);
}
diff --git a/lib/filesystemview.php b/lib/filesystemview.php
index faf3f0bd4cc..a488b4953d5 100644
--- a/lib/filesystemview.php
+++ b/lib/filesystemview.php
@@ -197,11 +197,32 @@ class OC_FilesystemView {
}
return false;
}
- public function is_readable($path) {
- return $this->basicOperation('is_readable', $path);
+ /**
+ * @deprecated Replaced by isReadable() as part of CRUDS
+ */
+ public function is_readable($path){
+ return $this->basicOperation('isReadable',$path);
+ }
+ /**
+ * @deprecated Replaced by isCreatable(), isUpdatable(), isDeletable() as part of CRUDS
+ */
+ public function is_writable($path){
+ return $this->basicOperation('isUpdatable',$path);
+ }
+ public function isCreatable($path) {
+ return $this->basicOperation('isCreatable', $path);
+ }
+ public function isReadable($path) {
+ return $this->basicOperation('isReadable', $path);
+ }
+ public function isUpdatable($path) {
+ return $this->basicOperation('isUpdatable', $path);
+ }
+ public function isDeletable($path) {
+ return $this->basicOperation('isDeletable', $path);
}
- public function is_writable($path) {
- return $this->basicOperation('is_writable', $path);
+ public function isSharable($path) {
+ return $this->basicOperation('isSharable', $path);
}
public function file_exists($path) {
if($path=='/'){
diff --git a/lib/group.php b/lib/group.php
index 7b137f0f8f1..a3bdbf9e003 100644
--- a/lib/group.php
+++ b/lib/group.php
@@ -237,10 +237,10 @@ class OC_Group {
*
* Returns a list with all groups
*/
- public static function getGroups(){
- $groups=array();
- foreach(self::$_usedBackends as $backend){
- $groups=array_merge($backend->getGroups(),$groups);
+ public static function getGroups($search = '', $limit = 10, $offset = 0) {
+ $groups = array();
+ foreach (self::$_usedBackends as $backend) {
+ $groups = array_merge($backend->getGroups($search, $limit, $offset), $groups);
}
asort($groups);
return $groups;
diff --git a/lib/group/backend.php b/lib/group/backend.php
index ebc078f152a..3f2909caa15 100644
--- a/lib/group/backend.php
+++ b/lib/group/backend.php
@@ -105,7 +105,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface {
*
* Returns a list with all groups
*/
- public function getGroups(){
+ public function getGroups($search = '', $limit = 10, $offset = 0) {
return array();
}
diff --git a/lib/group/database.php b/lib/group/database.php
index 2770ec185c4..6314a127438 100644
--- a/lib/group/database.php
+++ b/lib/group/database.php
@@ -164,15 +164,13 @@ class OC_Group_Database extends OC_Group_Backend {
*
* Returns a list with all groups
*/
- public function getGroups(){
- $query = OC_DB::prepare( "SELECT gid FROM `*PREFIX*groups`" );
- $result = $query->execute();
-
+ public function getGroups($search = '', $limit = 10, $offset = 0) {
+ $query = OC_DB::prepare('SELECT gid FROM *PREFIX*groups WHERE gid LIKE ? LIMIT '.$limit.' OFFSET '.$offset);
+ $result = $query->execute(array($search.'%'));
$groups = array();
- while( $row = $result->fetchRow()){
- $groups[] = $row["gid"];
+ while ($row = $result->fetchRow()) {
+ $groups[] = $row['gid'];
}
-
return $groups;
}
diff --git a/lib/group/interface.php b/lib/group/interface.php
index 7cca6061e10..6e492e72748 100644
--- a/lib/group/interface.php
+++ b/lib/group/interface.php
@@ -58,7 +58,7 @@ interface OC_Group_Interface {
*
* Returns a list with all groups
*/
- public function getGroups();
+ public function getGroups($search = '', $limit = 10, $offset = 0);
/**
* check if a group exists
diff --git a/lib/public/share.php b/lib/public/share.php
new file mode 100644
index 00000000000..3053da47e86
--- /dev/null
+++ b/lib/public/share.php
@@ -0,0 +1,844 @@
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+namespace OCP;
+
+\OC_Hook::connect('OC_User', 'post_deleteUser', 'OCP\Share', 'post_deleteUser');
+\OC_Hook::connect('OC_User', 'post_addToGroup', 'OCP\Share', 'post_addToGroup');
+\OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OCP\Share', 'post_removeFromGroup');
+
+/**
+* This class provides the ability for apps to share their content between users.
+* Apps must create a backend class that extends OCP\Share_Backend and register it with this class.
+*/
+class Share {
+
+ const SHARE_TYPE_USER = 0;
+ const SHARE_TYPE_GROUP = 1;
+ const SHARE_TYPE_PRIVATE_LINK = 3;
+
+ /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
+ * Construct permissions for share() and setPermissions with Or (|) e.g. Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
+ * Check if permission is granted with And (&) e.g. Check if delete is granted: if ($permissions & PERMISSION_DELETE)
+ * Remove permissions with And (&) and Not (~) e.g. Remove the update permission: $permissions &= ~PERMISSION_UPDATE
+ * Apps are required to handle permissions on their own, this class only stores and manages the permissions of shares
+ */
+ const PERMISSION_CREATE = 4;
+ const PERMISSION_READ = 1;
+ const PERMISSION_UPDATE = 2;
+ const PERMISSION_DELETE = 8;
+ const PERMISSION_SHARE = 16;
+
+ const FORMAT_NONE = -1;
+ const FORMAT_STATUSES = -2;
+
+ private static $shareTypeUserAndGroups = -1;
+ private static $shareTypeGroupUserUnique = 2;
+ private static $backends = array();
+ private static $backendTypes = array();
+
+ /**
+ * @brief Register a sharing backend class that extends OCP\Share_Backend for an item type
+ * @param string Item type
+ * @param string Backend class
+ * @param string (optional) Depends on item type
+ * @param array (optional) List of supported file extensions if this item type depends on files
+ * @return Returns true if backend is registered or false if error
+ */
+ public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
+ if (!isset(self::$backendTypes[$itemType])) {
+ self::$backendTypes[$itemType] = array('class' => $class, 'collectionOf' => $collectionOf, 'supportedFileExtensions' => $supportedFileExtensions);
+ return true;
+ }
+ \OC_Log::write('OCP\Share', 'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class'].' is already registered for '.$itemType, \OC_Log::WARN);
+ return false;
+ }
+
+ /**
+ * @brief Get the items of item type shared with the current user
+ * @param string Item type
+ * @param int Format (optional) Format type must be defined by the backend
+ * @param int Number of items to return (optional) Returns all by default
+ * @return Return depends on format
+ */
+ public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE, $parameters = null, $limit = -1) {
+ return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format, $parameters, $limit);
+ }
+
+ /**
+ * @brief Get the item of item type shared with the current user
+ * @param string Item type
+ * @param string Item target
+ * @param int Format (optional) Format type must be defined by the backend
+ * @return Return depends on format
+ */
+ public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE, $parameters = null) {
+ return self::getItems($itemType, $itemTarget, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format, $parameters, 1);
+ }
+
+ /**
+ * @brief Get the item of item type shared with the current user by source
+ * @param string Item type
+ * @param string Item source
+ * @param int Format (optional) Format type must be defined by the backend
+ * @return Return depends on format
+ */
+ public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE, $parameters = null) {
+ return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format, $parameters, 1, true);
+ }
+
+ /**
+ * @brief Get the shared items of item type owned by the current user
+ * @param string Item type
+ * @param int Format (optional) Format type must be defined by the backend
+ * @param int Number of items to return (optional) Returns all by default
+ * @return Return depends on format
+ */
+ public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null, $limit = -1) {
+ return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format, $parameters, $limit);
+ }
+
+ /**
+ * @brief Get the shared item of item type owned by the current user
+ * @param string Item type
+ * @param string Item
+ * @param int Format (optional) Format type must be defined by the backend
+ * @return Return depends on format
+ */
+ public static function getItemShared($itemType, $item, $format = self::FORMAT_NONE, $parameters = null) {
+ return self::getItems($itemType, $item, null, null, \OC_User::getUser(), $format, $parameters);
+ }
+
+ /**
+ * @brief Get the shared item of item type owned by the current user by source
+ * @param string Item type
+ * @param string Item source
+ * @param int Format (optional) Format type must be defined by the backend
+ * @return Return depends on format
+ */
+ public static function getItemSharedBySource($itemType, $item, $format = self::FORMAT_NONE, $parameters = null) {
+ return self::getItems($itemType, $item, null, null, \OC_User::getUser(), $format, $parameters, -1, true);
+ }
+
+ /**
+ * @brief Share an item with a user, group, or via private link
+ * @param string Item type
+ * @param string Item
+ * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_PRIVATE_LINK
+ * @param string User or group the item is being shared with
+ * @param int CRUDS permissions
+ * @return bool Returns true on success or false on failure
+ */
+ public static function share($itemType, $item, $shareType, $shareWith, $permissions) {
+ $uidOwner = \OC_User::getUser();
+ // Verify share type and sharing conditions are met
+ switch ($shareType) {
+ case self::SHARE_TYPE_USER:
+ if ($shareWith == $uidOwner) {
+ \OC_Log::write('OCP\Share', 'Sharing '.$item.' failed, because the user '.$shareWith.' is the item owner', \OC_Log::ERROR);
+ return false;
+ }
+ if (!\OC_User::userExists($shareWith)) {
+ \OC_Log::write('OCP\Share', 'Sharing '.$item.' failed, because the user '.$shareWith.' does not exist', \OC_Log::ERROR);
+ return false;
+ } else {
+ $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
+ if (empty($inGroup)) {
+ \OC_Log::write('OCP\Share', 'Sharing '.$item.' failed, because the user '.$shareWith.' is not a member of any groups that '.$uidOwner.' is a member of', \OC_Log::ERROR);
+ return false;
+ }
+ }
+ break;
+ case self::SHARE_TYPE_GROUP:
+ if (!\OC_Group::groupExists($shareWith)) {
+ \OC_Log::write('OCP\Share', 'Sharing '.$item.' failed, because the group '.$shareWith.' does not exist', \OC_Log::ERROR);
+ return false;
+ } else if (!\OC_Group::inGroup($uidOwner, $shareWith)) {
+ \OC_Log::write('OCP\Share', 'Sharing '.$item.' failed, because '.$uidOwner.' is not a member of the group '.$shareWith, \OC_Log::ERROR);
+ return false;
+ }
+ // Convert share with into an array with the keys group and users
+ $group = $shareWith;
+ $shareWith = array();
+ $shareWith['group'] = $group;
+ $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
+ break;
+ case self::SHARE_TYPE_PRIVATE_LINK:
+ $shareWith = md5(uniqid($item, true));
+ return self::put($itemType, $item, $shareType, $shareWith, $uidOwner, $permissions);
+ // Future share types need to include their own conditions
+ default:
+ \OC_Log::write('OCP\Share', 'Share type '.$shareType.' is not valid for '.$item, \OC_Log::ERROR);
+ return false;
+ }
+ if (self::getItems($itemType, $item, $shareType, $shareWith, $uidOwner, self::FORMAT_NONE, null, 1)) {
+ \OC_Log::write('OCP\Share', 'Sharing '.$item.' failed, because this item is already shared with '.$shareWith, \OC_Log::ERROR);
+ return false;
+ }
+ if ($collectionTypes = self::getCollectionItemTypes($itemType)) {
+ foreach ($collectionTypes as $collectionType) {
+ $collections = self::getItems($collectionType, null, self::SHARE_TYPE_USER, $shareWith, $uidOwner);
+ if ($backend = self::getBackend($collectionType)) {
+ if ($backend->inCollection($collections, $item)) {
+ \OC_Log::write('OCP\Share', 'Sharing '.$item.' failed, because this item is already shared with '.$shareWith.' inside a collection', \OC_Log::ERROR);
+ return false;
+ }
+ }
+ }
+ }
+ // If the item is a folder, scan through the folder looking for equivalent item types
+ if ($itemType == 'folder') {
+ $parentFolder = self::put('folder', $item, $shareType, $shareWith, $uidOwner, $permissions, true);
+ if ($parentFolder && $files = \OC_Files::getDirectoryContent($item)) {
+ for ($i = 0; $i < count($files); $i++) {
+ $name = substr($files[$i]['name'], strpos($files[$i]['name'], $item) - strlen($item));
+ if ($files[$i]['mimetype'] == 'httpd/unix-directory' && $children = \OC_Files::getDirectoryContent($name, '/')) {
+ // Continue scanning into child folders
+ array_push($files, $children);
+ } else {
+ // Pass on to put() to check if this item should be converted, the item won't be inserted into the database unless it can be converted
+ self::put('file', $name, $shareType, $shareWith, $uidOwner, $permissions, $parentFolder);
+ }
+ }
+ return $return;
+ }
+ return false;
+ } else {
+ // Put the item into the database
+ return self::put($itemType, $item, $shareType, $shareWith, $uidOwner, $permissions);
+ }
+ }
+
+ /**
+ * @brief Unshare an item from a user, group, or delete a private link
+ * @param string Item type
+ * @param string Item
+ * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_PRIVATE_LINK
+ * @param string User or group the item is being shared with
+ * @return Returns true on success or false on failure
+ */
+ public static function unshare($itemType, $item, $shareType, $shareWith) {
+ if ($item = self::getItems($itemType, $item, $shareType, $shareWith, \OC_User::getUser(), self::FORMAT_NONE, null, 1)) {
+ self::delete($item['id']);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @brief
+ * @param
+ * @param
+ * @return
+ */
+ public static function unshareFromSelf($itemType, $itemTarget) {
+ $uidSharedWith = \OC_User::getUser();
+ if ($item = self::getItems($itemType, $itemTarget, $uidSharedWith, true, null, false, 1)) {
+ // Check if item is inside a shared folder and was converted
+ if ($item['parent']) {
+ $query = \OC_DB::prepare('SELECT item_type FROM *PREFIX*share WHERE id = ? LIMIT 1');
+ $result = $query->execute(array($item['parent']))->fetchRow();
+ if (isset($result['item_type']) && $result['item_type'] == 'folder') {
+ return false;
+ }
+ }
+ // Check if this is a group share, if it is a group share a new entry needs to be created marked as unshared from self
+ if ($item['uid_shared_with'] == null) {
+ $query = \OC_DB::prepare('INSERT INTO *PREFIX*share VALUES(?,?,?,?,?,?,?,?,?,?)');
+ $result = $query->execute(array($item['item_type'], $item['item_source'], $item['item_target'], $uidSharedWith, $item['gid_shared_with'], $item['uid_owner'], self::UNSHARED_FROM_SELF, $item['stime'], $item['file_source'], $item['file_target']));
+ if (\OC_DB::isError($result)) {
+// \OC_Log::write('OCP\Share', 'Share type '.$shareType.' is not valid for item '.$item, \OC_Log::ERROR);
+ return false;
+ }
+ }
+ return self::delete($item['id'], true);
+ }
+ return false;
+ }
+
+ /**
+ * @brief Set the target name of the item for the current user
+ * @param string Item type
+ * @param string Old item name
+ * @param string New item name
+ * @return Returns true on success or false on failure
+ */
+ public static function setTarget($itemType, $oldTarget, $newTarget) {
+ if ($backend = self::getBackend($itemType)) {
+ $uidSharedWith = \OC_User::getUser();
+ // TODO Check permissions for setting target?
+ if ($item = self::getItems($itemType, $oldTarget, self::SHARE_TYPE_USER, $uidSharedWith, null, self::FORMAT_NONE, 1)) {
+ // Check if this is a group share
+ if ($item['uid_shared_with'] == null) {
+ // A new entry needs to be created exclusively for the user
+ $query = \OC_DB::prepare('INSERT INTO *PREFIX*share VALUES(?,?,?,?,?,?,?,?,?,?)');
+ if (isset($item['file_target'])) {
+ $fileTarget = $newTarget;
+ } else {
+ $fileTarget = null;
+ }
+ $query->execute(array($itemType, $item['item_source'], $newTarget, $uidSharedWith, $item['gid_shared_with'], $item['uid_owner'], $item['permissions'], $item['stime'], $item['file_source'], $fileTarget));
+ return true;
+ } else {
+ // Check if this item is a file or folder, update the file_target as well if this is the case
+ if ($itemType == 'file' || $itemType == 'folder') {
+ $query = \OC_DB::prepare('UPDATE *PREFIX*share SET item_target = ?, file_target = REPLACE(file_target, ?, ?) WHERE uid_shared_with = ?');
+ $query->execute(array($newTarget, $oldTarget, $newTarget, $uidSharedWith));
+ } else {
+ $query = \OC_DB::prepare('UPDATE *PREFIX*share SET item_target = ? WHERE item_type = ? AND item_target = ? AND uid_shared_with = ?');
+ $query->execute(array($newTarget, $itemType, $oldTarget, $uidSharedWith));
+ }
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @brief Set the permissions of an item for a specific user or group
+ * @param string Item type
+ * @param string Item
+ * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_PRIVATE_LINK
+ * @param string User or group the item is being shared with
+ * @param int CRUDS permissions
+ * @return Returns true on success or false on failure
+ */
+ public static function setPermissions($itemType, $item, $shareType, $shareWith, $permissions) {
+ if ($item = self::getItems($itemType, $item, $shareType, $shareWith, \OC_User::getUser(), self::FORMAT_NONE, null, 1)) {
+ // Check if this item is a reshare and verify that the permissions granted don't exceed the parent shared item
+ if (isset($item['parent'])) {
+ $query = \OC_DB::prepare('SELECT permissions FROM *PREFIX*share WHERE id = ? LIMIT 1');
+ $result = $query->execute(array($item['parent']))->fetchRow();
+ if (~(int)$result['permissions'] & $permissions) {
+ \OC_Log::write('OCP\Share', 'Setting permissions for '.$item.' failed, because the permissions exceed permissions granted to the parent item', \OC_Log::ERROR);
+ return false;
+ }
+ }
+ $query = \OC_DB::prepare('UPDATE *PREFIX*share SET permissions = ? WHERE id = ?');
+ $query->execute(array($permissions, $item['id']));
+ // Check if permissions were removed
+ if ($item['permissions'] & ~$permissions) {
+ // If share permission is removed all reshares must be deleted
+ if (($item['permissions'] & self::PERMISSION_SHARE) && (~$permissions & self::PERMISSION_SHARE)) {
+ self::delete($item['id'], true);
+ } else {
+ $ids = array();
+ $parents = array($item['id']);
+ while (!empty($parents)) {
+ $parents = "'".implode("','", $parents)."'";
+ $query = \OC_DB::prepare('SELECT id, permissions FROM *PREFIX*share WHERE parent IN ('.$parents.')');
+ $result = $query->execute();
+ // Reset parents array, only go through loop again if items are found that need permissions removed
+ $parents = array();
+ while ($item = $result->fetchRow()) {
+ // Check if permissions need to be removed
+ if ($item['permissions'] & ~$permissions) {
+ // Add to list of items that need permissions removed
+ $ids[] = $item['id'];
+ $parents[] = $item['id'];
+ }
+ }
+ }
+ // Remove the permissions for all reshares of this item
+ if (!empty($ids)) {
+ $ids = "'".implode("','", $ids)."'";
+ $query = \OC_DB::prepare('UPDATE *PREFIX*share SET permissions = permissions & ? WHERE id IN ('.$ids.')');
+ $query->execute(array($permissions));
+ }
+ }
+ }
+ return true;
+ }
+ \OC_Log::write('OCP\Share', 'Setting permissions for '.$item.' failed, because the item was not found', \OC_Log::ERROR);
+ return false;
+ }
+
+ /**
+ * @brief Get the backend class for the specified item type
+ * @param string Item type
+ * @return Sharing backend object
+ */
+ private static function getBackend($itemType) {
+ if (isset(self::$backends[$itemType])) {
+ return self::$backends[$itemType];
+ } else if (isset(self::$backendTypes[$itemType]['class'])) {
+ $class = self::$backendTypes[$itemType]['class'];
+ if (class_exists($class)) {
+ self::$backends[$itemType] = new $class;
+ if (!is_subclass_of(self::$backends[$itemType], 'OCP\Share_Backend')) {
+ \OC_Log::write('OCP\Share', 'Sharing backend '.$class.' must extend abstract class OC_Share_Backend', \OC_Log::ERROR);
+ return false;
+ }
+ return self::$backends[$itemType];
+ } else {
+ \OC_Log::write('OCP\Share', 'Sharing backend '.$class.' not found', \OC_Log::ERROR);
+ return false;
+ }
+ }
+ \OC_Log::write('OCP\Share', 'Sharing backend for '.$itemType.' not found', \OC_Log::ERROR);
+ return false;
+ }
+
+ /**
+ * @brief Get a list of collection item types for the specified item type
+ * @param string Item type
+ * @return array
+ */
+ private static function getCollectionItemTypes($itemType) {
+ $collectionTypes = array($itemType);
+ foreach (self::$backendTypes as $type => $backend) {
+ if (in_array($backend['collectionOf'], $collectionTypes)) {
+ $collectionTypes[] = $type;
+ }
+ }
+ if (count($collectionTypes) > 1) {
+ unset($collectionTypes[0]);
+ return $collectionTypes;
+ }
+ return false;
+ }
+
+ /**
+ * @brief Get shared items from the database
+ * @param string Item type
+ * @param string Item or item target (optional)
+ * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_PRIVATE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
+ * @param string User or group the item is being shared with
+ * @param string User that is the owner of shared items (optional)
+ * @param int Format to convert items to with formatItems()
+ * @param mixed Parameters to pass to formatItems()
+ * @param int Number of items to return, -1 to return all matches (optional)
+ * @param bool Is item the source (optional)
+ * @return mixed
+ *
+ * See public functions getItem(s)... for parameter usage
+ *
+ */
+ private static function getItems($itemType, $item = null, $shareType = null, $shareWith = null, $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $isSource = false) {
+ if ($backend = self::getBackend($itemType)) {
+ // Check if there are any parent types that include this type of items, e.g. a music album contains songs
+ if ($collectionTypes = self::getCollectionItemTypes($itemType)) {
+ $collectionTypes = array_merge(array($itemType), $collectionTypes);
+ $where = "WHERE item_type IN ('".implode("','", $collectionTypes)."')";
+ } else {
+ $where = "WHERE item_type = '".$itemType."'";
+ }
+ if (isset($shareType) && isset($shareWith)) {
+ // Include all user and group items
+ if ($shareType == self::$shareTypeUserAndGroups) {
+ $where .= " AND share_type IN (".self::SHARE_TYPE_USER.",".self::SHARE_TYPE_GROUP.",".self::$shareTypeGroupUserUnique.")";
+ $groups = \OC_Group::getUserGroups($shareWith);
+ $userAndGroups = array_merge(array($shareWith), $groups);
+ $where .= " AND share_with IN ('".implode("','", $userAndGroups)."')";
+ } else {
+ $where .= " AND share_type = ".$shareType." AND share_with = '".$shareWith."'";
+ }
+ }
+ if (isset($uidOwner)) {
+ $where .= " AND uid_owner = '".$uidOwner."'";
+ if (!isset($shareType)) {
+ // Prevent unique user targets for group shares from being selected
+ $where .= " AND share_type != '".self::$shareTypeGroupUserUnique."'";
+ }
+ }
+ if (isset($item)) {
+ // If looking for own shared items, check item_source else check item_target
+ if (isset($uidOwner)) {
+ $source = $backend->getSource($item, $uidOwner);
+ // If item type is a file, file source needs to be checked in case the item was converted
+ if ($itemType == 'file' || $itemType == 'folder') {
+ $where .= " AND file_source = ".\OC_FileCache::getId($source['file']);
+ } else {
+ // Check if this item depends on a file and getSource() returned an array
+ if (is_array($source)) {
+ $itemSource = $source['item'];
+ } else {
+ $itemSource = $source;
+ }
+ $where .= " AND item_source = '".$itemSource."'";
+ }
+ } else {
+ if ($isSource) {
+ if ($itemType == 'file' || $itemType == 'folder') {
+ $where .= " AND file_source = '".$item."'";
+ } else {
+ $where .= " AND item_source = '".$item."'";
+ }
+ } else {
+ if ($itemType == 'file' || $itemType == 'folder') {
+ $where .= " AND file_target = '".$item."'";
+ } else {
+ $where .= " AND item_target = '".$item."'";
+ }
+ }
+ }
+ } else if ($itemType == 'file') {
+ // TODO Exclude converted items inside shared folders
+ }
+ if ($limit != -1) {
+ if ($limit == 1 && $shareType == self::$shareTypeUserAndGroups) {
+ // Make sure the unique user target is returned if it exists, unique targets should follow the group share in the database
+ // If the limit is not 1, the filtering can be done later
+ $where .= ' ORDER BY id DESC';
+ }
+ $where .= ' LIMIT '.$limit;
+ }
+ if ($format == self::FORMAT_STATUSES) {
+ $select = 'id, item_type, item, item_source, share_type';
+ } else {
+ if (isset($uidOwner)) {
+ $select = 'id, item_type, item, item_source, parent, share_type, share_with, permissions, stime, file_source';
+ } else {
+ $select = '*';
+ }
+ }
+ $query = \OC_DB::prepare('SELECT '.$select.' FROM *PREFIX*share '.$where);
+ $result = $query->execute();
+ $items = array();
+ while ($item = $result->fetchRow()) {
+ // Return only the item instead of a 2-dimensional array
+ if ($limit == 1 && $format == self::FORMAT_NONE) {
+ return $item;
+ }
+ // Filter out duplicate group shares for users with unique targets
+ if ($item['share_type'] == self::$shareTypeGroupUserUnique) {
+ // Remove the parent group share
+ unset($items[$item['parent']]);
+ }
+ $items[$item['id']] = $item;
+ // TODO Add in parent item types children?
+ if ($collectionTypes && in_array($item['item_type'], $collectionTypes)) {
+ $children[] = $item;
+ }
+ }
+ if (!empty($items)) {
+ if ($format == self::FORMAT_NONE) {
+ return $items;
+ } else if ($format == self::FORMAT_STATUSES) {
+ $statuses = array();
+ foreach ($items as $item) {
+ if ($item['share_type'] == self::SHARE_TYPE_PRIVATE_LINK) {
+ $statuses[$item['item']] = true;
+ } else if (!isset($statuses[$item['item']])) {
+ $statuses[$item['item']] = false;
+ }
+ }
+ return $statuses;
+ } else {
+ return $backend->formatItems($items, $format, $parameters);
+ }
+ } else if ($limit == 1 || (isset($uidOwner) && isset($item))) {
+ return false;
+ }
+ }
+ return array();
+ }
+
+ /**
+ * @brief Put shared item into the database
+ * @param string Item type
+ * @param string Item
+ * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_PRIVATE_LINK
+ * @param string User or group the item is being shared with
+ * @param int CRUDS permissions
+ * @param bool|array Parent folder target (optional)
+ * @return bool Returns true on success or false on failure
+ */
+ private static function put($itemType, $item, $shareType, $shareWith, $uidOwner, $permissions, $parentFolder = null) {
+ // Check file extension for an equivalent item type to convert to
+ if ($itemType == 'file') {
+ $extension = strtolower(substr($item, strrpos($item, '.') + 1));
+ foreach (self::$backends as $type => $backend) {
+ if (isset($backend->dependsOn) && $backend->dependsOn == 'file' && isset($backend->supportedFileExtensions) && in_array($extension, $backend->supportedFileExtensions)) {
+ $itemType = $type;
+ break;
+ }
+ }
+ // Exit if this is being called for a file inside a folder, and no equivalent item type is found
+ if (isset($parentFolder) && $itemType == 'file') {
+ return false;
+ }
+ }
+ if ($backend = self::getBackend($itemType)) {
+ // Check if this is a reshare
+ if ($checkReshare = self::getItemSharedWith($itemType, $item)) {
+ if ($checkReshare['permissions'] & self::PERMISSION_SHARE) {
+ // TODO Don't check if inside folder
+ $parent = $checkReshare['id'];
+ $itemSource = $checkReshare['item_source'];
+ $fileSource = $checkReshare['file_source'];
+ $fileTarget = $checkReshare['file_target'];
+ } else {
+ \OC_Log::write('OCP\Share', 'Sharing '.$item.' failed, because resharing is not allowed', \OC_Log::ERROR);
+ return false;
+ }
+ } else {
+ $parent = null;
+ $source = $backend->getSource($item, $uidOwner);
+ if (!$source) {
+ \OC_Log::write('OCP\Share', 'Sharing '.$item.' failed, because the sharing backend for '.$itemType.' could not find its source', \OC_Log::ERROR);
+ return false;
+ } else if (is_array($source)) {
+ $itemSource = $source['item'];
+ $fileSource = \OC_FileCache::getId($source['file']);
+ if ($fileSource == -1) {
+ \OC_Log::write('OCP\Share', 'Sharing '.$item.' failed, because the file could not be found in the file cache', \OC_Log::ERROR);
+ return false;
+ }
+ } else {
+ $itemSource = $source;
+ $fileSource = null;
+ }
+ }
+ $query = \OC_DB::prepare('INSERT INTO *PREFIX*share (item_type, item, item_source, item_target, parent, share_type, share_with, uid_owner, permissions, stime, file_source, file_target) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
+ // Share with a group
+ if ($shareType == self::SHARE_TYPE_GROUP) {
+ if (isset($fileSource)) {
+ if ($parentFolder) {
+ if ($parentFolder === true) {
+ $groupFileTarget = self::getBackend('file')->generateTarget($source['file'], false);
+ // Set group default file target for future use
+ $parentFolders[0]['folder'] = $groupFileTarget;
+ } else {
+ // Get group default file target
+ $groupFileTarget = $parentFolder[0]['folder'].$item;
+ $parent = $parentFolder[0]['id'];
+ unset($parentFolder[0]);
+ // Only loop through users we know have different file target paths
+ $uidSharedWith = array_keys($parentFolder);
+ }
+ } else {
+ $groupFileTarget = self::getBackend('file')->generateTarget($source['file'], false);
+ }
+ } else {
+ $groupFileTarget = null;
+ }
+ $groupItemTarget = $backend->generateTarget($item, false);
+ $query->execute(array($itemType, $item, $itemSource, $groupItemTarget, $parent, $shareType, $shareWith['group'], $uidOwner, $permissions, time(), $fileSource, $groupFileTarget));
+ // Save this id, any extra rows for this group share will need to reference it
+ $parent = \OC_DB::insertid('*PREFIX*share');
+ // Loop through all users of this group in case we need to add an extra row
+ foreach ($shareWith['users'] as $uid) {
+ $itemTarget = $backend->generateTarget($item, $uid);
+ if (isset($fileSource)) {
+ if ($parentFolder) {
+ if ($parentFolder === true) {
+ $fileTarget = self::getBackend('file')->generateTarget($source['file'], $uid);
+ if ($fileTarget != $groupFileTarget) {
+ $parentFolders[$uid]['folder'] = $fileTarget;
+ }
+ } else if (isset($parentFolder[$uid])) {
+ $fileTarget = $parentFolder[$uid]['folder'].$item;
+ $parent = $parentFolder[$uid]['id'];
+ }
+ } else {
+ $fileTarget = self::getBackend('file')->generateTarget($source['file'], $uid);
+ }
+ } else {
+ $fileTarget = null;
+ }
+ // Insert an extra row for the group share if the item or file target is unique for this user
+ if ($itemTarget != $groupItemTarget || (isset($fileSource) && $fileTarget != $groupFileTarget)) {
+ $query->execute(array($itemType, $item, $itemSource, $itemTarget, $parent, self::$shareTypeGroupUserUnique, $uid, $uidOwner, $permissions, time(), $fileSource, $fileTarget));
+ $id = \OC_DB::insertid('*PREFIX*share');
+ }
+ if ($parentFolder === true) {
+ $parentFolders['id'] = $id;
+ }
+ }
+ if ($parentFolder === true) {
+ // Return parent folders to preserve file target paths for potential children
+ return $parentFolders;
+ }
+ } else {
+ if ($shareType == self::SHARE_TYPE_PRIVATE_LINK) {
+ $itemTarget = null;
+ } else {
+ $itemTarget = $backend->generateTarget($item, $shareWith);
+ }
+ if (isset($fileSource)) {
+ if ($parentFolder) {
+ if ($parentFolder === true) {
+ $fileTarget = self::getBackend('file')->generateTarget($source['file'], $shareWith);
+ $parentFolders['folder'] = $fileTarget;
+ } else {
+ $fileTarget = $parentFolder['folder'].$item;
+ $parent = $parentFolder['id'];
+ }
+ } else {
+ if ($shareType == self::SHARE_TYPE_PRIVATE_LINK) {
+ $fileTarget = basename($source['file']);
+ } else {
+ $fileTarget = self::getBackend('file')->generateTarget($source['file'], $shareWith);
+ }
+ }
+ } else {
+ $fileTarget = null;
+ }
+ $query->execute(array($itemType, $item, $itemSource, $itemTarget, $parent, $shareType, $shareWith, $uidOwner, $permissions, time(), $fileSource, $fileTarget));
+ $id = \OC_DB::insertid('*PREFIX*share');
+ if ($parentFolder === true) {
+ $parentFolders['id'] = $id;
+ // Return parent folder to preserve file target paths for potential children
+ return $parentFolders;
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @brief Delete all reshares of an item
+ * @param int Id of item to delete
+ * @param bool If true, exclude the parent from the delete (optional)
+ * @param string The user that the parent was shared with (optinal)
+ */
+ private static function delete($parent, $excludeParent = false, $uidOwner = null) {
+ $ids = array($parent);
+ $parents = array($parent);
+ while (!empty($parents)) {
+ $parents = "'".implode("','", $parents)."'";
+ // Check the owner on the first search of reshares, useful for finding and deleting the reshares by a single user of a group share
+ if (count($ids) == 1 && isset($uidOwner)) {
+ $query = \OC_DB::prepare('SELECT id FROM *PREFIX*share WHERE parent IN ('.$parents.') AND uid_owner = ?');
+ $result = $query->execute(array($uidOwner));
+ } else {
+ $query = \OC_DB::prepare('SELECT id FROM *PREFIX*share WHERE parent IN ('.$parents.')');
+ $result = $query->execute();
+ }
+ // Reset parents array, only go through loop again if items are found
+ $parents = array();
+ while ($item = $result->fetchRow()) {
+ $ids[] = $item['id'];
+ $parents[] = $item['id'];
+ }
+ }
+ if ($excludeParent) {
+ unset($ids[0]);
+ }
+ if (!empty($ids)) {
+ $ids = "'".implode("','", $ids)."'";
+ $query = \OC_DB::prepare('DELETE FROM *PREFIX*share WHERE id IN ('.$ids.')');
+ $query->execute();
+ }
+ }
+
+ /**
+ * Hook Listeners
+ */
+
+ public static function post_deleteUser($arguments) {
+ // Delete any items shared with the deleted user
+ $query = \OC_DB::prepare('DELETE FROM *PREFIX*share WHERE share_with = ?');
+ $result = $query->execute(array($arguments['uid']));
+ // Delete any items the deleted user shared
+ $query = \OC_DB::prepare('SELECT id FROM *PREFIX*share WHERE uid_owner = ?');
+ $result = $query->execute(array($arguments['uid']));
+ while ($item = $result->fetchRow()) {
+ self::delete($item['id']);
+ }
+ }
+
+ public static function post_addToGroup($arguments) {
+ // TODO
+ }
+
+ public static function post_removeFromGroup($arguments) {
+ $query = \OC_DB::prepare('SELECT id, share_type FROM *PREFIX*share WHERE (share_type = ? AND share_with = ?) OR (share_type = ? AND share_with = ?)');
+ $result = $query->execute(array(self::SHARE_TYPE_GROUP, $arguments['gid'], self::$shareTypeGroupUserUnique, $arguments['uid']));
+ while ($item = $result->fetchRow()) {
+ if ($item['share_type'] == self::SHARE_TYPE_GROUP) {
+ // Delete all reshares by this user of the group share
+ self::delete($item['id'], true, $arguments['uid']);
+ } else {
+ self::delete($item['id']);
+ }
+ }
+ }
+
+}
+
+/**
+* Abstract backend class that apps must extend to share content.
+*/
+abstract class Share_Backend {
+
+ public $dependsOn;
+ public $supportedFileExtensions = array();
+
+ /**
+ * @brief Get the source of the item to be stored in the database
+ * @param string Item
+ * @param string Owner of the item
+ * @return mixed|array|false Source
+ *
+ * Return an array if the item is file dependent, the array needs two keys: 'item' and 'file'
+ * Return false if the item does not exist for the user
+ *
+ * The formatItems() function will translate the source returned back into the item
+ */
+ public abstract function getSource($item, $uid);
+
+
+
+ /**
+ * @brief Get a unique name of the item for the specified user
+ * @param string Item
+ * @param string|false User the item is being shared with
+ * @param array|null List of similar item names already existing as shared items
+ * @return string Target name
+ *
+ * This function needs to verify that the user does not already have an item with this name.
+ * If it does generate a new name e.g. name_#
+ */
+ public abstract function generateTarget($item, $uid, $exclude = null);
+
+
+
+ /**
+ * @brief Converts the shared item sources back into the item in the specified format
+ * @param array Shared items
+ * @param int Format
+ * @return ?
+ *
+ * The items array is a 3-dimensional array with the item_source as the first key and the share id as the second key to an array with the share info.
+ * The key/value pairs included in the share info depend on the function originally called:
+ * If called by getItem(s)Shared: id, item_type, item, item_source, share_type, share_with, permissions, stime, file_source
+ * If called by getItem(s)SharedWith: id, item_type, item, item_source, item_target, share_type, share_with, permissions, stime, file_source, file_target
+ * This function allows the backend to control the output of shared items with custom formats.
+ * It is only called through calls to the public getItem(s)Shared(With) functions.
+ */
+ public abstract function formatItems($items, $format, $parameters = null);
+
+
+}
+
+abstract class Share_Backend_Collection extends Share_Backend {
+
+ public abstract function inCollection($collections, $item);
+
+ public abstract function getChildren($item);
+
+}
+
+?>
diff --git a/lib/public/user.php b/lib/public/user.php
index 713e366b968..178d1dddd36 100644
--- a/lib/public/user.php
+++ b/lib/public/user.php
@@ -51,7 +51,7 @@ class User {
*
* Get a list of all users.
*/
- public static function getUsers(){
+ public static function getUsers($search = '', $limit = 10, $offset = 0) {
return \OC_USER::getUsers();
}
diff --git a/lib/user.php b/lib/user.php
index 49a0a2a10ce..95177bc77de 100644
--- a/lib/user.php
+++ b/lib/user.php
@@ -338,12 +338,12 @@ class OC_User {
*
* Get a list of all users.
*/
- public static function getUsers(){
- $users=array();
- foreach(self::$_usedBackends as $backend){
- $backendUsers=$backend->getUsers();
- if(is_array($backendUsers)){
- $users=array_merge($users,$backendUsers);
+ public static function getUsers($search = '', $limit = 10, $offset = 0) {
+ $users = array();
+ foreach (self::$_usedBackends as $backend) {
+ $backendUsers = $backend->getUsers($search, $limit, $offset);
+ if (is_array($backendUsers)) {
+ $users = array_merge($users, $backendUsers);
}
}
asort($users);
diff --git a/lib/user/backend.php b/lib/user/backend.php
index daa942d261c..ff00ef08f6c 100644
--- a/lib/user/backend.php
+++ b/lib/user/backend.php
@@ -97,7 +97,7 @@ abstract class OC_User_Backend implements OC_User_Interface {
*
* Get a list of all users.
*/
- public function getUsers(){
+ public function getUsers($search = '', $limit = 10, $offset = 0) {
return array();
}
diff --git a/lib/user/database.php b/lib/user/database.php
index cc27b3ddbfd..968814d9d57 100644
--- a/lib/user/database.php
+++ b/lib/user/database.php
@@ -154,13 +154,12 @@ class OC_User_Database extends OC_User_Backend {
*
* Get a list of all users.
*/
- public function getUsers(){
- $query = OC_DB::prepare( "SELECT uid FROM *PREFIX*users" );
- $result = $query->execute();
-
- $users=array();
- while( $row = $result->fetchRow()){
- $users[] = $row["uid"];
+ public function getUsers($search = '', $limit = 10, $offset = 0) {
+ $query = OC_DB::prepare('SELECT uid FROM *PREFIX*users WHERE uid LIKE ? LIMIT '.$limit.' OFFSET '.$offset);
+ $result = $query->execute(array($search.'%'));
+ $users = array();
+ while ($row = $result->fetchRow()) {
+ $users[] = $row['uid'];
}
return $users;
}
diff --git a/lib/user/interface.php b/lib/user/interface.php
index dc3685dc20d..b3286cd2f9e 100644
--- a/lib/user/interface.php
+++ b/lib/user/interface.php
@@ -48,7 +48,7 @@ interface OC_User_Interface {
*
* Get a list of all users.
*/
- public function getUsers();
+ public function getUsers($search = '', $limit = 10, $offset = 0);
/**
* @brief check if a user exists
diff --git a/tests/lib/share/backend.php b/tests/lib/share/backend.php
new file mode 100644
index 00000000000..4f2fcce235e
--- /dev/null
+++ b/tests/lib/share/backend.php
@@ -0,0 +1,66 @@
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+abstract class Test_Share_Backend extends UnitTestCase {
+
+ protected $userBackend;
+ protected $user1;
+ protected $user2;
+ protected $groupBackend;
+ protected $group;
+ protected $itemType;
+ protected $item;
+
+ public function setUp() {
+ OC_User::clearBackends();
+ OC_User::useBackend('dummy');
+ $this->user1 = uniqid('user_');
+ $this->user2 = uniqid('user_');
+ OC_User::createUser($this->user1, 'pass1');
+ OC_User::createUser($this->user2, 'pass2');
+ OC_Group::clearBackends();
+ OC_Group::useBackend(new OC_Group_Dummy);
+ $this->group = uniqid('group_');
+ OC_Group::createGroup($this->group);
+ }
+
+ public function testShareWithUserNonExistentItem() {
+ $this->assertFalse(OCP\Share::share($this->itemType, uniqid('foobar_'), OCP\Share::SHARETYPE_USER, $this->user2, OCP\Share::PERMISSION_READ));
+ }
+
+ public function testShareWithUserItem() {
+ $this->assertTrue(OCP\Share::share($this->itemType, $this->item, OCP\Share::SHARETYPE_USER, $this->user2, OCP\Share::PERMISSION_READ));
+ }
+
+ public function testShareWithGroupNonExistentItem() {
+ $this->assertFalse(OCP\Share::share($this->itemType, uniqid('foobar_'), OCP\Share::SHARETYPE_GROUP, $this->group, OCP\Share::PERMISSION_READ));
+ }
+
+ public function testShareWithGroupItem() {
+ $this->assertTrue(OCP\Share::share($this->itemType, $this->item, OCP\Share::SHARETYPE_GROUP, $this->group, OCP\Share::PERMISSION_READ));
+ }
+
+ public function testShareWithUserAlreadySharedWith() {
+ $this->assertTrue(OCP\Share::share($this->itemType, $this->item, OCP\Share::SHARETYPE_USER, $this->user2, OCP\Share::PERMISSION_READ));
+ $this->assertFalse(OCP\Share::share($this->itemType, $this->item, OCP\Share::SHARETYPE_USER, $this->user2, OCP\Share::PERMISSION_READ));
+ }
+
+}
diff --git a/tests/lib/share/share.php b/tests/lib/share/share.php
new file mode 100644
index 00000000000..eca2c9bc58a
--- /dev/null
+++ b/tests/lib/share/share.php
@@ -0,0 +1,161 @@
+<?php
+/**
+* ownCloud
+*
+* @author Michael Gapczynski
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*/
+
+class Test_Share_Base extends UnitTestCase {
+
+ protected $itemType;
+ protected $userBackend;
+ protected $user1;
+ protected $user2;
+ protected $groupBackend;
+ protected $group1;
+ protected $group2;
+
+
+ public function setUp() {
+ OC_User::clearBackends();
+ OC_User::useBackend('dummy');
+ $this->user1 = uniqid('user_');
+ $this->user2 = uniqid('user_');
+ OC_User::createUser($this->user1, 'pass1');
+ OC_User::createUser($this->user2, 'pass2');
+ OC_Group::clearBackends();
+ OC_Group::useBackend(new OC_Group_Dummy);
+ $this->group1 = uniqid('group_');
+ $this->group2 = uniqid('group_');
+ OC_Group::createGroup($this->group1);
+ OC_Group::createGroup($this->group2);
+ }
+
+ public function testShareInvalidShareType() {
+ $this->assertFalse(OCP\Share::share('file', 'test.txt', 'foobar', $this->user1, OCP\Share::PERMISSION_READ));
+ }
+
+ public function testShareInvalidItemType() {
+ $this->assertFalse(OCP\Share::share('foobar', 'test.txt', OCP\Share::SHARETYPE_USER, $this->user1, OCP\Share::PERMISSION_READ));
+ }
+
+ public function testShareWithSelf() {
+ OC_User::setUserId($this->user1);
+ $this->assertFalse(OCP\Share::share('file', 'test.txt', OCP\Share::SHARETYPE_USER, $this->user1, OCP\Share::PERMISSION_READ));
+ }
+
+ public function testShareWithNonExistentUser() {
+ $this->assertFalse(OCP\Share::share('file', 'test.txt', OCP\Share::SHARETYPE_USER, 'foobar', OCP\Share::PERMISSION_READ));
+ }
+
+ public function testShareWithUserOwnerNotPartOfGroup() {
+
+ }
+
+ public function testShareWithUserAlreadySharedWith() {
+
+ }
+
+ public function testShareWithNonExistentGroup() {
+ $this->assertFalse(OCP\Share::share('file', 'test.txt', OCP\Share::SHARETYPE_GROUP, 'foobar', OCP\Share::PERMISSION_READ));
+ }
+
+ public function testShareWithGroupOwnerNotPartOfGroup() {
+
+ }
+
+
+ public function testShareWithGroupItem() {
+
+ }
+
+ public function testUnshareInvalidShareType() {
+
+ }
+
+ public function testUnshareNonExistentItem() {
+
+ }
+
+ public function testUnshareFromUserItem() {
+
+ }
+
+ public function testUnshareFromGroupItem() {
+
+ }
+
+
+
+
+
+ // Test owner not in same group (false)
+
+
+
+ // Test non-existant item type
+
+ // Test valid item
+
+ // Test existing shared item (false)
+
+ // Test unsharing item
+
+ // Test setting permissions
+
+ // Test setting permissions not as owner (false)
+
+ // Test setting target
+
+ // Test setting target as owner (false)
+
+ // Spam reshares
+
+
+
+ // Test non-existant group
+
+
+ // Test owner not part of group
+
+ // Test existing shared item with group
+
+ // Test valid item, valid name for all users
+
+ // Test unsharing item
+
+ // Test item with name conflicts
+
+ // Test unsharing item
+
+ // Test setting permissions
+
+ // Test setting target no name conflicts
+
+ // Test setting target with conflicts
+
+ // Spam reshares
+
+
+
+
+
+ public function testPrivateLink() {
+
+ }
+
+}