3 * @copyright Copyright (C) 2010-2023, 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;
27 use Friendica\Core\Storage\Exception\InvalidClassStorageException;
28 use Friendica\Core\Storage\Exception\ReferenceStorageException;
29 use Friendica\Object\Image;
30 use Friendica\Util\DateTimeFormat;
31 use Friendica\Util\Mimetype;
32 use Friendica\Security\Security;
35 * Class to handle attach database table
41 * Return a list of fields that are associated with the attach table
43 * @return array field list
46 private static function getFields(): array
48 $allfields = DI::dbaDefinition()->getAll();
49 $fields = array_keys($allfields['attach']['fields']);
50 array_splice($fields, array_search('data', $fields), 1);
55 * Select rows from the attach table and return them as array
57 * @param array $fields Array of selected fields, empty for all
58 * @param array $conditions Array of fields for conditions
59 * @param array $params Array of several parameters
64 * @see \Friendica\Database\DBA::selectToArray
66 public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
69 $fields = self::getFields();
72 return DBA::selectToArray('attach', $fields, $conditions, $params);
76 * Retrieve a single record from the attach table
78 * @param array $fields Array of selected fields, empty for all
79 * @param array $conditions Array of fields for conditions
80 * @param array $params Array of several parameters
85 * @see \Friendica\Database\DBA::select
87 public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
90 $fields = self::getFields();
93 return DBA::selectFirst('attach', $fields, $conditions, $params);
97 * Check if attachment with given conditions exists
99 * @param array $conditions Array of extra conditions
104 public static function exists(array $conditions): bool
106 return DBA::exists('attach', $conditions);
110 * Retrive a single record given the ID
112 * @param int $id Row id of the record
117 * @see \Friendica\Database\DBA::select
119 public static function getById(int $id)
121 return self::selectFirst([], ['id' => $id]);
125 * Retrive a single record given the ID
127 * @param int $id Row id of the record
132 * @see \Friendica\Database\DBA::select
134 public static function getByIdWithPermission(int $id)
136 $r = self::selectFirst(['uid'], ['id' => $id]);
141 $sql_acl = Security::getPermissionsSQLByUserId($r['uid']);
144 '`id` = ?' . $sql_acl,
148 $item = self::selectFirst([], $conditions);
154 * Get file data for given row id. null if row id does not exist
156 * @param array $item Attachment data. Needs at least 'id', 'backend-class', 'backend-ref'
158 * @return string|null file data or null on failure
161 public static function getData(array $item)
163 if (!empty($item['data'])) {
164 return $item['data'];
168 $backendClass = DI::storageManager()->getByName($item['backend-class'] ?? '');
169 $backendRef = $item['backend-ref'];
170 return $backendClass->get($backendRef);
171 } catch (InvalidClassStorageException $storageException) {
172 // legacy data storage in 'data' column
173 $i = self::selectFirst(['data'], ['id' => $item['id']]);
178 } catch (ReferenceStorageException $referenceStorageException) {
179 DI::logger()->debug('No data found for item', ['item' => $item, 'exception' => $referenceStorageException]);
185 * Store new file metadata in db and binary in default backend
187 * @param string $data Binary data
188 * @param integer $uid User ID
189 * @param string $filename Filename
190 * @param string $filetype Mimetype. optional, default = ''
191 * @param integer $filesize File size in bytes. optional, default = null
192 * @param string $allow_cid Permissions, allowed contacts. optional, default = ''
193 * @param string $allow_gid Permissions, allowed groups. optional, default = ''
194 * @param string $deny_cid Permissions, denied contacts.optional, default = ''
195 * @param string $deny_gid Permissions, denied group.optional, default = ''
197 * @return boolean|integer Row id on success, False on errors
198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
200 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 = '')
202 if ($filetype === '') {
203 $filetype = Mimetype::getContentType($filename);
206 if (is_null($filesize)) {
207 $filesize = strlen($data);
210 $backend_ref = DI::storage()->put($data);
213 $hash = System::createGUID(64);
214 $created = DateTimeFormat::utcNow();
219 'filename' => $filename,
220 'filetype' => $filetype,
221 'filesize' => $filesize,
223 'created' => $created,
224 'edited' => $created,
225 'allow_cid' => $allow_cid,
226 'allow_gid' => $allow_gid,
227 'deny_cid' => $deny_cid,
228 'deny_gid' => $deny_gid,
229 'backend-class' => (string)DI::storage(),
230 'backend-ref' => $backend_ref
233 $r = DBA::insert('attach', $fields);
235 return DBA::lastInsertId();
241 * Store new file metadata in db and binary in default backend from existing file
243 * @param string $src Source file name
244 * @param int $uid User id
245 * @param string $filename Optional file name
246 * @param string $allow_cid
247 * @param string $allow_gid
248 * @param string $deny_cid
249 * @param string $deny_gid
250 * @return boolean|int Insert id or false on failure
251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
253 public static function storeFile(string $src, int $uid, string $filename = '', string $allow_cid = '', string $allow_gid = '', string $deny_cid = '', string $deny_gid = '')
255 if ($filename === '') {
256 $filename = basename($src);
259 $data = @file_get_contents($src);
261 return self::store($data, $uid, $filename, '', null, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
266 * Update an attached file
268 * @param array $fields Contains the fields that are updated
269 * @param array $conditions Condition array with the key values
270 * @param Image $img Image data to update. Optional, default null.
271 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
273 * @return boolean Was the update successful?
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 * @see \Friendica\Database\DBA::update
278 public static function update(array $fields, array $conditions, Image $img = null, array $old_fields = []): bool
280 if (!is_null($img)) {
281 // get items to update
282 $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
284 foreach($items as $item) {
286 $backend_class = DI::storageManager()->getWritableStorageByName($item['backend-class'] ?? '');
287 $fields['backend-ref'] = $backend_class->put($img->asString(), $item['backend-ref'] ?? '');
288 } catch (InvalidClassStorageException $storageException) {
289 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
290 } catch (ReferenceStorageException $referenceStorageException) {
291 DI::logger()->debug('Item doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
296 $fields['edited'] = DateTimeFormat::utcNow();
298 return DBA::update('attach', $fields, $conditions, $old_fields);
303 * Delete info from table and data from storage
305 * @param array $conditions Field condition(s)
306 * @param array $options Options array, Optional
311 * @see \Friendica\Database\DBA::delete
313 public static function delete(array $conditions, array $options = []): bool
315 // get items to delete data info
316 $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
318 foreach($items as $item) {
320 $backend_class = DI::storageManager()->getWritableStorageByName($item['backend-class'] ?? '');
321 $backend_class->delete($item['backend-ref'] ?? '');
322 } catch (InvalidClassStorageException $storageException) {
323 DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
324 } catch (ReferenceStorageException $referenceStorageException) {
325 DI::logger()->debug('Item doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
329 return DBA::delete('attach', $conditions, $options);