3 * @copyright Copyright (C) 2010-2021, 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\Model\Storage\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 dabatase table
41 * Return a list of fields that are associated with the attach table
43 * @return array field list
46 private static function getFields()
48 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
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)
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($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($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 file data
161 public static function getData($item)
163 if (!empty($item['data'])) {
164 return $item['data'];
167 $backendClass = DI::storageManager()->getByName($item['backend-class'] ?? '');
168 if (empty($backendClass)) {
169 // legacy data storage in 'data' column
170 $i = self::selectFirst(['data'], ['id' => $item['id']]);
176 $backendRef = $item['backend-ref'];
178 return $backendClass->get($backendRef);
179 } catch (ReferenceStorageException $referenceStorageException) {
180 DI::logger()->debug('No data found for item', ['item' => $item, 'exception' => $referenceStorageException]);
187 * Store new file metadata in db and binary in default backend
189 * @param string $data Binary data
190 * @param integer $uid User ID
191 * @param string $filename Filename
192 * @param string $filetype Mimetype. optional, default = ''
193 * @param integer $filesize File size in bytes. optional, default = null
194 * @param string $allow_cid Permissions, allowed contacts. optional, default = ''
195 * @param string $allow_gid Permissions, allowed groups. optional, default = ''
196 * @param string $deny_cid Permissions, denied contacts.optional, default = ''
197 * @param string $deny_gid Permissions, denied greoup.optional, default = ''
199 * @return boolean/integer Row id on success, False on errors
200 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
202 public static function store($data, $uid, $filename, $filetype = '' , $filesize = null, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '')
204 if ($filetype === '') {
205 $filetype = Mimetype::getContentType($filename);
208 if (is_null($filesize)) {
209 $filesize = strlen($data);
212 $backend_ref = DI::storage()->put($data);
215 $hash = System::createGUID(64);
216 $created = DateTimeFormat::utcNow();
221 'filename' => $filename,
222 'filetype' => $filetype,
223 'filesize' => $filesize,
225 'created' => $created,
226 'edited' => $created,
227 'allow_cid' => $allow_cid,
228 'allow_gid' => $allow_gid,
229 'deny_cid' => $deny_cid,
230 'deny_gid' => $deny_gid,
231 'backend-class' => (string)DI::storage(),
232 'backend-ref' => $backend_ref
235 $r = DBA::insert('attach', $fields);
237 return DBA::lastInsertId();
243 * Store new file metadata in db and binary in default backend from existing file
247 * @param string $filename
248 * @param string $allow_cid
249 * @param string $allow_gid
250 * @param string $deny_cid
251 * @param string $deny_gid
252 * @return boolean True on success
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 public static function storeFile($src, $uid, $filename = '', $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '')
257 if ($filename === '') {
258 $filename = basename($src);
261 $data = @file_get_contents($src);
263 return self::store($data, $uid, $filename, '', null, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
268 * Update an attached file
270 * @param array $fields Contains the fields that are updated
271 * @param array $conditions Condition array with the key values
272 * @param Image $img Image data to update. Optional, default null.
273 * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
275 * @return boolean Was the update successful?
277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
278 * @see \Friendica\Database\DBA::update
280 public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
282 if (!is_null($img)) {
283 // get items to update
284 $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
286 foreach($items as $item) {
287 $backend_class = DI::storageManager()->getWritableStorageByName($item['backend-class'] ?? '');
288 if (!empty($backend_class)) {
289 $fields['backend-ref'] = $backend_class->put($img->asString(), $item['backend-ref'] ?? '');
291 $fields['data'] = $img->asString();
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 = [])
315 // get items to delete data info
316 $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
318 foreach($items as $item) {
319 $backend_class = DI::storageManager()->getWritableStorageByName($item['backend-class'] ?? '');
320 if (!empty($backend_class)) {
322 $backend_class->delete($item['backend-ref'] ?? '');
323 } catch (ReferenceStorageException $referenceStorageException) {
324 DI::logger()->debug('Item doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
329 return DBA::delete('attach', $conditions, $options);