@@ -35,159 +35,159 @@ |
||
35 | 35 | */ |
36 | 36 | class Update { |
37 | 37 | |
38 | - /** @var \OC\Files\View */ |
|
39 | - protected $view; |
|
40 | - |
|
41 | - /** @var \OC\Encryption\Util */ |
|
42 | - protected $util; |
|
43 | - |
|
44 | - /** @var \OC\Files\Mount\Manager */ |
|
45 | - protected $mountManager; |
|
46 | - |
|
47 | - /** @var \OC\Encryption\Manager */ |
|
48 | - protected $encryptionManager; |
|
49 | - |
|
50 | - /** @var string */ |
|
51 | - protected $uid; |
|
52 | - |
|
53 | - /** @var \OC\Encryption\File */ |
|
54 | - protected $file; |
|
55 | - |
|
56 | - /** |
|
57 | - * |
|
58 | - * @param \OC\Files\View $view |
|
59 | - * @param \OC\Encryption\Util $util |
|
60 | - * @param \OC\Files\Mount\Manager $mountManager |
|
61 | - * @param \OC\Encryption\Manager $encryptionManager |
|
62 | - * @param \OC\Encryption\File $file |
|
63 | - * @param string $uid |
|
64 | - */ |
|
65 | - public function __construct( |
|
66 | - View $view, |
|
67 | - Util $util, |
|
68 | - Mount\Manager $mountManager, |
|
69 | - Manager $encryptionManager, |
|
70 | - File $file, |
|
71 | - $uid |
|
72 | - ) { |
|
73 | - $this->view = $view; |
|
74 | - $this->util = $util; |
|
75 | - $this->mountManager = $mountManager; |
|
76 | - $this->encryptionManager = $encryptionManager; |
|
77 | - $this->file = $file; |
|
78 | - $this->uid = $uid; |
|
79 | - } |
|
80 | - |
|
81 | - /** |
|
82 | - * hook after file was shared |
|
83 | - * |
|
84 | - * @param array $params |
|
85 | - */ |
|
86 | - public function postShared($params) { |
|
87 | - if ($this->encryptionManager->isEnabled()) { |
|
88 | - if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') { |
|
89 | - $path = Filesystem::getPath($params['fileSource']); |
|
90 | - [$owner, $ownerPath] = $this->getOwnerPath($path); |
|
91 | - $absPath = '/' . $owner . '/files/' . $ownerPath; |
|
92 | - $this->update($absPath); |
|
93 | - } |
|
94 | - } |
|
95 | - } |
|
96 | - |
|
97 | - /** |
|
98 | - * hook after file was unshared |
|
99 | - * |
|
100 | - * @param array $params |
|
101 | - */ |
|
102 | - public function postUnshared($params) { |
|
103 | - if ($this->encryptionManager->isEnabled()) { |
|
104 | - if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') { |
|
105 | - $path = Filesystem::getPath($params['fileSource']); |
|
106 | - [$owner, $ownerPath] = $this->getOwnerPath($path); |
|
107 | - $absPath = '/' . $owner . '/files/' . $ownerPath; |
|
108 | - $this->update($absPath); |
|
109 | - } |
|
110 | - } |
|
111 | - } |
|
112 | - |
|
113 | - /** |
|
114 | - * inform encryption module that a file was restored from the trash bin, |
|
115 | - * e.g. to update the encryption keys |
|
116 | - * |
|
117 | - * @param array $params |
|
118 | - */ |
|
119 | - public function postRestore($params) { |
|
120 | - if ($this->encryptionManager->isEnabled()) { |
|
121 | - $path = Filesystem::normalizePath('/' . $this->uid . '/files/' . $params['filePath']); |
|
122 | - $this->update($path); |
|
123 | - } |
|
124 | - } |
|
125 | - |
|
126 | - /** |
|
127 | - * inform encryption module that a file was renamed, |
|
128 | - * e.g. to update the encryption keys |
|
129 | - * |
|
130 | - * @param array $params |
|
131 | - */ |
|
132 | - public function postRename($params) { |
|
133 | - $source = $params['oldpath']; |
|
134 | - $target = $params['newpath']; |
|
135 | - if ( |
|
136 | - $this->encryptionManager->isEnabled() && |
|
137 | - dirname($source) !== dirname($target) |
|
138 | - ) { |
|
139 | - [$owner, $ownerPath] = $this->getOwnerPath($target); |
|
140 | - $absPath = '/' . $owner . '/files/' . $ownerPath; |
|
141 | - $this->update($absPath); |
|
142 | - } |
|
143 | - } |
|
144 | - |
|
145 | - /** |
|
146 | - * get owner and path relative to data/<owner>/files |
|
147 | - * |
|
148 | - * @param string $path path to file for current user |
|
149 | - * @return array ['owner' => $owner, 'path' => $path] |
|
150 | - * @throw \InvalidArgumentException |
|
151 | - */ |
|
152 | - protected function getOwnerPath($path) { |
|
153 | - $info = Filesystem::getFileInfo($path); |
|
154 | - $owner = Filesystem::getOwner($path); |
|
155 | - $view = new View('/' . $owner . '/files'); |
|
156 | - $path = $view->getPath($info->getId()); |
|
157 | - if ($path === null) { |
|
158 | - throw new \InvalidArgumentException('No file found for ' . $info->getId()); |
|
159 | - } |
|
160 | - |
|
161 | - return [$owner, $path]; |
|
162 | - } |
|
163 | - |
|
164 | - /** |
|
165 | - * notify encryption module about added/removed users from a file/folder |
|
166 | - * |
|
167 | - * @param string $path relative to data/ |
|
168 | - * @throws Exceptions\ModuleDoesNotExistsException |
|
169 | - */ |
|
170 | - public function update($path) { |
|
171 | - $encryptionModule = $this->encryptionManager->getEncryptionModule(); |
|
172 | - |
|
173 | - // if the encryption module doesn't encrypt the files on a per-user basis |
|
174 | - // we have nothing to do here. |
|
175 | - if ($encryptionModule->needDetailedAccessList() === false) { |
|
176 | - return; |
|
177 | - } |
|
178 | - |
|
179 | - // if a folder was shared, get a list of all (sub-)folders |
|
180 | - if ($this->view->is_dir($path)) { |
|
181 | - $allFiles = $this->util->getAllFiles($path); |
|
182 | - } else { |
|
183 | - $allFiles = [$path]; |
|
184 | - } |
|
185 | - |
|
186 | - |
|
187 | - |
|
188 | - foreach ($allFiles as $file) { |
|
189 | - $usersSharing = $this->file->getAccessList($file); |
|
190 | - $encryptionModule->update($file, $this->uid, $usersSharing); |
|
191 | - } |
|
192 | - } |
|
38 | + /** @var \OC\Files\View */ |
|
39 | + protected $view; |
|
40 | + |
|
41 | + /** @var \OC\Encryption\Util */ |
|
42 | + protected $util; |
|
43 | + |
|
44 | + /** @var \OC\Files\Mount\Manager */ |
|
45 | + protected $mountManager; |
|
46 | + |
|
47 | + /** @var \OC\Encryption\Manager */ |
|
48 | + protected $encryptionManager; |
|
49 | + |
|
50 | + /** @var string */ |
|
51 | + protected $uid; |
|
52 | + |
|
53 | + /** @var \OC\Encryption\File */ |
|
54 | + protected $file; |
|
55 | + |
|
56 | + /** |
|
57 | + * |
|
58 | + * @param \OC\Files\View $view |
|
59 | + * @param \OC\Encryption\Util $util |
|
60 | + * @param \OC\Files\Mount\Manager $mountManager |
|
61 | + * @param \OC\Encryption\Manager $encryptionManager |
|
62 | + * @param \OC\Encryption\File $file |
|
63 | + * @param string $uid |
|
64 | + */ |
|
65 | + public function __construct( |
|
66 | + View $view, |
|
67 | + Util $util, |
|
68 | + Mount\Manager $mountManager, |
|
69 | + Manager $encryptionManager, |
|
70 | + File $file, |
|
71 | + $uid |
|
72 | + ) { |
|
73 | + $this->view = $view; |
|
74 | + $this->util = $util; |
|
75 | + $this->mountManager = $mountManager; |
|
76 | + $this->encryptionManager = $encryptionManager; |
|
77 | + $this->file = $file; |
|
78 | + $this->uid = $uid; |
|
79 | + } |
|
80 | + |
|
81 | + /** |
|
82 | + * hook after file was shared |
|
83 | + * |
|
84 | + * @param array $params |
|
85 | + */ |
|
86 | + public function postShared($params) { |
|
87 | + if ($this->encryptionManager->isEnabled()) { |
|
88 | + if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') { |
|
89 | + $path = Filesystem::getPath($params['fileSource']); |
|
90 | + [$owner, $ownerPath] = $this->getOwnerPath($path); |
|
91 | + $absPath = '/' . $owner . '/files/' . $ownerPath; |
|
92 | + $this->update($absPath); |
|
93 | + } |
|
94 | + } |
|
95 | + } |
|
96 | + |
|
97 | + /** |
|
98 | + * hook after file was unshared |
|
99 | + * |
|
100 | + * @param array $params |
|
101 | + */ |
|
102 | + public function postUnshared($params) { |
|
103 | + if ($this->encryptionManager->isEnabled()) { |
|
104 | + if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') { |
|
105 | + $path = Filesystem::getPath($params['fileSource']); |
|
106 | + [$owner, $ownerPath] = $this->getOwnerPath($path); |
|
107 | + $absPath = '/' . $owner . '/files/' . $ownerPath; |
|
108 | + $this->update($absPath); |
|
109 | + } |
|
110 | + } |
|
111 | + } |
|
112 | + |
|
113 | + /** |
|
114 | + * inform encryption module that a file was restored from the trash bin, |
|
115 | + * e.g. to update the encryption keys |
|
116 | + * |
|
117 | + * @param array $params |
|
118 | + */ |
|
119 | + public function postRestore($params) { |
|
120 | + if ($this->encryptionManager->isEnabled()) { |
|
121 | + $path = Filesystem::normalizePath('/' . $this->uid . '/files/' . $params['filePath']); |
|
122 | + $this->update($path); |
|
123 | + } |
|
124 | + } |
|
125 | + |
|
126 | + /** |
|
127 | + * inform encryption module that a file was renamed, |
|
128 | + * e.g. to update the encryption keys |
|
129 | + * |
|
130 | + * @param array $params |
|
131 | + */ |
|
132 | + public function postRename($params) { |
|
133 | + $source = $params['oldpath']; |
|
134 | + $target = $params['newpath']; |
|
135 | + if ( |
|
136 | + $this->encryptionManager->isEnabled() && |
|
137 | + dirname($source) !== dirname($target) |
|
138 | + ) { |
|
139 | + [$owner, $ownerPath] = $this->getOwnerPath($target); |
|
140 | + $absPath = '/' . $owner . '/files/' . $ownerPath; |
|
141 | + $this->update($absPath); |
|
142 | + } |
|
143 | + } |
|
144 | + |
|
145 | + /** |
|
146 | + * get owner and path relative to data/<owner>/files |
|
147 | + * |
|
148 | + * @param string $path path to file for current user |
|
149 | + * @return array ['owner' => $owner, 'path' => $path] |
|
150 | + * @throw \InvalidArgumentException |
|
151 | + */ |
|
152 | + protected function getOwnerPath($path) { |
|
153 | + $info = Filesystem::getFileInfo($path); |
|
154 | + $owner = Filesystem::getOwner($path); |
|
155 | + $view = new View('/' . $owner . '/files'); |
|
156 | + $path = $view->getPath($info->getId()); |
|
157 | + if ($path === null) { |
|
158 | + throw new \InvalidArgumentException('No file found for ' . $info->getId()); |
|
159 | + } |
|
160 | + |
|
161 | + return [$owner, $path]; |
|
162 | + } |
|
163 | + |
|
164 | + /** |
|
165 | + * notify encryption module about added/removed users from a file/folder |
|
166 | + * |
|
167 | + * @param string $path relative to data/ |
|
168 | + * @throws Exceptions\ModuleDoesNotExistsException |
|
169 | + */ |
|
170 | + public function update($path) { |
|
171 | + $encryptionModule = $this->encryptionManager->getEncryptionModule(); |
|
172 | + |
|
173 | + // if the encryption module doesn't encrypt the files on a per-user basis |
|
174 | + // we have nothing to do here. |
|
175 | + if ($encryptionModule->needDetailedAccessList() === false) { |
|
176 | + return; |
|
177 | + } |
|
178 | + |
|
179 | + // if a folder was shared, get a list of all (sub-)folders |
|
180 | + if ($this->view->is_dir($path)) { |
|
181 | + $allFiles = $this->util->getAllFiles($path); |
|
182 | + } else { |
|
183 | + $allFiles = [$path]; |
|
184 | + } |
|
185 | + |
|
186 | + |
|
187 | + |
|
188 | + foreach ($allFiles as $file) { |
|
189 | + $usersSharing = $this->file->getAccessList($file); |
|
190 | + $encryptionModule->update($file, $this->uid, $usersSharing); |
|
191 | + } |
|
192 | + } |
|
193 | 193 | } |
@@ -88,7 +88,7 @@ discard block |
||
88 | 88 | if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') { |
89 | 89 | $path = Filesystem::getPath($params['fileSource']); |
90 | 90 | [$owner, $ownerPath] = $this->getOwnerPath($path); |
91 | - $absPath = '/' . $owner . '/files/' . $ownerPath; |
|
91 | + $absPath = '/'.$owner.'/files/'.$ownerPath; |
|
92 | 92 | $this->update($absPath); |
93 | 93 | } |
94 | 94 | } |
@@ -104,7 +104,7 @@ discard block |
||
104 | 104 | if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') { |
105 | 105 | $path = Filesystem::getPath($params['fileSource']); |
106 | 106 | [$owner, $ownerPath] = $this->getOwnerPath($path); |
107 | - $absPath = '/' . $owner . '/files/' . $ownerPath; |
|
107 | + $absPath = '/'.$owner.'/files/'.$ownerPath; |
|
108 | 108 | $this->update($absPath); |
109 | 109 | } |
110 | 110 | } |
@@ -118,7 +118,7 @@ discard block |
||
118 | 118 | */ |
119 | 119 | public function postRestore($params) { |
120 | 120 | if ($this->encryptionManager->isEnabled()) { |
121 | - $path = Filesystem::normalizePath('/' . $this->uid . '/files/' . $params['filePath']); |
|
121 | + $path = Filesystem::normalizePath('/'.$this->uid.'/files/'.$params['filePath']); |
|
122 | 122 | $this->update($path); |
123 | 123 | } |
124 | 124 | } |
@@ -137,7 +137,7 @@ discard block |
||
137 | 137 | dirname($source) !== dirname($target) |
138 | 138 | ) { |
139 | 139 | [$owner, $ownerPath] = $this->getOwnerPath($target); |
140 | - $absPath = '/' . $owner . '/files/' . $ownerPath; |
|
140 | + $absPath = '/'.$owner.'/files/'.$ownerPath; |
|
141 | 141 | $this->update($absPath); |
142 | 142 | } |
143 | 143 | } |
@@ -152,10 +152,10 @@ discard block |
||
152 | 152 | protected function getOwnerPath($path) { |
153 | 153 | $info = Filesystem::getFileInfo($path); |
154 | 154 | $owner = Filesystem::getOwner($path); |
155 | - $view = new View('/' . $owner . '/files'); |
|
155 | + $view = new View('/'.$owner.'/files'); |
|
156 | 156 | $path = $view->getPath($info->getId()); |
157 | 157 | if ($path === null) { |
158 | - throw new \InvalidArgumentException('No file found for ' . $info->getId()); |
|
158 | + throw new \InvalidArgumentException('No file found for '.$info->getId()); |
|
159 | 159 | } |
160 | 160 | |
161 | 161 | return [$owner, $path]; |
@@ -35,94 +35,94 @@ |
||
35 | 35 | |
36 | 36 | class File implements \OCP\Encryption\IFile { |
37 | 37 | |
38 | - /** @var Util */ |
|
39 | - protected $util; |
|
40 | - |
|
41 | - /** @var IRootFolder */ |
|
42 | - private $rootFolder; |
|
43 | - |
|
44 | - /** @var IManager */ |
|
45 | - private $shareManager; |
|
46 | - |
|
47 | - /** |
|
48 | - * cache results of already checked folders |
|
49 | - * |
|
50 | - * @var array |
|
51 | - */ |
|
52 | - protected $cache; |
|
53 | - |
|
54 | - public function __construct(Util $util, |
|
55 | - IRootFolder $rootFolder, |
|
56 | - IManager $shareManager) { |
|
57 | - $this->util = $util; |
|
58 | - $this->cache = new CappedMemoryCache(); |
|
59 | - $this->rootFolder = $rootFolder; |
|
60 | - $this->shareManager = $shareManager; |
|
61 | - } |
|
62 | - |
|
63 | - |
|
64 | - /** |
|
65 | - * get list of users with access to the file |
|
66 | - * |
|
67 | - * @param string $path to the file |
|
68 | - * @return array ['users' => $uniqueUserIds, 'public' => $public] |
|
69 | - */ |
|
70 | - public function getAccessList($path) { |
|
71 | - |
|
72 | - // Make sure that a share key is generated for the owner too |
|
73 | - [$owner, $ownerPath] = $this->util->getUidAndFilename($path); |
|
74 | - |
|
75 | - // always add owner to the list of users with access to the file |
|
76 | - $userIds = [$owner]; |
|
77 | - |
|
78 | - if (!$this->util->isFile($owner . '/' . $ownerPath)) { |
|
79 | - return ['users' => $userIds, 'public' => false]; |
|
80 | - } |
|
81 | - |
|
82 | - $ownerPath = substr($ownerPath, strlen('/files')); |
|
83 | - $userFolder = $this->rootFolder->getUserFolder($owner); |
|
84 | - try { |
|
85 | - $file = $userFolder->get($ownerPath); |
|
86 | - } catch (NotFoundException $e) { |
|
87 | - $file = null; |
|
88 | - } |
|
89 | - $ownerPath = $this->util->stripPartialFileExtension($ownerPath); |
|
90 | - |
|
91 | - // first get the shares for the parent and cache the result so that we don't |
|
92 | - // need to check all parents for every file |
|
93 | - $parent = dirname($ownerPath); |
|
94 | - $parentNode = $userFolder->get($parent); |
|
95 | - if (isset($this->cache[$parent])) { |
|
96 | - $resultForParents = $this->cache[$parent]; |
|
97 | - } else { |
|
98 | - $resultForParents = $this->shareManager->getAccessList($parentNode); |
|
99 | - $this->cache[$parent] = $resultForParents; |
|
100 | - } |
|
101 | - $userIds = array_merge($userIds, $resultForParents['users']); |
|
102 | - $public = $resultForParents['public'] || $resultForParents['remote']; |
|
103 | - |
|
104 | - |
|
105 | - // Find out who, if anyone, is sharing the file |
|
106 | - if ($file !== null) { |
|
107 | - $resultForFile = $this->shareManager->getAccessList($file, false); |
|
108 | - $userIds = array_merge($userIds, $resultForFile['users']); |
|
109 | - $public = $resultForFile['public'] || $resultForFile['remote'] || $public; |
|
110 | - } |
|
111 | - |
|
112 | - // check if it is a group mount |
|
113 | - if (\OCP\App::isEnabled("files_external")) { |
|
114 | - $mounts = \OCA\Files_External\MountConfig::getSystemMountPoints(); |
|
115 | - foreach ($mounts as $mount) { |
|
116 | - if ($mount['mountpoint'] == substr($ownerPath, 1, strlen($mount['mountpoint']))) { |
|
117 | - $mountedFor = $this->util->getUserWithAccessToMountPoint($mount['applicable']['users'], $mount['applicable']['groups']); |
|
118 | - $userIds = array_merge($userIds, $mountedFor); |
|
119 | - } |
|
120 | - } |
|
121 | - } |
|
122 | - |
|
123 | - // Remove duplicate UIDs |
|
124 | - $uniqueUserIds = array_unique($userIds); |
|
125 | - |
|
126 | - return ['users' => $uniqueUserIds, 'public' => $public]; |
|
127 | - } |
|
38 | + /** @var Util */ |
|
39 | + protected $util; |
|
40 | + |
|
41 | + /** @var IRootFolder */ |
|
42 | + private $rootFolder; |
|
43 | + |
|
44 | + /** @var IManager */ |
|
45 | + private $shareManager; |
|
46 | + |
|
47 | + /** |
|
48 | + * cache results of already checked folders |
|
49 | + * |
|
50 | + * @var array |
|
51 | + */ |
|
52 | + protected $cache; |
|
53 | + |
|
54 | + public function __construct(Util $util, |
|
55 | + IRootFolder $rootFolder, |
|
56 | + IManager $shareManager) { |
|
57 | + $this->util = $util; |
|
58 | + $this->cache = new CappedMemoryCache(); |
|
59 | + $this->rootFolder = $rootFolder; |
|
60 | + $this->shareManager = $shareManager; |
|
61 | + } |
|
62 | + |
|
63 | + |
|
64 | + /** |
|
65 | + * get list of users with access to the file |
|
66 | + * |
|
67 | + * @param string $path to the file |
|
68 | + * @return array ['users' => $uniqueUserIds, 'public' => $public] |
|
69 | + */ |
|
70 | + public function getAccessList($path) { |
|
71 | + |
|
72 | + // Make sure that a share key is generated for the owner too |
|
73 | + [$owner, $ownerPath] = $this->util->getUidAndFilename($path); |
|
74 | + |
|
75 | + // always add owner to the list of users with access to the file |
|
76 | + $userIds = [$owner]; |
|
77 | + |
|
78 | + if (!$this->util->isFile($owner . '/' . $ownerPath)) { |
|
79 | + return ['users' => $userIds, 'public' => false]; |
|
80 | + } |
|
81 | + |
|
82 | + $ownerPath = substr($ownerPath, strlen('/files')); |
|
83 | + $userFolder = $this->rootFolder->getUserFolder($owner); |
|
84 | + try { |
|
85 | + $file = $userFolder->get($ownerPath); |
|
86 | + } catch (NotFoundException $e) { |
|
87 | + $file = null; |
|
88 | + } |
|
89 | + $ownerPath = $this->util->stripPartialFileExtension($ownerPath); |
|
90 | + |
|
91 | + // first get the shares for the parent and cache the result so that we don't |
|
92 | + // need to check all parents for every file |
|
93 | + $parent = dirname($ownerPath); |
|
94 | + $parentNode = $userFolder->get($parent); |
|
95 | + if (isset($this->cache[$parent])) { |
|
96 | + $resultForParents = $this->cache[$parent]; |
|
97 | + } else { |
|
98 | + $resultForParents = $this->shareManager->getAccessList($parentNode); |
|
99 | + $this->cache[$parent] = $resultForParents; |
|
100 | + } |
|
101 | + $userIds = array_merge($userIds, $resultForParents['users']); |
|
102 | + $public = $resultForParents['public'] || $resultForParents['remote']; |
|
103 | + |
|
104 | + |
|
105 | + // Find out who, if anyone, is sharing the file |
|
106 | + if ($file !== null) { |
|
107 | + $resultForFile = $this->shareManager->getAccessList($file, false); |
|
108 | + $userIds = array_merge($userIds, $resultForFile['users']); |
|
109 | + $public = $resultForFile['public'] || $resultForFile['remote'] || $public; |
|
110 | + } |
|
111 | + |
|
112 | + // check if it is a group mount |
|
113 | + if (\OCP\App::isEnabled("files_external")) { |
|
114 | + $mounts = \OCA\Files_External\MountConfig::getSystemMountPoints(); |
|
115 | + foreach ($mounts as $mount) { |
|
116 | + if ($mount['mountpoint'] == substr($ownerPath, 1, strlen($mount['mountpoint']))) { |
|
117 | + $mountedFor = $this->util->getUserWithAccessToMountPoint($mount['applicable']['users'], $mount['applicable']['groups']); |
|
118 | + $userIds = array_merge($userIds, $mountedFor); |
|
119 | + } |
|
120 | + } |
|
121 | + } |
|
122 | + |
|
123 | + // Remove duplicate UIDs |
|
124 | + $uniqueUserIds = array_unique($userIds); |
|
125 | + |
|
126 | + return ['users' => $uniqueUserIds, 'public' => $public]; |
|
127 | + } |
|
128 | 128 | } |
@@ -48,311 +48,311 @@ |
||
48 | 48 | */ |
49 | 49 | class OC_Template extends \OC\Template\Base { |
50 | 50 | |
51 | - /** @var string */ |
|
52 | - private $renderAs; // Create a full page? |
|
53 | - |
|
54 | - /** @var string */ |
|
55 | - private $path; // The path to the template |
|
56 | - |
|
57 | - /** @var array */ |
|
58 | - private $headers = []; //custom headers |
|
59 | - |
|
60 | - /** @var string */ |
|
61 | - protected $app; // app id |
|
62 | - |
|
63 | - protected static $initTemplateEngineFirstRun = true; |
|
64 | - |
|
65 | - /** |
|
66 | - * Constructor |
|
67 | - * |
|
68 | - * @param string $app app providing the template |
|
69 | - * @param string $name of the template file (without suffix) |
|
70 | - * @param string $renderAs If $renderAs is set, OC_Template will try to |
|
71 | - * produce a full page in the according layout. For |
|
72 | - * now, $renderAs can be set to "guest", "user" or |
|
73 | - * "admin". |
|
74 | - * @param bool $registerCall = true |
|
75 | - */ |
|
76 | - public function __construct($app, $name, $renderAs = TemplateResponse::RENDER_AS_BLANK, $registerCall = true) { |
|
77 | - // Read the selected theme from the config file |
|
78 | - self::initTemplateEngine($renderAs); |
|
79 | - |
|
80 | - $theme = OC_Util::getTheme(); |
|
81 | - |
|
82 | - $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : ''; |
|
83 | - |
|
84 | - $parts = explode('/', $app); // fix translation when app is something like core/lostpassword |
|
85 | - $l10n = \OC::$server->getL10N($parts[0]); |
|
86 | - /** @var \OCP\Defaults $themeDefaults */ |
|
87 | - $themeDefaults = \OC::$server->query(\OCP\Defaults::class); |
|
88 | - |
|
89 | - [$path, $template] = $this->findTemplate($theme, $app, $name); |
|
90 | - |
|
91 | - // Set the private data |
|
92 | - $this->renderAs = $renderAs; |
|
93 | - $this->path = $path; |
|
94 | - $this->app = $app; |
|
95 | - |
|
96 | - parent::__construct($template, $requestToken, $l10n, $themeDefaults); |
|
97 | - } |
|
98 | - |
|
99 | - /** |
|
100 | - * @param string $renderAs |
|
101 | - */ |
|
102 | - public static function initTemplateEngine($renderAs) { |
|
103 | - if (self::$initTemplateEngineFirstRun) { |
|
104 | - |
|
105 | - //apps that started before the template initialization can load their own scripts/styles |
|
106 | - //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true |
|
107 | - //meaning the last script/style in this list will be loaded first |
|
108 | - if (\OC::$server->getSystemConfig()->getValue('installed', false) && $renderAs !== TemplateResponse::RENDER_AS_ERROR && !\OCP\Util::needUpgrade()) { |
|
109 | - if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') { |
|
110 | - OC_Util::addScript('backgroundjobs', null, true); |
|
111 | - } |
|
112 | - } |
|
113 | - OC_Util::addStyle('css-variables', null, true); |
|
114 | - OC_Util::addStyle('server', null, true); |
|
115 | - OC_Util::addTranslations('core', null, true); |
|
116 | - |
|
117 | - if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
118 | - OC_Util::addScript('merged-template-prepend', null, true); |
|
119 | - OC_Util::addScript('dist/files_client', null, true); |
|
120 | - OC_Util::addScript('dist/files_fileinfo', null, true); |
|
121 | - } |
|
122 | - OC_Util::addScript('core', 'dist/main', true); |
|
123 | - |
|
124 | - if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) { |
|
125 | - // shim for the davclient.js library |
|
126 | - \OCP\Util::addScript('dist/files_iedavclient'); |
|
127 | - } |
|
128 | - |
|
129 | - self::$initTemplateEngineFirstRun = false; |
|
130 | - } |
|
131 | - } |
|
132 | - |
|
133 | - |
|
134 | - /** |
|
135 | - * find the template with the given name |
|
136 | - * @param string $name of the template file (without suffix) |
|
137 | - * |
|
138 | - * Will select the template file for the selected theme. |
|
139 | - * Checking all the possible locations. |
|
140 | - * @param string $theme |
|
141 | - * @param string $app |
|
142 | - * @return string[] |
|
143 | - */ |
|
144 | - protected function findTemplate($theme, $app, $name) { |
|
145 | - // Check if it is a app template or not. |
|
146 | - if ($app !== '') { |
|
147 | - $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app)); |
|
148 | - } else { |
|
149 | - $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT); |
|
150 | - } |
|
151 | - $locator = new \OC\Template\TemplateFileLocator($dirs); |
|
152 | - $template = $locator->find($name); |
|
153 | - $path = $locator->getPath(); |
|
154 | - return [$path, $template]; |
|
155 | - } |
|
156 | - |
|
157 | - /** |
|
158 | - * Add a custom element to the header |
|
159 | - * @param string $tag tag name of the element |
|
160 | - * @param array $attributes array of attributes for the element |
|
161 | - * @param string $text the text content for the element. If $text is null then the |
|
162 | - * element will be written as empty element. So use "" to get a closing tag. |
|
163 | - */ |
|
164 | - public function addHeader($tag, $attributes, $text = null) { |
|
165 | - $this->headers[] = [ |
|
166 | - 'tag' => $tag, |
|
167 | - 'attributes' => $attributes, |
|
168 | - 'text' => $text |
|
169 | - ]; |
|
170 | - } |
|
171 | - |
|
172 | - /** |
|
173 | - * Process the template |
|
174 | - * @return string |
|
175 | - * |
|
176 | - * This function process the template. If $this->renderAs is set, it |
|
177 | - * will produce a full page. |
|
178 | - */ |
|
179 | - public function fetchPage($additionalParams = null) { |
|
180 | - $data = parent::fetchPage($additionalParams); |
|
181 | - |
|
182 | - if ($this->renderAs) { |
|
183 | - $page = new TemplateLayout($this->renderAs, $this->app); |
|
184 | - |
|
185 | - if (is_array($additionalParams)) { |
|
186 | - foreach ($additionalParams as $key => $value) { |
|
187 | - $page->assign($key, $value); |
|
188 | - } |
|
189 | - } |
|
190 | - |
|
191 | - // Add custom headers |
|
192 | - $headers = ''; |
|
193 | - foreach (OC_Util::$headers as $header) { |
|
194 | - $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']); |
|
195 | - if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) { |
|
196 | - $headers .= ' defer'; |
|
197 | - } |
|
198 | - foreach ($header['attributes'] as $name => $value) { |
|
199 | - $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"'; |
|
200 | - } |
|
201 | - if ($header['text'] !== null) { |
|
202 | - $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>'; |
|
203 | - } else { |
|
204 | - $headers .= '/>'; |
|
205 | - } |
|
206 | - } |
|
207 | - |
|
208 | - $page->assign('headers', $headers); |
|
209 | - |
|
210 | - $page->assign('content', $data); |
|
211 | - return $page->fetchPage($additionalParams); |
|
212 | - } |
|
213 | - |
|
214 | - return $data; |
|
215 | - } |
|
216 | - |
|
217 | - /** |
|
218 | - * Include template |
|
219 | - * |
|
220 | - * @param string $file |
|
221 | - * @param array|null $additionalParams |
|
222 | - * @return string returns content of included template |
|
223 | - * |
|
224 | - * Includes another template. use <?php echo $this->inc('template'); ?> to |
|
225 | - * do this. |
|
226 | - */ |
|
227 | - public function inc($file, $additionalParams = null) { |
|
228 | - return $this->load($this->path.$file.'.php', $additionalParams); |
|
229 | - } |
|
230 | - |
|
231 | - /** |
|
232 | - * Shortcut to print a simple page for users |
|
233 | - * @param string $application The application we render the template for |
|
234 | - * @param string $name Name of the template |
|
235 | - * @param array $parameters Parameters for the template |
|
236 | - * @return boolean|null |
|
237 | - */ |
|
238 | - public static function printUserPage($application, $name, $parameters = []) { |
|
239 | - $content = new OC_Template($application, $name, "user"); |
|
240 | - foreach ($parameters as $key => $value) { |
|
241 | - $content->assign($key, $value); |
|
242 | - } |
|
243 | - print $content->printPage(); |
|
244 | - } |
|
245 | - |
|
246 | - /** |
|
247 | - * Shortcut to print a simple page for admins |
|
248 | - * @param string $application The application we render the template for |
|
249 | - * @param string $name Name of the template |
|
250 | - * @param array $parameters Parameters for the template |
|
251 | - * @return bool |
|
252 | - */ |
|
253 | - public static function printAdminPage($application, $name, $parameters = []) { |
|
254 | - $content = new OC_Template($application, $name, "admin"); |
|
255 | - foreach ($parameters as $key => $value) { |
|
256 | - $content->assign($key, $value); |
|
257 | - } |
|
258 | - return $content->printPage(); |
|
259 | - } |
|
260 | - |
|
261 | - /** |
|
262 | - * Shortcut to print a simple page for guests |
|
263 | - * @param string $application The application we render the template for |
|
264 | - * @param string $name Name of the template |
|
265 | - * @param array|string $parameters Parameters for the template |
|
266 | - * @return bool |
|
267 | - */ |
|
268 | - public static function printGuestPage($application, $name, $parameters = []) { |
|
269 | - $content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest'); |
|
270 | - foreach ($parameters as $key => $value) { |
|
271 | - $content->assign($key, $value); |
|
272 | - } |
|
273 | - return $content->printPage(); |
|
274 | - } |
|
275 | - |
|
276 | - /** |
|
277 | - * Print a fatal error page and terminates the script |
|
278 | - * @param string $error_msg The error message to show |
|
279 | - * @param string $hint An optional hint message - needs to be properly escape |
|
280 | - * @param int $statusCode |
|
281 | - * @suppress PhanAccessMethodInternal |
|
282 | - */ |
|
283 | - public static function printErrorPage($error_msg, $hint = '', $statusCode = 500) { |
|
284 | - if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) { |
|
285 | - \OC_App::loadApp('theming'); |
|
286 | - } |
|
287 | - |
|
288 | - |
|
289 | - if ($error_msg === $hint) { |
|
290 | - // If the hint is the same as the message there is no need to display it twice. |
|
291 | - $hint = ''; |
|
292 | - } |
|
293 | - |
|
294 | - http_response_code($statusCode); |
|
295 | - try { |
|
296 | - $content = new \OC_Template('', 'error', 'error', false); |
|
297 | - $errors = [['error' => $error_msg, 'hint' => $hint]]; |
|
298 | - $content->assign('errors', $errors); |
|
299 | - $content->printPage(); |
|
300 | - } catch (\Exception $e) { |
|
301 | - $logger = \OC::$server->getLogger(); |
|
302 | - $logger->error("$error_msg $hint", ['app' => 'core']); |
|
303 | - $logger->logException($e, ['app' => 'core']); |
|
304 | - |
|
305 | - header('Content-Type: text/plain; charset=utf-8'); |
|
306 | - print("$error_msg $hint"); |
|
307 | - } |
|
308 | - die(); |
|
309 | - } |
|
310 | - |
|
311 | - /** |
|
312 | - * print error page using Exception details |
|
313 | - * @param Exception|Throwable $exception |
|
314 | - * @param int $statusCode |
|
315 | - * @return bool|string |
|
316 | - * @suppress PhanAccessMethodInternal |
|
317 | - */ |
|
318 | - public static function printExceptionErrorPage($exception, $statusCode = 503) { |
|
319 | - http_response_code($statusCode); |
|
320 | - try { |
|
321 | - $request = \OC::$server->getRequest(); |
|
322 | - $content = new \OC_Template('', 'exception', 'error', false); |
|
323 | - $content->assign('errorClass', get_class($exception)); |
|
324 | - $content->assign('errorMsg', $exception->getMessage()); |
|
325 | - $content->assign('errorCode', $exception->getCode()); |
|
326 | - $content->assign('file', $exception->getFile()); |
|
327 | - $content->assign('line', $exception->getLine()); |
|
328 | - $content->assign('exception', $exception); |
|
329 | - $content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false)); |
|
330 | - $content->assign('remoteAddr', $request->getRemoteAddress()); |
|
331 | - $content->assign('requestID', $request->getId()); |
|
332 | - $content->printPage(); |
|
333 | - } catch (\Exception $e) { |
|
334 | - try { |
|
335 | - $logger = \OC::$server->getLogger(); |
|
336 | - $logger->logException($exception, ['app' => 'core']); |
|
337 | - $logger->logException($e, ['app' => 'core']); |
|
338 | - } catch (Throwable $e) { |
|
339 | - // no way to log it properly - but to avoid a white page of death we send some output |
|
340 | - header('Content-Type: text/plain; charset=utf-8'); |
|
341 | - print("Internal Server Error\n\n"); |
|
342 | - print("The server encountered an internal error and was unable to complete your request.\n"); |
|
343 | - print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n"); |
|
344 | - print("More details can be found in the server log.\n"); |
|
345 | - |
|
346 | - // and then throw it again to log it at least to the web server error log |
|
347 | - throw $e; |
|
348 | - } |
|
349 | - |
|
350 | - header('Content-Type: text/plain; charset=utf-8'); |
|
351 | - print("Internal Server Error\n\n"); |
|
352 | - print("The server encountered an internal error and was unable to complete your request.\n"); |
|
353 | - print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n"); |
|
354 | - print("More details can be found in the server log.\n"); |
|
355 | - } |
|
356 | - die(); |
|
357 | - } |
|
51 | + /** @var string */ |
|
52 | + private $renderAs; // Create a full page? |
|
53 | + |
|
54 | + /** @var string */ |
|
55 | + private $path; // The path to the template |
|
56 | + |
|
57 | + /** @var array */ |
|
58 | + private $headers = []; //custom headers |
|
59 | + |
|
60 | + /** @var string */ |
|
61 | + protected $app; // app id |
|
62 | + |
|
63 | + protected static $initTemplateEngineFirstRun = true; |
|
64 | + |
|
65 | + /** |
|
66 | + * Constructor |
|
67 | + * |
|
68 | + * @param string $app app providing the template |
|
69 | + * @param string $name of the template file (without suffix) |
|
70 | + * @param string $renderAs If $renderAs is set, OC_Template will try to |
|
71 | + * produce a full page in the according layout. For |
|
72 | + * now, $renderAs can be set to "guest", "user" or |
|
73 | + * "admin". |
|
74 | + * @param bool $registerCall = true |
|
75 | + */ |
|
76 | + public function __construct($app, $name, $renderAs = TemplateResponse::RENDER_AS_BLANK, $registerCall = true) { |
|
77 | + // Read the selected theme from the config file |
|
78 | + self::initTemplateEngine($renderAs); |
|
79 | + |
|
80 | + $theme = OC_Util::getTheme(); |
|
81 | + |
|
82 | + $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : ''; |
|
83 | + |
|
84 | + $parts = explode('/', $app); // fix translation when app is something like core/lostpassword |
|
85 | + $l10n = \OC::$server->getL10N($parts[0]); |
|
86 | + /** @var \OCP\Defaults $themeDefaults */ |
|
87 | + $themeDefaults = \OC::$server->query(\OCP\Defaults::class); |
|
88 | + |
|
89 | + [$path, $template] = $this->findTemplate($theme, $app, $name); |
|
90 | + |
|
91 | + // Set the private data |
|
92 | + $this->renderAs = $renderAs; |
|
93 | + $this->path = $path; |
|
94 | + $this->app = $app; |
|
95 | + |
|
96 | + parent::__construct($template, $requestToken, $l10n, $themeDefaults); |
|
97 | + } |
|
98 | + |
|
99 | + /** |
|
100 | + * @param string $renderAs |
|
101 | + */ |
|
102 | + public static function initTemplateEngine($renderAs) { |
|
103 | + if (self::$initTemplateEngineFirstRun) { |
|
104 | + |
|
105 | + //apps that started before the template initialization can load their own scripts/styles |
|
106 | + //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true |
|
107 | + //meaning the last script/style in this list will be loaded first |
|
108 | + if (\OC::$server->getSystemConfig()->getValue('installed', false) && $renderAs !== TemplateResponse::RENDER_AS_ERROR && !\OCP\Util::needUpgrade()) { |
|
109 | + if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') { |
|
110 | + OC_Util::addScript('backgroundjobs', null, true); |
|
111 | + } |
|
112 | + } |
|
113 | + OC_Util::addStyle('css-variables', null, true); |
|
114 | + OC_Util::addStyle('server', null, true); |
|
115 | + OC_Util::addTranslations('core', null, true); |
|
116 | + |
|
117 | + if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
118 | + OC_Util::addScript('merged-template-prepend', null, true); |
|
119 | + OC_Util::addScript('dist/files_client', null, true); |
|
120 | + OC_Util::addScript('dist/files_fileinfo', null, true); |
|
121 | + } |
|
122 | + OC_Util::addScript('core', 'dist/main', true); |
|
123 | + |
|
124 | + if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) { |
|
125 | + // shim for the davclient.js library |
|
126 | + \OCP\Util::addScript('dist/files_iedavclient'); |
|
127 | + } |
|
128 | + |
|
129 | + self::$initTemplateEngineFirstRun = false; |
|
130 | + } |
|
131 | + } |
|
132 | + |
|
133 | + |
|
134 | + /** |
|
135 | + * find the template with the given name |
|
136 | + * @param string $name of the template file (without suffix) |
|
137 | + * |
|
138 | + * Will select the template file for the selected theme. |
|
139 | + * Checking all the possible locations. |
|
140 | + * @param string $theme |
|
141 | + * @param string $app |
|
142 | + * @return string[] |
|
143 | + */ |
|
144 | + protected function findTemplate($theme, $app, $name) { |
|
145 | + // Check if it is a app template or not. |
|
146 | + if ($app !== '') { |
|
147 | + $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app)); |
|
148 | + } else { |
|
149 | + $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT); |
|
150 | + } |
|
151 | + $locator = new \OC\Template\TemplateFileLocator($dirs); |
|
152 | + $template = $locator->find($name); |
|
153 | + $path = $locator->getPath(); |
|
154 | + return [$path, $template]; |
|
155 | + } |
|
156 | + |
|
157 | + /** |
|
158 | + * Add a custom element to the header |
|
159 | + * @param string $tag tag name of the element |
|
160 | + * @param array $attributes array of attributes for the element |
|
161 | + * @param string $text the text content for the element. If $text is null then the |
|
162 | + * element will be written as empty element. So use "" to get a closing tag. |
|
163 | + */ |
|
164 | + public function addHeader($tag, $attributes, $text = null) { |
|
165 | + $this->headers[] = [ |
|
166 | + 'tag' => $tag, |
|
167 | + 'attributes' => $attributes, |
|
168 | + 'text' => $text |
|
169 | + ]; |
|
170 | + } |
|
171 | + |
|
172 | + /** |
|
173 | + * Process the template |
|
174 | + * @return string |
|
175 | + * |
|
176 | + * This function process the template. If $this->renderAs is set, it |
|
177 | + * will produce a full page. |
|
178 | + */ |
|
179 | + public function fetchPage($additionalParams = null) { |
|
180 | + $data = parent::fetchPage($additionalParams); |
|
181 | + |
|
182 | + if ($this->renderAs) { |
|
183 | + $page = new TemplateLayout($this->renderAs, $this->app); |
|
184 | + |
|
185 | + if (is_array($additionalParams)) { |
|
186 | + foreach ($additionalParams as $key => $value) { |
|
187 | + $page->assign($key, $value); |
|
188 | + } |
|
189 | + } |
|
190 | + |
|
191 | + // Add custom headers |
|
192 | + $headers = ''; |
|
193 | + foreach (OC_Util::$headers as $header) { |
|
194 | + $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']); |
|
195 | + if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) { |
|
196 | + $headers .= ' defer'; |
|
197 | + } |
|
198 | + foreach ($header['attributes'] as $name => $value) { |
|
199 | + $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"'; |
|
200 | + } |
|
201 | + if ($header['text'] !== null) { |
|
202 | + $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>'; |
|
203 | + } else { |
|
204 | + $headers .= '/>'; |
|
205 | + } |
|
206 | + } |
|
207 | + |
|
208 | + $page->assign('headers', $headers); |
|
209 | + |
|
210 | + $page->assign('content', $data); |
|
211 | + return $page->fetchPage($additionalParams); |
|
212 | + } |
|
213 | + |
|
214 | + return $data; |
|
215 | + } |
|
216 | + |
|
217 | + /** |
|
218 | + * Include template |
|
219 | + * |
|
220 | + * @param string $file |
|
221 | + * @param array|null $additionalParams |
|
222 | + * @return string returns content of included template |
|
223 | + * |
|
224 | + * Includes another template. use <?php echo $this->inc('template'); ?> to |
|
225 | + * do this. |
|
226 | + */ |
|
227 | + public function inc($file, $additionalParams = null) { |
|
228 | + return $this->load($this->path.$file.'.php', $additionalParams); |
|
229 | + } |
|
230 | + |
|
231 | + /** |
|
232 | + * Shortcut to print a simple page for users |
|
233 | + * @param string $application The application we render the template for |
|
234 | + * @param string $name Name of the template |
|
235 | + * @param array $parameters Parameters for the template |
|
236 | + * @return boolean|null |
|
237 | + */ |
|
238 | + public static function printUserPage($application, $name, $parameters = []) { |
|
239 | + $content = new OC_Template($application, $name, "user"); |
|
240 | + foreach ($parameters as $key => $value) { |
|
241 | + $content->assign($key, $value); |
|
242 | + } |
|
243 | + print $content->printPage(); |
|
244 | + } |
|
245 | + |
|
246 | + /** |
|
247 | + * Shortcut to print a simple page for admins |
|
248 | + * @param string $application The application we render the template for |
|
249 | + * @param string $name Name of the template |
|
250 | + * @param array $parameters Parameters for the template |
|
251 | + * @return bool |
|
252 | + */ |
|
253 | + public static function printAdminPage($application, $name, $parameters = []) { |
|
254 | + $content = new OC_Template($application, $name, "admin"); |
|
255 | + foreach ($parameters as $key => $value) { |
|
256 | + $content->assign($key, $value); |
|
257 | + } |
|
258 | + return $content->printPage(); |
|
259 | + } |
|
260 | + |
|
261 | + /** |
|
262 | + * Shortcut to print a simple page for guests |
|
263 | + * @param string $application The application we render the template for |
|
264 | + * @param string $name Name of the template |
|
265 | + * @param array|string $parameters Parameters for the template |
|
266 | + * @return bool |
|
267 | + */ |
|
268 | + public static function printGuestPage($application, $name, $parameters = []) { |
|
269 | + $content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest'); |
|
270 | + foreach ($parameters as $key => $value) { |
|
271 | + $content->assign($key, $value); |
|
272 | + } |
|
273 | + return $content->printPage(); |
|
274 | + } |
|
275 | + |
|
276 | + /** |
|
277 | + * Print a fatal error page and terminates the script |
|
278 | + * @param string $error_msg The error message to show |
|
279 | + * @param string $hint An optional hint message - needs to be properly escape |
|
280 | + * @param int $statusCode |
|
281 | + * @suppress PhanAccessMethodInternal |
|
282 | + */ |
|
283 | + public static function printErrorPage($error_msg, $hint = '', $statusCode = 500) { |
|
284 | + if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) { |
|
285 | + \OC_App::loadApp('theming'); |
|
286 | + } |
|
287 | + |
|
288 | + |
|
289 | + if ($error_msg === $hint) { |
|
290 | + // If the hint is the same as the message there is no need to display it twice. |
|
291 | + $hint = ''; |
|
292 | + } |
|
293 | + |
|
294 | + http_response_code($statusCode); |
|
295 | + try { |
|
296 | + $content = new \OC_Template('', 'error', 'error', false); |
|
297 | + $errors = [['error' => $error_msg, 'hint' => $hint]]; |
|
298 | + $content->assign('errors', $errors); |
|
299 | + $content->printPage(); |
|
300 | + } catch (\Exception $e) { |
|
301 | + $logger = \OC::$server->getLogger(); |
|
302 | + $logger->error("$error_msg $hint", ['app' => 'core']); |
|
303 | + $logger->logException($e, ['app' => 'core']); |
|
304 | + |
|
305 | + header('Content-Type: text/plain; charset=utf-8'); |
|
306 | + print("$error_msg $hint"); |
|
307 | + } |
|
308 | + die(); |
|
309 | + } |
|
310 | + |
|
311 | + /** |
|
312 | + * print error page using Exception details |
|
313 | + * @param Exception|Throwable $exception |
|
314 | + * @param int $statusCode |
|
315 | + * @return bool|string |
|
316 | + * @suppress PhanAccessMethodInternal |
|
317 | + */ |
|
318 | + public static function printExceptionErrorPage($exception, $statusCode = 503) { |
|
319 | + http_response_code($statusCode); |
|
320 | + try { |
|
321 | + $request = \OC::$server->getRequest(); |
|
322 | + $content = new \OC_Template('', 'exception', 'error', false); |
|
323 | + $content->assign('errorClass', get_class($exception)); |
|
324 | + $content->assign('errorMsg', $exception->getMessage()); |
|
325 | + $content->assign('errorCode', $exception->getCode()); |
|
326 | + $content->assign('file', $exception->getFile()); |
|
327 | + $content->assign('line', $exception->getLine()); |
|
328 | + $content->assign('exception', $exception); |
|
329 | + $content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false)); |
|
330 | + $content->assign('remoteAddr', $request->getRemoteAddress()); |
|
331 | + $content->assign('requestID', $request->getId()); |
|
332 | + $content->printPage(); |
|
333 | + } catch (\Exception $e) { |
|
334 | + try { |
|
335 | + $logger = \OC::$server->getLogger(); |
|
336 | + $logger->logException($exception, ['app' => 'core']); |
|
337 | + $logger->logException($e, ['app' => 'core']); |
|
338 | + } catch (Throwable $e) { |
|
339 | + // no way to log it properly - but to avoid a white page of death we send some output |
|
340 | + header('Content-Type: text/plain; charset=utf-8'); |
|
341 | + print("Internal Server Error\n\n"); |
|
342 | + print("The server encountered an internal error and was unable to complete your request.\n"); |
|
343 | + print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n"); |
|
344 | + print("More details can be found in the server log.\n"); |
|
345 | + |
|
346 | + // and then throw it again to log it at least to the web server error log |
|
347 | + throw $e; |
|
348 | + } |
|
349 | + |
|
350 | + header('Content-Type: text/plain; charset=utf-8'); |
|
351 | + print("Internal Server Error\n\n"); |
|
352 | + print("The server encountered an internal error and was unable to complete your request.\n"); |
|
353 | + print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n"); |
|
354 | + print("More details can be found in the server log.\n"); |
|
355 | + } |
|
356 | + die(); |
|
357 | + } |
|
358 | 358 | } |
@@ -43,259 +43,259 @@ |
||
43 | 43 | * @package OC\Mail |
44 | 44 | */ |
45 | 45 | class Message implements IMessage { |
46 | - /** @var Swift_Message */ |
|
47 | - private $swiftMessage; |
|
48 | - /** @var bool */ |
|
49 | - private $plainTextOnly; |
|
50 | - |
|
51 | - public function __construct(Swift_Message $swiftMessage, bool $plainTextOnly) { |
|
52 | - $this->swiftMessage = $swiftMessage; |
|
53 | - $this->plainTextOnly = $plainTextOnly; |
|
54 | - } |
|
55 | - |
|
56 | - /** |
|
57 | - * @param IAttachment $attachment |
|
58 | - * @return $this |
|
59 | - * @since 13.0.0 |
|
60 | - */ |
|
61 | - public function attach(IAttachment $attachment): IMessage { |
|
62 | - /** @var Attachment $attachment */ |
|
63 | - $this->swiftMessage->attach($attachment->getSwiftAttachment()); |
|
64 | - return $this; |
|
65 | - } |
|
66 | - |
|
67 | - /** |
|
68 | - * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains |
|
69 | - * FIXME: Remove this once SwiftMailer supports IDN |
|
70 | - * |
|
71 | - * @param array $addresses Array of mail addresses, key will get converted |
|
72 | - * @return array Converted addresses if `idn_to_ascii` exists |
|
73 | - */ |
|
74 | - protected function convertAddresses(array $addresses): array { |
|
75 | - if (!function_exists('idn_to_ascii') || !defined('INTL_IDNA_VARIANT_UTS46')) { |
|
76 | - return $addresses; |
|
77 | - } |
|
78 | - |
|
79 | - $convertedAddresses = []; |
|
80 | - |
|
81 | - foreach ($addresses as $email => $readableName) { |
|
82 | - if (!is_numeric($email)) { |
|
83 | - [$name, $domain] = explode('@', $email, 2); |
|
84 | - $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); |
|
85 | - $convertedAddresses[$name.'@'.$domain] = $readableName; |
|
86 | - } else { |
|
87 | - [$name, $domain] = explode('@', $readableName, 2); |
|
88 | - $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); |
|
89 | - $convertedAddresses[$email] = $name.'@'.$domain; |
|
90 | - } |
|
91 | - } |
|
92 | - |
|
93 | - return $convertedAddresses; |
|
94 | - } |
|
95 | - |
|
96 | - /** |
|
97 | - * Set the from address of this message. |
|
98 | - * |
|
99 | - * If no "From" address is used \OC\Mail\Mailer will use mail_from_address and mail_domain from config.php |
|
100 | - * |
|
101 | - * @param array $addresses Example: array('[email protected]', '[email protected]' => 'A name') |
|
102 | - * @return $this |
|
103 | - */ |
|
104 | - public function setFrom(array $addresses): IMessage { |
|
105 | - $addresses = $this->convertAddresses($addresses); |
|
106 | - |
|
107 | - $this->swiftMessage->setFrom($addresses); |
|
108 | - return $this; |
|
109 | - } |
|
110 | - |
|
111 | - /** |
|
112 | - * Get the from address of this message. |
|
113 | - * |
|
114 | - * @return array |
|
115 | - */ |
|
116 | - public function getFrom(): array { |
|
117 | - return $this->swiftMessage->getFrom() ?? []; |
|
118 | - } |
|
119 | - |
|
120 | - /** |
|
121 | - * Set the Reply-To address of this message |
|
122 | - * |
|
123 | - * @param array $addresses |
|
124 | - * @return $this |
|
125 | - */ |
|
126 | - public function setReplyTo(array $addresses): IMessage { |
|
127 | - $addresses = $this->convertAddresses($addresses); |
|
128 | - |
|
129 | - $this->swiftMessage->setReplyTo($addresses); |
|
130 | - return $this; |
|
131 | - } |
|
132 | - |
|
133 | - /** |
|
134 | - * Returns the Reply-To address of this message |
|
135 | - * |
|
136 | - * @return string |
|
137 | - */ |
|
138 | - public function getReplyTo(): string { |
|
139 | - return $this->swiftMessage->getReplyTo(); |
|
140 | - } |
|
141 | - |
|
142 | - /** |
|
143 | - * Set the to addresses of this message. |
|
144 | - * |
|
145 | - * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name') |
|
146 | - * @return $this |
|
147 | - */ |
|
148 | - public function setTo(array $recipients): IMessage { |
|
149 | - $recipients = $this->convertAddresses($recipients); |
|
150 | - |
|
151 | - $this->swiftMessage->setTo($recipients); |
|
152 | - return $this; |
|
153 | - } |
|
154 | - |
|
155 | - /** |
|
156 | - * Get the to address of this message. |
|
157 | - * |
|
158 | - * @return array |
|
159 | - */ |
|
160 | - public function getTo(): array { |
|
161 | - return $this->swiftMessage->getTo() ?? []; |
|
162 | - } |
|
163 | - |
|
164 | - /** |
|
165 | - * Set the CC recipients of this message. |
|
166 | - * |
|
167 | - * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name') |
|
168 | - * @return $this |
|
169 | - */ |
|
170 | - public function setCc(array $recipients): IMessage { |
|
171 | - $recipients = $this->convertAddresses($recipients); |
|
172 | - |
|
173 | - $this->swiftMessage->setCc($recipients); |
|
174 | - return $this; |
|
175 | - } |
|
176 | - |
|
177 | - /** |
|
178 | - * Get the cc address of this message. |
|
179 | - * |
|
180 | - * @return array |
|
181 | - */ |
|
182 | - public function getCc(): array { |
|
183 | - return $this->swiftMessage->getCc() ?? []; |
|
184 | - } |
|
185 | - |
|
186 | - /** |
|
187 | - * Set the BCC recipients of this message. |
|
188 | - * |
|
189 | - * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name') |
|
190 | - * @return $this |
|
191 | - */ |
|
192 | - public function setBcc(array $recipients): IMessage { |
|
193 | - $recipients = $this->convertAddresses($recipients); |
|
194 | - |
|
195 | - $this->swiftMessage->setBcc($recipients); |
|
196 | - return $this; |
|
197 | - } |
|
198 | - |
|
199 | - /** |
|
200 | - * Get the Bcc address of this message. |
|
201 | - * |
|
202 | - * @return array |
|
203 | - */ |
|
204 | - public function getBcc(): array { |
|
205 | - return $this->swiftMessage->getBcc() ?? []; |
|
206 | - } |
|
207 | - |
|
208 | - /** |
|
209 | - * Set the subject of this message. |
|
210 | - * |
|
211 | - * @param string $subject |
|
212 | - * @return IMessage |
|
213 | - */ |
|
214 | - public function setSubject(string $subject): IMessage { |
|
215 | - $this->swiftMessage->setSubject($subject); |
|
216 | - return $this; |
|
217 | - } |
|
218 | - |
|
219 | - /** |
|
220 | - * Get the from subject of this message. |
|
221 | - * |
|
222 | - * @return string |
|
223 | - */ |
|
224 | - public function getSubject(): string { |
|
225 | - return $this->swiftMessage->getSubject(); |
|
226 | - } |
|
227 | - |
|
228 | - /** |
|
229 | - * Set the plain-text body of this message. |
|
230 | - * |
|
231 | - * @param string $body |
|
232 | - * @return $this |
|
233 | - */ |
|
234 | - public function setPlainBody(string $body): IMessage { |
|
235 | - $this->swiftMessage->setBody($body); |
|
236 | - return $this; |
|
237 | - } |
|
238 | - |
|
239 | - /** |
|
240 | - * Get the plain body of this message. |
|
241 | - * |
|
242 | - * @return string |
|
243 | - */ |
|
244 | - public function getPlainBody(): string { |
|
245 | - return $this->swiftMessage->getBody(); |
|
246 | - } |
|
247 | - |
|
248 | - /** |
|
249 | - * Set the HTML body of this message. Consider also sending a plain-text body instead of only an HTML one. |
|
250 | - * |
|
251 | - * @param string $body |
|
252 | - * @return $this |
|
253 | - */ |
|
254 | - public function setHtmlBody($body) { |
|
255 | - if (!$this->plainTextOnly) { |
|
256 | - $this->swiftMessage->addPart($body, 'text/html'); |
|
257 | - } |
|
258 | - return $this; |
|
259 | - } |
|
260 | - |
|
261 | - /** |
|
262 | - * Get's the underlying SwiftMessage |
|
263 | - * @param Swift_Message $swiftMessage |
|
264 | - */ |
|
265 | - public function setSwiftMessage(Swift_Message $swiftMessage): void { |
|
266 | - $this->swiftMessage = $swiftMessage; |
|
267 | - } |
|
268 | - |
|
269 | - /** |
|
270 | - * Get's the underlying SwiftMessage |
|
271 | - * @return Swift_Message |
|
272 | - */ |
|
273 | - public function getSwiftMessage(): Swift_Message { |
|
274 | - return $this->swiftMessage; |
|
275 | - } |
|
276 | - |
|
277 | - /** |
|
278 | - * @param string $body |
|
279 | - * @param string $contentType |
|
280 | - * @return $this |
|
281 | - */ |
|
282 | - public function setBody($body, $contentType) { |
|
283 | - if (!$this->plainTextOnly || $contentType !== 'text/html') { |
|
284 | - $this->swiftMessage->setBody($body, $contentType); |
|
285 | - } |
|
286 | - return $this; |
|
287 | - } |
|
288 | - |
|
289 | - /** |
|
290 | - * @param IEMailTemplate $emailTemplate |
|
291 | - * @return $this |
|
292 | - */ |
|
293 | - public function useTemplate(IEMailTemplate $emailTemplate): IMessage { |
|
294 | - $this->setSubject($emailTemplate->renderSubject()); |
|
295 | - $this->setPlainBody($emailTemplate->renderText()); |
|
296 | - if (!$this->plainTextOnly) { |
|
297 | - $this->setHtmlBody($emailTemplate->renderHtml()); |
|
298 | - } |
|
299 | - return $this; |
|
300 | - } |
|
46 | + /** @var Swift_Message */ |
|
47 | + private $swiftMessage; |
|
48 | + /** @var bool */ |
|
49 | + private $plainTextOnly; |
|
50 | + |
|
51 | + public function __construct(Swift_Message $swiftMessage, bool $plainTextOnly) { |
|
52 | + $this->swiftMessage = $swiftMessage; |
|
53 | + $this->plainTextOnly = $plainTextOnly; |
|
54 | + } |
|
55 | + |
|
56 | + /** |
|
57 | + * @param IAttachment $attachment |
|
58 | + * @return $this |
|
59 | + * @since 13.0.0 |
|
60 | + */ |
|
61 | + public function attach(IAttachment $attachment): IMessage { |
|
62 | + /** @var Attachment $attachment */ |
|
63 | + $this->swiftMessage->attach($attachment->getSwiftAttachment()); |
|
64 | + return $this; |
|
65 | + } |
|
66 | + |
|
67 | + /** |
|
68 | + * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains |
|
69 | + * FIXME: Remove this once SwiftMailer supports IDN |
|
70 | + * |
|
71 | + * @param array $addresses Array of mail addresses, key will get converted |
|
72 | + * @return array Converted addresses if `idn_to_ascii` exists |
|
73 | + */ |
|
74 | + protected function convertAddresses(array $addresses): array { |
|
75 | + if (!function_exists('idn_to_ascii') || !defined('INTL_IDNA_VARIANT_UTS46')) { |
|
76 | + return $addresses; |
|
77 | + } |
|
78 | + |
|
79 | + $convertedAddresses = []; |
|
80 | + |
|
81 | + foreach ($addresses as $email => $readableName) { |
|
82 | + if (!is_numeric($email)) { |
|
83 | + [$name, $domain] = explode('@', $email, 2); |
|
84 | + $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); |
|
85 | + $convertedAddresses[$name.'@'.$domain] = $readableName; |
|
86 | + } else { |
|
87 | + [$name, $domain] = explode('@', $readableName, 2); |
|
88 | + $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); |
|
89 | + $convertedAddresses[$email] = $name.'@'.$domain; |
|
90 | + } |
|
91 | + } |
|
92 | + |
|
93 | + return $convertedAddresses; |
|
94 | + } |
|
95 | + |
|
96 | + /** |
|
97 | + * Set the from address of this message. |
|
98 | + * |
|
99 | + * If no "From" address is used \OC\Mail\Mailer will use mail_from_address and mail_domain from config.php |
|
100 | + * |
|
101 | + * @param array $addresses Example: array('[email protected]', '[email protected]' => 'A name') |
|
102 | + * @return $this |
|
103 | + */ |
|
104 | + public function setFrom(array $addresses): IMessage { |
|
105 | + $addresses = $this->convertAddresses($addresses); |
|
106 | + |
|
107 | + $this->swiftMessage->setFrom($addresses); |
|
108 | + return $this; |
|
109 | + } |
|
110 | + |
|
111 | + /** |
|
112 | + * Get the from address of this message. |
|
113 | + * |
|
114 | + * @return array |
|
115 | + */ |
|
116 | + public function getFrom(): array { |
|
117 | + return $this->swiftMessage->getFrom() ?? []; |
|
118 | + } |
|
119 | + |
|
120 | + /** |
|
121 | + * Set the Reply-To address of this message |
|
122 | + * |
|
123 | + * @param array $addresses |
|
124 | + * @return $this |
|
125 | + */ |
|
126 | + public function setReplyTo(array $addresses): IMessage { |
|
127 | + $addresses = $this->convertAddresses($addresses); |
|
128 | + |
|
129 | + $this->swiftMessage->setReplyTo($addresses); |
|
130 | + return $this; |
|
131 | + } |
|
132 | + |
|
133 | + /** |
|
134 | + * Returns the Reply-To address of this message |
|
135 | + * |
|
136 | + * @return string |
|
137 | + */ |
|
138 | + public function getReplyTo(): string { |
|
139 | + return $this->swiftMessage->getReplyTo(); |
|
140 | + } |
|
141 | + |
|
142 | + /** |
|
143 | + * Set the to addresses of this message. |
|
144 | + * |
|
145 | + * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name') |
|
146 | + * @return $this |
|
147 | + */ |
|
148 | + public function setTo(array $recipients): IMessage { |
|
149 | + $recipients = $this->convertAddresses($recipients); |
|
150 | + |
|
151 | + $this->swiftMessage->setTo($recipients); |
|
152 | + return $this; |
|
153 | + } |
|
154 | + |
|
155 | + /** |
|
156 | + * Get the to address of this message. |
|
157 | + * |
|
158 | + * @return array |
|
159 | + */ |
|
160 | + public function getTo(): array { |
|
161 | + return $this->swiftMessage->getTo() ?? []; |
|
162 | + } |
|
163 | + |
|
164 | + /** |
|
165 | + * Set the CC recipients of this message. |
|
166 | + * |
|
167 | + * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name') |
|
168 | + * @return $this |
|
169 | + */ |
|
170 | + public function setCc(array $recipients): IMessage { |
|
171 | + $recipients = $this->convertAddresses($recipients); |
|
172 | + |
|
173 | + $this->swiftMessage->setCc($recipients); |
|
174 | + return $this; |
|
175 | + } |
|
176 | + |
|
177 | + /** |
|
178 | + * Get the cc address of this message. |
|
179 | + * |
|
180 | + * @return array |
|
181 | + */ |
|
182 | + public function getCc(): array { |
|
183 | + return $this->swiftMessage->getCc() ?? []; |
|
184 | + } |
|
185 | + |
|
186 | + /** |
|
187 | + * Set the BCC recipients of this message. |
|
188 | + * |
|
189 | + * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name') |
|
190 | + * @return $this |
|
191 | + */ |
|
192 | + public function setBcc(array $recipients): IMessage { |
|
193 | + $recipients = $this->convertAddresses($recipients); |
|
194 | + |
|
195 | + $this->swiftMessage->setBcc($recipients); |
|
196 | + return $this; |
|
197 | + } |
|
198 | + |
|
199 | + /** |
|
200 | + * Get the Bcc address of this message. |
|
201 | + * |
|
202 | + * @return array |
|
203 | + */ |
|
204 | + public function getBcc(): array { |
|
205 | + return $this->swiftMessage->getBcc() ?? []; |
|
206 | + } |
|
207 | + |
|
208 | + /** |
|
209 | + * Set the subject of this message. |
|
210 | + * |
|
211 | + * @param string $subject |
|
212 | + * @return IMessage |
|
213 | + */ |
|
214 | + public function setSubject(string $subject): IMessage { |
|
215 | + $this->swiftMessage->setSubject($subject); |
|
216 | + return $this; |
|
217 | + } |
|
218 | + |
|
219 | + /** |
|
220 | + * Get the from subject of this message. |
|
221 | + * |
|
222 | + * @return string |
|
223 | + */ |
|
224 | + public function getSubject(): string { |
|
225 | + return $this->swiftMessage->getSubject(); |
|
226 | + } |
|
227 | + |
|
228 | + /** |
|
229 | + * Set the plain-text body of this message. |
|
230 | + * |
|
231 | + * @param string $body |
|
232 | + * @return $this |
|
233 | + */ |
|
234 | + public function setPlainBody(string $body): IMessage { |
|
235 | + $this->swiftMessage->setBody($body); |
|
236 | + return $this; |
|
237 | + } |
|
238 | + |
|
239 | + /** |
|
240 | + * Get the plain body of this message. |
|
241 | + * |
|
242 | + * @return string |
|
243 | + */ |
|
244 | + public function getPlainBody(): string { |
|
245 | + return $this->swiftMessage->getBody(); |
|
246 | + } |
|
247 | + |
|
248 | + /** |
|
249 | + * Set the HTML body of this message. Consider also sending a plain-text body instead of only an HTML one. |
|
250 | + * |
|
251 | + * @param string $body |
|
252 | + * @return $this |
|
253 | + */ |
|
254 | + public function setHtmlBody($body) { |
|
255 | + if (!$this->plainTextOnly) { |
|
256 | + $this->swiftMessage->addPart($body, 'text/html'); |
|
257 | + } |
|
258 | + return $this; |
|
259 | + } |
|
260 | + |
|
261 | + /** |
|
262 | + * Get's the underlying SwiftMessage |
|
263 | + * @param Swift_Message $swiftMessage |
|
264 | + */ |
|
265 | + public function setSwiftMessage(Swift_Message $swiftMessage): void { |
|
266 | + $this->swiftMessage = $swiftMessage; |
|
267 | + } |
|
268 | + |
|
269 | + /** |
|
270 | + * Get's the underlying SwiftMessage |
|
271 | + * @return Swift_Message |
|
272 | + */ |
|
273 | + public function getSwiftMessage(): Swift_Message { |
|
274 | + return $this->swiftMessage; |
|
275 | + } |
|
276 | + |
|
277 | + /** |
|
278 | + * @param string $body |
|
279 | + * @param string $contentType |
|
280 | + * @return $this |
|
281 | + */ |
|
282 | + public function setBody($body, $contentType) { |
|
283 | + if (!$this->plainTextOnly || $contentType !== 'text/html') { |
|
284 | + $this->swiftMessage->setBody($body, $contentType); |
|
285 | + } |
|
286 | + return $this; |
|
287 | + } |
|
288 | + |
|
289 | + /** |
|
290 | + * @param IEMailTemplate $emailTemplate |
|
291 | + * @return $this |
|
292 | + */ |
|
293 | + public function useTemplate(IEMailTemplate $emailTemplate): IMessage { |
|
294 | + $this->setSubject($emailTemplate->renderSubject()); |
|
295 | + $this->setPlainBody($emailTemplate->renderText()); |
|
296 | + if (!$this->plainTextOnly) { |
|
297 | + $this->setHtmlBody($emailTemplate->renderHtml()); |
|
298 | + } |
|
299 | + return $this; |
|
300 | + } |
|
301 | 301 | } |
@@ -70,260 +70,260 @@ |
||
70 | 70 | * @package OC\Mail |
71 | 71 | */ |
72 | 72 | class Mailer implements IMailer { |
73 | - /** @var \Swift_Mailer Cached mailer */ |
|
74 | - private $instance = null; |
|
75 | - /** @var IConfig */ |
|
76 | - private $config; |
|
77 | - /** @var ILogger */ |
|
78 | - private $logger; |
|
79 | - /** @var Defaults */ |
|
80 | - private $defaults; |
|
81 | - /** @var IURLGenerator */ |
|
82 | - private $urlGenerator; |
|
83 | - /** @var IL10N */ |
|
84 | - private $l10n; |
|
85 | - /** @var IEventDispatcher */ |
|
86 | - private $dispatcher; |
|
87 | - /** @var IFactory */ |
|
88 | - private $l10nFactory; |
|
89 | - |
|
90 | - /** |
|
91 | - * @param IConfig $config |
|
92 | - * @param ILogger $logger |
|
93 | - * @param Defaults $defaults |
|
94 | - * @param IURLGenerator $urlGenerator |
|
95 | - * @param IL10N $l10n |
|
96 | - * @param IEventDispatcher $dispatcher |
|
97 | - */ |
|
98 | - public function __construct(IConfig $config, |
|
99 | - ILogger $logger, |
|
100 | - Defaults $defaults, |
|
101 | - IURLGenerator $urlGenerator, |
|
102 | - IL10N $l10n, |
|
103 | - IEventDispatcher $dispatcher, |
|
104 | - IFactory $l10nFactory) { |
|
105 | - $this->config = $config; |
|
106 | - $this->logger = $logger; |
|
107 | - $this->defaults = $defaults; |
|
108 | - $this->urlGenerator = $urlGenerator; |
|
109 | - $this->l10n = $l10n; |
|
110 | - $this->dispatcher = $dispatcher; |
|
111 | - $this->l10nFactory = $l10nFactory; |
|
112 | - } |
|
113 | - |
|
114 | - /** |
|
115 | - * Creates a new message object that can be passed to send() |
|
116 | - * |
|
117 | - * @return IMessage |
|
118 | - */ |
|
119 | - public function createMessage(): IMessage { |
|
120 | - $plainTextOnly = $this->config->getSystemValue('mail_send_plaintext_only', false); |
|
121 | - return new Message(new \Swift_Message(), $plainTextOnly); |
|
122 | - } |
|
123 | - |
|
124 | - /** |
|
125 | - * @param string|null $data |
|
126 | - * @param string|null $filename |
|
127 | - * @param string|null $contentType |
|
128 | - * @return IAttachment |
|
129 | - * @since 13.0.0 |
|
130 | - */ |
|
131 | - public function createAttachment($data = null, $filename = null, $contentType = null): IAttachment { |
|
132 | - return new Attachment(new \Swift_Attachment($data, $filename, $contentType)); |
|
133 | - } |
|
134 | - |
|
135 | - /** |
|
136 | - * @param string $path |
|
137 | - * @param string|null $contentType |
|
138 | - * @return IAttachment |
|
139 | - * @since 13.0.0 |
|
140 | - */ |
|
141 | - public function createAttachmentFromPath(string $path, $contentType = null): IAttachment { |
|
142 | - return new Attachment(\Swift_Attachment::fromPath($path, $contentType)); |
|
143 | - } |
|
144 | - |
|
145 | - /** |
|
146 | - * Creates a new email template object |
|
147 | - * |
|
148 | - * @param string $emailId |
|
149 | - * @param array $data |
|
150 | - * @return IEMailTemplate |
|
151 | - * @since 12.0.0 |
|
152 | - */ |
|
153 | - public function createEMailTemplate(string $emailId, array $data = []): IEMailTemplate { |
|
154 | - $class = $this->config->getSystemValue('mail_template_class', ''); |
|
155 | - |
|
156 | - if ($class !== '' && class_exists($class) && is_a($class, EMailTemplate::class, true)) { |
|
157 | - return new $class( |
|
158 | - $this->defaults, |
|
159 | - $this->urlGenerator, |
|
160 | - $this->l10nFactory, |
|
161 | - $emailId, |
|
162 | - $data |
|
163 | - ); |
|
164 | - } |
|
165 | - |
|
166 | - return new EMailTemplate( |
|
167 | - $this->defaults, |
|
168 | - $this->urlGenerator, |
|
169 | - $this->l10nFactory, |
|
170 | - $emailId, |
|
171 | - $data |
|
172 | - ); |
|
173 | - } |
|
174 | - |
|
175 | - /** |
|
176 | - * Send the specified message. Also sets the from address to the value defined in config.php |
|
177 | - * if no-one has been passed. |
|
178 | - * |
|
179 | - * @param IMessage|Message $message Message to send |
|
180 | - * @return string[] Array with failed recipients. Be aware that this depends on the used mail backend and |
|
181 | - * therefore should be considered |
|
182 | - * @throws \Exception In case it was not possible to send the message. (for example if an invalid mail address |
|
183 | - * has been supplied.) |
|
184 | - */ |
|
185 | - public function send(IMessage $message): array { |
|
186 | - $debugMode = $this->config->getSystemValue('mail_smtpdebug', false); |
|
187 | - |
|
188 | - if (empty($message->getFrom())) { |
|
189 | - $message->setFrom([\OCP\Util::getDefaultEmailAddress('no-reply') => $this->defaults->getName()]); |
|
190 | - } |
|
191 | - |
|
192 | - $failedRecipients = []; |
|
193 | - |
|
194 | - $mailer = $this->getInstance(); |
|
195 | - |
|
196 | - // Enable logger if debug mode is enabled |
|
197 | - if ($debugMode) { |
|
198 | - $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger(); |
|
199 | - $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger)); |
|
200 | - } |
|
201 | - |
|
202 | - |
|
203 | - $this->dispatcher->dispatchTyped(new BeforeMessageSent($message)); |
|
204 | - |
|
205 | - $mailer->send($message->getSwiftMessage(), $failedRecipients); |
|
206 | - |
|
207 | - // Debugging logging |
|
208 | - $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject()); |
|
209 | - $this->logger->debug($logMessage, ['app' => 'core']); |
|
210 | - if ($debugMode && isset($mailLogger)) { |
|
211 | - $this->logger->debug($mailLogger->dump(), ['app' => 'core']); |
|
212 | - } |
|
213 | - |
|
214 | - return $failedRecipients; |
|
215 | - } |
|
216 | - |
|
217 | - /** |
|
218 | - * Checks if an e-mail address is valid |
|
219 | - * |
|
220 | - * @param string $email Email address to be validated |
|
221 | - * @return bool True if the mail address is valid, false otherwise |
|
222 | - */ |
|
223 | - public function validateMailAddress(string $email): bool { |
|
224 | - if ($email === '') { |
|
225 | - // Shortcut: empty addresses are never valid |
|
226 | - return false; |
|
227 | - } |
|
228 | - $validator = new EmailValidator(); |
|
229 | - $validation = new RFCValidation(); |
|
230 | - |
|
231 | - return $validator->isValid($this->convertEmail($email), $validation); |
|
232 | - } |
|
233 | - |
|
234 | - /** |
|
235 | - * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains |
|
236 | - * |
|
237 | - * FIXME: Remove this once SwiftMailer supports IDN |
|
238 | - * |
|
239 | - * @param string $email |
|
240 | - * @return string Converted mail address if `idn_to_ascii` exists |
|
241 | - */ |
|
242 | - protected function convertEmail(string $email): string { |
|
243 | - if (!function_exists('idn_to_ascii') || !defined('INTL_IDNA_VARIANT_UTS46') || strpos($email, '@') === false) { |
|
244 | - return $email; |
|
245 | - } |
|
246 | - |
|
247 | - [$name, $domain] = explode('@', $email, 2); |
|
248 | - $domain = idn_to_ascii($domain, 0,INTL_IDNA_VARIANT_UTS46); |
|
249 | - return $name.'@'.$domain; |
|
250 | - } |
|
251 | - |
|
252 | - protected function getInstance(): \Swift_Mailer { |
|
253 | - if (!is_null($this->instance)) { |
|
254 | - return $this->instance; |
|
255 | - } |
|
256 | - |
|
257 | - $transport = null; |
|
258 | - |
|
259 | - switch ($this->config->getSystemValue('mail_smtpmode', 'smtp')) { |
|
260 | - case 'sendmail': |
|
261 | - $transport = $this->getSendMailInstance(); |
|
262 | - break; |
|
263 | - case 'smtp': |
|
264 | - default: |
|
265 | - $transport = $this->getSmtpInstance(); |
|
266 | - break; |
|
267 | - } |
|
268 | - |
|
269 | - return new \Swift_Mailer($transport); |
|
270 | - } |
|
271 | - |
|
272 | - /** |
|
273 | - * Returns the SMTP transport |
|
274 | - * |
|
275 | - * @return \Swift_SmtpTransport |
|
276 | - */ |
|
277 | - protected function getSmtpInstance(): \Swift_SmtpTransport { |
|
278 | - $transport = new \Swift_SmtpTransport(); |
|
279 | - $transport->setTimeout($this->config->getSystemValue('mail_smtptimeout', 10)); |
|
280 | - $transport->setHost($this->config->getSystemValue('mail_smtphost', '127.0.0.1')); |
|
281 | - $transport->setPort($this->config->getSystemValue('mail_smtpport', 25)); |
|
282 | - if ($this->config->getSystemValue('mail_smtpauth', false)) { |
|
283 | - $transport->setUsername($this->config->getSystemValue('mail_smtpname', '')); |
|
284 | - $transport->setPassword($this->config->getSystemValue('mail_smtppassword', '')); |
|
285 | - $transport->setAuthMode($this->config->getSystemValue('mail_smtpauthtype', 'LOGIN')); |
|
286 | - } |
|
287 | - $smtpSecurity = $this->config->getSystemValue('mail_smtpsecure', ''); |
|
288 | - if (!empty($smtpSecurity)) { |
|
289 | - $transport->setEncryption($smtpSecurity); |
|
290 | - } |
|
291 | - $streamingOptions = $this->config->getSystemValue('mail_smtpstreamoptions', []); |
|
292 | - if (is_array($streamingOptions) && !empty($streamingOptions)) { |
|
293 | - $transport->setStreamOptions($streamingOptions); |
|
294 | - } |
|
295 | - |
|
296 | - return $transport; |
|
297 | - } |
|
298 | - |
|
299 | - /** |
|
300 | - * Returns the sendmail transport |
|
301 | - * |
|
302 | - * @return \Swift_SendmailTransport |
|
303 | - */ |
|
304 | - protected function getSendMailInstance(): \Swift_SendmailTransport { |
|
305 | - switch ($this->config->getSystemValue('mail_smtpmode', 'smtp')) { |
|
306 | - case 'qmail': |
|
307 | - $binaryPath = '/var/qmail/bin/sendmail'; |
|
308 | - break; |
|
309 | - default: |
|
310 | - $sendmail = \OC_Helper::findBinaryPath('sendmail'); |
|
311 | - if ($sendmail === null) { |
|
312 | - $sendmail = '/usr/sbin/sendmail'; |
|
313 | - } |
|
314 | - $binaryPath = $sendmail; |
|
315 | - break; |
|
316 | - } |
|
317 | - |
|
318 | - switch ($this->config->getSystemValue('mail_sendmailmode', 'smtp')) { |
|
319 | - case 'pipe': |
|
320 | - $binaryParam = ' -t'; |
|
321 | - break; |
|
322 | - default: |
|
323 | - $binaryParam = ' -bs'; |
|
324 | - break; |
|
325 | - } |
|
326 | - |
|
327 | - return new \Swift_SendmailTransport($binaryPath . $binaryParam); |
|
328 | - } |
|
73 | + /** @var \Swift_Mailer Cached mailer */ |
|
74 | + private $instance = null; |
|
75 | + /** @var IConfig */ |
|
76 | + private $config; |
|
77 | + /** @var ILogger */ |
|
78 | + private $logger; |
|
79 | + /** @var Defaults */ |
|
80 | + private $defaults; |
|
81 | + /** @var IURLGenerator */ |
|
82 | + private $urlGenerator; |
|
83 | + /** @var IL10N */ |
|
84 | + private $l10n; |
|
85 | + /** @var IEventDispatcher */ |
|
86 | + private $dispatcher; |
|
87 | + /** @var IFactory */ |
|
88 | + private $l10nFactory; |
|
89 | + |
|
90 | + /** |
|
91 | + * @param IConfig $config |
|
92 | + * @param ILogger $logger |
|
93 | + * @param Defaults $defaults |
|
94 | + * @param IURLGenerator $urlGenerator |
|
95 | + * @param IL10N $l10n |
|
96 | + * @param IEventDispatcher $dispatcher |
|
97 | + */ |
|
98 | + public function __construct(IConfig $config, |
|
99 | + ILogger $logger, |
|
100 | + Defaults $defaults, |
|
101 | + IURLGenerator $urlGenerator, |
|
102 | + IL10N $l10n, |
|
103 | + IEventDispatcher $dispatcher, |
|
104 | + IFactory $l10nFactory) { |
|
105 | + $this->config = $config; |
|
106 | + $this->logger = $logger; |
|
107 | + $this->defaults = $defaults; |
|
108 | + $this->urlGenerator = $urlGenerator; |
|
109 | + $this->l10n = $l10n; |
|
110 | + $this->dispatcher = $dispatcher; |
|
111 | + $this->l10nFactory = $l10nFactory; |
|
112 | + } |
|
113 | + |
|
114 | + /** |
|
115 | + * Creates a new message object that can be passed to send() |
|
116 | + * |
|
117 | + * @return IMessage |
|
118 | + */ |
|
119 | + public function createMessage(): IMessage { |
|
120 | + $plainTextOnly = $this->config->getSystemValue('mail_send_plaintext_only', false); |
|
121 | + return new Message(new \Swift_Message(), $plainTextOnly); |
|
122 | + } |
|
123 | + |
|
124 | + /** |
|
125 | + * @param string|null $data |
|
126 | + * @param string|null $filename |
|
127 | + * @param string|null $contentType |
|
128 | + * @return IAttachment |
|
129 | + * @since 13.0.0 |
|
130 | + */ |
|
131 | + public function createAttachment($data = null, $filename = null, $contentType = null): IAttachment { |
|
132 | + return new Attachment(new \Swift_Attachment($data, $filename, $contentType)); |
|
133 | + } |
|
134 | + |
|
135 | + /** |
|
136 | + * @param string $path |
|
137 | + * @param string|null $contentType |
|
138 | + * @return IAttachment |
|
139 | + * @since 13.0.0 |
|
140 | + */ |
|
141 | + public function createAttachmentFromPath(string $path, $contentType = null): IAttachment { |
|
142 | + return new Attachment(\Swift_Attachment::fromPath($path, $contentType)); |
|
143 | + } |
|
144 | + |
|
145 | + /** |
|
146 | + * Creates a new email template object |
|
147 | + * |
|
148 | + * @param string $emailId |
|
149 | + * @param array $data |
|
150 | + * @return IEMailTemplate |
|
151 | + * @since 12.0.0 |
|
152 | + */ |
|
153 | + public function createEMailTemplate(string $emailId, array $data = []): IEMailTemplate { |
|
154 | + $class = $this->config->getSystemValue('mail_template_class', ''); |
|
155 | + |
|
156 | + if ($class !== '' && class_exists($class) && is_a($class, EMailTemplate::class, true)) { |
|
157 | + return new $class( |
|
158 | + $this->defaults, |
|
159 | + $this->urlGenerator, |
|
160 | + $this->l10nFactory, |
|
161 | + $emailId, |
|
162 | + $data |
|
163 | + ); |
|
164 | + } |
|
165 | + |
|
166 | + return new EMailTemplate( |
|
167 | + $this->defaults, |
|
168 | + $this->urlGenerator, |
|
169 | + $this->l10nFactory, |
|
170 | + $emailId, |
|
171 | + $data |
|
172 | + ); |
|
173 | + } |
|
174 | + |
|
175 | + /** |
|
176 | + * Send the specified message. Also sets the from address to the value defined in config.php |
|
177 | + * if no-one has been passed. |
|
178 | + * |
|
179 | + * @param IMessage|Message $message Message to send |
|
180 | + * @return string[] Array with failed recipients. Be aware that this depends on the used mail backend and |
|
181 | + * therefore should be considered |
|
182 | + * @throws \Exception In case it was not possible to send the message. (for example if an invalid mail address |
|
183 | + * has been supplied.) |
|
184 | + */ |
|
185 | + public function send(IMessage $message): array { |
|
186 | + $debugMode = $this->config->getSystemValue('mail_smtpdebug', false); |
|
187 | + |
|
188 | + if (empty($message->getFrom())) { |
|
189 | + $message->setFrom([\OCP\Util::getDefaultEmailAddress('no-reply') => $this->defaults->getName()]); |
|
190 | + } |
|
191 | + |
|
192 | + $failedRecipients = []; |
|
193 | + |
|
194 | + $mailer = $this->getInstance(); |
|
195 | + |
|
196 | + // Enable logger if debug mode is enabled |
|
197 | + if ($debugMode) { |
|
198 | + $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger(); |
|
199 | + $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger)); |
|
200 | + } |
|
201 | + |
|
202 | + |
|
203 | + $this->dispatcher->dispatchTyped(new BeforeMessageSent($message)); |
|
204 | + |
|
205 | + $mailer->send($message->getSwiftMessage(), $failedRecipients); |
|
206 | + |
|
207 | + // Debugging logging |
|
208 | + $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject()); |
|
209 | + $this->logger->debug($logMessage, ['app' => 'core']); |
|
210 | + if ($debugMode && isset($mailLogger)) { |
|
211 | + $this->logger->debug($mailLogger->dump(), ['app' => 'core']); |
|
212 | + } |
|
213 | + |
|
214 | + return $failedRecipients; |
|
215 | + } |
|
216 | + |
|
217 | + /** |
|
218 | + * Checks if an e-mail address is valid |
|
219 | + * |
|
220 | + * @param string $email Email address to be validated |
|
221 | + * @return bool True if the mail address is valid, false otherwise |
|
222 | + */ |
|
223 | + public function validateMailAddress(string $email): bool { |
|
224 | + if ($email === '') { |
|
225 | + // Shortcut: empty addresses are never valid |
|
226 | + return false; |
|
227 | + } |
|
228 | + $validator = new EmailValidator(); |
|
229 | + $validation = new RFCValidation(); |
|
230 | + |
|
231 | + return $validator->isValid($this->convertEmail($email), $validation); |
|
232 | + } |
|
233 | + |
|
234 | + /** |
|
235 | + * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains |
|
236 | + * |
|
237 | + * FIXME: Remove this once SwiftMailer supports IDN |
|
238 | + * |
|
239 | + * @param string $email |
|
240 | + * @return string Converted mail address if `idn_to_ascii` exists |
|
241 | + */ |
|
242 | + protected function convertEmail(string $email): string { |
|
243 | + if (!function_exists('idn_to_ascii') || !defined('INTL_IDNA_VARIANT_UTS46') || strpos($email, '@') === false) { |
|
244 | + return $email; |
|
245 | + } |
|
246 | + |
|
247 | + [$name, $domain] = explode('@', $email, 2); |
|
248 | + $domain = idn_to_ascii($domain, 0,INTL_IDNA_VARIANT_UTS46); |
|
249 | + return $name.'@'.$domain; |
|
250 | + } |
|
251 | + |
|
252 | + protected function getInstance(): \Swift_Mailer { |
|
253 | + if (!is_null($this->instance)) { |
|
254 | + return $this->instance; |
|
255 | + } |
|
256 | + |
|
257 | + $transport = null; |
|
258 | + |
|
259 | + switch ($this->config->getSystemValue('mail_smtpmode', 'smtp')) { |
|
260 | + case 'sendmail': |
|
261 | + $transport = $this->getSendMailInstance(); |
|
262 | + break; |
|
263 | + case 'smtp': |
|
264 | + default: |
|
265 | + $transport = $this->getSmtpInstance(); |
|
266 | + break; |
|
267 | + } |
|
268 | + |
|
269 | + return new \Swift_Mailer($transport); |
|
270 | + } |
|
271 | + |
|
272 | + /** |
|
273 | + * Returns the SMTP transport |
|
274 | + * |
|
275 | + * @return \Swift_SmtpTransport |
|
276 | + */ |
|
277 | + protected function getSmtpInstance(): \Swift_SmtpTransport { |
|
278 | + $transport = new \Swift_SmtpTransport(); |
|
279 | + $transport->setTimeout($this->config->getSystemValue('mail_smtptimeout', 10)); |
|
280 | + $transport->setHost($this->config->getSystemValue('mail_smtphost', '127.0.0.1')); |
|
281 | + $transport->setPort($this->config->getSystemValue('mail_smtpport', 25)); |
|
282 | + if ($this->config->getSystemValue('mail_smtpauth', false)) { |
|
283 | + $transport->setUsername($this->config->getSystemValue('mail_smtpname', '')); |
|
284 | + $transport->setPassword($this->config->getSystemValue('mail_smtppassword', '')); |
|
285 | + $transport->setAuthMode($this->config->getSystemValue('mail_smtpauthtype', 'LOGIN')); |
|
286 | + } |
|
287 | + $smtpSecurity = $this->config->getSystemValue('mail_smtpsecure', ''); |
|
288 | + if (!empty($smtpSecurity)) { |
|
289 | + $transport->setEncryption($smtpSecurity); |
|
290 | + } |
|
291 | + $streamingOptions = $this->config->getSystemValue('mail_smtpstreamoptions', []); |
|
292 | + if (is_array($streamingOptions) && !empty($streamingOptions)) { |
|
293 | + $transport->setStreamOptions($streamingOptions); |
|
294 | + } |
|
295 | + |
|
296 | + return $transport; |
|
297 | + } |
|
298 | + |
|
299 | + /** |
|
300 | + * Returns the sendmail transport |
|
301 | + * |
|
302 | + * @return \Swift_SendmailTransport |
|
303 | + */ |
|
304 | + protected function getSendMailInstance(): \Swift_SendmailTransport { |
|
305 | + switch ($this->config->getSystemValue('mail_smtpmode', 'smtp')) { |
|
306 | + case 'qmail': |
|
307 | + $binaryPath = '/var/qmail/bin/sendmail'; |
|
308 | + break; |
|
309 | + default: |
|
310 | + $sendmail = \OC_Helper::findBinaryPath('sendmail'); |
|
311 | + if ($sendmail === null) { |
|
312 | + $sendmail = '/usr/sbin/sendmail'; |
|
313 | + } |
|
314 | + $binaryPath = $sendmail; |
|
315 | + break; |
|
316 | + } |
|
317 | + |
|
318 | + switch ($this->config->getSystemValue('mail_sendmailmode', 'smtp')) { |
|
319 | + case 'pipe': |
|
320 | + $binaryParam = ' -t'; |
|
321 | + break; |
|
322 | + default: |
|
323 | + $binaryParam = ' -bs'; |
|
324 | + break; |
|
325 | + } |
|
326 | + |
|
327 | + return new \Swift_SendmailTransport($binaryPath . $binaryParam); |
|
328 | + } |
|
329 | 329 | } |
@@ -245,7 +245,7 @@ discard block |
||
245 | 245 | } |
246 | 246 | |
247 | 247 | [$name, $domain] = explode('@', $email, 2); |
248 | - $domain = idn_to_ascii($domain, 0,INTL_IDNA_VARIANT_UTS46); |
|
248 | + $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); |
|
249 | 249 | return $name.'@'.$domain; |
250 | 250 | } |
251 | 251 | |
@@ -324,6 +324,6 @@ discard block |
||
324 | 324 | break; |
325 | 325 | } |
326 | 326 | |
327 | - return new \Swift_SendmailTransport($binaryPath . $binaryParam); |
|
327 | + return new \Swift_SendmailTransport($binaryPath.$binaryParam); |
|
328 | 328 | } |
329 | 329 | } |
@@ -38,135 +38,135 @@ |
||
38 | 38 | use OCP\Security\ICrypto; |
39 | 39 | |
40 | 40 | class Manager { |
41 | - /** @var IAppData */ |
|
42 | - private $appData; |
|
43 | - /** @var ICrypto */ |
|
44 | - private $crypto; |
|
45 | - /** @var IConfig */ |
|
46 | - private $config; |
|
47 | - /** @var ILogger */ |
|
48 | - private $logger; |
|
49 | - |
|
50 | - public function __construct(Factory $appDataFactory, |
|
51 | - ICrypto $crypto, |
|
52 | - IConfig $config, |
|
53 | - ILogger $logger |
|
54 | - ) { |
|
55 | - $this->appData = $appDataFactory->get('identityproof'); |
|
56 | - $this->crypto = $crypto; |
|
57 | - $this->config = $config; |
|
58 | - $this->logger = $logger; |
|
59 | - } |
|
60 | - |
|
61 | - /** |
|
62 | - * Calls the openssl functions to generate a public and private key. |
|
63 | - * In a separate function for unit testing purposes. |
|
64 | - * |
|
65 | - * @return array [$publicKey, $privateKey] |
|
66 | - * @throws \RuntimeException |
|
67 | - */ |
|
68 | - protected function generateKeyPair(): array { |
|
69 | - $config = [ |
|
70 | - 'digest_alg' => 'sha512', |
|
71 | - 'private_key_bits' => 2048, |
|
72 | - ]; |
|
73 | - |
|
74 | - // Generate new key |
|
75 | - $res = openssl_pkey_new($config); |
|
76 | - |
|
77 | - if ($res === false) { |
|
78 | - $this->logOpensslError(); |
|
79 | - throw new \RuntimeException('OpenSSL reported a problem'); |
|
80 | - } |
|
81 | - |
|
82 | - if (openssl_pkey_export($res, $privateKey, null, $config) === false) { |
|
83 | - $this->logOpensslError(); |
|
84 | - throw new \RuntimeException('OpenSSL reported a problem'); |
|
85 | - } |
|
86 | - |
|
87 | - // Extract the public key from $res to $pubKey |
|
88 | - $publicKey = openssl_pkey_get_details($res); |
|
89 | - $publicKey = $publicKey['key']; |
|
90 | - |
|
91 | - return [$publicKey, $privateKey]; |
|
92 | - } |
|
93 | - |
|
94 | - /** |
|
95 | - * Generate a key for a given ID |
|
96 | - * Note: If a key already exists it will be overwritten |
|
97 | - * |
|
98 | - * @param string $id key id |
|
99 | - * @return Key |
|
100 | - * @throws \RuntimeException |
|
101 | - */ |
|
102 | - protected function generateKey(string $id): Key { |
|
103 | - [$publicKey, $privateKey] = $this->generateKeyPair(); |
|
104 | - |
|
105 | - // Write the private and public key to the disk |
|
106 | - try { |
|
107 | - $this->appData->newFolder($id); |
|
108 | - } catch (\Exception $e) { |
|
109 | - } |
|
110 | - $folder = $this->appData->getFolder($id); |
|
111 | - $folder->newFile('private') |
|
112 | - ->putContent($this->crypto->encrypt($privateKey)); |
|
113 | - $folder->newFile('public') |
|
114 | - ->putContent($publicKey); |
|
115 | - |
|
116 | - return new Key($publicKey, $privateKey); |
|
117 | - } |
|
118 | - |
|
119 | - /** |
|
120 | - * Get key for a specific id |
|
121 | - * |
|
122 | - * @param string $id |
|
123 | - * @return Key |
|
124 | - * @throws \RuntimeException |
|
125 | - */ |
|
126 | - protected function retrieveKey(string $id): Key { |
|
127 | - try { |
|
128 | - $folder = $this->appData->getFolder($id); |
|
129 | - $privateKey = $this->crypto->decrypt( |
|
130 | - $folder->getFile('private')->getContent() |
|
131 | - ); |
|
132 | - $publicKey = $folder->getFile('public')->getContent(); |
|
133 | - return new Key($publicKey, $privateKey); |
|
134 | - } catch (\Exception $e) { |
|
135 | - return $this->generateKey($id); |
|
136 | - } |
|
137 | - } |
|
138 | - |
|
139 | - /** |
|
140 | - * Get public and private key for $user |
|
141 | - * |
|
142 | - * @param IUser $user |
|
143 | - * @return Key |
|
144 | - * @throws \RuntimeException |
|
145 | - */ |
|
146 | - public function getKey(IUser $user): Key { |
|
147 | - $uid = $user->getUID(); |
|
148 | - return $this->retrieveKey('user-' . $uid); |
|
149 | - } |
|
150 | - |
|
151 | - /** |
|
152 | - * Get instance wide public and private key |
|
153 | - * |
|
154 | - * @return Key |
|
155 | - * @throws \RuntimeException |
|
156 | - */ |
|
157 | - public function getSystemKey(): Key { |
|
158 | - $instanceId = $this->config->getSystemValue('instanceid', null); |
|
159 | - if ($instanceId === null) { |
|
160 | - throw new \RuntimeException('no instance id!'); |
|
161 | - } |
|
162 | - return $this->retrieveKey('system-' . $instanceId); |
|
163 | - } |
|
164 | - |
|
165 | - private function logOpensslError(): void { |
|
166 | - $errors = []; |
|
167 | - while ($error = openssl_error_string()) { |
|
168 | - $errors[] = $error; |
|
169 | - } |
|
170 | - $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors)); |
|
171 | - } |
|
41 | + /** @var IAppData */ |
|
42 | + private $appData; |
|
43 | + /** @var ICrypto */ |
|
44 | + private $crypto; |
|
45 | + /** @var IConfig */ |
|
46 | + private $config; |
|
47 | + /** @var ILogger */ |
|
48 | + private $logger; |
|
49 | + |
|
50 | + public function __construct(Factory $appDataFactory, |
|
51 | + ICrypto $crypto, |
|
52 | + IConfig $config, |
|
53 | + ILogger $logger |
|
54 | + ) { |
|
55 | + $this->appData = $appDataFactory->get('identityproof'); |
|
56 | + $this->crypto = $crypto; |
|
57 | + $this->config = $config; |
|
58 | + $this->logger = $logger; |
|
59 | + } |
|
60 | + |
|
61 | + /** |
|
62 | + * Calls the openssl functions to generate a public and private key. |
|
63 | + * In a separate function for unit testing purposes. |
|
64 | + * |
|
65 | + * @return array [$publicKey, $privateKey] |
|
66 | + * @throws \RuntimeException |
|
67 | + */ |
|
68 | + protected function generateKeyPair(): array { |
|
69 | + $config = [ |
|
70 | + 'digest_alg' => 'sha512', |
|
71 | + 'private_key_bits' => 2048, |
|
72 | + ]; |
|
73 | + |
|
74 | + // Generate new key |
|
75 | + $res = openssl_pkey_new($config); |
|
76 | + |
|
77 | + if ($res === false) { |
|
78 | + $this->logOpensslError(); |
|
79 | + throw new \RuntimeException('OpenSSL reported a problem'); |
|
80 | + } |
|
81 | + |
|
82 | + if (openssl_pkey_export($res, $privateKey, null, $config) === false) { |
|
83 | + $this->logOpensslError(); |
|
84 | + throw new \RuntimeException('OpenSSL reported a problem'); |
|
85 | + } |
|
86 | + |
|
87 | + // Extract the public key from $res to $pubKey |
|
88 | + $publicKey = openssl_pkey_get_details($res); |
|
89 | + $publicKey = $publicKey['key']; |
|
90 | + |
|
91 | + return [$publicKey, $privateKey]; |
|
92 | + } |
|
93 | + |
|
94 | + /** |
|
95 | + * Generate a key for a given ID |
|
96 | + * Note: If a key already exists it will be overwritten |
|
97 | + * |
|
98 | + * @param string $id key id |
|
99 | + * @return Key |
|
100 | + * @throws \RuntimeException |
|
101 | + */ |
|
102 | + protected function generateKey(string $id): Key { |
|
103 | + [$publicKey, $privateKey] = $this->generateKeyPair(); |
|
104 | + |
|
105 | + // Write the private and public key to the disk |
|
106 | + try { |
|
107 | + $this->appData->newFolder($id); |
|
108 | + } catch (\Exception $e) { |
|
109 | + } |
|
110 | + $folder = $this->appData->getFolder($id); |
|
111 | + $folder->newFile('private') |
|
112 | + ->putContent($this->crypto->encrypt($privateKey)); |
|
113 | + $folder->newFile('public') |
|
114 | + ->putContent($publicKey); |
|
115 | + |
|
116 | + return new Key($publicKey, $privateKey); |
|
117 | + } |
|
118 | + |
|
119 | + /** |
|
120 | + * Get key for a specific id |
|
121 | + * |
|
122 | + * @param string $id |
|
123 | + * @return Key |
|
124 | + * @throws \RuntimeException |
|
125 | + */ |
|
126 | + protected function retrieveKey(string $id): Key { |
|
127 | + try { |
|
128 | + $folder = $this->appData->getFolder($id); |
|
129 | + $privateKey = $this->crypto->decrypt( |
|
130 | + $folder->getFile('private')->getContent() |
|
131 | + ); |
|
132 | + $publicKey = $folder->getFile('public')->getContent(); |
|
133 | + return new Key($publicKey, $privateKey); |
|
134 | + } catch (\Exception $e) { |
|
135 | + return $this->generateKey($id); |
|
136 | + } |
|
137 | + } |
|
138 | + |
|
139 | + /** |
|
140 | + * Get public and private key for $user |
|
141 | + * |
|
142 | + * @param IUser $user |
|
143 | + * @return Key |
|
144 | + * @throws \RuntimeException |
|
145 | + */ |
|
146 | + public function getKey(IUser $user): Key { |
|
147 | + $uid = $user->getUID(); |
|
148 | + return $this->retrieveKey('user-' . $uid); |
|
149 | + } |
|
150 | + |
|
151 | + /** |
|
152 | + * Get instance wide public and private key |
|
153 | + * |
|
154 | + * @return Key |
|
155 | + * @throws \RuntimeException |
|
156 | + */ |
|
157 | + public function getSystemKey(): Key { |
|
158 | + $instanceId = $this->config->getSystemValue('instanceid', null); |
|
159 | + if ($instanceId === null) { |
|
160 | + throw new \RuntimeException('no instance id!'); |
|
161 | + } |
|
162 | + return $this->retrieveKey('system-' . $instanceId); |
|
163 | + } |
|
164 | + |
|
165 | + private function logOpensslError(): void { |
|
166 | + $errors = []; |
|
167 | + while ($error = openssl_error_string()) { |
|
168 | + $errors[] = $error; |
|
169 | + } |
|
170 | + $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors)); |
|
171 | + } |
|
172 | 172 | } |
@@ -28,55 +28,55 @@ |
||
28 | 28 | use OCP\DB\QueryBuilder\IQueryFunction; |
29 | 29 | |
30 | 30 | class QuoteHelper { |
31 | - /** |
|
32 | - * @param array|string|ILiteral|IParameter|IQueryFunction $strings string, Literal or Parameter |
|
33 | - * @return array|string |
|
34 | - */ |
|
35 | - public function quoteColumnNames($strings) { |
|
36 | - if (!is_array($strings)) { |
|
37 | - return $this->quoteColumnName($strings); |
|
38 | - } |
|
31 | + /** |
|
32 | + * @param array|string|ILiteral|IParameter|IQueryFunction $strings string, Literal or Parameter |
|
33 | + * @return array|string |
|
34 | + */ |
|
35 | + public function quoteColumnNames($strings) { |
|
36 | + if (!is_array($strings)) { |
|
37 | + return $this->quoteColumnName($strings); |
|
38 | + } |
|
39 | 39 | |
40 | - $return = []; |
|
41 | - foreach ($strings as $string) { |
|
42 | - $return[] = $this->quoteColumnName($string); |
|
43 | - } |
|
40 | + $return = []; |
|
41 | + foreach ($strings as $string) { |
|
42 | + $return[] = $this->quoteColumnName($string); |
|
43 | + } |
|
44 | 44 | |
45 | - return $return; |
|
46 | - } |
|
45 | + return $return; |
|
46 | + } |
|
47 | 47 | |
48 | - /** |
|
49 | - * @param string|ILiteral|IParameter|IQueryFunction $string string, Literal or Parameter |
|
50 | - * @return string |
|
51 | - */ |
|
52 | - public function quoteColumnName($string) { |
|
53 | - if ($string instanceof IParameter || $string instanceof ILiteral || $string instanceof IQueryFunction) { |
|
54 | - return (string) $string; |
|
55 | - } |
|
48 | + /** |
|
49 | + * @param string|ILiteral|IParameter|IQueryFunction $string string, Literal or Parameter |
|
50 | + * @return string |
|
51 | + */ |
|
52 | + public function quoteColumnName($string) { |
|
53 | + if ($string instanceof IParameter || $string instanceof ILiteral || $string instanceof IQueryFunction) { |
|
54 | + return (string) $string; |
|
55 | + } |
|
56 | 56 | |
57 | - if ($string === null || $string === 'null' || $string === '*') { |
|
58 | - return $string; |
|
59 | - } |
|
57 | + if ($string === null || $string === 'null' || $string === '*') { |
|
58 | + return $string; |
|
59 | + } |
|
60 | 60 | |
61 | - if (!is_string($string)) { |
|
62 | - throw new \InvalidArgumentException('Only strings, Literals and Parameters are allowed'); |
|
63 | - } |
|
61 | + if (!is_string($string)) { |
|
62 | + throw new \InvalidArgumentException('Only strings, Literals and Parameters are allowed'); |
|
63 | + } |
|
64 | 64 | |
65 | - $string = str_replace(' AS ', ' as ', $string); |
|
66 | - if (substr_count($string, ' as ')) { |
|
67 | - return implode(' as ', array_map([$this, 'quoteColumnName'], explode(' as ', $string, 2))); |
|
68 | - } |
|
65 | + $string = str_replace(' AS ', ' as ', $string); |
|
66 | + if (substr_count($string, ' as ')) { |
|
67 | + return implode(' as ', array_map([$this, 'quoteColumnName'], explode(' as ', $string, 2))); |
|
68 | + } |
|
69 | 69 | |
70 | - if (substr_count($string, '.')) { |
|
71 | - [$alias, $columnName] = explode('.', $string, 2); |
|
70 | + if (substr_count($string, '.')) { |
|
71 | + [$alias, $columnName] = explode('.', $string, 2); |
|
72 | 72 | |
73 | - if ($columnName === '*') { |
|
74 | - return '`' . $alias . '`.*'; |
|
75 | - } |
|
73 | + if ($columnName === '*') { |
|
74 | + return '`' . $alias . '`.*'; |
|
75 | + } |
|
76 | 76 | |
77 | - return '`' . $alias . '`.`' . $columnName . '`'; |
|
78 | - } |
|
77 | + return '`' . $alias . '`.`' . $columnName . '`'; |
|
78 | + } |
|
79 | 79 | |
80 | - return '`' . $string . '`'; |
|
81 | - } |
|
80 | + return '`' . $string . '`'; |
|
81 | + } |
|
82 | 82 | } |
@@ -71,12 +71,12 @@ |
||
71 | 71 | [$alias, $columnName] = explode('.', $string, 2); |
72 | 72 | |
73 | 73 | if ($columnName === '*') { |
74 | - return '`' . $alias . '`.*'; |
|
74 | + return '`'.$alias.'`.*'; |
|
75 | 75 | } |
76 | 76 | |
77 | - return '`' . $alias . '`.`' . $columnName . '`'; |
|
77 | + return '`'.$alias.'`.`'.$columnName.'`'; |
|
78 | 78 | } |
79 | 79 | |
80 | - return '`' . $string . '`'; |
|
80 | + return '`'.$string.'`'; |
|
81 | 81 | } |
82 | 82 | } |
@@ -77,1830 +77,1830 @@ |
||
77 | 77 | */ |
78 | 78 | class Manager implements IManager { |
79 | 79 | |
80 | - /** @var IProviderFactory */ |
|
81 | - private $factory; |
|
82 | - /** @var ILogger */ |
|
83 | - private $logger; |
|
84 | - /** @var IConfig */ |
|
85 | - private $config; |
|
86 | - /** @var ISecureRandom */ |
|
87 | - private $secureRandom; |
|
88 | - /** @var IHasher */ |
|
89 | - private $hasher; |
|
90 | - /** @var IMountManager */ |
|
91 | - private $mountManager; |
|
92 | - /** @var IGroupManager */ |
|
93 | - private $groupManager; |
|
94 | - /** @var IL10N */ |
|
95 | - private $l; |
|
96 | - /** @var IFactory */ |
|
97 | - private $l10nFactory; |
|
98 | - /** @var IUserManager */ |
|
99 | - private $userManager; |
|
100 | - /** @var IRootFolder */ |
|
101 | - private $rootFolder; |
|
102 | - /** @var CappedMemoryCache */ |
|
103 | - private $sharingDisabledForUsersCache; |
|
104 | - /** @var EventDispatcherInterface */ |
|
105 | - private $legacyDispatcher; |
|
106 | - /** @var LegacyHooks */ |
|
107 | - private $legacyHooks; |
|
108 | - /** @var IMailer */ |
|
109 | - private $mailer; |
|
110 | - /** @var IURLGenerator */ |
|
111 | - private $urlGenerator; |
|
112 | - /** @var \OC_Defaults */ |
|
113 | - private $defaults; |
|
114 | - /** @var IEventDispatcher */ |
|
115 | - private $dispatcher; |
|
116 | - |
|
117 | - |
|
118 | - /** |
|
119 | - * Manager constructor. |
|
120 | - * |
|
121 | - * @param ILogger $logger |
|
122 | - * @param IConfig $config |
|
123 | - * @param ISecureRandom $secureRandom |
|
124 | - * @param IHasher $hasher |
|
125 | - * @param IMountManager $mountManager |
|
126 | - * @param IGroupManager $groupManager |
|
127 | - * @param IL10N $l |
|
128 | - * @param IFactory $l10nFactory |
|
129 | - * @param IProviderFactory $factory |
|
130 | - * @param IUserManager $userManager |
|
131 | - * @param IRootFolder $rootFolder |
|
132 | - * @param EventDispatcherInterface $eventDispatcher |
|
133 | - * @param IMailer $mailer |
|
134 | - * @param IURLGenerator $urlGenerator |
|
135 | - * @param \OC_Defaults $defaults |
|
136 | - */ |
|
137 | - public function __construct( |
|
138 | - ILogger $logger, |
|
139 | - IConfig $config, |
|
140 | - ISecureRandom $secureRandom, |
|
141 | - IHasher $hasher, |
|
142 | - IMountManager $mountManager, |
|
143 | - IGroupManager $groupManager, |
|
144 | - IL10N $l, |
|
145 | - IFactory $l10nFactory, |
|
146 | - IProviderFactory $factory, |
|
147 | - IUserManager $userManager, |
|
148 | - IRootFolder $rootFolder, |
|
149 | - EventDispatcherInterface $legacyDispatcher, |
|
150 | - IMailer $mailer, |
|
151 | - IURLGenerator $urlGenerator, |
|
152 | - \OC_Defaults $defaults, |
|
153 | - IEventDispatcher $dispatcher |
|
154 | - ) { |
|
155 | - $this->logger = $logger; |
|
156 | - $this->config = $config; |
|
157 | - $this->secureRandom = $secureRandom; |
|
158 | - $this->hasher = $hasher; |
|
159 | - $this->mountManager = $mountManager; |
|
160 | - $this->groupManager = $groupManager; |
|
161 | - $this->l = $l; |
|
162 | - $this->l10nFactory = $l10nFactory; |
|
163 | - $this->factory = $factory; |
|
164 | - $this->userManager = $userManager; |
|
165 | - $this->rootFolder = $rootFolder; |
|
166 | - $this->legacyDispatcher = $legacyDispatcher; |
|
167 | - $this->sharingDisabledForUsersCache = new CappedMemoryCache(); |
|
168 | - $this->legacyHooks = new LegacyHooks($this->legacyDispatcher); |
|
169 | - $this->mailer = $mailer; |
|
170 | - $this->urlGenerator = $urlGenerator; |
|
171 | - $this->defaults = $defaults; |
|
172 | - $this->dispatcher = $dispatcher; |
|
173 | - } |
|
174 | - |
|
175 | - /** |
|
176 | - * Convert from a full share id to a tuple (providerId, shareId) |
|
177 | - * |
|
178 | - * @param string $id |
|
179 | - * @return string[] |
|
180 | - */ |
|
181 | - private function splitFullId($id) { |
|
182 | - return explode(':', $id, 2); |
|
183 | - } |
|
184 | - |
|
185 | - /** |
|
186 | - * Verify if a password meets all requirements |
|
187 | - * |
|
188 | - * @param string $password |
|
189 | - * @throws \Exception |
|
190 | - */ |
|
191 | - protected function verifyPassword($password) { |
|
192 | - if ($password === null) { |
|
193 | - // No password is set, check if this is allowed. |
|
194 | - if ($this->shareApiLinkEnforcePassword()) { |
|
195 | - throw new \InvalidArgumentException('Passwords are enforced for link shares'); |
|
196 | - } |
|
197 | - |
|
198 | - return; |
|
199 | - } |
|
200 | - |
|
201 | - // Let others verify the password |
|
202 | - try { |
|
203 | - $this->legacyDispatcher->dispatch(new ValidatePasswordPolicyEvent($password)); |
|
204 | - } catch (HintException $e) { |
|
205 | - throw new \Exception($e->getHint()); |
|
206 | - } |
|
207 | - } |
|
208 | - |
|
209 | - /** |
|
210 | - * Check for generic requirements before creating a share |
|
211 | - * |
|
212 | - * @param IShare $share |
|
213 | - * @throws \InvalidArgumentException |
|
214 | - * @throws GenericShareException |
|
215 | - * |
|
216 | - * @suppress PhanUndeclaredClassMethod |
|
217 | - */ |
|
218 | - protected function generalCreateChecks(IShare $share) { |
|
219 | - if ($share->getShareType() === IShare::TYPE_USER) { |
|
220 | - // We expect a valid user as sharedWith for user shares |
|
221 | - if (!$this->userManager->userExists($share->getSharedWith())) { |
|
222 | - throw new \InvalidArgumentException('SharedWith is not a valid user'); |
|
223 | - } |
|
224 | - } elseif ($share->getShareType() === IShare::TYPE_GROUP) { |
|
225 | - // We expect a valid group as sharedWith for group shares |
|
226 | - if (!$this->groupManager->groupExists($share->getSharedWith())) { |
|
227 | - throw new \InvalidArgumentException('SharedWith is not a valid group'); |
|
228 | - } |
|
229 | - } elseif ($share->getShareType() === IShare::TYPE_LINK) { |
|
230 | - if ($share->getSharedWith() !== null) { |
|
231 | - throw new \InvalidArgumentException('SharedWith should be empty'); |
|
232 | - } |
|
233 | - } elseif ($share->getShareType() === IShare::TYPE_REMOTE) { |
|
234 | - if ($share->getSharedWith() === null) { |
|
235 | - throw new \InvalidArgumentException('SharedWith should not be empty'); |
|
236 | - } |
|
237 | - } elseif ($share->getShareType() === IShare::TYPE_REMOTE_GROUP) { |
|
238 | - if ($share->getSharedWith() === null) { |
|
239 | - throw new \InvalidArgumentException('SharedWith should not be empty'); |
|
240 | - } |
|
241 | - } elseif ($share->getShareType() === IShare::TYPE_EMAIL) { |
|
242 | - if ($share->getSharedWith() === null) { |
|
243 | - throw new \InvalidArgumentException('SharedWith should not be empty'); |
|
244 | - } |
|
245 | - } elseif ($share->getShareType() === IShare::TYPE_CIRCLE) { |
|
246 | - $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith()); |
|
247 | - if ($circle === null) { |
|
248 | - throw new \InvalidArgumentException('SharedWith is not a valid circle'); |
|
249 | - } |
|
250 | - } elseif ($share->getShareType() === IShare::TYPE_ROOM) { |
|
251 | - } elseif ($share->getShareType() === IShare::TYPE_DECK) { |
|
252 | - } else { |
|
253 | - // We can't handle other types yet |
|
254 | - throw new \InvalidArgumentException('unknown share type'); |
|
255 | - } |
|
256 | - |
|
257 | - // Verify the initiator of the share is set |
|
258 | - if ($share->getSharedBy() === null) { |
|
259 | - throw new \InvalidArgumentException('SharedBy should be set'); |
|
260 | - } |
|
261 | - |
|
262 | - // Cannot share with yourself |
|
263 | - if ($share->getShareType() === IShare::TYPE_USER && |
|
264 | - $share->getSharedWith() === $share->getSharedBy()) { |
|
265 | - throw new \InvalidArgumentException('Can’t share with yourself'); |
|
266 | - } |
|
267 | - |
|
268 | - // The path should be set |
|
269 | - if ($share->getNode() === null) { |
|
270 | - throw new \InvalidArgumentException('Path should be set'); |
|
271 | - } |
|
272 | - |
|
273 | - // And it should be a file or a folder |
|
274 | - if (!($share->getNode() instanceof \OCP\Files\File) && |
|
275 | - !($share->getNode() instanceof \OCP\Files\Folder)) { |
|
276 | - throw new \InvalidArgumentException('Path should be either a file or a folder'); |
|
277 | - } |
|
278 | - |
|
279 | - // And you can't share your rootfolder |
|
280 | - if ($this->userManager->userExists($share->getSharedBy())) { |
|
281 | - $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); |
|
282 | - } else { |
|
283 | - $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()); |
|
284 | - } |
|
285 | - if ($userFolder->getId() === $share->getNode()->getId()) { |
|
286 | - throw new \InvalidArgumentException('You can’t share your root folder'); |
|
287 | - } |
|
288 | - |
|
289 | - // Check if we actually have share permissions |
|
290 | - if (!$share->getNode()->isShareable()) { |
|
291 | - $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getName()]); |
|
292 | - throw new GenericShareException($message_t, $message_t, 404); |
|
293 | - } |
|
294 | - |
|
295 | - // Permissions should be set |
|
296 | - if ($share->getPermissions() === null) { |
|
297 | - throw new \InvalidArgumentException('A share requires permissions'); |
|
298 | - } |
|
299 | - |
|
300 | - $isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage'); |
|
301 | - $permissions = 0; |
|
302 | - |
|
303 | - if (!$isFederatedShare && $share->getNode()->getOwner() && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) { |
|
304 | - $userMounts = array_filter($userFolder->getById($share->getNode()->getId()), function ($mount) { |
|
305 | - // We need to filter since there might be other mountpoints that contain the file |
|
306 | - // e.g. if the user has access to the same external storage that the file is originating from |
|
307 | - return $mount->getStorage()->instanceOfStorage(ISharedStorage::class); |
|
308 | - }); |
|
309 | - $userMount = array_shift($userMounts); |
|
310 | - if ($userMount === null) { |
|
311 | - throw new GenericShareException('Could not get proper share mount for ' . $share->getNode()->getId() . '. Failing since else the next calls are called with null'); |
|
312 | - } |
|
313 | - $mount = $userMount->getMountPoint(); |
|
314 | - // When it's a reshare use the parent share permissions as maximum |
|
315 | - $userMountPointId = $mount->getStorageRootId(); |
|
316 | - $userMountPoints = $userFolder->getById($userMountPointId); |
|
317 | - $userMountPoint = array_shift($userMountPoints); |
|
318 | - |
|
319 | - if ($userMountPoint === null) { |
|
320 | - throw new GenericShareException('Could not get proper user mount for ' . $userMountPointId . '. Failing since else the next calls are called with null'); |
|
321 | - } |
|
322 | - |
|
323 | - /* Check if this is an incoming share */ |
|
324 | - $incomingShares = $this->getSharedWith($share->getSharedBy(), IShare::TYPE_USER, $userMountPoint, -1, 0); |
|
325 | - $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), IShare::TYPE_GROUP, $userMountPoint, -1, 0)); |
|
326 | - $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), IShare::TYPE_CIRCLE, $userMountPoint, -1, 0)); |
|
327 | - $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), IShare::TYPE_ROOM, $userMountPoint, -1, 0)); |
|
328 | - |
|
329 | - /** @var IShare[] $incomingShares */ |
|
330 | - if (!empty($incomingShares)) { |
|
331 | - foreach ($incomingShares as $incomingShare) { |
|
332 | - $permissions |= $incomingShare->getPermissions(); |
|
333 | - } |
|
334 | - } |
|
335 | - } else { |
|
336 | - /* |
|
80 | + /** @var IProviderFactory */ |
|
81 | + private $factory; |
|
82 | + /** @var ILogger */ |
|
83 | + private $logger; |
|
84 | + /** @var IConfig */ |
|
85 | + private $config; |
|
86 | + /** @var ISecureRandom */ |
|
87 | + private $secureRandom; |
|
88 | + /** @var IHasher */ |
|
89 | + private $hasher; |
|
90 | + /** @var IMountManager */ |
|
91 | + private $mountManager; |
|
92 | + /** @var IGroupManager */ |
|
93 | + private $groupManager; |
|
94 | + /** @var IL10N */ |
|
95 | + private $l; |
|
96 | + /** @var IFactory */ |
|
97 | + private $l10nFactory; |
|
98 | + /** @var IUserManager */ |
|
99 | + private $userManager; |
|
100 | + /** @var IRootFolder */ |
|
101 | + private $rootFolder; |
|
102 | + /** @var CappedMemoryCache */ |
|
103 | + private $sharingDisabledForUsersCache; |
|
104 | + /** @var EventDispatcherInterface */ |
|
105 | + private $legacyDispatcher; |
|
106 | + /** @var LegacyHooks */ |
|
107 | + private $legacyHooks; |
|
108 | + /** @var IMailer */ |
|
109 | + private $mailer; |
|
110 | + /** @var IURLGenerator */ |
|
111 | + private $urlGenerator; |
|
112 | + /** @var \OC_Defaults */ |
|
113 | + private $defaults; |
|
114 | + /** @var IEventDispatcher */ |
|
115 | + private $dispatcher; |
|
116 | + |
|
117 | + |
|
118 | + /** |
|
119 | + * Manager constructor. |
|
120 | + * |
|
121 | + * @param ILogger $logger |
|
122 | + * @param IConfig $config |
|
123 | + * @param ISecureRandom $secureRandom |
|
124 | + * @param IHasher $hasher |
|
125 | + * @param IMountManager $mountManager |
|
126 | + * @param IGroupManager $groupManager |
|
127 | + * @param IL10N $l |
|
128 | + * @param IFactory $l10nFactory |
|
129 | + * @param IProviderFactory $factory |
|
130 | + * @param IUserManager $userManager |
|
131 | + * @param IRootFolder $rootFolder |
|
132 | + * @param EventDispatcherInterface $eventDispatcher |
|
133 | + * @param IMailer $mailer |
|
134 | + * @param IURLGenerator $urlGenerator |
|
135 | + * @param \OC_Defaults $defaults |
|
136 | + */ |
|
137 | + public function __construct( |
|
138 | + ILogger $logger, |
|
139 | + IConfig $config, |
|
140 | + ISecureRandom $secureRandom, |
|
141 | + IHasher $hasher, |
|
142 | + IMountManager $mountManager, |
|
143 | + IGroupManager $groupManager, |
|
144 | + IL10N $l, |
|
145 | + IFactory $l10nFactory, |
|
146 | + IProviderFactory $factory, |
|
147 | + IUserManager $userManager, |
|
148 | + IRootFolder $rootFolder, |
|
149 | + EventDispatcherInterface $legacyDispatcher, |
|
150 | + IMailer $mailer, |
|
151 | + IURLGenerator $urlGenerator, |
|
152 | + \OC_Defaults $defaults, |
|
153 | + IEventDispatcher $dispatcher |
|
154 | + ) { |
|
155 | + $this->logger = $logger; |
|
156 | + $this->config = $config; |
|
157 | + $this->secureRandom = $secureRandom; |
|
158 | + $this->hasher = $hasher; |
|
159 | + $this->mountManager = $mountManager; |
|
160 | + $this->groupManager = $groupManager; |
|
161 | + $this->l = $l; |
|
162 | + $this->l10nFactory = $l10nFactory; |
|
163 | + $this->factory = $factory; |
|
164 | + $this->userManager = $userManager; |
|
165 | + $this->rootFolder = $rootFolder; |
|
166 | + $this->legacyDispatcher = $legacyDispatcher; |
|
167 | + $this->sharingDisabledForUsersCache = new CappedMemoryCache(); |
|
168 | + $this->legacyHooks = new LegacyHooks($this->legacyDispatcher); |
|
169 | + $this->mailer = $mailer; |
|
170 | + $this->urlGenerator = $urlGenerator; |
|
171 | + $this->defaults = $defaults; |
|
172 | + $this->dispatcher = $dispatcher; |
|
173 | + } |
|
174 | + |
|
175 | + /** |
|
176 | + * Convert from a full share id to a tuple (providerId, shareId) |
|
177 | + * |
|
178 | + * @param string $id |
|
179 | + * @return string[] |
|
180 | + */ |
|
181 | + private function splitFullId($id) { |
|
182 | + return explode(':', $id, 2); |
|
183 | + } |
|
184 | + |
|
185 | + /** |
|
186 | + * Verify if a password meets all requirements |
|
187 | + * |
|
188 | + * @param string $password |
|
189 | + * @throws \Exception |
|
190 | + */ |
|
191 | + protected function verifyPassword($password) { |
|
192 | + if ($password === null) { |
|
193 | + // No password is set, check if this is allowed. |
|
194 | + if ($this->shareApiLinkEnforcePassword()) { |
|
195 | + throw new \InvalidArgumentException('Passwords are enforced for link shares'); |
|
196 | + } |
|
197 | + |
|
198 | + return; |
|
199 | + } |
|
200 | + |
|
201 | + // Let others verify the password |
|
202 | + try { |
|
203 | + $this->legacyDispatcher->dispatch(new ValidatePasswordPolicyEvent($password)); |
|
204 | + } catch (HintException $e) { |
|
205 | + throw new \Exception($e->getHint()); |
|
206 | + } |
|
207 | + } |
|
208 | + |
|
209 | + /** |
|
210 | + * Check for generic requirements before creating a share |
|
211 | + * |
|
212 | + * @param IShare $share |
|
213 | + * @throws \InvalidArgumentException |
|
214 | + * @throws GenericShareException |
|
215 | + * |
|
216 | + * @suppress PhanUndeclaredClassMethod |
|
217 | + */ |
|
218 | + protected function generalCreateChecks(IShare $share) { |
|
219 | + if ($share->getShareType() === IShare::TYPE_USER) { |
|
220 | + // We expect a valid user as sharedWith for user shares |
|
221 | + if (!$this->userManager->userExists($share->getSharedWith())) { |
|
222 | + throw new \InvalidArgumentException('SharedWith is not a valid user'); |
|
223 | + } |
|
224 | + } elseif ($share->getShareType() === IShare::TYPE_GROUP) { |
|
225 | + // We expect a valid group as sharedWith for group shares |
|
226 | + if (!$this->groupManager->groupExists($share->getSharedWith())) { |
|
227 | + throw new \InvalidArgumentException('SharedWith is not a valid group'); |
|
228 | + } |
|
229 | + } elseif ($share->getShareType() === IShare::TYPE_LINK) { |
|
230 | + if ($share->getSharedWith() !== null) { |
|
231 | + throw new \InvalidArgumentException('SharedWith should be empty'); |
|
232 | + } |
|
233 | + } elseif ($share->getShareType() === IShare::TYPE_REMOTE) { |
|
234 | + if ($share->getSharedWith() === null) { |
|
235 | + throw new \InvalidArgumentException('SharedWith should not be empty'); |
|
236 | + } |
|
237 | + } elseif ($share->getShareType() === IShare::TYPE_REMOTE_GROUP) { |
|
238 | + if ($share->getSharedWith() === null) { |
|
239 | + throw new \InvalidArgumentException('SharedWith should not be empty'); |
|
240 | + } |
|
241 | + } elseif ($share->getShareType() === IShare::TYPE_EMAIL) { |
|
242 | + if ($share->getSharedWith() === null) { |
|
243 | + throw new \InvalidArgumentException('SharedWith should not be empty'); |
|
244 | + } |
|
245 | + } elseif ($share->getShareType() === IShare::TYPE_CIRCLE) { |
|
246 | + $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith()); |
|
247 | + if ($circle === null) { |
|
248 | + throw new \InvalidArgumentException('SharedWith is not a valid circle'); |
|
249 | + } |
|
250 | + } elseif ($share->getShareType() === IShare::TYPE_ROOM) { |
|
251 | + } elseif ($share->getShareType() === IShare::TYPE_DECK) { |
|
252 | + } else { |
|
253 | + // We can't handle other types yet |
|
254 | + throw new \InvalidArgumentException('unknown share type'); |
|
255 | + } |
|
256 | + |
|
257 | + // Verify the initiator of the share is set |
|
258 | + if ($share->getSharedBy() === null) { |
|
259 | + throw new \InvalidArgumentException('SharedBy should be set'); |
|
260 | + } |
|
261 | + |
|
262 | + // Cannot share with yourself |
|
263 | + if ($share->getShareType() === IShare::TYPE_USER && |
|
264 | + $share->getSharedWith() === $share->getSharedBy()) { |
|
265 | + throw new \InvalidArgumentException('Can’t share with yourself'); |
|
266 | + } |
|
267 | + |
|
268 | + // The path should be set |
|
269 | + if ($share->getNode() === null) { |
|
270 | + throw new \InvalidArgumentException('Path should be set'); |
|
271 | + } |
|
272 | + |
|
273 | + // And it should be a file or a folder |
|
274 | + if (!($share->getNode() instanceof \OCP\Files\File) && |
|
275 | + !($share->getNode() instanceof \OCP\Files\Folder)) { |
|
276 | + throw new \InvalidArgumentException('Path should be either a file or a folder'); |
|
277 | + } |
|
278 | + |
|
279 | + // And you can't share your rootfolder |
|
280 | + if ($this->userManager->userExists($share->getSharedBy())) { |
|
281 | + $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); |
|
282 | + } else { |
|
283 | + $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()); |
|
284 | + } |
|
285 | + if ($userFolder->getId() === $share->getNode()->getId()) { |
|
286 | + throw new \InvalidArgumentException('You can’t share your root folder'); |
|
287 | + } |
|
288 | + |
|
289 | + // Check if we actually have share permissions |
|
290 | + if (!$share->getNode()->isShareable()) { |
|
291 | + $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getName()]); |
|
292 | + throw new GenericShareException($message_t, $message_t, 404); |
|
293 | + } |
|
294 | + |
|
295 | + // Permissions should be set |
|
296 | + if ($share->getPermissions() === null) { |
|
297 | + throw new \InvalidArgumentException('A share requires permissions'); |
|
298 | + } |
|
299 | + |
|
300 | + $isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage'); |
|
301 | + $permissions = 0; |
|
302 | + |
|
303 | + if (!$isFederatedShare && $share->getNode()->getOwner() && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) { |
|
304 | + $userMounts = array_filter($userFolder->getById($share->getNode()->getId()), function ($mount) { |
|
305 | + // We need to filter since there might be other mountpoints that contain the file |
|
306 | + // e.g. if the user has access to the same external storage that the file is originating from |
|
307 | + return $mount->getStorage()->instanceOfStorage(ISharedStorage::class); |
|
308 | + }); |
|
309 | + $userMount = array_shift($userMounts); |
|
310 | + if ($userMount === null) { |
|
311 | + throw new GenericShareException('Could not get proper share mount for ' . $share->getNode()->getId() . '. Failing since else the next calls are called with null'); |
|
312 | + } |
|
313 | + $mount = $userMount->getMountPoint(); |
|
314 | + // When it's a reshare use the parent share permissions as maximum |
|
315 | + $userMountPointId = $mount->getStorageRootId(); |
|
316 | + $userMountPoints = $userFolder->getById($userMountPointId); |
|
317 | + $userMountPoint = array_shift($userMountPoints); |
|
318 | + |
|
319 | + if ($userMountPoint === null) { |
|
320 | + throw new GenericShareException('Could not get proper user mount for ' . $userMountPointId . '. Failing since else the next calls are called with null'); |
|
321 | + } |
|
322 | + |
|
323 | + /* Check if this is an incoming share */ |
|
324 | + $incomingShares = $this->getSharedWith($share->getSharedBy(), IShare::TYPE_USER, $userMountPoint, -1, 0); |
|
325 | + $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), IShare::TYPE_GROUP, $userMountPoint, -1, 0)); |
|
326 | + $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), IShare::TYPE_CIRCLE, $userMountPoint, -1, 0)); |
|
327 | + $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), IShare::TYPE_ROOM, $userMountPoint, -1, 0)); |
|
328 | + |
|
329 | + /** @var IShare[] $incomingShares */ |
|
330 | + if (!empty($incomingShares)) { |
|
331 | + foreach ($incomingShares as $incomingShare) { |
|
332 | + $permissions |= $incomingShare->getPermissions(); |
|
333 | + } |
|
334 | + } |
|
335 | + } else { |
|
336 | + /* |
|
337 | 337 | * Quick fix for #23536 |
338 | 338 | * Non moveable mount points do not have update and delete permissions |
339 | 339 | * while we 'most likely' do have that on the storage. |
340 | 340 | */ |
341 | - $permissions = $share->getNode()->getPermissions(); |
|
342 | - if (!($share->getNode()->getMountPoint() instanceof MoveableMount)) { |
|
343 | - $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE; |
|
344 | - } |
|
345 | - } |
|
346 | - |
|
347 | - // Check that we do not share with more permissions than we have |
|
348 | - if ($share->getPermissions() & ~$permissions) { |
|
349 | - $path = $userFolder->getRelativePath($share->getNode()->getPath()); |
|
350 | - $message_t = $this->l->t('Can’t increase permissions of %s', [$path]); |
|
351 | - throw new GenericShareException($message_t, $message_t, 404); |
|
352 | - } |
|
353 | - |
|
354 | - |
|
355 | - // Check that read permissions are always set |
|
356 | - // Link shares are allowed to have no read permissions to allow upload to hidden folders |
|
357 | - $noReadPermissionRequired = $share->getShareType() === IShare::TYPE_LINK |
|
358 | - || $share->getShareType() === IShare::TYPE_EMAIL; |
|
359 | - if (!$noReadPermissionRequired && |
|
360 | - ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) { |
|
361 | - throw new \InvalidArgumentException('Shares need at least read permissions'); |
|
362 | - } |
|
363 | - |
|
364 | - if ($share->getNode() instanceof \OCP\Files\File) { |
|
365 | - if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) { |
|
366 | - $message_t = $this->l->t('Files can’t be shared with delete permissions'); |
|
367 | - throw new GenericShareException($message_t); |
|
368 | - } |
|
369 | - if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) { |
|
370 | - $message_t = $this->l->t('Files can’t be shared with create permissions'); |
|
371 | - throw new GenericShareException($message_t); |
|
372 | - } |
|
373 | - } |
|
374 | - } |
|
375 | - |
|
376 | - /** |
|
377 | - * Validate if the expiration date fits the system settings |
|
378 | - * |
|
379 | - * @param IShare $share The share to validate the expiration date of |
|
380 | - * @return IShare The modified share object |
|
381 | - * @throws GenericShareException |
|
382 | - * @throws \InvalidArgumentException |
|
383 | - * @throws \Exception |
|
384 | - */ |
|
385 | - protected function validateExpirationDateInternal(IShare $share) { |
|
386 | - $expirationDate = $share->getExpirationDate(); |
|
387 | - |
|
388 | - if ($expirationDate !== null) { |
|
389 | - //Make sure the expiration date is a date |
|
390 | - $expirationDate->setTime(0, 0, 0); |
|
391 | - |
|
392 | - $date = new \DateTime(); |
|
393 | - $date->setTime(0, 0, 0); |
|
394 | - if ($date >= $expirationDate) { |
|
395 | - $message = $this->l->t('Expiration date is in the past'); |
|
396 | - throw new GenericShareException($message, $message, 404); |
|
397 | - } |
|
398 | - } |
|
399 | - |
|
400 | - // If expiredate is empty set a default one if there is a default |
|
401 | - $fullId = null; |
|
402 | - try { |
|
403 | - $fullId = $share->getFullId(); |
|
404 | - } catch (\UnexpectedValueException $e) { |
|
405 | - // This is a new share |
|
406 | - } |
|
407 | - |
|
408 | - if ($fullId === null && $expirationDate === null && $this->shareApiInternalDefaultExpireDate()) { |
|
409 | - $expirationDate = new \DateTime(); |
|
410 | - $expirationDate->setTime(0,0,0); |
|
411 | - |
|
412 | - $days = (int)$this->config->getAppValue('core', 'internal_defaultExpDays', (string)$this->shareApiInternalDefaultExpireDays()); |
|
413 | - if ($days > $this->shareApiInternalDefaultExpireDays()) { |
|
414 | - $days = $this->shareApiInternalDefaultExpireDays(); |
|
415 | - } |
|
416 | - $expirationDate->add(new \DateInterval('P'.$days.'D')); |
|
417 | - } |
|
418 | - |
|
419 | - // If we enforce the expiration date check that is does not exceed |
|
420 | - if ($this->shareApiInternalDefaultExpireDateEnforced()) { |
|
421 | - if ($expirationDate === null) { |
|
422 | - throw new \InvalidArgumentException('Expiration date is enforced'); |
|
423 | - } |
|
424 | - |
|
425 | - $date = new \DateTime(); |
|
426 | - $date->setTime(0, 0, 0); |
|
427 | - $date->add(new \DateInterval('P' . $this->shareApiInternalDefaultExpireDays() . 'D')); |
|
428 | - if ($date < $expirationDate) { |
|
429 | - $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiInternalDefaultExpireDays()]); |
|
430 | - throw new GenericShareException($message, $message, 404); |
|
431 | - } |
|
432 | - } |
|
433 | - |
|
434 | - $accepted = true; |
|
435 | - $message = ''; |
|
436 | - \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [ |
|
437 | - 'expirationDate' => &$expirationDate, |
|
438 | - 'accepted' => &$accepted, |
|
439 | - 'message' => &$message, |
|
440 | - 'passwordSet' => $share->getPassword() !== null, |
|
441 | - ]); |
|
442 | - |
|
443 | - if (!$accepted) { |
|
444 | - throw new \Exception($message); |
|
445 | - } |
|
446 | - |
|
447 | - $share->setExpirationDate($expirationDate); |
|
448 | - |
|
449 | - return $share; |
|
450 | - } |
|
451 | - |
|
452 | - /** |
|
453 | - * Validate if the expiration date fits the system settings |
|
454 | - * |
|
455 | - * @param IShare $share The share to validate the expiration date of |
|
456 | - * @return IShare The modified share object |
|
457 | - * @throws GenericShareException |
|
458 | - * @throws \InvalidArgumentException |
|
459 | - * @throws \Exception |
|
460 | - */ |
|
461 | - protected function validateExpirationDate(IShare $share) { |
|
462 | - $expirationDate = $share->getExpirationDate(); |
|
463 | - |
|
464 | - if ($expirationDate !== null) { |
|
465 | - //Make sure the expiration date is a date |
|
466 | - $expirationDate->setTime(0, 0, 0); |
|
467 | - |
|
468 | - $date = new \DateTime(); |
|
469 | - $date->setTime(0, 0, 0); |
|
470 | - if ($date >= $expirationDate) { |
|
471 | - $message = $this->l->t('Expiration date is in the past'); |
|
472 | - throw new GenericShareException($message, $message, 404); |
|
473 | - } |
|
474 | - } |
|
475 | - |
|
476 | - // If expiredate is empty set a default one if there is a default |
|
477 | - $fullId = null; |
|
478 | - try { |
|
479 | - $fullId = $share->getFullId(); |
|
480 | - } catch (\UnexpectedValueException $e) { |
|
481 | - // This is a new share |
|
482 | - } |
|
483 | - |
|
484 | - if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) { |
|
485 | - $expirationDate = new \DateTime(); |
|
486 | - $expirationDate->setTime(0,0,0); |
|
487 | - |
|
488 | - $days = (int)$this->config->getAppValue('core', 'link_defaultExpDays', $this->shareApiLinkDefaultExpireDays()); |
|
489 | - if ($days > $this->shareApiLinkDefaultExpireDays()) { |
|
490 | - $days = $this->shareApiLinkDefaultExpireDays(); |
|
491 | - } |
|
492 | - $expirationDate->add(new \DateInterval('P'.$days.'D')); |
|
493 | - } |
|
494 | - |
|
495 | - // If we enforce the expiration date check that is does not exceed |
|
496 | - if ($this->shareApiLinkDefaultExpireDateEnforced()) { |
|
497 | - if ($expirationDate === null) { |
|
498 | - throw new \InvalidArgumentException('Expiration date is enforced'); |
|
499 | - } |
|
500 | - |
|
501 | - $date = new \DateTime(); |
|
502 | - $date->setTime(0, 0, 0); |
|
503 | - $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D')); |
|
504 | - if ($date < $expirationDate) { |
|
505 | - $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]); |
|
506 | - throw new GenericShareException($message, $message, 404); |
|
507 | - } |
|
508 | - } |
|
509 | - |
|
510 | - $accepted = true; |
|
511 | - $message = ''; |
|
512 | - \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [ |
|
513 | - 'expirationDate' => &$expirationDate, |
|
514 | - 'accepted' => &$accepted, |
|
515 | - 'message' => &$message, |
|
516 | - 'passwordSet' => $share->getPassword() !== null, |
|
517 | - ]); |
|
518 | - |
|
519 | - if (!$accepted) { |
|
520 | - throw new \Exception($message); |
|
521 | - } |
|
522 | - |
|
523 | - $share->setExpirationDate($expirationDate); |
|
524 | - |
|
525 | - return $share; |
|
526 | - } |
|
527 | - |
|
528 | - /** |
|
529 | - * Check for pre share requirements for user shares |
|
530 | - * |
|
531 | - * @param IShare $share |
|
532 | - * @throws \Exception |
|
533 | - */ |
|
534 | - protected function userCreateChecks(IShare $share) { |
|
535 | - // Check if we can share with group members only |
|
536 | - if ($this->shareWithGroupMembersOnly()) { |
|
537 | - $sharedBy = $this->userManager->get($share->getSharedBy()); |
|
538 | - $sharedWith = $this->userManager->get($share->getSharedWith()); |
|
539 | - // Verify we can share with this user |
|
540 | - $groups = array_intersect( |
|
541 | - $this->groupManager->getUserGroupIds($sharedBy), |
|
542 | - $this->groupManager->getUserGroupIds($sharedWith) |
|
543 | - ); |
|
544 | - if (empty($groups)) { |
|
545 | - $message_t = $this->l->t('Sharing is only allowed with group members'); |
|
546 | - throw new \Exception($message_t); |
|
547 | - } |
|
548 | - } |
|
549 | - |
|
550 | - /* |
|
341 | + $permissions = $share->getNode()->getPermissions(); |
|
342 | + if (!($share->getNode()->getMountPoint() instanceof MoveableMount)) { |
|
343 | + $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE; |
|
344 | + } |
|
345 | + } |
|
346 | + |
|
347 | + // Check that we do not share with more permissions than we have |
|
348 | + if ($share->getPermissions() & ~$permissions) { |
|
349 | + $path = $userFolder->getRelativePath($share->getNode()->getPath()); |
|
350 | + $message_t = $this->l->t('Can’t increase permissions of %s', [$path]); |
|
351 | + throw new GenericShareException($message_t, $message_t, 404); |
|
352 | + } |
|
353 | + |
|
354 | + |
|
355 | + // Check that read permissions are always set |
|
356 | + // Link shares are allowed to have no read permissions to allow upload to hidden folders |
|
357 | + $noReadPermissionRequired = $share->getShareType() === IShare::TYPE_LINK |
|
358 | + || $share->getShareType() === IShare::TYPE_EMAIL; |
|
359 | + if (!$noReadPermissionRequired && |
|
360 | + ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) { |
|
361 | + throw new \InvalidArgumentException('Shares need at least read permissions'); |
|
362 | + } |
|
363 | + |
|
364 | + if ($share->getNode() instanceof \OCP\Files\File) { |
|
365 | + if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) { |
|
366 | + $message_t = $this->l->t('Files can’t be shared with delete permissions'); |
|
367 | + throw new GenericShareException($message_t); |
|
368 | + } |
|
369 | + if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) { |
|
370 | + $message_t = $this->l->t('Files can’t be shared with create permissions'); |
|
371 | + throw new GenericShareException($message_t); |
|
372 | + } |
|
373 | + } |
|
374 | + } |
|
375 | + |
|
376 | + /** |
|
377 | + * Validate if the expiration date fits the system settings |
|
378 | + * |
|
379 | + * @param IShare $share The share to validate the expiration date of |
|
380 | + * @return IShare The modified share object |
|
381 | + * @throws GenericShareException |
|
382 | + * @throws \InvalidArgumentException |
|
383 | + * @throws \Exception |
|
384 | + */ |
|
385 | + protected function validateExpirationDateInternal(IShare $share) { |
|
386 | + $expirationDate = $share->getExpirationDate(); |
|
387 | + |
|
388 | + if ($expirationDate !== null) { |
|
389 | + //Make sure the expiration date is a date |
|
390 | + $expirationDate->setTime(0, 0, 0); |
|
391 | + |
|
392 | + $date = new \DateTime(); |
|
393 | + $date->setTime(0, 0, 0); |
|
394 | + if ($date >= $expirationDate) { |
|
395 | + $message = $this->l->t('Expiration date is in the past'); |
|
396 | + throw new GenericShareException($message, $message, 404); |
|
397 | + } |
|
398 | + } |
|
399 | + |
|
400 | + // If expiredate is empty set a default one if there is a default |
|
401 | + $fullId = null; |
|
402 | + try { |
|
403 | + $fullId = $share->getFullId(); |
|
404 | + } catch (\UnexpectedValueException $e) { |
|
405 | + // This is a new share |
|
406 | + } |
|
407 | + |
|
408 | + if ($fullId === null && $expirationDate === null && $this->shareApiInternalDefaultExpireDate()) { |
|
409 | + $expirationDate = new \DateTime(); |
|
410 | + $expirationDate->setTime(0,0,0); |
|
411 | + |
|
412 | + $days = (int)$this->config->getAppValue('core', 'internal_defaultExpDays', (string)$this->shareApiInternalDefaultExpireDays()); |
|
413 | + if ($days > $this->shareApiInternalDefaultExpireDays()) { |
|
414 | + $days = $this->shareApiInternalDefaultExpireDays(); |
|
415 | + } |
|
416 | + $expirationDate->add(new \DateInterval('P'.$days.'D')); |
|
417 | + } |
|
418 | + |
|
419 | + // If we enforce the expiration date check that is does not exceed |
|
420 | + if ($this->shareApiInternalDefaultExpireDateEnforced()) { |
|
421 | + if ($expirationDate === null) { |
|
422 | + throw new \InvalidArgumentException('Expiration date is enforced'); |
|
423 | + } |
|
424 | + |
|
425 | + $date = new \DateTime(); |
|
426 | + $date->setTime(0, 0, 0); |
|
427 | + $date->add(new \DateInterval('P' . $this->shareApiInternalDefaultExpireDays() . 'D')); |
|
428 | + if ($date < $expirationDate) { |
|
429 | + $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiInternalDefaultExpireDays()]); |
|
430 | + throw new GenericShareException($message, $message, 404); |
|
431 | + } |
|
432 | + } |
|
433 | + |
|
434 | + $accepted = true; |
|
435 | + $message = ''; |
|
436 | + \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [ |
|
437 | + 'expirationDate' => &$expirationDate, |
|
438 | + 'accepted' => &$accepted, |
|
439 | + 'message' => &$message, |
|
440 | + 'passwordSet' => $share->getPassword() !== null, |
|
441 | + ]); |
|
442 | + |
|
443 | + if (!$accepted) { |
|
444 | + throw new \Exception($message); |
|
445 | + } |
|
446 | + |
|
447 | + $share->setExpirationDate($expirationDate); |
|
448 | + |
|
449 | + return $share; |
|
450 | + } |
|
451 | + |
|
452 | + /** |
|
453 | + * Validate if the expiration date fits the system settings |
|
454 | + * |
|
455 | + * @param IShare $share The share to validate the expiration date of |
|
456 | + * @return IShare The modified share object |
|
457 | + * @throws GenericShareException |
|
458 | + * @throws \InvalidArgumentException |
|
459 | + * @throws \Exception |
|
460 | + */ |
|
461 | + protected function validateExpirationDate(IShare $share) { |
|
462 | + $expirationDate = $share->getExpirationDate(); |
|
463 | + |
|
464 | + if ($expirationDate !== null) { |
|
465 | + //Make sure the expiration date is a date |
|
466 | + $expirationDate->setTime(0, 0, 0); |
|
467 | + |
|
468 | + $date = new \DateTime(); |
|
469 | + $date->setTime(0, 0, 0); |
|
470 | + if ($date >= $expirationDate) { |
|
471 | + $message = $this->l->t('Expiration date is in the past'); |
|
472 | + throw new GenericShareException($message, $message, 404); |
|
473 | + } |
|
474 | + } |
|
475 | + |
|
476 | + // If expiredate is empty set a default one if there is a default |
|
477 | + $fullId = null; |
|
478 | + try { |
|
479 | + $fullId = $share->getFullId(); |
|
480 | + } catch (\UnexpectedValueException $e) { |
|
481 | + // This is a new share |
|
482 | + } |
|
483 | + |
|
484 | + if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) { |
|
485 | + $expirationDate = new \DateTime(); |
|
486 | + $expirationDate->setTime(0,0,0); |
|
487 | + |
|
488 | + $days = (int)$this->config->getAppValue('core', 'link_defaultExpDays', $this->shareApiLinkDefaultExpireDays()); |
|
489 | + if ($days > $this->shareApiLinkDefaultExpireDays()) { |
|
490 | + $days = $this->shareApiLinkDefaultExpireDays(); |
|
491 | + } |
|
492 | + $expirationDate->add(new \DateInterval('P'.$days.'D')); |
|
493 | + } |
|
494 | + |
|
495 | + // If we enforce the expiration date check that is does not exceed |
|
496 | + if ($this->shareApiLinkDefaultExpireDateEnforced()) { |
|
497 | + if ($expirationDate === null) { |
|
498 | + throw new \InvalidArgumentException('Expiration date is enforced'); |
|
499 | + } |
|
500 | + |
|
501 | + $date = new \DateTime(); |
|
502 | + $date->setTime(0, 0, 0); |
|
503 | + $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D')); |
|
504 | + if ($date < $expirationDate) { |
|
505 | + $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]); |
|
506 | + throw new GenericShareException($message, $message, 404); |
|
507 | + } |
|
508 | + } |
|
509 | + |
|
510 | + $accepted = true; |
|
511 | + $message = ''; |
|
512 | + \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [ |
|
513 | + 'expirationDate' => &$expirationDate, |
|
514 | + 'accepted' => &$accepted, |
|
515 | + 'message' => &$message, |
|
516 | + 'passwordSet' => $share->getPassword() !== null, |
|
517 | + ]); |
|
518 | + |
|
519 | + if (!$accepted) { |
|
520 | + throw new \Exception($message); |
|
521 | + } |
|
522 | + |
|
523 | + $share->setExpirationDate($expirationDate); |
|
524 | + |
|
525 | + return $share; |
|
526 | + } |
|
527 | + |
|
528 | + /** |
|
529 | + * Check for pre share requirements for user shares |
|
530 | + * |
|
531 | + * @param IShare $share |
|
532 | + * @throws \Exception |
|
533 | + */ |
|
534 | + protected function userCreateChecks(IShare $share) { |
|
535 | + // Check if we can share with group members only |
|
536 | + if ($this->shareWithGroupMembersOnly()) { |
|
537 | + $sharedBy = $this->userManager->get($share->getSharedBy()); |
|
538 | + $sharedWith = $this->userManager->get($share->getSharedWith()); |
|
539 | + // Verify we can share with this user |
|
540 | + $groups = array_intersect( |
|
541 | + $this->groupManager->getUserGroupIds($sharedBy), |
|
542 | + $this->groupManager->getUserGroupIds($sharedWith) |
|
543 | + ); |
|
544 | + if (empty($groups)) { |
|
545 | + $message_t = $this->l->t('Sharing is only allowed with group members'); |
|
546 | + throw new \Exception($message_t); |
|
547 | + } |
|
548 | + } |
|
549 | + |
|
550 | + /* |
|
551 | 551 | * TODO: Could be costly, fix |
552 | 552 | * |
553 | 553 | * Also this is not what we want in the future.. then we want to squash identical shares. |
554 | 554 | */ |
555 | - $provider = $this->factory->getProviderForType(IShare::TYPE_USER); |
|
556 | - $existingShares = $provider->getSharesByPath($share->getNode()); |
|
557 | - foreach ($existingShares as $existingShare) { |
|
558 | - // Ignore if it is the same share |
|
559 | - try { |
|
560 | - if ($existingShare->getFullId() === $share->getFullId()) { |
|
561 | - continue; |
|
562 | - } |
|
563 | - } catch (\UnexpectedValueException $e) { |
|
564 | - //Shares are not identical |
|
565 | - } |
|
566 | - |
|
567 | - // Identical share already existst |
|
568 | - if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) { |
|
569 | - throw new \Exception('Path is already shared with this user'); |
|
570 | - } |
|
571 | - |
|
572 | - // The share is already shared with this user via a group share |
|
573 | - if ($existingShare->getShareType() === IShare::TYPE_GROUP) { |
|
574 | - $group = $this->groupManager->get($existingShare->getSharedWith()); |
|
575 | - if (!is_null($group)) { |
|
576 | - $user = $this->userManager->get($share->getSharedWith()); |
|
577 | - |
|
578 | - if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) { |
|
579 | - throw new \Exception('Path is already shared with this user'); |
|
580 | - } |
|
581 | - } |
|
582 | - } |
|
583 | - } |
|
584 | - } |
|
585 | - |
|
586 | - /** |
|
587 | - * Check for pre share requirements for group shares |
|
588 | - * |
|
589 | - * @param IShare $share |
|
590 | - * @throws \Exception |
|
591 | - */ |
|
592 | - protected function groupCreateChecks(IShare $share) { |
|
593 | - // Verify group shares are allowed |
|
594 | - if (!$this->allowGroupSharing()) { |
|
595 | - throw new \Exception('Group sharing is now allowed'); |
|
596 | - } |
|
597 | - |
|
598 | - // Verify if the user can share with this group |
|
599 | - if ($this->shareWithGroupMembersOnly()) { |
|
600 | - $sharedBy = $this->userManager->get($share->getSharedBy()); |
|
601 | - $sharedWith = $this->groupManager->get($share->getSharedWith()); |
|
602 | - if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) { |
|
603 | - throw new \Exception('Sharing is only allowed within your own groups'); |
|
604 | - } |
|
605 | - } |
|
606 | - |
|
607 | - /* |
|
555 | + $provider = $this->factory->getProviderForType(IShare::TYPE_USER); |
|
556 | + $existingShares = $provider->getSharesByPath($share->getNode()); |
|
557 | + foreach ($existingShares as $existingShare) { |
|
558 | + // Ignore if it is the same share |
|
559 | + try { |
|
560 | + if ($existingShare->getFullId() === $share->getFullId()) { |
|
561 | + continue; |
|
562 | + } |
|
563 | + } catch (\UnexpectedValueException $e) { |
|
564 | + //Shares are not identical |
|
565 | + } |
|
566 | + |
|
567 | + // Identical share already existst |
|
568 | + if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) { |
|
569 | + throw new \Exception('Path is already shared with this user'); |
|
570 | + } |
|
571 | + |
|
572 | + // The share is already shared with this user via a group share |
|
573 | + if ($existingShare->getShareType() === IShare::TYPE_GROUP) { |
|
574 | + $group = $this->groupManager->get($existingShare->getSharedWith()); |
|
575 | + if (!is_null($group)) { |
|
576 | + $user = $this->userManager->get($share->getSharedWith()); |
|
577 | + |
|
578 | + if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) { |
|
579 | + throw new \Exception('Path is already shared with this user'); |
|
580 | + } |
|
581 | + } |
|
582 | + } |
|
583 | + } |
|
584 | + } |
|
585 | + |
|
586 | + /** |
|
587 | + * Check for pre share requirements for group shares |
|
588 | + * |
|
589 | + * @param IShare $share |
|
590 | + * @throws \Exception |
|
591 | + */ |
|
592 | + protected function groupCreateChecks(IShare $share) { |
|
593 | + // Verify group shares are allowed |
|
594 | + if (!$this->allowGroupSharing()) { |
|
595 | + throw new \Exception('Group sharing is now allowed'); |
|
596 | + } |
|
597 | + |
|
598 | + // Verify if the user can share with this group |
|
599 | + if ($this->shareWithGroupMembersOnly()) { |
|
600 | + $sharedBy = $this->userManager->get($share->getSharedBy()); |
|
601 | + $sharedWith = $this->groupManager->get($share->getSharedWith()); |
|
602 | + if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) { |
|
603 | + throw new \Exception('Sharing is only allowed within your own groups'); |
|
604 | + } |
|
605 | + } |
|
606 | + |
|
607 | + /* |
|
608 | 608 | * TODO: Could be costly, fix |
609 | 609 | * |
610 | 610 | * Also this is not what we want in the future.. then we want to squash identical shares. |
611 | 611 | */ |
612 | - $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP); |
|
613 | - $existingShares = $provider->getSharesByPath($share->getNode()); |
|
614 | - foreach ($existingShares as $existingShare) { |
|
615 | - try { |
|
616 | - if ($existingShare->getFullId() === $share->getFullId()) { |
|
617 | - continue; |
|
618 | - } |
|
619 | - } catch (\UnexpectedValueException $e) { |
|
620 | - //It is a new share so just continue |
|
621 | - } |
|
622 | - |
|
623 | - if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) { |
|
624 | - throw new \Exception('Path is already shared with this group'); |
|
625 | - } |
|
626 | - } |
|
627 | - } |
|
628 | - |
|
629 | - /** |
|
630 | - * Check for pre share requirements for link shares |
|
631 | - * |
|
632 | - * @param IShare $share |
|
633 | - * @throws \Exception |
|
634 | - */ |
|
635 | - protected function linkCreateChecks(IShare $share) { |
|
636 | - // Are link shares allowed? |
|
637 | - if (!$this->shareApiAllowLinks()) { |
|
638 | - throw new \Exception('Link sharing is not allowed'); |
|
639 | - } |
|
640 | - |
|
641 | - // Check if public upload is allowed |
|
642 | - if (!$this->shareApiLinkAllowPublicUpload() && |
|
643 | - ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) { |
|
644 | - throw new \InvalidArgumentException('Public upload is not allowed'); |
|
645 | - } |
|
646 | - } |
|
647 | - |
|
648 | - /** |
|
649 | - * To make sure we don't get invisible link shares we set the parent |
|
650 | - * of a link if it is a reshare. This is a quick word around |
|
651 | - * until we can properly display multiple link shares in the UI |
|
652 | - * |
|
653 | - * See: https://github.com/owncloud/core/issues/22295 |
|
654 | - * |
|
655 | - * FIXME: Remove once multiple link shares can be properly displayed |
|
656 | - * |
|
657 | - * @param IShare $share |
|
658 | - */ |
|
659 | - protected function setLinkParent(IShare $share) { |
|
660 | - |
|
661 | - // No sense in checking if the method is not there. |
|
662 | - if (method_exists($share, 'setParent')) { |
|
663 | - $storage = $share->getNode()->getStorage(); |
|
664 | - if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { |
|
665 | - /** @var \OCA\Files_Sharing\SharedStorage $storage */ |
|
666 | - $share->setParent($storage->getShareId()); |
|
667 | - } |
|
668 | - } |
|
669 | - } |
|
670 | - |
|
671 | - /** |
|
672 | - * @param File|Folder $path |
|
673 | - */ |
|
674 | - protected function pathCreateChecks($path) { |
|
675 | - // Make sure that we do not share a path that contains a shared mountpoint |
|
676 | - if ($path instanceof \OCP\Files\Folder) { |
|
677 | - $mounts = $this->mountManager->findIn($path->getPath()); |
|
678 | - foreach ($mounts as $mount) { |
|
679 | - if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { |
|
680 | - throw new \InvalidArgumentException('Path contains files shared with you'); |
|
681 | - } |
|
682 | - } |
|
683 | - } |
|
684 | - } |
|
685 | - |
|
686 | - /** |
|
687 | - * Check if the user that is sharing can actually share |
|
688 | - * |
|
689 | - * @param IShare $share |
|
690 | - * @throws \Exception |
|
691 | - */ |
|
692 | - protected function canShare(IShare $share) { |
|
693 | - if (!$this->shareApiEnabled()) { |
|
694 | - throw new \Exception('Sharing is disabled'); |
|
695 | - } |
|
696 | - |
|
697 | - if ($this->sharingDisabledForUser($share->getSharedBy())) { |
|
698 | - throw new \Exception('Sharing is disabled for you'); |
|
699 | - } |
|
700 | - } |
|
701 | - |
|
702 | - /** |
|
703 | - * Share a path |
|
704 | - * |
|
705 | - * @param IShare $share |
|
706 | - * @return IShare The share object |
|
707 | - * @throws \Exception |
|
708 | - * |
|
709 | - * TODO: handle link share permissions or check them |
|
710 | - */ |
|
711 | - public function createShare(IShare $share) { |
|
712 | - $this->canShare($share); |
|
713 | - |
|
714 | - $this->generalCreateChecks($share); |
|
715 | - |
|
716 | - // Verify if there are any issues with the path |
|
717 | - $this->pathCreateChecks($share->getNode()); |
|
718 | - |
|
719 | - /* |
|
612 | + $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP); |
|
613 | + $existingShares = $provider->getSharesByPath($share->getNode()); |
|
614 | + foreach ($existingShares as $existingShare) { |
|
615 | + try { |
|
616 | + if ($existingShare->getFullId() === $share->getFullId()) { |
|
617 | + continue; |
|
618 | + } |
|
619 | + } catch (\UnexpectedValueException $e) { |
|
620 | + //It is a new share so just continue |
|
621 | + } |
|
622 | + |
|
623 | + if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) { |
|
624 | + throw new \Exception('Path is already shared with this group'); |
|
625 | + } |
|
626 | + } |
|
627 | + } |
|
628 | + |
|
629 | + /** |
|
630 | + * Check for pre share requirements for link shares |
|
631 | + * |
|
632 | + * @param IShare $share |
|
633 | + * @throws \Exception |
|
634 | + */ |
|
635 | + protected function linkCreateChecks(IShare $share) { |
|
636 | + // Are link shares allowed? |
|
637 | + if (!$this->shareApiAllowLinks()) { |
|
638 | + throw new \Exception('Link sharing is not allowed'); |
|
639 | + } |
|
640 | + |
|
641 | + // Check if public upload is allowed |
|
642 | + if (!$this->shareApiLinkAllowPublicUpload() && |
|
643 | + ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) { |
|
644 | + throw new \InvalidArgumentException('Public upload is not allowed'); |
|
645 | + } |
|
646 | + } |
|
647 | + |
|
648 | + /** |
|
649 | + * To make sure we don't get invisible link shares we set the parent |
|
650 | + * of a link if it is a reshare. This is a quick word around |
|
651 | + * until we can properly display multiple link shares in the UI |
|
652 | + * |
|
653 | + * See: https://github.com/owncloud/core/issues/22295 |
|
654 | + * |
|
655 | + * FIXME: Remove once multiple link shares can be properly displayed |
|
656 | + * |
|
657 | + * @param IShare $share |
|
658 | + */ |
|
659 | + protected function setLinkParent(IShare $share) { |
|
660 | + |
|
661 | + // No sense in checking if the method is not there. |
|
662 | + if (method_exists($share, 'setParent')) { |
|
663 | + $storage = $share->getNode()->getStorage(); |
|
664 | + if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { |
|
665 | + /** @var \OCA\Files_Sharing\SharedStorage $storage */ |
|
666 | + $share->setParent($storage->getShareId()); |
|
667 | + } |
|
668 | + } |
|
669 | + } |
|
670 | + |
|
671 | + /** |
|
672 | + * @param File|Folder $path |
|
673 | + */ |
|
674 | + protected function pathCreateChecks($path) { |
|
675 | + // Make sure that we do not share a path that contains a shared mountpoint |
|
676 | + if ($path instanceof \OCP\Files\Folder) { |
|
677 | + $mounts = $this->mountManager->findIn($path->getPath()); |
|
678 | + foreach ($mounts as $mount) { |
|
679 | + if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { |
|
680 | + throw new \InvalidArgumentException('Path contains files shared with you'); |
|
681 | + } |
|
682 | + } |
|
683 | + } |
|
684 | + } |
|
685 | + |
|
686 | + /** |
|
687 | + * Check if the user that is sharing can actually share |
|
688 | + * |
|
689 | + * @param IShare $share |
|
690 | + * @throws \Exception |
|
691 | + */ |
|
692 | + protected function canShare(IShare $share) { |
|
693 | + if (!$this->shareApiEnabled()) { |
|
694 | + throw new \Exception('Sharing is disabled'); |
|
695 | + } |
|
696 | + |
|
697 | + if ($this->sharingDisabledForUser($share->getSharedBy())) { |
|
698 | + throw new \Exception('Sharing is disabled for you'); |
|
699 | + } |
|
700 | + } |
|
701 | + |
|
702 | + /** |
|
703 | + * Share a path |
|
704 | + * |
|
705 | + * @param IShare $share |
|
706 | + * @return IShare The share object |
|
707 | + * @throws \Exception |
|
708 | + * |
|
709 | + * TODO: handle link share permissions or check them |
|
710 | + */ |
|
711 | + public function createShare(IShare $share) { |
|
712 | + $this->canShare($share); |
|
713 | + |
|
714 | + $this->generalCreateChecks($share); |
|
715 | + |
|
716 | + // Verify if there are any issues with the path |
|
717 | + $this->pathCreateChecks($share->getNode()); |
|
718 | + |
|
719 | + /* |
|
720 | 720 | * On creation of a share the owner is always the owner of the path |
721 | 721 | * Except for mounted federated shares. |
722 | 722 | */ |
723 | - $storage = $share->getNode()->getStorage(); |
|
724 | - if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { |
|
725 | - $parent = $share->getNode()->getParent(); |
|
726 | - while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { |
|
727 | - $parent = $parent->getParent(); |
|
728 | - } |
|
729 | - $share->setShareOwner($parent->getOwner()->getUID()); |
|
730 | - } else { |
|
731 | - if ($share->getNode()->getOwner()) { |
|
732 | - $share->setShareOwner($share->getNode()->getOwner()->getUID()); |
|
733 | - } else { |
|
734 | - $share->setShareOwner($share->getSharedBy()); |
|
735 | - } |
|
736 | - } |
|
737 | - |
|
738 | - //Verify share type |
|
739 | - if ($share->getShareType() === IShare::TYPE_USER) { |
|
740 | - $this->userCreateChecks($share); |
|
741 | - |
|
742 | - //Verify the expiration date |
|
743 | - $share = $this->validateExpirationDateInternal($share); |
|
744 | - } elseif ($share->getShareType() === IShare::TYPE_GROUP) { |
|
745 | - $this->groupCreateChecks($share); |
|
746 | - |
|
747 | - //Verify the expiration date |
|
748 | - $share = $this->validateExpirationDateInternal($share); |
|
749 | - } elseif ($share->getShareType() === IShare::TYPE_LINK) { |
|
750 | - $this->linkCreateChecks($share); |
|
751 | - $this->setLinkParent($share); |
|
752 | - |
|
753 | - /* |
|
723 | + $storage = $share->getNode()->getStorage(); |
|
724 | + if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { |
|
725 | + $parent = $share->getNode()->getParent(); |
|
726 | + while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { |
|
727 | + $parent = $parent->getParent(); |
|
728 | + } |
|
729 | + $share->setShareOwner($parent->getOwner()->getUID()); |
|
730 | + } else { |
|
731 | + if ($share->getNode()->getOwner()) { |
|
732 | + $share->setShareOwner($share->getNode()->getOwner()->getUID()); |
|
733 | + } else { |
|
734 | + $share->setShareOwner($share->getSharedBy()); |
|
735 | + } |
|
736 | + } |
|
737 | + |
|
738 | + //Verify share type |
|
739 | + if ($share->getShareType() === IShare::TYPE_USER) { |
|
740 | + $this->userCreateChecks($share); |
|
741 | + |
|
742 | + //Verify the expiration date |
|
743 | + $share = $this->validateExpirationDateInternal($share); |
|
744 | + } elseif ($share->getShareType() === IShare::TYPE_GROUP) { |
|
745 | + $this->groupCreateChecks($share); |
|
746 | + |
|
747 | + //Verify the expiration date |
|
748 | + $share = $this->validateExpirationDateInternal($share); |
|
749 | + } elseif ($share->getShareType() === IShare::TYPE_LINK) { |
|
750 | + $this->linkCreateChecks($share); |
|
751 | + $this->setLinkParent($share); |
|
752 | + |
|
753 | + /* |
|
754 | 754 | * For now ignore a set token. |
755 | 755 | */ |
756 | - $share->setToken( |
|
757 | - $this->secureRandom->generate( |
|
758 | - \OC\Share\Constants::TOKEN_LENGTH, |
|
759 | - \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE |
|
760 | - ) |
|
761 | - ); |
|
762 | - |
|
763 | - //Verify the expiration date |
|
764 | - $share = $this->validateExpirationDate($share); |
|
765 | - |
|
766 | - //Verify the password |
|
767 | - $this->verifyPassword($share->getPassword()); |
|
768 | - |
|
769 | - // If a password is set. Hash it! |
|
770 | - if ($share->getPassword() !== null) { |
|
771 | - $share->setPassword($this->hasher->hash($share->getPassword())); |
|
772 | - } |
|
773 | - } elseif ($share->getShareType() === IShare::TYPE_EMAIL) { |
|
774 | - $share->setToken( |
|
775 | - $this->secureRandom->generate( |
|
776 | - \OC\Share\Constants::TOKEN_LENGTH, |
|
777 | - \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE |
|
778 | - ) |
|
779 | - ); |
|
780 | - } |
|
781 | - |
|
782 | - // Cannot share with the owner |
|
783 | - if ($share->getShareType() === IShare::TYPE_USER && |
|
784 | - $share->getSharedWith() === $share->getShareOwner()) { |
|
785 | - throw new \InvalidArgumentException('Can’t share with the share owner'); |
|
786 | - } |
|
787 | - |
|
788 | - // Generate the target |
|
789 | - $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName(); |
|
790 | - $target = \OC\Files\Filesystem::normalizePath($target); |
|
791 | - $share->setTarget($target); |
|
792 | - |
|
793 | - // Pre share event |
|
794 | - $event = new GenericEvent($share); |
|
795 | - $this->legacyDispatcher->dispatch('OCP\Share::preShare', $event); |
|
796 | - if ($event->isPropagationStopped() && $event->hasArgument('error')) { |
|
797 | - throw new \Exception($event->getArgument('error')); |
|
798 | - } |
|
799 | - |
|
800 | - $oldShare = $share; |
|
801 | - $provider = $this->factory->getProviderForType($share->getShareType()); |
|
802 | - $share = $provider->create($share); |
|
803 | - //reuse the node we already have |
|
804 | - $share->setNode($oldShare->getNode()); |
|
805 | - |
|
806 | - // Reset the target if it is null for the new share |
|
807 | - if ($share->getTarget() === '') { |
|
808 | - $share->setTarget($target); |
|
809 | - } |
|
810 | - |
|
811 | - // Post share event |
|
812 | - $event = new GenericEvent($share); |
|
813 | - $this->legacyDispatcher->dispatch('OCP\Share::postShare', $event); |
|
814 | - |
|
815 | - $this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share)); |
|
816 | - |
|
817 | - if ($this->config->getSystemValueBool('sharing.enable_share_mail', true) |
|
818 | - && $share->getShareType() === IShare::TYPE_USER) { |
|
819 | - $mailSend = $share->getMailSend(); |
|
820 | - if ($mailSend === true) { |
|
821 | - $user = $this->userManager->get($share->getSharedWith()); |
|
822 | - if ($user !== null) { |
|
823 | - $emailAddress = $user->getEMailAddress(); |
|
824 | - if ($emailAddress !== null && $emailAddress !== '') { |
|
825 | - $userLang = $this->l10nFactory->getUserLanguage($user); |
|
826 | - $l = $this->l10nFactory->get('lib', $userLang); |
|
827 | - $this->sendMailNotification( |
|
828 | - $l, |
|
829 | - $share->getNode()->getName(), |
|
830 | - $this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]), |
|
831 | - $share->getSharedBy(), |
|
832 | - $emailAddress, |
|
833 | - $share->getExpirationDate() |
|
834 | - ); |
|
835 | - $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']); |
|
836 | - } else { |
|
837 | - $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']); |
|
838 | - } |
|
839 | - } else { |
|
840 | - $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']); |
|
841 | - } |
|
842 | - } else { |
|
843 | - $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']); |
|
844 | - } |
|
845 | - } |
|
846 | - |
|
847 | - return $share; |
|
848 | - } |
|
849 | - |
|
850 | - /** |
|
851 | - * Send mail notifications |
|
852 | - * |
|
853 | - * This method will catch and log mail transmission errors |
|
854 | - * |
|
855 | - * @param IL10N $l Language of the recipient |
|
856 | - * @param string $filename file/folder name |
|
857 | - * @param string $link link to the file/folder |
|
858 | - * @param string $initiator user ID of share sender |
|
859 | - * @param string $shareWith email address of share receiver |
|
860 | - * @param \DateTime|null $expiration |
|
861 | - */ |
|
862 | - protected function sendMailNotification(IL10N $l, |
|
863 | - $filename, |
|
864 | - $link, |
|
865 | - $initiator, |
|
866 | - $shareWith, |
|
867 | - \DateTime $expiration = null) { |
|
868 | - $initiatorUser = $this->userManager->get($initiator); |
|
869 | - $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator; |
|
870 | - |
|
871 | - $message = $this->mailer->createMessage(); |
|
872 | - |
|
873 | - $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [ |
|
874 | - 'filename' => $filename, |
|
875 | - 'link' => $link, |
|
876 | - 'initiator' => $initiatorDisplayName, |
|
877 | - 'expiration' => $expiration, |
|
878 | - 'shareWith' => $shareWith, |
|
879 | - ]); |
|
880 | - |
|
881 | - $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename])); |
|
882 | - $emailTemplate->addHeader(); |
|
883 | - $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false); |
|
884 | - $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]); |
|
885 | - |
|
886 | - $emailTemplate->addBodyText( |
|
887 | - htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')), |
|
888 | - $text |
|
889 | - ); |
|
890 | - $emailTemplate->addBodyButton( |
|
891 | - $l->t('Open »%s«', [$filename]), |
|
892 | - $link |
|
893 | - ); |
|
894 | - |
|
895 | - $message->setTo([$shareWith]); |
|
896 | - |
|
897 | - // The "From" contains the sharers name |
|
898 | - $instanceName = $this->defaults->getName(); |
|
899 | - $senderName = $l->t( |
|
900 | - '%1$s via %2$s', |
|
901 | - [ |
|
902 | - $initiatorDisplayName, |
|
903 | - $instanceName |
|
904 | - ] |
|
905 | - ); |
|
906 | - $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]); |
|
907 | - |
|
908 | - // The "Reply-To" is set to the sharer if an mail address is configured |
|
909 | - // also the default footer contains a "Do not reply" which needs to be adjusted. |
|
910 | - $initiatorEmail = $initiatorUser->getEMailAddress(); |
|
911 | - if ($initiatorEmail !== null) { |
|
912 | - $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]); |
|
913 | - $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan($l->getLanguageCode()) !== '' ? ' - ' . $this->defaults->getSlogan($l->getLanguageCode()) : '')); |
|
914 | - } else { |
|
915 | - $emailTemplate->addFooter('', $l->getLanguageCode()); |
|
916 | - } |
|
917 | - |
|
918 | - $message->useTemplate($emailTemplate); |
|
919 | - try { |
|
920 | - $failedRecipients = $this->mailer->send($message); |
|
921 | - if (!empty($failedRecipients)) { |
|
922 | - $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients)); |
|
923 | - return; |
|
924 | - } |
|
925 | - } catch (\Exception $e) { |
|
926 | - $this->logger->logException($e, ['message' => 'Share notification mail could not be sent']); |
|
927 | - } |
|
928 | - } |
|
929 | - |
|
930 | - /** |
|
931 | - * Update a share |
|
932 | - * |
|
933 | - * @param IShare $share |
|
934 | - * @return IShare The share object |
|
935 | - * @throws \InvalidArgumentException |
|
936 | - */ |
|
937 | - public function updateShare(IShare $share) { |
|
938 | - $expirationDateUpdated = false; |
|
939 | - |
|
940 | - $this->canShare($share); |
|
941 | - |
|
942 | - try { |
|
943 | - $originalShare = $this->getShareById($share->getFullId()); |
|
944 | - } catch (\UnexpectedValueException $e) { |
|
945 | - throw new \InvalidArgumentException('Share does not have a full id'); |
|
946 | - } |
|
947 | - |
|
948 | - // We can't change the share type! |
|
949 | - if ($share->getShareType() !== $originalShare->getShareType()) { |
|
950 | - throw new \InvalidArgumentException('Can’t change share type'); |
|
951 | - } |
|
952 | - |
|
953 | - // We can only change the recipient on user shares |
|
954 | - if ($share->getSharedWith() !== $originalShare->getSharedWith() && |
|
955 | - $share->getShareType() !== IShare::TYPE_USER) { |
|
956 | - throw new \InvalidArgumentException('Can only update recipient on user shares'); |
|
957 | - } |
|
958 | - |
|
959 | - // Cannot share with the owner |
|
960 | - if ($share->getShareType() === IShare::TYPE_USER && |
|
961 | - $share->getSharedWith() === $share->getShareOwner()) { |
|
962 | - throw new \InvalidArgumentException('Can’t share with the share owner'); |
|
963 | - } |
|
964 | - |
|
965 | - $this->generalCreateChecks($share); |
|
966 | - |
|
967 | - if ($share->getShareType() === IShare::TYPE_USER) { |
|
968 | - $this->userCreateChecks($share); |
|
969 | - |
|
970 | - if ($share->getExpirationDate() != $originalShare->getExpirationDate()) { |
|
971 | - //Verify the expiration date |
|
972 | - $this->validateExpirationDate($share); |
|
973 | - $expirationDateUpdated = true; |
|
974 | - } |
|
975 | - } elseif ($share->getShareType() === IShare::TYPE_GROUP) { |
|
976 | - $this->groupCreateChecks($share); |
|
977 | - |
|
978 | - if ($share->getExpirationDate() != $originalShare->getExpirationDate()) { |
|
979 | - //Verify the expiration date |
|
980 | - $this->validateExpirationDate($share); |
|
981 | - $expirationDateUpdated = true; |
|
982 | - } |
|
983 | - } elseif ($share->getShareType() === IShare::TYPE_LINK) { |
|
984 | - $this->linkCreateChecks($share); |
|
985 | - |
|
986 | - $plainTextPassword = $share->getPassword(); |
|
987 | - |
|
988 | - $this->updateSharePasswordIfNeeded($share, $originalShare); |
|
989 | - |
|
990 | - if (empty($plainTextPassword) && $share->getSendPasswordByTalk()) { |
|
991 | - throw new \InvalidArgumentException('Can’t enable sending the password by Talk with an empty password'); |
|
992 | - } |
|
993 | - |
|
994 | - if ($share->getExpirationDate() != $originalShare->getExpirationDate()) { |
|
995 | - //Verify the expiration date |
|
996 | - $this->validateExpirationDate($share); |
|
997 | - $expirationDateUpdated = true; |
|
998 | - } |
|
999 | - } elseif ($share->getShareType() === IShare::TYPE_EMAIL) { |
|
1000 | - // The new password is not set again if it is the same as the old |
|
1001 | - // one. |
|
1002 | - $plainTextPassword = $share->getPassword(); |
|
1003 | - if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare)) { |
|
1004 | - $plainTextPassword = null; |
|
1005 | - } |
|
1006 | - if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) { |
|
1007 | - // If the same password was already sent by mail the recipient |
|
1008 | - // would already have access to the share without having to call |
|
1009 | - // the sharer to verify her identity |
|
1010 | - throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password'); |
|
1011 | - } elseif (empty($plainTextPassword) && $originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()) { |
|
1012 | - throw new \InvalidArgumentException('Can’t disable sending the password by Talk without setting a new password'); |
|
1013 | - } |
|
1014 | - } |
|
1015 | - |
|
1016 | - $this->pathCreateChecks($share->getNode()); |
|
1017 | - |
|
1018 | - // Now update the share! |
|
1019 | - $provider = $this->factory->getProviderForType($share->getShareType()); |
|
1020 | - if ($share->getShareType() === IShare::TYPE_EMAIL) { |
|
1021 | - $share = $provider->update($share, $plainTextPassword); |
|
1022 | - } else { |
|
1023 | - $share = $provider->update($share); |
|
1024 | - } |
|
1025 | - |
|
1026 | - if ($expirationDateUpdated === true) { |
|
1027 | - \OC_Hook::emit(Share::class, 'post_set_expiration_date', [ |
|
1028 | - 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', |
|
1029 | - 'itemSource' => $share->getNode()->getId(), |
|
1030 | - 'date' => $share->getExpirationDate(), |
|
1031 | - 'uidOwner' => $share->getSharedBy(), |
|
1032 | - ]); |
|
1033 | - } |
|
1034 | - |
|
1035 | - if ($share->getPassword() !== $originalShare->getPassword()) { |
|
1036 | - \OC_Hook::emit(Share::class, 'post_update_password', [ |
|
1037 | - 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', |
|
1038 | - 'itemSource' => $share->getNode()->getId(), |
|
1039 | - 'uidOwner' => $share->getSharedBy(), |
|
1040 | - 'token' => $share->getToken(), |
|
1041 | - 'disabled' => is_null($share->getPassword()), |
|
1042 | - ]); |
|
1043 | - } |
|
1044 | - |
|
1045 | - if ($share->getPermissions() !== $originalShare->getPermissions()) { |
|
1046 | - if ($this->userManager->userExists($share->getShareOwner())) { |
|
1047 | - $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()); |
|
1048 | - } else { |
|
1049 | - $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); |
|
1050 | - } |
|
1051 | - \OC_Hook::emit(Share::class, 'post_update_permissions', [ |
|
1052 | - 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', |
|
1053 | - 'itemSource' => $share->getNode()->getId(), |
|
1054 | - 'shareType' => $share->getShareType(), |
|
1055 | - 'shareWith' => $share->getSharedWith(), |
|
1056 | - 'uidOwner' => $share->getSharedBy(), |
|
1057 | - 'permissions' => $share->getPermissions(), |
|
1058 | - 'path' => $userFolder->getRelativePath($share->getNode()->getPath()), |
|
1059 | - ]); |
|
1060 | - } |
|
1061 | - |
|
1062 | - return $share; |
|
1063 | - } |
|
1064 | - |
|
1065 | - /** |
|
1066 | - * Accept a share. |
|
1067 | - * |
|
1068 | - * @param IShare $share |
|
1069 | - * @param string $recipientId |
|
1070 | - * @return IShare The share object |
|
1071 | - * @throws \InvalidArgumentException |
|
1072 | - * @since 9.0.0 |
|
1073 | - */ |
|
1074 | - public function acceptShare(IShare $share, string $recipientId): IShare { |
|
1075 | - [$providerId, ] = $this->splitFullId($share->getFullId()); |
|
1076 | - $provider = $this->factory->getProvider($providerId); |
|
1077 | - |
|
1078 | - if (!method_exists($provider, 'acceptShare')) { |
|
1079 | - // TODO FIX ME |
|
1080 | - throw new \InvalidArgumentException('Share provider does not support accepting'); |
|
1081 | - } |
|
1082 | - $provider->acceptShare($share, $recipientId); |
|
1083 | - $event = new GenericEvent($share); |
|
1084 | - $this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event); |
|
1085 | - |
|
1086 | - return $share; |
|
1087 | - } |
|
1088 | - |
|
1089 | - /** |
|
1090 | - * Updates the password of the given share if it is not the same as the |
|
1091 | - * password of the original share. |
|
1092 | - * |
|
1093 | - * @param IShare $share the share to update its password. |
|
1094 | - * @param IShare $originalShare the original share to compare its |
|
1095 | - * password with. |
|
1096 | - * @return boolean whether the password was updated or not. |
|
1097 | - */ |
|
1098 | - private function updateSharePasswordIfNeeded(IShare $share, IShare $originalShare) { |
|
1099 | - $passwordsAreDifferent = ($share->getPassword() !== $originalShare->getPassword()) && |
|
1100 | - (($share->getPassword() !== null && $originalShare->getPassword() === null) || |
|
1101 | - ($share->getPassword() === null && $originalShare->getPassword() !== null) || |
|
1102 | - ($share->getPassword() !== null && $originalShare->getPassword() !== null && |
|
1103 | - !$this->hasher->verify($share->getPassword(), $originalShare->getPassword()))); |
|
1104 | - |
|
1105 | - // Password updated. |
|
1106 | - if ($passwordsAreDifferent) { |
|
1107 | - //Verify the password |
|
1108 | - $this->verifyPassword($share->getPassword()); |
|
1109 | - |
|
1110 | - // If a password is set. Hash it! |
|
1111 | - if ($share->getPassword() !== null) { |
|
1112 | - $share->setPassword($this->hasher->hash($share->getPassword())); |
|
1113 | - |
|
1114 | - return true; |
|
1115 | - } |
|
1116 | - } else { |
|
1117 | - // Reset the password to the original one, as it is either the same |
|
1118 | - // as the "new" password or a hashed version of it. |
|
1119 | - $share->setPassword($originalShare->getPassword()); |
|
1120 | - } |
|
1121 | - |
|
1122 | - return false; |
|
1123 | - } |
|
1124 | - |
|
1125 | - /** |
|
1126 | - * Delete all the children of this share |
|
1127 | - * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in |
|
1128 | - * |
|
1129 | - * @param IShare $share |
|
1130 | - * @return IShare[] List of deleted shares |
|
1131 | - */ |
|
1132 | - protected function deleteChildren(IShare $share) { |
|
1133 | - $deletedShares = []; |
|
1134 | - |
|
1135 | - $provider = $this->factory->getProviderForType($share->getShareType()); |
|
1136 | - |
|
1137 | - foreach ($provider->getChildren($share) as $child) { |
|
1138 | - $deletedChildren = $this->deleteChildren($child); |
|
1139 | - $deletedShares = array_merge($deletedShares, $deletedChildren); |
|
1140 | - |
|
1141 | - $provider->delete($child); |
|
1142 | - $this->dispatcher->dispatchTyped(new Share\Events\ShareDeletedEvent($child)); |
|
1143 | - $deletedShares[] = $child; |
|
1144 | - } |
|
1145 | - |
|
1146 | - return $deletedShares; |
|
1147 | - } |
|
1148 | - |
|
1149 | - /** |
|
1150 | - * Delete a share |
|
1151 | - * |
|
1152 | - * @param IShare $share |
|
1153 | - * @throws ShareNotFound |
|
1154 | - * @throws \InvalidArgumentException |
|
1155 | - */ |
|
1156 | - public function deleteShare(IShare $share) { |
|
1157 | - try { |
|
1158 | - $share->getFullId(); |
|
1159 | - } catch (\UnexpectedValueException $e) { |
|
1160 | - throw new \InvalidArgumentException('Share does not have a full id'); |
|
1161 | - } |
|
1162 | - |
|
1163 | - $event = new GenericEvent($share); |
|
1164 | - $this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event); |
|
1165 | - |
|
1166 | - // Get all children and delete them as well |
|
1167 | - $deletedShares = $this->deleteChildren($share); |
|
1168 | - |
|
1169 | - // Do the actual delete |
|
1170 | - $provider = $this->factory->getProviderForType($share->getShareType()); |
|
1171 | - $provider->delete($share); |
|
1172 | - |
|
1173 | - $this->dispatcher->dispatchTyped(new Share\Events\ShareDeletedEvent($share)); |
|
1174 | - |
|
1175 | - // All the deleted shares caused by this delete |
|
1176 | - $deletedShares[] = $share; |
|
1177 | - |
|
1178 | - // Emit post hook |
|
1179 | - $event->setArgument('deletedShares', $deletedShares); |
|
1180 | - $this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event); |
|
1181 | - } |
|
1182 | - |
|
1183 | - |
|
1184 | - /** |
|
1185 | - * Unshare a file as the recipient. |
|
1186 | - * This can be different from a regular delete for example when one of |
|
1187 | - * the users in a groups deletes that share. But the provider should |
|
1188 | - * handle this. |
|
1189 | - * |
|
1190 | - * @param IShare $share |
|
1191 | - * @param string $recipientId |
|
1192 | - */ |
|
1193 | - public function deleteFromSelf(IShare $share, $recipientId) { |
|
1194 | - [$providerId, ] = $this->splitFullId($share->getFullId()); |
|
1195 | - $provider = $this->factory->getProvider($providerId); |
|
1196 | - |
|
1197 | - $provider->deleteFromSelf($share, $recipientId); |
|
1198 | - $event = new GenericEvent($share); |
|
1199 | - $this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event); |
|
1200 | - } |
|
1201 | - |
|
1202 | - public function restoreShare(IShare $share, string $recipientId): IShare { |
|
1203 | - [$providerId, ] = $this->splitFullId($share->getFullId()); |
|
1204 | - $provider = $this->factory->getProvider($providerId); |
|
1205 | - |
|
1206 | - return $provider->restore($share, $recipientId); |
|
1207 | - } |
|
1208 | - |
|
1209 | - /** |
|
1210 | - * @inheritdoc |
|
1211 | - */ |
|
1212 | - public function moveShare(IShare $share, $recipientId) { |
|
1213 | - if ($share->getShareType() === IShare::TYPE_LINK) { |
|
1214 | - throw new \InvalidArgumentException('Can’t change target of link share'); |
|
1215 | - } |
|
1216 | - |
|
1217 | - if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() !== $recipientId) { |
|
1218 | - throw new \InvalidArgumentException('Invalid recipient'); |
|
1219 | - } |
|
1220 | - |
|
1221 | - if ($share->getShareType() === IShare::TYPE_GROUP) { |
|
1222 | - $sharedWith = $this->groupManager->get($share->getSharedWith()); |
|
1223 | - if (is_null($sharedWith)) { |
|
1224 | - throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist'); |
|
1225 | - } |
|
1226 | - $recipient = $this->userManager->get($recipientId); |
|
1227 | - if (!$sharedWith->inGroup($recipient)) { |
|
1228 | - throw new \InvalidArgumentException('Invalid recipient'); |
|
1229 | - } |
|
1230 | - } |
|
1231 | - |
|
1232 | - [$providerId, ] = $this->splitFullId($share->getFullId()); |
|
1233 | - $provider = $this->factory->getProvider($providerId); |
|
1234 | - |
|
1235 | - return $provider->move($share, $recipientId); |
|
1236 | - } |
|
1237 | - |
|
1238 | - public function getSharesInFolder($userId, Folder $node, $reshares = false) { |
|
1239 | - $providers = $this->factory->getAllProviders(); |
|
1240 | - |
|
1241 | - return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares) { |
|
1242 | - $newShares = $provider->getSharesInFolder($userId, $node, $reshares); |
|
1243 | - foreach ($newShares as $fid => $data) { |
|
1244 | - if (!isset($shares[$fid])) { |
|
1245 | - $shares[$fid] = []; |
|
1246 | - } |
|
1247 | - |
|
1248 | - $shares[$fid] = array_merge($shares[$fid], $data); |
|
1249 | - } |
|
1250 | - return $shares; |
|
1251 | - }, []); |
|
1252 | - } |
|
1253 | - |
|
1254 | - /** |
|
1255 | - * @inheritdoc |
|
1256 | - */ |
|
1257 | - public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) { |
|
1258 | - if ($path !== null && |
|
1259 | - !($path instanceof \OCP\Files\File) && |
|
1260 | - !($path instanceof \OCP\Files\Folder)) { |
|
1261 | - throw new \InvalidArgumentException('invalid path'); |
|
1262 | - } |
|
1263 | - |
|
1264 | - try { |
|
1265 | - $provider = $this->factory->getProviderForType($shareType); |
|
1266 | - } catch (ProviderException $e) { |
|
1267 | - return []; |
|
1268 | - } |
|
1269 | - |
|
1270 | - $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset); |
|
1271 | - |
|
1272 | - /* |
|
756 | + $share->setToken( |
|
757 | + $this->secureRandom->generate( |
|
758 | + \OC\Share\Constants::TOKEN_LENGTH, |
|
759 | + \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE |
|
760 | + ) |
|
761 | + ); |
|
762 | + |
|
763 | + //Verify the expiration date |
|
764 | + $share = $this->validateExpirationDate($share); |
|
765 | + |
|
766 | + //Verify the password |
|
767 | + $this->verifyPassword($share->getPassword()); |
|
768 | + |
|
769 | + // If a password is set. Hash it! |
|
770 | + if ($share->getPassword() !== null) { |
|
771 | + $share->setPassword($this->hasher->hash($share->getPassword())); |
|
772 | + } |
|
773 | + } elseif ($share->getShareType() === IShare::TYPE_EMAIL) { |
|
774 | + $share->setToken( |
|
775 | + $this->secureRandom->generate( |
|
776 | + \OC\Share\Constants::TOKEN_LENGTH, |
|
777 | + \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE |
|
778 | + ) |
|
779 | + ); |
|
780 | + } |
|
781 | + |
|
782 | + // Cannot share with the owner |
|
783 | + if ($share->getShareType() === IShare::TYPE_USER && |
|
784 | + $share->getSharedWith() === $share->getShareOwner()) { |
|
785 | + throw new \InvalidArgumentException('Can’t share with the share owner'); |
|
786 | + } |
|
787 | + |
|
788 | + // Generate the target |
|
789 | + $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName(); |
|
790 | + $target = \OC\Files\Filesystem::normalizePath($target); |
|
791 | + $share->setTarget($target); |
|
792 | + |
|
793 | + // Pre share event |
|
794 | + $event = new GenericEvent($share); |
|
795 | + $this->legacyDispatcher->dispatch('OCP\Share::preShare', $event); |
|
796 | + if ($event->isPropagationStopped() && $event->hasArgument('error')) { |
|
797 | + throw new \Exception($event->getArgument('error')); |
|
798 | + } |
|
799 | + |
|
800 | + $oldShare = $share; |
|
801 | + $provider = $this->factory->getProviderForType($share->getShareType()); |
|
802 | + $share = $provider->create($share); |
|
803 | + //reuse the node we already have |
|
804 | + $share->setNode($oldShare->getNode()); |
|
805 | + |
|
806 | + // Reset the target if it is null for the new share |
|
807 | + if ($share->getTarget() === '') { |
|
808 | + $share->setTarget($target); |
|
809 | + } |
|
810 | + |
|
811 | + // Post share event |
|
812 | + $event = new GenericEvent($share); |
|
813 | + $this->legacyDispatcher->dispatch('OCP\Share::postShare', $event); |
|
814 | + |
|
815 | + $this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share)); |
|
816 | + |
|
817 | + if ($this->config->getSystemValueBool('sharing.enable_share_mail', true) |
|
818 | + && $share->getShareType() === IShare::TYPE_USER) { |
|
819 | + $mailSend = $share->getMailSend(); |
|
820 | + if ($mailSend === true) { |
|
821 | + $user = $this->userManager->get($share->getSharedWith()); |
|
822 | + if ($user !== null) { |
|
823 | + $emailAddress = $user->getEMailAddress(); |
|
824 | + if ($emailAddress !== null && $emailAddress !== '') { |
|
825 | + $userLang = $this->l10nFactory->getUserLanguage($user); |
|
826 | + $l = $this->l10nFactory->get('lib', $userLang); |
|
827 | + $this->sendMailNotification( |
|
828 | + $l, |
|
829 | + $share->getNode()->getName(), |
|
830 | + $this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]), |
|
831 | + $share->getSharedBy(), |
|
832 | + $emailAddress, |
|
833 | + $share->getExpirationDate() |
|
834 | + ); |
|
835 | + $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']); |
|
836 | + } else { |
|
837 | + $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']); |
|
838 | + } |
|
839 | + } else { |
|
840 | + $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']); |
|
841 | + } |
|
842 | + } else { |
|
843 | + $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']); |
|
844 | + } |
|
845 | + } |
|
846 | + |
|
847 | + return $share; |
|
848 | + } |
|
849 | + |
|
850 | + /** |
|
851 | + * Send mail notifications |
|
852 | + * |
|
853 | + * This method will catch and log mail transmission errors |
|
854 | + * |
|
855 | + * @param IL10N $l Language of the recipient |
|
856 | + * @param string $filename file/folder name |
|
857 | + * @param string $link link to the file/folder |
|
858 | + * @param string $initiator user ID of share sender |
|
859 | + * @param string $shareWith email address of share receiver |
|
860 | + * @param \DateTime|null $expiration |
|
861 | + */ |
|
862 | + protected function sendMailNotification(IL10N $l, |
|
863 | + $filename, |
|
864 | + $link, |
|
865 | + $initiator, |
|
866 | + $shareWith, |
|
867 | + \DateTime $expiration = null) { |
|
868 | + $initiatorUser = $this->userManager->get($initiator); |
|
869 | + $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator; |
|
870 | + |
|
871 | + $message = $this->mailer->createMessage(); |
|
872 | + |
|
873 | + $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [ |
|
874 | + 'filename' => $filename, |
|
875 | + 'link' => $link, |
|
876 | + 'initiator' => $initiatorDisplayName, |
|
877 | + 'expiration' => $expiration, |
|
878 | + 'shareWith' => $shareWith, |
|
879 | + ]); |
|
880 | + |
|
881 | + $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename])); |
|
882 | + $emailTemplate->addHeader(); |
|
883 | + $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false); |
|
884 | + $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]); |
|
885 | + |
|
886 | + $emailTemplate->addBodyText( |
|
887 | + htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')), |
|
888 | + $text |
|
889 | + ); |
|
890 | + $emailTemplate->addBodyButton( |
|
891 | + $l->t('Open »%s«', [$filename]), |
|
892 | + $link |
|
893 | + ); |
|
894 | + |
|
895 | + $message->setTo([$shareWith]); |
|
896 | + |
|
897 | + // The "From" contains the sharers name |
|
898 | + $instanceName = $this->defaults->getName(); |
|
899 | + $senderName = $l->t( |
|
900 | + '%1$s via %2$s', |
|
901 | + [ |
|
902 | + $initiatorDisplayName, |
|
903 | + $instanceName |
|
904 | + ] |
|
905 | + ); |
|
906 | + $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]); |
|
907 | + |
|
908 | + // The "Reply-To" is set to the sharer if an mail address is configured |
|
909 | + // also the default footer contains a "Do not reply" which needs to be adjusted. |
|
910 | + $initiatorEmail = $initiatorUser->getEMailAddress(); |
|
911 | + if ($initiatorEmail !== null) { |
|
912 | + $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]); |
|
913 | + $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan($l->getLanguageCode()) !== '' ? ' - ' . $this->defaults->getSlogan($l->getLanguageCode()) : '')); |
|
914 | + } else { |
|
915 | + $emailTemplate->addFooter('', $l->getLanguageCode()); |
|
916 | + } |
|
917 | + |
|
918 | + $message->useTemplate($emailTemplate); |
|
919 | + try { |
|
920 | + $failedRecipients = $this->mailer->send($message); |
|
921 | + if (!empty($failedRecipients)) { |
|
922 | + $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients)); |
|
923 | + return; |
|
924 | + } |
|
925 | + } catch (\Exception $e) { |
|
926 | + $this->logger->logException($e, ['message' => 'Share notification mail could not be sent']); |
|
927 | + } |
|
928 | + } |
|
929 | + |
|
930 | + /** |
|
931 | + * Update a share |
|
932 | + * |
|
933 | + * @param IShare $share |
|
934 | + * @return IShare The share object |
|
935 | + * @throws \InvalidArgumentException |
|
936 | + */ |
|
937 | + public function updateShare(IShare $share) { |
|
938 | + $expirationDateUpdated = false; |
|
939 | + |
|
940 | + $this->canShare($share); |
|
941 | + |
|
942 | + try { |
|
943 | + $originalShare = $this->getShareById($share->getFullId()); |
|
944 | + } catch (\UnexpectedValueException $e) { |
|
945 | + throw new \InvalidArgumentException('Share does not have a full id'); |
|
946 | + } |
|
947 | + |
|
948 | + // We can't change the share type! |
|
949 | + if ($share->getShareType() !== $originalShare->getShareType()) { |
|
950 | + throw new \InvalidArgumentException('Can’t change share type'); |
|
951 | + } |
|
952 | + |
|
953 | + // We can only change the recipient on user shares |
|
954 | + if ($share->getSharedWith() !== $originalShare->getSharedWith() && |
|
955 | + $share->getShareType() !== IShare::TYPE_USER) { |
|
956 | + throw new \InvalidArgumentException('Can only update recipient on user shares'); |
|
957 | + } |
|
958 | + |
|
959 | + // Cannot share with the owner |
|
960 | + if ($share->getShareType() === IShare::TYPE_USER && |
|
961 | + $share->getSharedWith() === $share->getShareOwner()) { |
|
962 | + throw new \InvalidArgumentException('Can’t share with the share owner'); |
|
963 | + } |
|
964 | + |
|
965 | + $this->generalCreateChecks($share); |
|
966 | + |
|
967 | + if ($share->getShareType() === IShare::TYPE_USER) { |
|
968 | + $this->userCreateChecks($share); |
|
969 | + |
|
970 | + if ($share->getExpirationDate() != $originalShare->getExpirationDate()) { |
|
971 | + //Verify the expiration date |
|
972 | + $this->validateExpirationDate($share); |
|
973 | + $expirationDateUpdated = true; |
|
974 | + } |
|
975 | + } elseif ($share->getShareType() === IShare::TYPE_GROUP) { |
|
976 | + $this->groupCreateChecks($share); |
|
977 | + |
|
978 | + if ($share->getExpirationDate() != $originalShare->getExpirationDate()) { |
|
979 | + //Verify the expiration date |
|
980 | + $this->validateExpirationDate($share); |
|
981 | + $expirationDateUpdated = true; |
|
982 | + } |
|
983 | + } elseif ($share->getShareType() === IShare::TYPE_LINK) { |
|
984 | + $this->linkCreateChecks($share); |
|
985 | + |
|
986 | + $plainTextPassword = $share->getPassword(); |
|
987 | + |
|
988 | + $this->updateSharePasswordIfNeeded($share, $originalShare); |
|
989 | + |
|
990 | + if (empty($plainTextPassword) && $share->getSendPasswordByTalk()) { |
|
991 | + throw new \InvalidArgumentException('Can’t enable sending the password by Talk with an empty password'); |
|
992 | + } |
|
993 | + |
|
994 | + if ($share->getExpirationDate() != $originalShare->getExpirationDate()) { |
|
995 | + //Verify the expiration date |
|
996 | + $this->validateExpirationDate($share); |
|
997 | + $expirationDateUpdated = true; |
|
998 | + } |
|
999 | + } elseif ($share->getShareType() === IShare::TYPE_EMAIL) { |
|
1000 | + // The new password is not set again if it is the same as the old |
|
1001 | + // one. |
|
1002 | + $plainTextPassword = $share->getPassword(); |
|
1003 | + if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare)) { |
|
1004 | + $plainTextPassword = null; |
|
1005 | + } |
|
1006 | + if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) { |
|
1007 | + // If the same password was already sent by mail the recipient |
|
1008 | + // would already have access to the share without having to call |
|
1009 | + // the sharer to verify her identity |
|
1010 | + throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password'); |
|
1011 | + } elseif (empty($plainTextPassword) && $originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()) { |
|
1012 | + throw new \InvalidArgumentException('Can’t disable sending the password by Talk without setting a new password'); |
|
1013 | + } |
|
1014 | + } |
|
1015 | + |
|
1016 | + $this->pathCreateChecks($share->getNode()); |
|
1017 | + |
|
1018 | + // Now update the share! |
|
1019 | + $provider = $this->factory->getProviderForType($share->getShareType()); |
|
1020 | + if ($share->getShareType() === IShare::TYPE_EMAIL) { |
|
1021 | + $share = $provider->update($share, $plainTextPassword); |
|
1022 | + } else { |
|
1023 | + $share = $provider->update($share); |
|
1024 | + } |
|
1025 | + |
|
1026 | + if ($expirationDateUpdated === true) { |
|
1027 | + \OC_Hook::emit(Share::class, 'post_set_expiration_date', [ |
|
1028 | + 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', |
|
1029 | + 'itemSource' => $share->getNode()->getId(), |
|
1030 | + 'date' => $share->getExpirationDate(), |
|
1031 | + 'uidOwner' => $share->getSharedBy(), |
|
1032 | + ]); |
|
1033 | + } |
|
1034 | + |
|
1035 | + if ($share->getPassword() !== $originalShare->getPassword()) { |
|
1036 | + \OC_Hook::emit(Share::class, 'post_update_password', [ |
|
1037 | + 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', |
|
1038 | + 'itemSource' => $share->getNode()->getId(), |
|
1039 | + 'uidOwner' => $share->getSharedBy(), |
|
1040 | + 'token' => $share->getToken(), |
|
1041 | + 'disabled' => is_null($share->getPassword()), |
|
1042 | + ]); |
|
1043 | + } |
|
1044 | + |
|
1045 | + if ($share->getPermissions() !== $originalShare->getPermissions()) { |
|
1046 | + if ($this->userManager->userExists($share->getShareOwner())) { |
|
1047 | + $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()); |
|
1048 | + } else { |
|
1049 | + $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); |
|
1050 | + } |
|
1051 | + \OC_Hook::emit(Share::class, 'post_update_permissions', [ |
|
1052 | + 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', |
|
1053 | + 'itemSource' => $share->getNode()->getId(), |
|
1054 | + 'shareType' => $share->getShareType(), |
|
1055 | + 'shareWith' => $share->getSharedWith(), |
|
1056 | + 'uidOwner' => $share->getSharedBy(), |
|
1057 | + 'permissions' => $share->getPermissions(), |
|
1058 | + 'path' => $userFolder->getRelativePath($share->getNode()->getPath()), |
|
1059 | + ]); |
|
1060 | + } |
|
1061 | + |
|
1062 | + return $share; |
|
1063 | + } |
|
1064 | + |
|
1065 | + /** |
|
1066 | + * Accept a share. |
|
1067 | + * |
|
1068 | + * @param IShare $share |
|
1069 | + * @param string $recipientId |
|
1070 | + * @return IShare The share object |
|
1071 | + * @throws \InvalidArgumentException |
|
1072 | + * @since 9.0.0 |
|
1073 | + */ |
|
1074 | + public function acceptShare(IShare $share, string $recipientId): IShare { |
|
1075 | + [$providerId, ] = $this->splitFullId($share->getFullId()); |
|
1076 | + $provider = $this->factory->getProvider($providerId); |
|
1077 | + |
|
1078 | + if (!method_exists($provider, 'acceptShare')) { |
|
1079 | + // TODO FIX ME |
|
1080 | + throw new \InvalidArgumentException('Share provider does not support accepting'); |
|
1081 | + } |
|
1082 | + $provider->acceptShare($share, $recipientId); |
|
1083 | + $event = new GenericEvent($share); |
|
1084 | + $this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event); |
|
1085 | + |
|
1086 | + return $share; |
|
1087 | + } |
|
1088 | + |
|
1089 | + /** |
|
1090 | + * Updates the password of the given share if it is not the same as the |
|
1091 | + * password of the original share. |
|
1092 | + * |
|
1093 | + * @param IShare $share the share to update its password. |
|
1094 | + * @param IShare $originalShare the original share to compare its |
|
1095 | + * password with. |
|
1096 | + * @return boolean whether the password was updated or not. |
|
1097 | + */ |
|
1098 | + private function updateSharePasswordIfNeeded(IShare $share, IShare $originalShare) { |
|
1099 | + $passwordsAreDifferent = ($share->getPassword() !== $originalShare->getPassword()) && |
|
1100 | + (($share->getPassword() !== null && $originalShare->getPassword() === null) || |
|
1101 | + ($share->getPassword() === null && $originalShare->getPassword() !== null) || |
|
1102 | + ($share->getPassword() !== null && $originalShare->getPassword() !== null && |
|
1103 | + !$this->hasher->verify($share->getPassword(), $originalShare->getPassword()))); |
|
1104 | + |
|
1105 | + // Password updated. |
|
1106 | + if ($passwordsAreDifferent) { |
|
1107 | + //Verify the password |
|
1108 | + $this->verifyPassword($share->getPassword()); |
|
1109 | + |
|
1110 | + // If a password is set. Hash it! |
|
1111 | + if ($share->getPassword() !== null) { |
|
1112 | + $share->setPassword($this->hasher->hash($share->getPassword())); |
|
1113 | + |
|
1114 | + return true; |
|
1115 | + } |
|
1116 | + } else { |
|
1117 | + // Reset the password to the original one, as it is either the same |
|
1118 | + // as the "new" password or a hashed version of it. |
|
1119 | + $share->setPassword($originalShare->getPassword()); |
|
1120 | + } |
|
1121 | + |
|
1122 | + return false; |
|
1123 | + } |
|
1124 | + |
|
1125 | + /** |
|
1126 | + * Delete all the children of this share |
|
1127 | + * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in |
|
1128 | + * |
|
1129 | + * @param IShare $share |
|
1130 | + * @return IShare[] List of deleted shares |
|
1131 | + */ |
|
1132 | + protected function deleteChildren(IShare $share) { |
|
1133 | + $deletedShares = []; |
|
1134 | + |
|
1135 | + $provider = $this->factory->getProviderForType($share->getShareType()); |
|
1136 | + |
|
1137 | + foreach ($provider->getChildren($share) as $child) { |
|
1138 | + $deletedChildren = $this->deleteChildren($child); |
|
1139 | + $deletedShares = array_merge($deletedShares, $deletedChildren); |
|
1140 | + |
|
1141 | + $provider->delete($child); |
|
1142 | + $this->dispatcher->dispatchTyped(new Share\Events\ShareDeletedEvent($child)); |
|
1143 | + $deletedShares[] = $child; |
|
1144 | + } |
|
1145 | + |
|
1146 | + return $deletedShares; |
|
1147 | + } |
|
1148 | + |
|
1149 | + /** |
|
1150 | + * Delete a share |
|
1151 | + * |
|
1152 | + * @param IShare $share |
|
1153 | + * @throws ShareNotFound |
|
1154 | + * @throws \InvalidArgumentException |
|
1155 | + */ |
|
1156 | + public function deleteShare(IShare $share) { |
|
1157 | + try { |
|
1158 | + $share->getFullId(); |
|
1159 | + } catch (\UnexpectedValueException $e) { |
|
1160 | + throw new \InvalidArgumentException('Share does not have a full id'); |
|
1161 | + } |
|
1162 | + |
|
1163 | + $event = new GenericEvent($share); |
|
1164 | + $this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event); |
|
1165 | + |
|
1166 | + // Get all children and delete them as well |
|
1167 | + $deletedShares = $this->deleteChildren($share); |
|
1168 | + |
|
1169 | + // Do the actual delete |
|
1170 | + $provider = $this->factory->getProviderForType($share->getShareType()); |
|
1171 | + $provider->delete($share); |
|
1172 | + |
|
1173 | + $this->dispatcher->dispatchTyped(new Share\Events\ShareDeletedEvent($share)); |
|
1174 | + |
|
1175 | + // All the deleted shares caused by this delete |
|
1176 | + $deletedShares[] = $share; |
|
1177 | + |
|
1178 | + // Emit post hook |
|
1179 | + $event->setArgument('deletedShares', $deletedShares); |
|
1180 | + $this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event); |
|
1181 | + } |
|
1182 | + |
|
1183 | + |
|
1184 | + /** |
|
1185 | + * Unshare a file as the recipient. |
|
1186 | + * This can be different from a regular delete for example when one of |
|
1187 | + * the users in a groups deletes that share. But the provider should |
|
1188 | + * handle this. |
|
1189 | + * |
|
1190 | + * @param IShare $share |
|
1191 | + * @param string $recipientId |
|
1192 | + */ |
|
1193 | + public function deleteFromSelf(IShare $share, $recipientId) { |
|
1194 | + [$providerId, ] = $this->splitFullId($share->getFullId()); |
|
1195 | + $provider = $this->factory->getProvider($providerId); |
|
1196 | + |
|
1197 | + $provider->deleteFromSelf($share, $recipientId); |
|
1198 | + $event = new GenericEvent($share); |
|
1199 | + $this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event); |
|
1200 | + } |
|
1201 | + |
|
1202 | + public function restoreShare(IShare $share, string $recipientId): IShare { |
|
1203 | + [$providerId, ] = $this->splitFullId($share->getFullId()); |
|
1204 | + $provider = $this->factory->getProvider($providerId); |
|
1205 | + |
|
1206 | + return $provider->restore($share, $recipientId); |
|
1207 | + } |
|
1208 | + |
|
1209 | + /** |
|
1210 | + * @inheritdoc |
|
1211 | + */ |
|
1212 | + public function moveShare(IShare $share, $recipientId) { |
|
1213 | + if ($share->getShareType() === IShare::TYPE_LINK) { |
|
1214 | + throw new \InvalidArgumentException('Can’t change target of link share'); |
|
1215 | + } |
|
1216 | + |
|
1217 | + if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() !== $recipientId) { |
|
1218 | + throw new \InvalidArgumentException('Invalid recipient'); |
|
1219 | + } |
|
1220 | + |
|
1221 | + if ($share->getShareType() === IShare::TYPE_GROUP) { |
|
1222 | + $sharedWith = $this->groupManager->get($share->getSharedWith()); |
|
1223 | + if (is_null($sharedWith)) { |
|
1224 | + throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist'); |
|
1225 | + } |
|
1226 | + $recipient = $this->userManager->get($recipientId); |
|
1227 | + if (!$sharedWith->inGroup($recipient)) { |
|
1228 | + throw new \InvalidArgumentException('Invalid recipient'); |
|
1229 | + } |
|
1230 | + } |
|
1231 | + |
|
1232 | + [$providerId, ] = $this->splitFullId($share->getFullId()); |
|
1233 | + $provider = $this->factory->getProvider($providerId); |
|
1234 | + |
|
1235 | + return $provider->move($share, $recipientId); |
|
1236 | + } |
|
1237 | + |
|
1238 | + public function getSharesInFolder($userId, Folder $node, $reshares = false) { |
|
1239 | + $providers = $this->factory->getAllProviders(); |
|
1240 | + |
|
1241 | + return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares) { |
|
1242 | + $newShares = $provider->getSharesInFolder($userId, $node, $reshares); |
|
1243 | + foreach ($newShares as $fid => $data) { |
|
1244 | + if (!isset($shares[$fid])) { |
|
1245 | + $shares[$fid] = []; |
|
1246 | + } |
|
1247 | + |
|
1248 | + $shares[$fid] = array_merge($shares[$fid], $data); |
|
1249 | + } |
|
1250 | + return $shares; |
|
1251 | + }, []); |
|
1252 | + } |
|
1253 | + |
|
1254 | + /** |
|
1255 | + * @inheritdoc |
|
1256 | + */ |
|
1257 | + public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) { |
|
1258 | + if ($path !== null && |
|
1259 | + !($path instanceof \OCP\Files\File) && |
|
1260 | + !($path instanceof \OCP\Files\Folder)) { |
|
1261 | + throw new \InvalidArgumentException('invalid path'); |
|
1262 | + } |
|
1263 | + |
|
1264 | + try { |
|
1265 | + $provider = $this->factory->getProviderForType($shareType); |
|
1266 | + } catch (ProviderException $e) { |
|
1267 | + return []; |
|
1268 | + } |
|
1269 | + |
|
1270 | + $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset); |
|
1271 | + |
|
1272 | + /* |
|
1273 | 1273 | * Work around so we don't return expired shares but still follow |
1274 | 1274 | * proper pagination. |
1275 | 1275 | */ |
1276 | 1276 | |
1277 | - $shares2 = []; |
|
1278 | - |
|
1279 | - while (true) { |
|
1280 | - $added = 0; |
|
1281 | - foreach ($shares as $share) { |
|
1282 | - try { |
|
1283 | - $this->checkExpireDate($share); |
|
1284 | - } catch (ShareNotFound $e) { |
|
1285 | - //Ignore since this basically means the share is deleted |
|
1286 | - continue; |
|
1287 | - } |
|
1288 | - |
|
1289 | - $added++; |
|
1290 | - $shares2[] = $share; |
|
1291 | - |
|
1292 | - if (count($shares2) === $limit) { |
|
1293 | - break; |
|
1294 | - } |
|
1295 | - } |
|
1296 | - |
|
1297 | - // If we did not fetch more shares than the limit then there are no more shares |
|
1298 | - if (count($shares) < $limit) { |
|
1299 | - break; |
|
1300 | - } |
|
1301 | - |
|
1302 | - if (count($shares2) === $limit) { |
|
1303 | - break; |
|
1304 | - } |
|
1305 | - |
|
1306 | - // If there was no limit on the select we are done |
|
1307 | - if ($limit === -1) { |
|
1308 | - break; |
|
1309 | - } |
|
1310 | - |
|
1311 | - $offset += $added; |
|
1312 | - |
|
1313 | - // Fetch again $limit shares |
|
1314 | - $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset); |
|
1315 | - |
|
1316 | - // No more shares means we are done |
|
1317 | - if (empty($shares)) { |
|
1318 | - break; |
|
1319 | - } |
|
1320 | - } |
|
1321 | - |
|
1322 | - $shares = $shares2; |
|
1323 | - |
|
1324 | - return $shares; |
|
1325 | - } |
|
1326 | - |
|
1327 | - /** |
|
1328 | - * @inheritdoc |
|
1329 | - */ |
|
1330 | - public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) { |
|
1331 | - try { |
|
1332 | - $provider = $this->factory->getProviderForType($shareType); |
|
1333 | - } catch (ProviderException $e) { |
|
1334 | - return []; |
|
1335 | - } |
|
1336 | - |
|
1337 | - $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset); |
|
1338 | - |
|
1339 | - // remove all shares which are already expired |
|
1340 | - foreach ($shares as $key => $share) { |
|
1341 | - try { |
|
1342 | - $this->checkExpireDate($share); |
|
1343 | - } catch (ShareNotFound $e) { |
|
1344 | - unset($shares[$key]); |
|
1345 | - } |
|
1346 | - } |
|
1347 | - |
|
1348 | - return $shares; |
|
1349 | - } |
|
1350 | - |
|
1351 | - /** |
|
1352 | - * @inheritdoc |
|
1353 | - */ |
|
1354 | - public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) { |
|
1355 | - $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset); |
|
1356 | - |
|
1357 | - // Only get deleted shares |
|
1358 | - $shares = array_filter($shares, function (IShare $share) { |
|
1359 | - return $share->getPermissions() === 0; |
|
1360 | - }); |
|
1361 | - |
|
1362 | - // Only get shares where the owner still exists |
|
1363 | - $shares = array_filter($shares, function (IShare $share) { |
|
1364 | - return $this->userManager->userExists($share->getShareOwner()); |
|
1365 | - }); |
|
1366 | - |
|
1367 | - return $shares; |
|
1368 | - } |
|
1369 | - |
|
1370 | - /** |
|
1371 | - * @inheritdoc |
|
1372 | - */ |
|
1373 | - public function getShareById($id, $recipient = null) { |
|
1374 | - if ($id === null) { |
|
1375 | - throw new ShareNotFound(); |
|
1376 | - } |
|
1377 | - |
|
1378 | - [$providerId, $id] = $this->splitFullId($id); |
|
1379 | - |
|
1380 | - try { |
|
1381 | - $provider = $this->factory->getProvider($providerId); |
|
1382 | - } catch (ProviderException $e) { |
|
1383 | - throw new ShareNotFound(); |
|
1384 | - } |
|
1385 | - |
|
1386 | - $share = $provider->getShareById($id, $recipient); |
|
1387 | - |
|
1388 | - $this->checkExpireDate($share); |
|
1389 | - |
|
1390 | - return $share; |
|
1391 | - } |
|
1392 | - |
|
1393 | - /** |
|
1394 | - * Get all the shares for a given path |
|
1395 | - * |
|
1396 | - * @param \OCP\Files\Node $path |
|
1397 | - * @param int $page |
|
1398 | - * @param int $perPage |
|
1399 | - * |
|
1400 | - * @return Share[] |
|
1401 | - */ |
|
1402 | - public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) { |
|
1403 | - return []; |
|
1404 | - } |
|
1405 | - |
|
1406 | - /** |
|
1407 | - * Get the share by token possible with password |
|
1408 | - * |
|
1409 | - * @param string $token |
|
1410 | - * @return IShare |
|
1411 | - * |
|
1412 | - * @throws ShareNotFound |
|
1413 | - */ |
|
1414 | - public function getShareByToken($token) { |
|
1415 | - // tokens can't be valid local user names |
|
1416 | - if ($this->userManager->userExists($token)) { |
|
1417 | - throw new ShareNotFound(); |
|
1418 | - } |
|
1419 | - $share = null; |
|
1420 | - try { |
|
1421 | - if ($this->shareApiAllowLinks()) { |
|
1422 | - $provider = $this->factory->getProviderForType(IShare::TYPE_LINK); |
|
1423 | - $share = $provider->getShareByToken($token); |
|
1424 | - } |
|
1425 | - } catch (ProviderException $e) { |
|
1426 | - } catch (ShareNotFound $e) { |
|
1427 | - } |
|
1428 | - |
|
1429 | - |
|
1430 | - // If it is not a link share try to fetch a federated share by token |
|
1431 | - if ($share === null) { |
|
1432 | - try { |
|
1433 | - $provider = $this->factory->getProviderForType(IShare::TYPE_REMOTE); |
|
1434 | - $share = $provider->getShareByToken($token); |
|
1435 | - } catch (ProviderException $e) { |
|
1436 | - } catch (ShareNotFound $e) { |
|
1437 | - } |
|
1438 | - } |
|
1439 | - |
|
1440 | - // If it is not a link share try to fetch a mail share by token |
|
1441 | - if ($share === null && $this->shareProviderExists(IShare::TYPE_EMAIL)) { |
|
1442 | - try { |
|
1443 | - $provider = $this->factory->getProviderForType(IShare::TYPE_EMAIL); |
|
1444 | - $share = $provider->getShareByToken($token); |
|
1445 | - } catch (ProviderException $e) { |
|
1446 | - } catch (ShareNotFound $e) { |
|
1447 | - } |
|
1448 | - } |
|
1449 | - |
|
1450 | - if ($share === null && $this->shareProviderExists(IShare::TYPE_CIRCLE)) { |
|
1451 | - try { |
|
1452 | - $provider = $this->factory->getProviderForType(IShare::TYPE_CIRCLE); |
|
1453 | - $share = $provider->getShareByToken($token); |
|
1454 | - } catch (ProviderException $e) { |
|
1455 | - } catch (ShareNotFound $e) { |
|
1456 | - } |
|
1457 | - } |
|
1458 | - |
|
1459 | - if ($share === null && $this->shareProviderExists(IShare::TYPE_ROOM)) { |
|
1460 | - try { |
|
1461 | - $provider = $this->factory->getProviderForType(IShare::TYPE_ROOM); |
|
1462 | - $share = $provider->getShareByToken($token); |
|
1463 | - } catch (ProviderException $e) { |
|
1464 | - } catch (ShareNotFound $e) { |
|
1465 | - } |
|
1466 | - } |
|
1467 | - |
|
1468 | - if ($share === null) { |
|
1469 | - throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); |
|
1470 | - } |
|
1471 | - |
|
1472 | - $this->checkExpireDate($share); |
|
1473 | - |
|
1474 | - /* |
|
1277 | + $shares2 = []; |
|
1278 | + |
|
1279 | + while (true) { |
|
1280 | + $added = 0; |
|
1281 | + foreach ($shares as $share) { |
|
1282 | + try { |
|
1283 | + $this->checkExpireDate($share); |
|
1284 | + } catch (ShareNotFound $e) { |
|
1285 | + //Ignore since this basically means the share is deleted |
|
1286 | + continue; |
|
1287 | + } |
|
1288 | + |
|
1289 | + $added++; |
|
1290 | + $shares2[] = $share; |
|
1291 | + |
|
1292 | + if (count($shares2) === $limit) { |
|
1293 | + break; |
|
1294 | + } |
|
1295 | + } |
|
1296 | + |
|
1297 | + // If we did not fetch more shares than the limit then there are no more shares |
|
1298 | + if (count($shares) < $limit) { |
|
1299 | + break; |
|
1300 | + } |
|
1301 | + |
|
1302 | + if (count($shares2) === $limit) { |
|
1303 | + break; |
|
1304 | + } |
|
1305 | + |
|
1306 | + // If there was no limit on the select we are done |
|
1307 | + if ($limit === -1) { |
|
1308 | + break; |
|
1309 | + } |
|
1310 | + |
|
1311 | + $offset += $added; |
|
1312 | + |
|
1313 | + // Fetch again $limit shares |
|
1314 | + $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset); |
|
1315 | + |
|
1316 | + // No more shares means we are done |
|
1317 | + if (empty($shares)) { |
|
1318 | + break; |
|
1319 | + } |
|
1320 | + } |
|
1321 | + |
|
1322 | + $shares = $shares2; |
|
1323 | + |
|
1324 | + return $shares; |
|
1325 | + } |
|
1326 | + |
|
1327 | + /** |
|
1328 | + * @inheritdoc |
|
1329 | + */ |
|
1330 | + public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) { |
|
1331 | + try { |
|
1332 | + $provider = $this->factory->getProviderForType($shareType); |
|
1333 | + } catch (ProviderException $e) { |
|
1334 | + return []; |
|
1335 | + } |
|
1336 | + |
|
1337 | + $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset); |
|
1338 | + |
|
1339 | + // remove all shares which are already expired |
|
1340 | + foreach ($shares as $key => $share) { |
|
1341 | + try { |
|
1342 | + $this->checkExpireDate($share); |
|
1343 | + } catch (ShareNotFound $e) { |
|
1344 | + unset($shares[$key]); |
|
1345 | + } |
|
1346 | + } |
|
1347 | + |
|
1348 | + return $shares; |
|
1349 | + } |
|
1350 | + |
|
1351 | + /** |
|
1352 | + * @inheritdoc |
|
1353 | + */ |
|
1354 | + public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) { |
|
1355 | + $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset); |
|
1356 | + |
|
1357 | + // Only get deleted shares |
|
1358 | + $shares = array_filter($shares, function (IShare $share) { |
|
1359 | + return $share->getPermissions() === 0; |
|
1360 | + }); |
|
1361 | + |
|
1362 | + // Only get shares where the owner still exists |
|
1363 | + $shares = array_filter($shares, function (IShare $share) { |
|
1364 | + return $this->userManager->userExists($share->getShareOwner()); |
|
1365 | + }); |
|
1366 | + |
|
1367 | + return $shares; |
|
1368 | + } |
|
1369 | + |
|
1370 | + /** |
|
1371 | + * @inheritdoc |
|
1372 | + */ |
|
1373 | + public function getShareById($id, $recipient = null) { |
|
1374 | + if ($id === null) { |
|
1375 | + throw new ShareNotFound(); |
|
1376 | + } |
|
1377 | + |
|
1378 | + [$providerId, $id] = $this->splitFullId($id); |
|
1379 | + |
|
1380 | + try { |
|
1381 | + $provider = $this->factory->getProvider($providerId); |
|
1382 | + } catch (ProviderException $e) { |
|
1383 | + throw new ShareNotFound(); |
|
1384 | + } |
|
1385 | + |
|
1386 | + $share = $provider->getShareById($id, $recipient); |
|
1387 | + |
|
1388 | + $this->checkExpireDate($share); |
|
1389 | + |
|
1390 | + return $share; |
|
1391 | + } |
|
1392 | + |
|
1393 | + /** |
|
1394 | + * Get all the shares for a given path |
|
1395 | + * |
|
1396 | + * @param \OCP\Files\Node $path |
|
1397 | + * @param int $page |
|
1398 | + * @param int $perPage |
|
1399 | + * |
|
1400 | + * @return Share[] |
|
1401 | + */ |
|
1402 | + public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) { |
|
1403 | + return []; |
|
1404 | + } |
|
1405 | + |
|
1406 | + /** |
|
1407 | + * Get the share by token possible with password |
|
1408 | + * |
|
1409 | + * @param string $token |
|
1410 | + * @return IShare |
|
1411 | + * |
|
1412 | + * @throws ShareNotFound |
|
1413 | + */ |
|
1414 | + public function getShareByToken($token) { |
|
1415 | + // tokens can't be valid local user names |
|
1416 | + if ($this->userManager->userExists($token)) { |
|
1417 | + throw new ShareNotFound(); |
|
1418 | + } |
|
1419 | + $share = null; |
|
1420 | + try { |
|
1421 | + if ($this->shareApiAllowLinks()) { |
|
1422 | + $provider = $this->factory->getProviderForType(IShare::TYPE_LINK); |
|
1423 | + $share = $provider->getShareByToken($token); |
|
1424 | + } |
|
1425 | + } catch (ProviderException $e) { |
|
1426 | + } catch (ShareNotFound $e) { |
|
1427 | + } |
|
1428 | + |
|
1429 | + |
|
1430 | + // If it is not a link share try to fetch a federated share by token |
|
1431 | + if ($share === null) { |
|
1432 | + try { |
|
1433 | + $provider = $this->factory->getProviderForType(IShare::TYPE_REMOTE); |
|
1434 | + $share = $provider->getShareByToken($token); |
|
1435 | + } catch (ProviderException $e) { |
|
1436 | + } catch (ShareNotFound $e) { |
|
1437 | + } |
|
1438 | + } |
|
1439 | + |
|
1440 | + // If it is not a link share try to fetch a mail share by token |
|
1441 | + if ($share === null && $this->shareProviderExists(IShare::TYPE_EMAIL)) { |
|
1442 | + try { |
|
1443 | + $provider = $this->factory->getProviderForType(IShare::TYPE_EMAIL); |
|
1444 | + $share = $provider->getShareByToken($token); |
|
1445 | + } catch (ProviderException $e) { |
|
1446 | + } catch (ShareNotFound $e) { |
|
1447 | + } |
|
1448 | + } |
|
1449 | + |
|
1450 | + if ($share === null && $this->shareProviderExists(IShare::TYPE_CIRCLE)) { |
|
1451 | + try { |
|
1452 | + $provider = $this->factory->getProviderForType(IShare::TYPE_CIRCLE); |
|
1453 | + $share = $provider->getShareByToken($token); |
|
1454 | + } catch (ProviderException $e) { |
|
1455 | + } catch (ShareNotFound $e) { |
|
1456 | + } |
|
1457 | + } |
|
1458 | + |
|
1459 | + if ($share === null && $this->shareProviderExists(IShare::TYPE_ROOM)) { |
|
1460 | + try { |
|
1461 | + $provider = $this->factory->getProviderForType(IShare::TYPE_ROOM); |
|
1462 | + $share = $provider->getShareByToken($token); |
|
1463 | + } catch (ProviderException $e) { |
|
1464 | + } catch (ShareNotFound $e) { |
|
1465 | + } |
|
1466 | + } |
|
1467 | + |
|
1468 | + if ($share === null) { |
|
1469 | + throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); |
|
1470 | + } |
|
1471 | + |
|
1472 | + $this->checkExpireDate($share); |
|
1473 | + |
|
1474 | + /* |
|
1475 | 1475 | * Reduce the permissions for link shares if public upload is not enabled |
1476 | 1476 | */ |
1477 | - if ($share->getShareType() === IShare::TYPE_LINK && |
|
1478 | - !$this->shareApiLinkAllowPublicUpload()) { |
|
1479 | - $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE)); |
|
1480 | - } |
|
1481 | - |
|
1482 | - return $share; |
|
1483 | - } |
|
1484 | - |
|
1485 | - protected function checkExpireDate($share) { |
|
1486 | - if ($share->isExpired()) { |
|
1487 | - $this->deleteShare($share); |
|
1488 | - throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); |
|
1489 | - } |
|
1490 | - } |
|
1491 | - |
|
1492 | - /** |
|
1493 | - * Verify the password of a public share |
|
1494 | - * |
|
1495 | - * @param IShare $share |
|
1496 | - * @param string $password |
|
1497 | - * @return bool |
|
1498 | - */ |
|
1499 | - public function checkPassword(IShare $share, $password) { |
|
1500 | - $passwordProtected = $share->getShareType() !== IShare::TYPE_LINK |
|
1501 | - || $share->getShareType() !== IShare::TYPE_EMAIL |
|
1502 | - || $share->getShareType() !== IShare::TYPE_CIRCLE; |
|
1503 | - if (!$passwordProtected) { |
|
1504 | - //TODO maybe exception? |
|
1505 | - return false; |
|
1506 | - } |
|
1507 | - |
|
1508 | - if ($password === null || $share->getPassword() === null) { |
|
1509 | - return false; |
|
1510 | - } |
|
1511 | - |
|
1512 | - $newHash = ''; |
|
1513 | - if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) { |
|
1514 | - return false; |
|
1515 | - } |
|
1516 | - |
|
1517 | - if (!empty($newHash)) { |
|
1518 | - $share->setPassword($newHash); |
|
1519 | - $provider = $this->factory->getProviderForType($share->getShareType()); |
|
1520 | - $provider->update($share); |
|
1521 | - } |
|
1522 | - |
|
1523 | - return true; |
|
1524 | - } |
|
1525 | - |
|
1526 | - /** |
|
1527 | - * @inheritdoc |
|
1528 | - */ |
|
1529 | - public function userDeleted($uid) { |
|
1530 | - $types = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_LINK, IShare::TYPE_REMOTE, IShare::TYPE_EMAIL]; |
|
1531 | - |
|
1532 | - foreach ($types as $type) { |
|
1533 | - try { |
|
1534 | - $provider = $this->factory->getProviderForType($type); |
|
1535 | - } catch (ProviderException $e) { |
|
1536 | - continue; |
|
1537 | - } |
|
1538 | - $provider->userDeleted($uid, $type); |
|
1539 | - } |
|
1540 | - } |
|
1541 | - |
|
1542 | - /** |
|
1543 | - * @inheritdoc |
|
1544 | - */ |
|
1545 | - public function groupDeleted($gid) { |
|
1546 | - $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP); |
|
1547 | - $provider->groupDeleted($gid); |
|
1548 | - |
|
1549 | - $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); |
|
1550 | - if ($excludedGroups === '') { |
|
1551 | - return; |
|
1552 | - } |
|
1553 | - |
|
1554 | - $excludedGroups = json_decode($excludedGroups, true); |
|
1555 | - if (json_last_error() !== JSON_ERROR_NONE) { |
|
1556 | - return; |
|
1557 | - } |
|
1558 | - |
|
1559 | - $excludedGroups = array_diff($excludedGroups, [$gid]); |
|
1560 | - $this->config->setAppValue('core', 'shareapi_exclude_groups_list', json_encode($excludedGroups)); |
|
1561 | - } |
|
1562 | - |
|
1563 | - /** |
|
1564 | - * @inheritdoc |
|
1565 | - */ |
|
1566 | - public function userDeletedFromGroup($uid, $gid) { |
|
1567 | - $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP); |
|
1568 | - $provider->userDeletedFromGroup($uid, $gid); |
|
1569 | - } |
|
1570 | - |
|
1571 | - /** |
|
1572 | - * Get access list to a path. This means |
|
1573 | - * all the users that can access a given path. |
|
1574 | - * |
|
1575 | - * Consider: |
|
1576 | - * -root |
|
1577 | - * |-folder1 (23) |
|
1578 | - * |-folder2 (32) |
|
1579 | - * |-fileA (42) |
|
1580 | - * |
|
1581 | - * fileA is shared with user1 and user1@server1 |
|
1582 | - * folder2 is shared with group2 (user4 is a member of group2) |
|
1583 | - * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2 |
|
1584 | - * |
|
1585 | - * Then the access list to '/folder1/folder2/fileA' with $currentAccess is: |
|
1586 | - * [ |
|
1587 | - * users => [ |
|
1588 | - * 'user1' => ['node_id' => 42, 'node_path' => '/fileA'], |
|
1589 | - * 'user4' => ['node_id' => 32, 'node_path' => '/folder2'], |
|
1590 | - * 'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'], |
|
1591 | - * ], |
|
1592 | - * remote => [ |
|
1593 | - * 'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'], |
|
1594 | - * 'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'], |
|
1595 | - * ], |
|
1596 | - * public => bool |
|
1597 | - * mail => bool |
|
1598 | - * ] |
|
1599 | - * |
|
1600 | - * The access list to '/folder1/folder2/fileA' **without** $currentAccess is: |
|
1601 | - * [ |
|
1602 | - * users => ['user1', 'user2', 'user4'], |
|
1603 | - * remote => bool, |
|
1604 | - * public => bool |
|
1605 | - * mail => bool |
|
1606 | - * ] |
|
1607 | - * |
|
1608 | - * This is required for encryption/activity |
|
1609 | - * |
|
1610 | - * @param \OCP\Files\Node $path |
|
1611 | - * @param bool $recursive Should we check all parent folders as well |
|
1612 | - * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it) |
|
1613 | - * @return array |
|
1614 | - */ |
|
1615 | - public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) { |
|
1616 | - $owner = $path->getOwner(); |
|
1617 | - |
|
1618 | - if ($owner === null) { |
|
1619 | - return []; |
|
1620 | - } |
|
1621 | - |
|
1622 | - $owner = $owner->getUID(); |
|
1623 | - |
|
1624 | - if ($currentAccess) { |
|
1625 | - $al = ['users' => [], 'remote' => [], 'public' => false]; |
|
1626 | - } else { |
|
1627 | - $al = ['users' => [], 'remote' => false, 'public' => false]; |
|
1628 | - } |
|
1629 | - if (!$this->userManager->userExists($owner)) { |
|
1630 | - return $al; |
|
1631 | - } |
|
1632 | - |
|
1633 | - //Get node for the owner and correct the owner in case of external storages |
|
1634 | - $userFolder = $this->rootFolder->getUserFolder($owner); |
|
1635 | - if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) { |
|
1636 | - $nodes = $userFolder->getById($path->getId()); |
|
1637 | - $path = array_shift($nodes); |
|
1638 | - if ($path->getOwner() === null) { |
|
1639 | - return []; |
|
1640 | - } |
|
1641 | - $owner = $path->getOwner()->getUID(); |
|
1642 | - } |
|
1643 | - |
|
1644 | - $providers = $this->factory->getAllProviders(); |
|
1645 | - |
|
1646 | - /** @var Node[] $nodes */ |
|
1647 | - $nodes = []; |
|
1648 | - |
|
1649 | - |
|
1650 | - if ($currentAccess) { |
|
1651 | - $ownerPath = $path->getPath(); |
|
1652 | - $ownerPath = explode('/', $ownerPath, 4); |
|
1653 | - if (count($ownerPath) < 4) { |
|
1654 | - $ownerPath = ''; |
|
1655 | - } else { |
|
1656 | - $ownerPath = $ownerPath[3]; |
|
1657 | - } |
|
1658 | - $al['users'][$owner] = [ |
|
1659 | - 'node_id' => $path->getId(), |
|
1660 | - 'node_path' => '/' . $ownerPath, |
|
1661 | - ]; |
|
1662 | - } else { |
|
1663 | - $al['users'][] = $owner; |
|
1664 | - } |
|
1665 | - |
|
1666 | - // Collect all the shares |
|
1667 | - while ($path->getPath() !== $userFolder->getPath()) { |
|
1668 | - $nodes[] = $path; |
|
1669 | - if (!$recursive) { |
|
1670 | - break; |
|
1671 | - } |
|
1672 | - $path = $path->getParent(); |
|
1673 | - } |
|
1674 | - |
|
1675 | - foreach ($providers as $provider) { |
|
1676 | - $tmp = $provider->getAccessList($nodes, $currentAccess); |
|
1677 | - |
|
1678 | - foreach ($tmp as $k => $v) { |
|
1679 | - if (isset($al[$k])) { |
|
1680 | - if (is_array($al[$k])) { |
|
1681 | - if ($currentAccess) { |
|
1682 | - $al[$k] += $v; |
|
1683 | - } else { |
|
1684 | - $al[$k] = array_merge($al[$k], $v); |
|
1685 | - $al[$k] = array_unique($al[$k]); |
|
1686 | - $al[$k] = array_values($al[$k]); |
|
1687 | - } |
|
1688 | - } else { |
|
1689 | - $al[$k] = $al[$k] || $v; |
|
1690 | - } |
|
1691 | - } else { |
|
1692 | - $al[$k] = $v; |
|
1693 | - } |
|
1694 | - } |
|
1695 | - } |
|
1696 | - |
|
1697 | - return $al; |
|
1698 | - } |
|
1699 | - |
|
1700 | - /** |
|
1701 | - * Create a new share |
|
1702 | - * |
|
1703 | - * @return IShare |
|
1704 | - */ |
|
1705 | - public function newShare() { |
|
1706 | - return new \OC\Share20\Share($this->rootFolder, $this->userManager); |
|
1707 | - } |
|
1708 | - |
|
1709 | - /** |
|
1710 | - * Is the share API enabled |
|
1711 | - * |
|
1712 | - * @return bool |
|
1713 | - */ |
|
1714 | - public function shareApiEnabled() { |
|
1715 | - return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes'; |
|
1716 | - } |
|
1717 | - |
|
1718 | - /** |
|
1719 | - * Is public link sharing enabled |
|
1720 | - * |
|
1721 | - * @return bool |
|
1722 | - */ |
|
1723 | - public function shareApiAllowLinks() { |
|
1724 | - return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes'; |
|
1725 | - } |
|
1726 | - |
|
1727 | - /** |
|
1728 | - * Is password on public link requires |
|
1729 | - * |
|
1730 | - * @return bool |
|
1731 | - */ |
|
1732 | - public function shareApiLinkEnforcePassword() { |
|
1733 | - return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes'; |
|
1734 | - } |
|
1735 | - |
|
1736 | - /** |
|
1737 | - * Is default link expire date enabled |
|
1738 | - * |
|
1739 | - * @return bool |
|
1740 | - */ |
|
1741 | - public function shareApiLinkDefaultExpireDate() { |
|
1742 | - return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes'; |
|
1743 | - } |
|
1744 | - |
|
1745 | - /** |
|
1746 | - * Is default link expire date enforced |
|
1747 | - *` |
|
1748 | - * @return bool |
|
1749 | - */ |
|
1750 | - public function shareApiLinkDefaultExpireDateEnforced() { |
|
1751 | - return $this->shareApiLinkDefaultExpireDate() && |
|
1752 | - $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes'; |
|
1753 | - } |
|
1754 | - |
|
1755 | - |
|
1756 | - /** |
|
1757 | - * Number of default link expire days |
|
1758 | - * @return int |
|
1759 | - */ |
|
1760 | - public function shareApiLinkDefaultExpireDays() { |
|
1761 | - return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7'); |
|
1762 | - } |
|
1763 | - |
|
1764 | - /** |
|
1765 | - * Is default internal expire date enabled |
|
1766 | - * |
|
1767 | - * @return bool |
|
1768 | - */ |
|
1769 | - public function shareApiInternalDefaultExpireDate(): bool { |
|
1770 | - return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes'; |
|
1771 | - } |
|
1772 | - |
|
1773 | - /** |
|
1774 | - * Is default expire date enforced |
|
1775 | - *` |
|
1776 | - * @return bool |
|
1777 | - */ |
|
1778 | - public function shareApiInternalDefaultExpireDateEnforced(): bool { |
|
1779 | - return $this->shareApiInternalDefaultExpireDate() && |
|
1780 | - $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes'; |
|
1781 | - } |
|
1782 | - |
|
1783 | - |
|
1784 | - /** |
|
1785 | - * Number of default expire days |
|
1786 | - * @return int |
|
1787 | - */ |
|
1788 | - public function shareApiInternalDefaultExpireDays(): int { |
|
1789 | - return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7'); |
|
1790 | - } |
|
1791 | - |
|
1792 | - /** |
|
1793 | - * Allow public upload on link shares |
|
1794 | - * |
|
1795 | - * @return bool |
|
1796 | - */ |
|
1797 | - public function shareApiLinkAllowPublicUpload() { |
|
1798 | - return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes'; |
|
1799 | - } |
|
1800 | - |
|
1801 | - /** |
|
1802 | - * check if user can only share with group members |
|
1803 | - * @return bool |
|
1804 | - */ |
|
1805 | - public function shareWithGroupMembersOnly() { |
|
1806 | - return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes'; |
|
1807 | - } |
|
1808 | - |
|
1809 | - /** |
|
1810 | - * Check if users can share with groups |
|
1811 | - * @return bool |
|
1812 | - */ |
|
1813 | - public function allowGroupSharing() { |
|
1814 | - return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes'; |
|
1815 | - } |
|
1816 | - |
|
1817 | - public function allowEnumeration(): bool { |
|
1818 | - return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes'; |
|
1819 | - } |
|
1820 | - |
|
1821 | - public function limitEnumerationToGroups(): bool { |
|
1822 | - return $this->allowEnumeration() && |
|
1823 | - $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes'; |
|
1824 | - } |
|
1825 | - |
|
1826 | - /** |
|
1827 | - * Copied from \OC_Util::isSharingDisabledForUser |
|
1828 | - * |
|
1829 | - * TODO: Deprecate fuction from OC_Util |
|
1830 | - * |
|
1831 | - * @param string $userId |
|
1832 | - * @return bool |
|
1833 | - */ |
|
1834 | - public function sharingDisabledForUser($userId) { |
|
1835 | - if ($userId === null) { |
|
1836 | - return false; |
|
1837 | - } |
|
1838 | - |
|
1839 | - if (isset($this->sharingDisabledForUsersCache[$userId])) { |
|
1840 | - return $this->sharingDisabledForUsersCache[$userId]; |
|
1841 | - } |
|
1842 | - |
|
1843 | - if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') { |
|
1844 | - $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); |
|
1845 | - $excludedGroups = json_decode($groupsList); |
|
1846 | - if (is_null($excludedGroups)) { |
|
1847 | - $excludedGroups = explode(',', $groupsList); |
|
1848 | - $newValue = json_encode($excludedGroups); |
|
1849 | - $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue); |
|
1850 | - } |
|
1851 | - $user = $this->userManager->get($userId); |
|
1852 | - $usersGroups = $this->groupManager->getUserGroupIds($user); |
|
1853 | - if (!empty($usersGroups)) { |
|
1854 | - $remainingGroups = array_diff($usersGroups, $excludedGroups); |
|
1855 | - // if the user is only in groups which are disabled for sharing then |
|
1856 | - // sharing is also disabled for the user |
|
1857 | - if (empty($remainingGroups)) { |
|
1858 | - $this->sharingDisabledForUsersCache[$userId] = true; |
|
1859 | - return true; |
|
1860 | - } |
|
1861 | - } |
|
1862 | - } |
|
1863 | - |
|
1864 | - $this->sharingDisabledForUsersCache[$userId] = false; |
|
1865 | - return false; |
|
1866 | - } |
|
1867 | - |
|
1868 | - /** |
|
1869 | - * @inheritdoc |
|
1870 | - */ |
|
1871 | - public function outgoingServer2ServerSharesAllowed() { |
|
1872 | - return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes'; |
|
1873 | - } |
|
1874 | - |
|
1875 | - /** |
|
1876 | - * @inheritdoc |
|
1877 | - */ |
|
1878 | - public function outgoingServer2ServerGroupSharesAllowed() { |
|
1879 | - return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes'; |
|
1880 | - } |
|
1881 | - |
|
1882 | - /** |
|
1883 | - * @inheritdoc |
|
1884 | - */ |
|
1885 | - public function shareProviderExists($shareType) { |
|
1886 | - try { |
|
1887 | - $this->factory->getProviderForType($shareType); |
|
1888 | - } catch (ProviderException $e) { |
|
1889 | - return false; |
|
1890 | - } |
|
1891 | - |
|
1892 | - return true; |
|
1893 | - } |
|
1894 | - |
|
1895 | - public function registerShareProvider(string $shareProviderClass): void { |
|
1896 | - $this->factory->registerProvider($shareProviderClass); |
|
1897 | - } |
|
1898 | - |
|
1899 | - public function getAllShares(): iterable { |
|
1900 | - $providers = $this->factory->getAllProviders(); |
|
1901 | - |
|
1902 | - foreach ($providers as $provider) { |
|
1903 | - yield from $provider->getAllShares(); |
|
1904 | - } |
|
1905 | - } |
|
1477 | + if ($share->getShareType() === IShare::TYPE_LINK && |
|
1478 | + !$this->shareApiLinkAllowPublicUpload()) { |
|
1479 | + $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE)); |
|
1480 | + } |
|
1481 | + |
|
1482 | + return $share; |
|
1483 | + } |
|
1484 | + |
|
1485 | + protected function checkExpireDate($share) { |
|
1486 | + if ($share->isExpired()) { |
|
1487 | + $this->deleteShare($share); |
|
1488 | + throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); |
|
1489 | + } |
|
1490 | + } |
|
1491 | + |
|
1492 | + /** |
|
1493 | + * Verify the password of a public share |
|
1494 | + * |
|
1495 | + * @param IShare $share |
|
1496 | + * @param string $password |
|
1497 | + * @return bool |
|
1498 | + */ |
|
1499 | + public function checkPassword(IShare $share, $password) { |
|
1500 | + $passwordProtected = $share->getShareType() !== IShare::TYPE_LINK |
|
1501 | + || $share->getShareType() !== IShare::TYPE_EMAIL |
|
1502 | + || $share->getShareType() !== IShare::TYPE_CIRCLE; |
|
1503 | + if (!$passwordProtected) { |
|
1504 | + //TODO maybe exception? |
|
1505 | + return false; |
|
1506 | + } |
|
1507 | + |
|
1508 | + if ($password === null || $share->getPassword() === null) { |
|
1509 | + return false; |
|
1510 | + } |
|
1511 | + |
|
1512 | + $newHash = ''; |
|
1513 | + if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) { |
|
1514 | + return false; |
|
1515 | + } |
|
1516 | + |
|
1517 | + if (!empty($newHash)) { |
|
1518 | + $share->setPassword($newHash); |
|
1519 | + $provider = $this->factory->getProviderForType($share->getShareType()); |
|
1520 | + $provider->update($share); |
|
1521 | + } |
|
1522 | + |
|
1523 | + return true; |
|
1524 | + } |
|
1525 | + |
|
1526 | + /** |
|
1527 | + * @inheritdoc |
|
1528 | + */ |
|
1529 | + public function userDeleted($uid) { |
|
1530 | + $types = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_LINK, IShare::TYPE_REMOTE, IShare::TYPE_EMAIL]; |
|
1531 | + |
|
1532 | + foreach ($types as $type) { |
|
1533 | + try { |
|
1534 | + $provider = $this->factory->getProviderForType($type); |
|
1535 | + } catch (ProviderException $e) { |
|
1536 | + continue; |
|
1537 | + } |
|
1538 | + $provider->userDeleted($uid, $type); |
|
1539 | + } |
|
1540 | + } |
|
1541 | + |
|
1542 | + /** |
|
1543 | + * @inheritdoc |
|
1544 | + */ |
|
1545 | + public function groupDeleted($gid) { |
|
1546 | + $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP); |
|
1547 | + $provider->groupDeleted($gid); |
|
1548 | + |
|
1549 | + $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); |
|
1550 | + if ($excludedGroups === '') { |
|
1551 | + return; |
|
1552 | + } |
|
1553 | + |
|
1554 | + $excludedGroups = json_decode($excludedGroups, true); |
|
1555 | + if (json_last_error() !== JSON_ERROR_NONE) { |
|
1556 | + return; |
|
1557 | + } |
|
1558 | + |
|
1559 | + $excludedGroups = array_diff($excludedGroups, [$gid]); |
|
1560 | + $this->config->setAppValue('core', 'shareapi_exclude_groups_list', json_encode($excludedGroups)); |
|
1561 | + } |
|
1562 | + |
|
1563 | + /** |
|
1564 | + * @inheritdoc |
|
1565 | + */ |
|
1566 | + public function userDeletedFromGroup($uid, $gid) { |
|
1567 | + $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP); |
|
1568 | + $provider->userDeletedFromGroup($uid, $gid); |
|
1569 | + } |
|
1570 | + |
|
1571 | + /** |
|
1572 | + * Get access list to a path. This means |
|
1573 | + * all the users that can access a given path. |
|
1574 | + * |
|
1575 | + * Consider: |
|
1576 | + * -root |
|
1577 | + * |-folder1 (23) |
|
1578 | + * |-folder2 (32) |
|
1579 | + * |-fileA (42) |
|
1580 | + * |
|
1581 | + * fileA is shared with user1 and user1@server1 |
|
1582 | + * folder2 is shared with group2 (user4 is a member of group2) |
|
1583 | + * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2 |
|
1584 | + * |
|
1585 | + * Then the access list to '/folder1/folder2/fileA' with $currentAccess is: |
|
1586 | + * [ |
|
1587 | + * users => [ |
|
1588 | + * 'user1' => ['node_id' => 42, 'node_path' => '/fileA'], |
|
1589 | + * 'user4' => ['node_id' => 32, 'node_path' => '/folder2'], |
|
1590 | + * 'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'], |
|
1591 | + * ], |
|
1592 | + * remote => [ |
|
1593 | + * 'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'], |
|
1594 | + * 'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'], |
|
1595 | + * ], |
|
1596 | + * public => bool |
|
1597 | + * mail => bool |
|
1598 | + * ] |
|
1599 | + * |
|
1600 | + * The access list to '/folder1/folder2/fileA' **without** $currentAccess is: |
|
1601 | + * [ |
|
1602 | + * users => ['user1', 'user2', 'user4'], |
|
1603 | + * remote => bool, |
|
1604 | + * public => bool |
|
1605 | + * mail => bool |
|
1606 | + * ] |
|
1607 | + * |
|
1608 | + * This is required for encryption/activity |
|
1609 | + * |
|
1610 | + * @param \OCP\Files\Node $path |
|
1611 | + * @param bool $recursive Should we check all parent folders as well |
|
1612 | + * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it) |
|
1613 | + * @return array |
|
1614 | + */ |
|
1615 | + public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) { |
|
1616 | + $owner = $path->getOwner(); |
|
1617 | + |
|
1618 | + if ($owner === null) { |
|
1619 | + return []; |
|
1620 | + } |
|
1621 | + |
|
1622 | + $owner = $owner->getUID(); |
|
1623 | + |
|
1624 | + if ($currentAccess) { |
|
1625 | + $al = ['users' => [], 'remote' => [], 'public' => false]; |
|
1626 | + } else { |
|
1627 | + $al = ['users' => [], 'remote' => false, 'public' => false]; |
|
1628 | + } |
|
1629 | + if (!$this->userManager->userExists($owner)) { |
|
1630 | + return $al; |
|
1631 | + } |
|
1632 | + |
|
1633 | + //Get node for the owner and correct the owner in case of external storages |
|
1634 | + $userFolder = $this->rootFolder->getUserFolder($owner); |
|
1635 | + if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) { |
|
1636 | + $nodes = $userFolder->getById($path->getId()); |
|
1637 | + $path = array_shift($nodes); |
|
1638 | + if ($path->getOwner() === null) { |
|
1639 | + return []; |
|
1640 | + } |
|
1641 | + $owner = $path->getOwner()->getUID(); |
|
1642 | + } |
|
1643 | + |
|
1644 | + $providers = $this->factory->getAllProviders(); |
|
1645 | + |
|
1646 | + /** @var Node[] $nodes */ |
|
1647 | + $nodes = []; |
|
1648 | + |
|
1649 | + |
|
1650 | + if ($currentAccess) { |
|
1651 | + $ownerPath = $path->getPath(); |
|
1652 | + $ownerPath = explode('/', $ownerPath, 4); |
|
1653 | + if (count($ownerPath) < 4) { |
|
1654 | + $ownerPath = ''; |
|
1655 | + } else { |
|
1656 | + $ownerPath = $ownerPath[3]; |
|
1657 | + } |
|
1658 | + $al['users'][$owner] = [ |
|
1659 | + 'node_id' => $path->getId(), |
|
1660 | + 'node_path' => '/' . $ownerPath, |
|
1661 | + ]; |
|
1662 | + } else { |
|
1663 | + $al['users'][] = $owner; |
|
1664 | + } |
|
1665 | + |
|
1666 | + // Collect all the shares |
|
1667 | + while ($path->getPath() !== $userFolder->getPath()) { |
|
1668 | + $nodes[] = $path; |
|
1669 | + if (!$recursive) { |
|
1670 | + break; |
|
1671 | + } |
|
1672 | + $path = $path->getParent(); |
|
1673 | + } |
|
1674 | + |
|
1675 | + foreach ($providers as $provider) { |
|
1676 | + $tmp = $provider->getAccessList($nodes, $currentAccess); |
|
1677 | + |
|
1678 | + foreach ($tmp as $k => $v) { |
|
1679 | + if (isset($al[$k])) { |
|
1680 | + if (is_array($al[$k])) { |
|
1681 | + if ($currentAccess) { |
|
1682 | + $al[$k] += $v; |
|
1683 | + } else { |
|
1684 | + $al[$k] = array_merge($al[$k], $v); |
|
1685 | + $al[$k] = array_unique($al[$k]); |
|
1686 | + $al[$k] = array_values($al[$k]); |
|
1687 | + } |
|
1688 | + } else { |
|
1689 | + $al[$k] = $al[$k] || $v; |
|
1690 | + } |
|
1691 | + } else { |
|
1692 | + $al[$k] = $v; |
|
1693 | + } |
|
1694 | + } |
|
1695 | + } |
|
1696 | + |
|
1697 | + return $al; |
|
1698 | + } |
|
1699 | + |
|
1700 | + /** |
|
1701 | + * Create a new share |
|
1702 | + * |
|
1703 | + * @return IShare |
|
1704 | + */ |
|
1705 | + public function newShare() { |
|
1706 | + return new \OC\Share20\Share($this->rootFolder, $this->userManager); |
|
1707 | + } |
|
1708 | + |
|
1709 | + /** |
|
1710 | + * Is the share API enabled |
|
1711 | + * |
|
1712 | + * @return bool |
|
1713 | + */ |
|
1714 | + public function shareApiEnabled() { |
|
1715 | + return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes'; |
|
1716 | + } |
|
1717 | + |
|
1718 | + /** |
|
1719 | + * Is public link sharing enabled |
|
1720 | + * |
|
1721 | + * @return bool |
|
1722 | + */ |
|
1723 | + public function shareApiAllowLinks() { |
|
1724 | + return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes'; |
|
1725 | + } |
|
1726 | + |
|
1727 | + /** |
|
1728 | + * Is password on public link requires |
|
1729 | + * |
|
1730 | + * @return bool |
|
1731 | + */ |
|
1732 | + public function shareApiLinkEnforcePassword() { |
|
1733 | + return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes'; |
|
1734 | + } |
|
1735 | + |
|
1736 | + /** |
|
1737 | + * Is default link expire date enabled |
|
1738 | + * |
|
1739 | + * @return bool |
|
1740 | + */ |
|
1741 | + public function shareApiLinkDefaultExpireDate() { |
|
1742 | + return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes'; |
|
1743 | + } |
|
1744 | + |
|
1745 | + /** |
|
1746 | + * Is default link expire date enforced |
|
1747 | + *` |
|
1748 | + * @return bool |
|
1749 | + */ |
|
1750 | + public function shareApiLinkDefaultExpireDateEnforced() { |
|
1751 | + return $this->shareApiLinkDefaultExpireDate() && |
|
1752 | + $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes'; |
|
1753 | + } |
|
1754 | + |
|
1755 | + |
|
1756 | + /** |
|
1757 | + * Number of default link expire days |
|
1758 | + * @return int |
|
1759 | + */ |
|
1760 | + public function shareApiLinkDefaultExpireDays() { |
|
1761 | + return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7'); |
|
1762 | + } |
|
1763 | + |
|
1764 | + /** |
|
1765 | + * Is default internal expire date enabled |
|
1766 | + * |
|
1767 | + * @return bool |
|
1768 | + */ |
|
1769 | + public function shareApiInternalDefaultExpireDate(): bool { |
|
1770 | + return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes'; |
|
1771 | + } |
|
1772 | + |
|
1773 | + /** |
|
1774 | + * Is default expire date enforced |
|
1775 | + *` |
|
1776 | + * @return bool |
|
1777 | + */ |
|
1778 | + public function shareApiInternalDefaultExpireDateEnforced(): bool { |
|
1779 | + return $this->shareApiInternalDefaultExpireDate() && |
|
1780 | + $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes'; |
|
1781 | + } |
|
1782 | + |
|
1783 | + |
|
1784 | + /** |
|
1785 | + * Number of default expire days |
|
1786 | + * @return int |
|
1787 | + */ |
|
1788 | + public function shareApiInternalDefaultExpireDays(): int { |
|
1789 | + return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7'); |
|
1790 | + } |
|
1791 | + |
|
1792 | + /** |
|
1793 | + * Allow public upload on link shares |
|
1794 | + * |
|
1795 | + * @return bool |
|
1796 | + */ |
|
1797 | + public function shareApiLinkAllowPublicUpload() { |
|
1798 | + return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes'; |
|
1799 | + } |
|
1800 | + |
|
1801 | + /** |
|
1802 | + * check if user can only share with group members |
|
1803 | + * @return bool |
|
1804 | + */ |
|
1805 | + public function shareWithGroupMembersOnly() { |
|
1806 | + return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes'; |
|
1807 | + } |
|
1808 | + |
|
1809 | + /** |
|
1810 | + * Check if users can share with groups |
|
1811 | + * @return bool |
|
1812 | + */ |
|
1813 | + public function allowGroupSharing() { |
|
1814 | + return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes'; |
|
1815 | + } |
|
1816 | + |
|
1817 | + public function allowEnumeration(): bool { |
|
1818 | + return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes'; |
|
1819 | + } |
|
1820 | + |
|
1821 | + public function limitEnumerationToGroups(): bool { |
|
1822 | + return $this->allowEnumeration() && |
|
1823 | + $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes'; |
|
1824 | + } |
|
1825 | + |
|
1826 | + /** |
|
1827 | + * Copied from \OC_Util::isSharingDisabledForUser |
|
1828 | + * |
|
1829 | + * TODO: Deprecate fuction from OC_Util |
|
1830 | + * |
|
1831 | + * @param string $userId |
|
1832 | + * @return bool |
|
1833 | + */ |
|
1834 | + public function sharingDisabledForUser($userId) { |
|
1835 | + if ($userId === null) { |
|
1836 | + return false; |
|
1837 | + } |
|
1838 | + |
|
1839 | + if (isset($this->sharingDisabledForUsersCache[$userId])) { |
|
1840 | + return $this->sharingDisabledForUsersCache[$userId]; |
|
1841 | + } |
|
1842 | + |
|
1843 | + if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') { |
|
1844 | + $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); |
|
1845 | + $excludedGroups = json_decode($groupsList); |
|
1846 | + if (is_null($excludedGroups)) { |
|
1847 | + $excludedGroups = explode(',', $groupsList); |
|
1848 | + $newValue = json_encode($excludedGroups); |
|
1849 | + $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue); |
|
1850 | + } |
|
1851 | + $user = $this->userManager->get($userId); |
|
1852 | + $usersGroups = $this->groupManager->getUserGroupIds($user); |
|
1853 | + if (!empty($usersGroups)) { |
|
1854 | + $remainingGroups = array_diff($usersGroups, $excludedGroups); |
|
1855 | + // if the user is only in groups which are disabled for sharing then |
|
1856 | + // sharing is also disabled for the user |
|
1857 | + if (empty($remainingGroups)) { |
|
1858 | + $this->sharingDisabledForUsersCache[$userId] = true; |
|
1859 | + return true; |
|
1860 | + } |
|
1861 | + } |
|
1862 | + } |
|
1863 | + |
|
1864 | + $this->sharingDisabledForUsersCache[$userId] = false; |
|
1865 | + return false; |
|
1866 | + } |
|
1867 | + |
|
1868 | + /** |
|
1869 | + * @inheritdoc |
|
1870 | + */ |
|
1871 | + public function outgoingServer2ServerSharesAllowed() { |
|
1872 | + return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes'; |
|
1873 | + } |
|
1874 | + |
|
1875 | + /** |
|
1876 | + * @inheritdoc |
|
1877 | + */ |
|
1878 | + public function outgoingServer2ServerGroupSharesAllowed() { |
|
1879 | + return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes'; |
|
1880 | + } |
|
1881 | + |
|
1882 | + /** |
|
1883 | + * @inheritdoc |
|
1884 | + */ |
|
1885 | + public function shareProviderExists($shareType) { |
|
1886 | + try { |
|
1887 | + $this->factory->getProviderForType($shareType); |
|
1888 | + } catch (ProviderException $e) { |
|
1889 | + return false; |
|
1890 | + } |
|
1891 | + |
|
1892 | + return true; |
|
1893 | + } |
|
1894 | + |
|
1895 | + public function registerShareProvider(string $shareProviderClass): void { |
|
1896 | + $this->factory->registerProvider($shareProviderClass); |
|
1897 | + } |
|
1898 | + |
|
1899 | + public function getAllShares(): iterable { |
|
1900 | + $providers = $this->factory->getAllProviders(); |
|
1901 | + |
|
1902 | + foreach ($providers as $provider) { |
|
1903 | + yield from $provider->getAllShares(); |
|
1904 | + } |
|
1905 | + } |
|
1906 | 1906 | } |
@@ -301,14 +301,14 @@ discard block |
||
301 | 301 | $permissions = 0; |
302 | 302 | |
303 | 303 | if (!$isFederatedShare && $share->getNode()->getOwner() && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) { |
304 | - $userMounts = array_filter($userFolder->getById($share->getNode()->getId()), function ($mount) { |
|
304 | + $userMounts = array_filter($userFolder->getById($share->getNode()->getId()), function($mount) { |
|
305 | 305 | // We need to filter since there might be other mountpoints that contain the file |
306 | 306 | // e.g. if the user has access to the same external storage that the file is originating from |
307 | 307 | return $mount->getStorage()->instanceOfStorage(ISharedStorage::class); |
308 | 308 | }); |
309 | 309 | $userMount = array_shift($userMounts); |
310 | 310 | if ($userMount === null) { |
311 | - throw new GenericShareException('Could not get proper share mount for ' . $share->getNode()->getId() . '. Failing since else the next calls are called with null'); |
|
311 | + throw new GenericShareException('Could not get proper share mount for '.$share->getNode()->getId().'. Failing since else the next calls are called with null'); |
|
312 | 312 | } |
313 | 313 | $mount = $userMount->getMountPoint(); |
314 | 314 | // When it's a reshare use the parent share permissions as maximum |
@@ -317,7 +317,7 @@ discard block |
||
317 | 317 | $userMountPoint = array_shift($userMountPoints); |
318 | 318 | |
319 | 319 | if ($userMountPoint === null) { |
320 | - throw new GenericShareException('Could not get proper user mount for ' . $userMountPointId . '. Failing since else the next calls are called with null'); |
|
320 | + throw new GenericShareException('Could not get proper user mount for '.$userMountPointId.'. Failing since else the next calls are called with null'); |
|
321 | 321 | } |
322 | 322 | |
323 | 323 | /* Check if this is an incoming share */ |
@@ -407,9 +407,9 @@ discard block |
||
407 | 407 | |
408 | 408 | if ($fullId === null && $expirationDate === null && $this->shareApiInternalDefaultExpireDate()) { |
409 | 409 | $expirationDate = new \DateTime(); |
410 | - $expirationDate->setTime(0,0,0); |
|
410 | + $expirationDate->setTime(0, 0, 0); |
|
411 | 411 | |
412 | - $days = (int)$this->config->getAppValue('core', 'internal_defaultExpDays', (string)$this->shareApiInternalDefaultExpireDays()); |
|
412 | + $days = (int) $this->config->getAppValue('core', 'internal_defaultExpDays', (string) $this->shareApiInternalDefaultExpireDays()); |
|
413 | 413 | if ($days > $this->shareApiInternalDefaultExpireDays()) { |
414 | 414 | $days = $this->shareApiInternalDefaultExpireDays(); |
415 | 415 | } |
@@ -424,7 +424,7 @@ discard block |
||
424 | 424 | |
425 | 425 | $date = new \DateTime(); |
426 | 426 | $date->setTime(0, 0, 0); |
427 | - $date->add(new \DateInterval('P' . $this->shareApiInternalDefaultExpireDays() . 'D')); |
|
427 | + $date->add(new \DateInterval('P'.$this->shareApiInternalDefaultExpireDays().'D')); |
|
428 | 428 | if ($date < $expirationDate) { |
429 | 429 | $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiInternalDefaultExpireDays()]); |
430 | 430 | throw new GenericShareException($message, $message, 404); |
@@ -483,9 +483,9 @@ discard block |
||
483 | 483 | |
484 | 484 | if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) { |
485 | 485 | $expirationDate = new \DateTime(); |
486 | - $expirationDate->setTime(0,0,0); |
|
486 | + $expirationDate->setTime(0, 0, 0); |
|
487 | 487 | |
488 | - $days = (int)$this->config->getAppValue('core', 'link_defaultExpDays', $this->shareApiLinkDefaultExpireDays()); |
|
488 | + $days = (int) $this->config->getAppValue('core', 'link_defaultExpDays', $this->shareApiLinkDefaultExpireDays()); |
|
489 | 489 | if ($days > $this->shareApiLinkDefaultExpireDays()) { |
490 | 490 | $days = $this->shareApiLinkDefaultExpireDays(); |
491 | 491 | } |
@@ -500,7 +500,7 @@ discard block |
||
500 | 500 | |
501 | 501 | $date = new \DateTime(); |
502 | 502 | $date->setTime(0, 0, 0); |
503 | - $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D')); |
|
503 | + $date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D')); |
|
504 | 504 | if ($date < $expirationDate) { |
505 | 505 | $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]); |
506 | 506 | throw new GenericShareException($message, $message, 404); |
@@ -786,7 +786,7 @@ discard block |
||
786 | 786 | } |
787 | 787 | |
788 | 788 | // Generate the target |
789 | - $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName(); |
|
789 | + $target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName(); |
|
790 | 790 | $target = \OC\Files\Filesystem::normalizePath($target); |
791 | 791 | $share->setTarget($target); |
792 | 792 | |
@@ -832,12 +832,12 @@ discard block |
||
832 | 832 | $emailAddress, |
833 | 833 | $share->getExpirationDate() |
834 | 834 | ); |
835 | - $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']); |
|
835 | + $this->logger->debug('Sent share notification to '.$emailAddress.' for share with ID '.$share->getId(), ['app' => 'share']); |
|
836 | 836 | } else { |
837 | - $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']); |
|
837 | + $this->logger->debug('Share notification not sent to '.$share->getSharedWith().' because email address is not set.', ['app' => 'share']); |
|
838 | 838 | } |
839 | 839 | } else { |
840 | - $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']); |
|
840 | + $this->logger->debug('Share notification not sent to '.$share->getSharedWith().' because user could not be found.', ['app' => 'share']); |
|
841 | 841 | } |
842 | 842 | } else { |
843 | 843 | $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']); |
@@ -884,7 +884,7 @@ discard block |
||
884 | 884 | $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]); |
885 | 885 | |
886 | 886 | $emailTemplate->addBodyText( |
887 | - htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')), |
|
887 | + htmlspecialchars($text.' '.$l->t('Click the button below to open it.')), |
|
888 | 888 | $text |
889 | 889 | ); |
890 | 890 | $emailTemplate->addBodyButton( |
@@ -910,7 +910,7 @@ discard block |
||
910 | 910 | $initiatorEmail = $initiatorUser->getEMailAddress(); |
911 | 911 | if ($initiatorEmail !== null) { |
912 | 912 | $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]); |
913 | - $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan($l->getLanguageCode()) !== '' ? ' - ' . $this->defaults->getSlogan($l->getLanguageCode()) : '')); |
|
913 | + $emailTemplate->addFooter($instanceName.($this->defaults->getSlogan($l->getLanguageCode()) !== '' ? ' - '.$this->defaults->getSlogan($l->getLanguageCode()) : '')); |
|
914 | 914 | } else { |
915 | 915 | $emailTemplate->addFooter('', $l->getLanguageCode()); |
916 | 916 | } |
@@ -919,7 +919,7 @@ discard block |
||
919 | 919 | try { |
920 | 920 | $failedRecipients = $this->mailer->send($message); |
921 | 921 | if (!empty($failedRecipients)) { |
922 | - $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients)); |
|
922 | + $this->logger->error('Share notification mail could not be sent to: '.implode(', ', $failedRecipients)); |
|
923 | 923 | return; |
924 | 924 | } |
925 | 925 | } catch (\Exception $e) { |
@@ -1221,7 +1221,7 @@ discard block |
||
1221 | 1221 | if ($share->getShareType() === IShare::TYPE_GROUP) { |
1222 | 1222 | $sharedWith = $this->groupManager->get($share->getSharedWith()); |
1223 | 1223 | if (is_null($sharedWith)) { |
1224 | - throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist'); |
|
1224 | + throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist'); |
|
1225 | 1225 | } |
1226 | 1226 | $recipient = $this->userManager->get($recipientId); |
1227 | 1227 | if (!$sharedWith->inGroup($recipient)) { |
@@ -1238,7 +1238,7 @@ discard block |
||
1238 | 1238 | public function getSharesInFolder($userId, Folder $node, $reshares = false) { |
1239 | 1239 | $providers = $this->factory->getAllProviders(); |
1240 | 1240 | |
1241 | - return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares) { |
|
1241 | + return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) { |
|
1242 | 1242 | $newShares = $provider->getSharesInFolder($userId, $node, $reshares); |
1243 | 1243 | foreach ($newShares as $fid => $data) { |
1244 | 1244 | if (!isset($shares[$fid])) { |
@@ -1355,12 +1355,12 @@ discard block |
||
1355 | 1355 | $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset); |
1356 | 1356 | |
1357 | 1357 | // Only get deleted shares |
1358 | - $shares = array_filter($shares, function (IShare $share) { |
|
1358 | + $shares = array_filter($shares, function(IShare $share) { |
|
1359 | 1359 | return $share->getPermissions() === 0; |
1360 | 1360 | }); |
1361 | 1361 | |
1362 | 1362 | // Only get shares where the owner still exists |
1363 | - $shares = array_filter($shares, function (IShare $share) { |
|
1363 | + $shares = array_filter($shares, function(IShare $share) { |
|
1364 | 1364 | return $this->userManager->userExists($share->getShareOwner()); |
1365 | 1365 | }); |
1366 | 1366 | |
@@ -1657,7 +1657,7 @@ discard block |
||
1657 | 1657 | } |
1658 | 1658 | $al['users'][$owner] = [ |
1659 | 1659 | 'node_id' => $path->getId(), |
1660 | - 'node_path' => '/' . $ownerPath, |
|
1660 | + 'node_path' => '/'.$ownerPath, |
|
1661 | 1661 | ]; |
1662 | 1662 | } else { |
1663 | 1663 | $al['users'][] = $owner; |
@@ -1758,7 +1758,7 @@ discard block |
||
1758 | 1758 | * @return int |
1759 | 1759 | */ |
1760 | 1760 | public function shareApiLinkDefaultExpireDays() { |
1761 | - return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7'); |
|
1761 | + return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7'); |
|
1762 | 1762 | } |
1763 | 1763 | |
1764 | 1764 | /** |
@@ -1786,7 +1786,7 @@ discard block |
||
1786 | 1786 | * @return int |
1787 | 1787 | */ |
1788 | 1788 | public function shareApiInternalDefaultExpireDays(): int { |
1789 | - return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7'); |
|
1789 | + return (int) $this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7'); |
|
1790 | 1790 | } |
1791 | 1791 | |
1792 | 1792 | /** |
@@ -50,277 +50,277 @@ |
||
50 | 50 | */ |
51 | 51 | abstract class Avatar implements IAvatar { |
52 | 52 | |
53 | - /** @var ILogger */ |
|
54 | - protected $logger; |
|
55 | - |
|
56 | - /** |
|
57 | - * https://github.com/sebdesign/cap-height -- for 500px height |
|
58 | - * Automated check: https://codepen.io/skjnldsv/pen/PydLBK/ |
|
59 | - * Noto Sans cap-height is 0.715 and we want a 200px caps height size |
|
60 | - * (0.4 letter-to-total-height ratio, 500*0.4=200), so: 200/0.715 = 280px. |
|
61 | - * Since we start from the baseline (text-anchor) we need to |
|
62 | - * shift the y axis by 100px (half the caps height): 500/2+100=350 |
|
63 | - * |
|
64 | - * @var string |
|
65 | - */ |
|
66 | - private $svgTemplate = '<?xml version="1.0" encoding="UTF-8" standalone="no"?> |
|
53 | + /** @var ILogger */ |
|
54 | + protected $logger; |
|
55 | + |
|
56 | + /** |
|
57 | + * https://github.com/sebdesign/cap-height -- for 500px height |
|
58 | + * Automated check: https://codepen.io/skjnldsv/pen/PydLBK/ |
|
59 | + * Noto Sans cap-height is 0.715 and we want a 200px caps height size |
|
60 | + * (0.4 letter-to-total-height ratio, 500*0.4=200), so: 200/0.715 = 280px. |
|
61 | + * Since we start from the baseline (text-anchor) we need to |
|
62 | + * shift the y axis by 100px (half the caps height): 500/2+100=350 |
|
63 | + * |
|
64 | + * @var string |
|
65 | + */ |
|
66 | + private $svgTemplate = '<?xml version="1.0" encoding="UTF-8" standalone="no"?> |
|
67 | 67 | <svg width="{size}" height="{size}" version="1.1" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg"> |
68 | 68 | <rect width="100%" height="100%" fill="#{fill}"></rect> |
69 | 69 | <text x="50%" y="350" style="font-weight:normal;font-size:280px;font-family:\'Noto Sans\';text-anchor:middle;fill:#fff">{letter}</text> |
70 | 70 | </svg>'; |
71 | 71 | |
72 | - /** |
|
73 | - * The base avatar constructor. |
|
74 | - * |
|
75 | - * @param ILogger $logger The logger |
|
76 | - */ |
|
77 | - public function __construct(ILogger $logger) { |
|
78 | - $this->logger = $logger; |
|
79 | - } |
|
80 | - |
|
81 | - /** |
|
82 | - * Returns the user display name. |
|
83 | - * |
|
84 | - * @return string |
|
85 | - */ |
|
86 | - abstract public function getDisplayName(): string; |
|
87 | - |
|
88 | - /** |
|
89 | - * Returns the first letter of the display name, or "?" if no name given. |
|
90 | - * |
|
91 | - * @return string |
|
92 | - */ |
|
93 | - private function getAvatarText(): string { |
|
94 | - $displayName = $this->getDisplayName(); |
|
95 | - if (empty($displayName) === true) { |
|
96 | - return '?'; |
|
97 | - } |
|
98 | - $firstTwoLetters = array_map(function ($namePart) { |
|
99 | - return mb_strtoupper(mb_substr($namePart, 0, 1), 'UTF-8'); |
|
100 | - }, explode(' ', $displayName, 2)); |
|
101 | - return implode('', $firstTwoLetters); |
|
102 | - } |
|
103 | - |
|
104 | - /** |
|
105 | - * @inheritdoc |
|
106 | - */ |
|
107 | - public function get($size = 64) { |
|
108 | - $size = (int) $size; |
|
109 | - |
|
110 | - try { |
|
111 | - $file = $this->getFile($size); |
|
112 | - } catch (NotFoundException $e) { |
|
113 | - return false; |
|
114 | - } |
|
115 | - |
|
116 | - $avatar = new OC_Image(); |
|
117 | - $avatar->loadFromData($file->getContent()); |
|
118 | - return $avatar; |
|
119 | - } |
|
120 | - |
|
121 | - /** |
|
122 | - * {size} = 500 |
|
123 | - * {fill} = hex color to fill |
|
124 | - * {letter} = Letter to display |
|
125 | - * |
|
126 | - * Generate SVG avatar |
|
127 | - * |
|
128 | - * @param int $size The requested image size in pixel |
|
129 | - * @return string |
|
130 | - * |
|
131 | - */ |
|
132 | - protected function getAvatarVector(int $size): string { |
|
133 | - $userDisplayName = $this->getDisplayName(); |
|
134 | - $bgRGB = $this->avatarBackgroundColor($userDisplayName); |
|
135 | - $bgHEX = sprintf("%02x%02x%02x", $bgRGB->r, $bgRGB->g, $bgRGB->b); |
|
136 | - $text = $this->getAvatarText(); |
|
137 | - $toReplace = ['{size}', '{fill}', '{letter}']; |
|
138 | - return str_replace($toReplace, [$size, $bgHEX, $text], $this->svgTemplate); |
|
139 | - } |
|
140 | - |
|
141 | - /** |
|
142 | - * Generate png avatar from svg with Imagick |
|
143 | - * |
|
144 | - * @param int $size |
|
145 | - * @return string|boolean |
|
146 | - */ |
|
147 | - protected function generateAvatarFromSvg(int $size) { |
|
148 | - if (!extension_loaded('imagick')) { |
|
149 | - return false; |
|
150 | - } |
|
151 | - try { |
|
152 | - $font = __DIR__ . '/../../core/fonts/NotoSans-Regular.ttf'; |
|
153 | - $svg = $this->getAvatarVector($size); |
|
154 | - $avatar = new Imagick(); |
|
155 | - $avatar->setFont($font); |
|
156 | - $avatar->readImageBlob($svg); |
|
157 | - $avatar->setImageFormat('png'); |
|
158 | - $image = new OC_Image(); |
|
159 | - $image->loadFromData($avatar); |
|
160 | - return $image->data(); |
|
161 | - } catch (\Exception $e) { |
|
162 | - return false; |
|
163 | - } |
|
164 | - } |
|
165 | - |
|
166 | - /** |
|
167 | - * Generate png avatar with GD |
|
168 | - * |
|
169 | - * @param string $userDisplayName |
|
170 | - * @param int $size |
|
171 | - * @return string |
|
172 | - */ |
|
173 | - protected function generateAvatar($userDisplayName, $size) { |
|
174 | - $text = $this->getAvatarText(); |
|
175 | - $backgroundColor = $this->avatarBackgroundColor($userDisplayName); |
|
176 | - |
|
177 | - $im = imagecreatetruecolor($size, $size); |
|
178 | - $background = imagecolorallocate( |
|
179 | - $im, |
|
180 | - $backgroundColor->r, |
|
181 | - $backgroundColor->g, |
|
182 | - $backgroundColor->b |
|
183 | - ); |
|
184 | - $white = imagecolorallocate($im, 255, 255, 255); |
|
185 | - imagefilledrectangle($im, 0, 0, $size, $size, $background); |
|
186 | - |
|
187 | - $font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf'; |
|
188 | - |
|
189 | - $fontSize = $size * 0.4; |
|
190 | - [$x, $y] = $this->imageTTFCenter( |
|
191 | - $im, $text, $font, (int)$fontSize |
|
192 | - ); |
|
193 | - |
|
194 | - imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text); |
|
195 | - |
|
196 | - ob_start(); |
|
197 | - imagepng($im); |
|
198 | - $data = ob_get_contents(); |
|
199 | - ob_end_clean(); |
|
200 | - |
|
201 | - return $data; |
|
202 | - } |
|
203 | - |
|
204 | - /** |
|
205 | - * Calculate real image ttf center |
|
206 | - * |
|
207 | - * @param resource $image |
|
208 | - * @param string $text text string |
|
209 | - * @param string $font font path |
|
210 | - * @param int $size font size |
|
211 | - * @param int $angle |
|
212 | - * @return array |
|
213 | - */ |
|
214 | - protected function imageTTFCenter( |
|
215 | - $image, |
|
216 | - string $text, |
|
217 | - string $font, |
|
218 | - int $size, |
|
219 | - $angle = 0 |
|
220 | - ): array { |
|
221 | - // Image width & height |
|
222 | - $xi = imagesx($image); |
|
223 | - $yi = imagesy($image); |
|
224 | - |
|
225 | - // bounding box |
|
226 | - $box = imagettfbbox($size, $angle, $font, $text); |
|
227 | - |
|
228 | - // imagettfbbox can return negative int |
|
229 | - $xr = abs(max($box[2], $box[4])); |
|
230 | - $yr = abs(max($box[5], $box[7])); |
|
231 | - |
|
232 | - // calculate bottom left placement |
|
233 | - $x = intval(($xi - $xr) / 2); |
|
234 | - $y = intval(($yi + $yr) / 2); |
|
235 | - |
|
236 | - return [$x, $y]; |
|
237 | - } |
|
238 | - |
|
239 | - /** |
|
240 | - * Calculate steps between two Colors |
|
241 | - * @param object Color $steps start color |
|
242 | - * @param object Color $ends end color |
|
243 | - * @return array [r,g,b] steps for each color to go from $steps to $ends |
|
244 | - */ |
|
245 | - private function stepCalc($steps, $ends) { |
|
246 | - $step = []; |
|
247 | - $step[0] = ($ends[1]->r - $ends[0]->r) / $steps; |
|
248 | - $step[1] = ($ends[1]->g - $ends[0]->g) / $steps; |
|
249 | - $step[2] = ($ends[1]->b - $ends[0]->b) / $steps; |
|
250 | - return $step; |
|
251 | - } |
|
252 | - |
|
253 | - /** |
|
254 | - * Convert a string to an integer evenly |
|
255 | - * @param string $hash the text to parse |
|
256 | - * @param int $maximum the maximum range |
|
257 | - * @return int[] between 0 and $maximum |
|
258 | - */ |
|
259 | - private function mixPalette($steps, $color1, $color2) { |
|
260 | - $palette = [$color1]; |
|
261 | - $step = $this->stepCalc($steps, [$color1, $color2]); |
|
262 | - for ($i = 1; $i < $steps; $i++) { |
|
263 | - $r = intval($color1->r + ($step[0] * $i)); |
|
264 | - $g = intval($color1->g + ($step[1] * $i)); |
|
265 | - $b = intval($color1->b + ($step[2] * $i)); |
|
266 | - $palette[] = new Color($r, $g, $b); |
|
267 | - } |
|
268 | - return $palette; |
|
269 | - } |
|
270 | - |
|
271 | - /** |
|
272 | - * Convert a string to an integer evenly |
|
273 | - * @param string $hash the text to parse |
|
274 | - * @param int $maximum the maximum range |
|
275 | - * @return int between 0 and $maximum |
|
276 | - */ |
|
277 | - private function hashToInt($hash, $maximum) { |
|
278 | - $final = 0; |
|
279 | - $result = []; |
|
280 | - |
|
281 | - // Splitting evenly the string |
|
282 | - for ($i = 0; $i < strlen($hash); $i++) { |
|
283 | - // chars in md5 goes up to f, hex:16 |
|
284 | - $result[] = intval(substr($hash, $i, 1), 16) % 16; |
|
285 | - } |
|
286 | - // Adds up all results |
|
287 | - foreach ($result as $value) { |
|
288 | - $final += $value; |
|
289 | - } |
|
290 | - // chars in md5 goes up to f, hex:16 |
|
291 | - return intval($final % $maximum); |
|
292 | - } |
|
293 | - |
|
294 | - /** |
|
295 | - * @param string $hash |
|
296 | - * @return Color Object containting r g b int in the range [0, 255] |
|
297 | - */ |
|
298 | - public function avatarBackgroundColor(string $hash) { |
|
299 | - // Normalize hash |
|
300 | - $hash = strtolower($hash); |
|
301 | - |
|
302 | - // Already a md5 hash? |
|
303 | - if (preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) { |
|
304 | - $hash = md5($hash); |
|
305 | - } |
|
306 | - |
|
307 | - // Remove unwanted char |
|
308 | - $hash = preg_replace('/[^0-9a-f]+/', '', $hash); |
|
309 | - |
|
310 | - $red = new Color(182, 70, 157); |
|
311 | - $yellow = new Color(221, 203, 85); |
|
312 | - $blue = new Color(0, 130, 201); // Nextcloud blue |
|
313 | - |
|
314 | - // Number of steps to go from a color to another |
|
315 | - // 3 colors * 6 will result in 18 generated colors |
|
316 | - $steps = 6; |
|
317 | - |
|
318 | - $palette1 = $this->mixPalette($steps, $red, $yellow); |
|
319 | - $palette2 = $this->mixPalette($steps, $yellow, $blue); |
|
320 | - $palette3 = $this->mixPalette($steps, $blue, $red); |
|
321 | - |
|
322 | - $finalPalette = array_merge($palette1, $palette2, $palette3); |
|
323 | - |
|
324 | - return $finalPalette[$this->hashToInt($hash, $steps * 3)]; |
|
325 | - } |
|
72 | + /** |
|
73 | + * The base avatar constructor. |
|
74 | + * |
|
75 | + * @param ILogger $logger The logger |
|
76 | + */ |
|
77 | + public function __construct(ILogger $logger) { |
|
78 | + $this->logger = $logger; |
|
79 | + } |
|
80 | + |
|
81 | + /** |
|
82 | + * Returns the user display name. |
|
83 | + * |
|
84 | + * @return string |
|
85 | + */ |
|
86 | + abstract public function getDisplayName(): string; |
|
87 | + |
|
88 | + /** |
|
89 | + * Returns the first letter of the display name, or "?" if no name given. |
|
90 | + * |
|
91 | + * @return string |
|
92 | + */ |
|
93 | + private function getAvatarText(): string { |
|
94 | + $displayName = $this->getDisplayName(); |
|
95 | + if (empty($displayName) === true) { |
|
96 | + return '?'; |
|
97 | + } |
|
98 | + $firstTwoLetters = array_map(function ($namePart) { |
|
99 | + return mb_strtoupper(mb_substr($namePart, 0, 1), 'UTF-8'); |
|
100 | + }, explode(' ', $displayName, 2)); |
|
101 | + return implode('', $firstTwoLetters); |
|
102 | + } |
|
103 | + |
|
104 | + /** |
|
105 | + * @inheritdoc |
|
106 | + */ |
|
107 | + public function get($size = 64) { |
|
108 | + $size = (int) $size; |
|
109 | + |
|
110 | + try { |
|
111 | + $file = $this->getFile($size); |
|
112 | + } catch (NotFoundException $e) { |
|
113 | + return false; |
|
114 | + } |
|
115 | + |
|
116 | + $avatar = new OC_Image(); |
|
117 | + $avatar->loadFromData($file->getContent()); |
|
118 | + return $avatar; |
|
119 | + } |
|
120 | + |
|
121 | + /** |
|
122 | + * {size} = 500 |
|
123 | + * {fill} = hex color to fill |
|
124 | + * {letter} = Letter to display |
|
125 | + * |
|
126 | + * Generate SVG avatar |
|
127 | + * |
|
128 | + * @param int $size The requested image size in pixel |
|
129 | + * @return string |
|
130 | + * |
|
131 | + */ |
|
132 | + protected function getAvatarVector(int $size): string { |
|
133 | + $userDisplayName = $this->getDisplayName(); |
|
134 | + $bgRGB = $this->avatarBackgroundColor($userDisplayName); |
|
135 | + $bgHEX = sprintf("%02x%02x%02x", $bgRGB->r, $bgRGB->g, $bgRGB->b); |
|
136 | + $text = $this->getAvatarText(); |
|
137 | + $toReplace = ['{size}', '{fill}', '{letter}']; |
|
138 | + return str_replace($toReplace, [$size, $bgHEX, $text], $this->svgTemplate); |
|
139 | + } |
|
140 | + |
|
141 | + /** |
|
142 | + * Generate png avatar from svg with Imagick |
|
143 | + * |
|
144 | + * @param int $size |
|
145 | + * @return string|boolean |
|
146 | + */ |
|
147 | + protected function generateAvatarFromSvg(int $size) { |
|
148 | + if (!extension_loaded('imagick')) { |
|
149 | + return false; |
|
150 | + } |
|
151 | + try { |
|
152 | + $font = __DIR__ . '/../../core/fonts/NotoSans-Regular.ttf'; |
|
153 | + $svg = $this->getAvatarVector($size); |
|
154 | + $avatar = new Imagick(); |
|
155 | + $avatar->setFont($font); |
|
156 | + $avatar->readImageBlob($svg); |
|
157 | + $avatar->setImageFormat('png'); |
|
158 | + $image = new OC_Image(); |
|
159 | + $image->loadFromData($avatar); |
|
160 | + return $image->data(); |
|
161 | + } catch (\Exception $e) { |
|
162 | + return false; |
|
163 | + } |
|
164 | + } |
|
165 | + |
|
166 | + /** |
|
167 | + * Generate png avatar with GD |
|
168 | + * |
|
169 | + * @param string $userDisplayName |
|
170 | + * @param int $size |
|
171 | + * @return string |
|
172 | + */ |
|
173 | + protected function generateAvatar($userDisplayName, $size) { |
|
174 | + $text = $this->getAvatarText(); |
|
175 | + $backgroundColor = $this->avatarBackgroundColor($userDisplayName); |
|
176 | + |
|
177 | + $im = imagecreatetruecolor($size, $size); |
|
178 | + $background = imagecolorallocate( |
|
179 | + $im, |
|
180 | + $backgroundColor->r, |
|
181 | + $backgroundColor->g, |
|
182 | + $backgroundColor->b |
|
183 | + ); |
|
184 | + $white = imagecolorallocate($im, 255, 255, 255); |
|
185 | + imagefilledrectangle($im, 0, 0, $size, $size, $background); |
|
186 | + |
|
187 | + $font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf'; |
|
188 | + |
|
189 | + $fontSize = $size * 0.4; |
|
190 | + [$x, $y] = $this->imageTTFCenter( |
|
191 | + $im, $text, $font, (int)$fontSize |
|
192 | + ); |
|
193 | + |
|
194 | + imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text); |
|
195 | + |
|
196 | + ob_start(); |
|
197 | + imagepng($im); |
|
198 | + $data = ob_get_contents(); |
|
199 | + ob_end_clean(); |
|
200 | + |
|
201 | + return $data; |
|
202 | + } |
|
203 | + |
|
204 | + /** |
|
205 | + * Calculate real image ttf center |
|
206 | + * |
|
207 | + * @param resource $image |
|
208 | + * @param string $text text string |
|
209 | + * @param string $font font path |
|
210 | + * @param int $size font size |
|
211 | + * @param int $angle |
|
212 | + * @return array |
|
213 | + */ |
|
214 | + protected function imageTTFCenter( |
|
215 | + $image, |
|
216 | + string $text, |
|
217 | + string $font, |
|
218 | + int $size, |
|
219 | + $angle = 0 |
|
220 | + ): array { |
|
221 | + // Image width & height |
|
222 | + $xi = imagesx($image); |
|
223 | + $yi = imagesy($image); |
|
224 | + |
|
225 | + // bounding box |
|
226 | + $box = imagettfbbox($size, $angle, $font, $text); |
|
227 | + |
|
228 | + // imagettfbbox can return negative int |
|
229 | + $xr = abs(max($box[2], $box[4])); |
|
230 | + $yr = abs(max($box[5], $box[7])); |
|
231 | + |
|
232 | + // calculate bottom left placement |
|
233 | + $x = intval(($xi - $xr) / 2); |
|
234 | + $y = intval(($yi + $yr) / 2); |
|
235 | + |
|
236 | + return [$x, $y]; |
|
237 | + } |
|
238 | + |
|
239 | + /** |
|
240 | + * Calculate steps between two Colors |
|
241 | + * @param object Color $steps start color |
|
242 | + * @param object Color $ends end color |
|
243 | + * @return array [r,g,b] steps for each color to go from $steps to $ends |
|
244 | + */ |
|
245 | + private function stepCalc($steps, $ends) { |
|
246 | + $step = []; |
|
247 | + $step[0] = ($ends[1]->r - $ends[0]->r) / $steps; |
|
248 | + $step[1] = ($ends[1]->g - $ends[0]->g) / $steps; |
|
249 | + $step[2] = ($ends[1]->b - $ends[0]->b) / $steps; |
|
250 | + return $step; |
|
251 | + } |
|
252 | + |
|
253 | + /** |
|
254 | + * Convert a string to an integer evenly |
|
255 | + * @param string $hash the text to parse |
|
256 | + * @param int $maximum the maximum range |
|
257 | + * @return int[] between 0 and $maximum |
|
258 | + */ |
|
259 | + private function mixPalette($steps, $color1, $color2) { |
|
260 | + $palette = [$color1]; |
|
261 | + $step = $this->stepCalc($steps, [$color1, $color2]); |
|
262 | + for ($i = 1; $i < $steps; $i++) { |
|
263 | + $r = intval($color1->r + ($step[0] * $i)); |
|
264 | + $g = intval($color1->g + ($step[1] * $i)); |
|
265 | + $b = intval($color1->b + ($step[2] * $i)); |
|
266 | + $palette[] = new Color($r, $g, $b); |
|
267 | + } |
|
268 | + return $palette; |
|
269 | + } |
|
270 | + |
|
271 | + /** |
|
272 | + * Convert a string to an integer evenly |
|
273 | + * @param string $hash the text to parse |
|
274 | + * @param int $maximum the maximum range |
|
275 | + * @return int between 0 and $maximum |
|
276 | + */ |
|
277 | + private function hashToInt($hash, $maximum) { |
|
278 | + $final = 0; |
|
279 | + $result = []; |
|
280 | + |
|
281 | + // Splitting evenly the string |
|
282 | + for ($i = 0; $i < strlen($hash); $i++) { |
|
283 | + // chars in md5 goes up to f, hex:16 |
|
284 | + $result[] = intval(substr($hash, $i, 1), 16) % 16; |
|
285 | + } |
|
286 | + // Adds up all results |
|
287 | + foreach ($result as $value) { |
|
288 | + $final += $value; |
|
289 | + } |
|
290 | + // chars in md5 goes up to f, hex:16 |
|
291 | + return intval($final % $maximum); |
|
292 | + } |
|
293 | + |
|
294 | + /** |
|
295 | + * @param string $hash |
|
296 | + * @return Color Object containting r g b int in the range [0, 255] |
|
297 | + */ |
|
298 | + public function avatarBackgroundColor(string $hash) { |
|
299 | + // Normalize hash |
|
300 | + $hash = strtolower($hash); |
|
301 | + |
|
302 | + // Already a md5 hash? |
|
303 | + if (preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) { |
|
304 | + $hash = md5($hash); |
|
305 | + } |
|
306 | + |
|
307 | + // Remove unwanted char |
|
308 | + $hash = preg_replace('/[^0-9a-f]+/', '', $hash); |
|
309 | + |
|
310 | + $red = new Color(182, 70, 157); |
|
311 | + $yellow = new Color(221, 203, 85); |
|
312 | + $blue = new Color(0, 130, 201); // Nextcloud blue |
|
313 | + |
|
314 | + // Number of steps to go from a color to another |
|
315 | + // 3 colors * 6 will result in 18 generated colors |
|
316 | + $steps = 6; |
|
317 | + |
|
318 | + $palette1 = $this->mixPalette($steps, $red, $yellow); |
|
319 | + $palette2 = $this->mixPalette($steps, $yellow, $blue); |
|
320 | + $palette3 = $this->mixPalette($steps, $blue, $red); |
|
321 | + |
|
322 | + $finalPalette = array_merge($palette1, $palette2, $palette3); |
|
323 | + |
|
324 | + return $finalPalette[$this->hashToInt($hash, $steps * 3)]; |
|
325 | + } |
|
326 | 326 | } |
@@ -95,7 +95,7 @@ discard block |
||
95 | 95 | if (empty($displayName) === true) { |
96 | 96 | return '?'; |
97 | 97 | } |
98 | - $firstTwoLetters = array_map(function ($namePart) { |
|
98 | + $firstTwoLetters = array_map(function($namePart) { |
|
99 | 99 | return mb_strtoupper(mb_substr($namePart, 0, 1), 'UTF-8'); |
100 | 100 | }, explode(' ', $displayName, 2)); |
101 | 101 | return implode('', $firstTwoLetters); |
@@ -149,7 +149,7 @@ discard block |
||
149 | 149 | return false; |
150 | 150 | } |
151 | 151 | try { |
152 | - $font = __DIR__ . '/../../core/fonts/NotoSans-Regular.ttf'; |
|
152 | + $font = __DIR__.'/../../core/fonts/NotoSans-Regular.ttf'; |
|
153 | 153 | $svg = $this->getAvatarVector($size); |
154 | 154 | $avatar = new Imagick(); |
155 | 155 | $avatar->setFont($font); |
@@ -184,11 +184,11 @@ discard block |
||
184 | 184 | $white = imagecolorallocate($im, 255, 255, 255); |
185 | 185 | imagefilledrectangle($im, 0, 0, $size, $size, $background); |
186 | 186 | |
187 | - $font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf'; |
|
187 | + $font = __DIR__.'/../../../core/fonts/NotoSans-Regular.ttf'; |
|
188 | 188 | |
189 | 189 | $fontSize = $size * 0.4; |
190 | 190 | [$x, $y] = $this->imageTTFCenter( |
191 | - $im, $text, $font, (int)$fontSize |
|
191 | + $im, $text, $font, (int) $fontSize |
|
192 | 192 | ); |
193 | 193 | |
194 | 194 | imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text); |