3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Core\System;
25 use Friendica\Database\DBA;
26 use Friendica\Database\DBStructure;
28 use Friendica\Core\Storage\Exception\InvalidClassStorageException;
29 use Friendica\Core\Storage\Exception\ReferenceStorageException;
30 use Friendica\Object\Image;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Mimetype;
33 use Friendica\Security\Security;
36 * Class to handle attach dabatase table
42 * Return a list of fields that are associated with the attach table
44 * @return array field list
47 private static function getFields(): array
49 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
50 $fields = array_keys($allfields['attach']['fields']);
51 array_splice($fields, array_search('data', $fields), 1);
56 * Select rows from the attach table and return them as array
58 * @param array $fields Array of selected fields, empty for all
59 * @param array $conditions Array of fields for conditions
60 * @param array $params Array of several parameters
65 * @see \Friendica\Database\DBA::selectToArray
67 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
70 $fields = self::getFields();
73 return DBA::selectToArray('attach', $fields, $conditions, $params);
77 * Retrieve a single record from the attach table
79 * @param array $fields Array of selected fields, empty for all
80 * @param array $conditions Array of fields for conditions
81 * @param array $params Array of several parameters
86 * @see \Friendica\Database\DBA::select
88 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
91 $fields = self::getFields();
94 return DBA::selectFirst('attach', $fields, $conditions, $params);
98 * Check if attachment with given conditions exists
100 * @param array $conditions Array of extra conditions
105 public static function exists(array $conditions): bool
107 return DBA::exists('attach', $conditions);
111 * Retrive a single record given the ID
113 * @param int $id Row id of the record
118 * @see \Friendica\Database\DBA::select
120 public static function getById(int $id)
122 return self::selectFirst([], ['id' => $id]);
126 * Retrive a single record given the ID
128 * @param int $id Row id of the record
133 * @see \Friendica\Database\DBA::select
135 public static function getByIdWithPermission(int $id)
137 $r = self::selectFirst(['uid'], ['id' => $id]);
142 $sql_acl = Security::getPermissionsSQLByUserId($r['uid']);
145 '`id` = ?' . $sql_acl,
149 $item = self::selectFirst([], $conditions);
155 * Get file data for given row id. null if row id does not exist
157 * @param array $item Attachment data. Needs at least 'id', 'backend-class', 'backend-ref'
159 * @return string|null file data or null on failure
162 public static function getData(array $item)
164 if (!empty($item['data'])) {
165 return $item['data'];
169 $backendClass = DI::storageManager()->getByName($item['backend-class'] ?? '');
170 $backendRef = $item['backend-ref'];
171 return $backendClass->get($backendRef);
172 } catch (InvalidClassStorageException $storageException) {
173 // legacy data storage in 'data' column
174 $i = self::selectFirst(['data'], ['id' => $item['id']]);
179 } catch (ReferenceStorageException $referenceStorageException) {
180 DI::logger()->debug('No data found for item', ['item' => $item, 'exception' => $referenceStorageException]);
186 * Store new file metadata in db and binary in default backend
188 * @param string $data Binary data
189 * @param integer $uid User ID
190 * @param string $filename Filename
191 * @param string $filetype Mimetype. optional, default = ''
192 * @param integer $filesize File size in bytes. optional, default = null
193 * @param string $allow_cid Permissions, allowed contacts. optional, default = ''
194 * @param string $allow_gid Permissions, allowed groups. optional, default = ''
195 * @param string $deny_cid Permissions, denied contacts.optional, default = ''
196 * @param string $deny_gid Permissions, denied greoup.optional, default = ''
198 * @return boolean|integer Row id on success, False on errors
199 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
201 public static function store(string $data, int $uid, string $filename, string $filetype = '' , int $filesize = null, string $allow_cid = '', string $allow_gid = '', string $deny_cid = '', string $deny_gid = '')
203 if ($filetype === '') {
204 $filetype = Mimetype::getContentType($filename);
207 if (is_null($filesize)) {
208 $filesize = strlen($data);
211 $backend_ref = DI::storage()->put($data);
214 $hash = System::createGUID(64);
215 $created = DateTimeFormat::utcNow();
220 'filename' => $filename,
221 'filetype' => $filetype,
222 'filesize' => $filesize,
224 'created' => $created,
225 'edited' => $created,
226 'allow_cid' => $allow_cid,
227 'allow_gid' => $allow_gid,
228 'deny_cid' => $deny_cid,
229 'deny_gid' => $deny_gid,
230 'backend-class' => (string)DI::storage(),
231 'backend-ref' => $backend_ref
234 $r = DBA::insert('attach', $fields);
236 return DBA::lastInsertId();
242 * Store new file metadata in db and binary in default backend from existing file
244 * @param string $src Source file name
245 * @param int $uid User id
246 * @param string $filename Optional file name
247 * @param string $allow_cid
248 * @param string $allow_gid
249 * @param string $deny_cid
250 * @param string $deny_gid
251 * @return boolean|int Insert id or false on failure
252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 public static function storeFile(string $src, int $uid, string $filename = '', string $allow_cid = '', string $allow_gid = '', string $deny_cid = '', string $deny_gid = '')
256 if ($filename === '') {
257 $filename = basename($src);
260 $data = @file_get_contents($src);
262 return self::store($data, $uid, $filename, '', null, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
267 * Update an attached file
269 * @param array $fields Contains the fields that are updated
270 * @param array $conditions Condition array with the key values
271 * @param Image $img Image data to update. Optional, default null.
272 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
274 * @return boolean Was the update successful?
276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
277 * @see \Friendica\Database\DBA::update
279 public static function update(array $fields, array $conditions, Image $img = null, array $old_fields = []): bool
281 if (!is_null($img)) {
282 // get items to update
283 $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
285 foreach($items as $item) {
287 $backend_class = DI::storageManager()->getWritableStorageByName($item['backend-class'] ?? '');
288 $fields['backend-ref'] = $backend_class->put($img->asString(), $item['backend-ref'] ?? '');
289 } catch (InvalidClassStorageException $storageException) {
290 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
291 } catch (ReferenceStorageException $referenceStorageException) {
292 DI::logger()->debug('Item doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
297 $fields['edited'] = DateTimeFormat::utcNow();
299 return DBA::update('attach', $fields, $conditions, $old_fields);
304 * Delete info from table and data from storage
306 * @param array $conditions Field condition(s)
307 * @param array $options Options array, Optional
312 * @see \Friendica\Database\DBA::delete
314 public static function delete(array $conditions, array $options = []): bool
316 // get items to delete data info
317 $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
319 foreach($items as $item) {
321 $backend_class = DI::storageManager()->getWritableStorageByName($item['backend-class'] ?? '');
322 $backend_class->delete($item['backend-ref'] ?? '');
323 } catch (InvalidClassStorageException $storageException) {
324 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
325 } catch (ReferenceStorageException $referenceStorageException) {
326 DI::logger()->debug('Item doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
330 return DBA::delete('attach', $conditions, $options);