]> git.mxchange.org Git - friendica.git/blob - src/Model/Attach.php
Language selector added, "channel" is now "channels"
[friendica.git] / src / Model / Attach.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use Friendica\Core\System;
25 use Friendica\Database\DBA;
26 use Friendica\DI;
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;
33
34 /**
35  * Class to handle attach database table
36  */
37 class Attach
38 {
39
40         /**
41          * Return a list of fields that are associated with the attach table
42          *
43          * @return array field list
44          * @throws \Exception
45          */
46         private static function getFields(): array
47         {
48                 $allfields = DI::dbaDefinition()->getAll();
49                 $fields = array_keys($allfields['attach']['fields']);
50                 array_splice($fields, array_search('data', $fields), 1);
51                 return $fields;
52         }
53
54         /**
55          * Select rows from the attach table and return them as array
56          *
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
60          *
61          * @return array|bool
62          *
63          * @throws \Exception
64          * @see   \Friendica\Database\DBA::selectToArray
65          */
66         public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
67         {
68                 if (empty($fields)) {
69                         $fields = self::getFields();
70                 }
71
72                 return DBA::selectToArray('attach', $fields, $conditions, $params);
73         }
74
75         /**
76          * Retrieve a single record from the attach table
77          *
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
81          *
82          * @return bool|array
83          *
84          * @throws \Exception
85          * @see   \Friendica\Database\DBA::select
86          */
87         public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
88         {
89                 if (empty($fields)) {
90                         $fields = self::getFields();
91                 }
92
93                 return DBA::selectFirst('attach', $fields, $conditions, $params);
94         }
95
96         /**
97          * Check if attachment with given conditions exists
98          *
99          * @param array $conditions Array of extra conditions
100          *
101          * @return boolean
102          * @throws \Exception
103          */
104         public static function exists(array $conditions): bool
105         {
106                 return DBA::exists('attach', $conditions);
107         }
108
109         /**
110          * Retrieve a single record given the ID
111          *
112          * @param int $id Row id of the record
113          *
114          * @return bool|array
115          *
116          * @throws \Exception
117          * @see   \Friendica\Database\DBA::select
118          */
119         public static function getById(int $id)
120         {
121                 return self::selectFirst([], ['id' => $id]);
122         }
123
124         /**
125          * Retrieve a single record given the ID
126          *
127          * @param int $id Row id of the record
128          *
129          * @return bool|array
130          *
131          * @throws \Exception
132          * @see   \Friendica\Database\DBA::select
133          */
134         public static function getByIdWithPermission(int $id)
135         {
136                 $r = self::selectFirst(['uid'], ['id' => $id]);
137                 if ($r === false) {
138                         return false;
139                 }
140
141                 $sql_acl = Security::getPermissionsSQLByUserId($r['uid']);
142
143                 $conditions = [
144                         '`id` = ?' . $sql_acl,
145                         $id
146                 ];
147
148                 $item = self::selectFirst([], $conditions);
149
150                 return $item;
151         }
152
153         /**
154          * Get file data for given row id. null if row id does not exist
155          *
156          * @param array $item Attachment data. Needs at least 'id', 'backend-class', 'backend-ref'
157          *
158          * @return string|null file data or null on failure
159          * @throws \Exception
160          */
161         public static function getData(array $item)
162         {
163                 if (!empty($item['data'])) {
164                         return $item['data'];
165                 }
166
167                 try {
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']]);
174                         if ($i === false) {
175                                 return null;
176                         }
177                         return $i['data'];
178                 } catch (ReferenceStorageException $referenceStorageException) {
179                         DI::logger()->debug('No data found for item', ['item' => $item, 'exception' => $referenceStorageException]);
180                         return '';
181                 }
182         }
183
184         /**
185          * Store new file metadata in db and binary in default backend
186          *
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 circles. optional, default = ''
194          * @param string  $deny_cid  Permissions, denied contacts. optional, default = ''
195          * @param string  $deny_gid  Permissions, denied circle. optional, default = ''
196          *
197          * @return boolean|integer Row id on success, False on errors
198          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
199          */
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 = '')
201         {
202                 if ($filetype === '') {
203                         $filetype = Mimetype::getContentType($filename);
204                 }
205
206                 if (is_null($filesize)) {
207                         $filesize = strlen($data);
208                 }
209
210                 $backend_ref = DI::storage()->put($data);
211                 $data = '';
212
213                 $hash = System::createGUID(64);
214                 $created = DateTimeFormat::utcNow();
215
216                 $fields = [
217                         'uid' => $uid,
218                         'hash' => $hash,
219                         'filename' => $filename,
220                         'filetype' => $filetype,
221                         'filesize' => $filesize,
222                         'data' => $data,
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
231                 ];
232
233                 $r = DBA::insert('attach', $fields);
234                 if ($r === true) {
235                         return DBA::lastInsertId();
236                 }
237                 return $r;
238         }
239
240         /**
241          * Store new file metadata in db and binary in default backend from existing file
242          *
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
252          */
253         public static function storeFile(string $src, int $uid, string $filename = '', string $allow_cid = '', string $allow_gid = '', string $deny_cid = '', string $deny_gid = '')
254         {
255                 if ($filename === '') {
256                         $filename = basename($src);
257                 }
258
259                 $data = @file_get_contents($src);
260
261                 return self::store($data, $uid, $filename, '', null, $allow_cid, $allow_gid,  $deny_cid, $deny_gid);
262         }
263
264
265         /**
266          * Update an attached file
267          *
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)
272          *
273          * @return boolean  Was the update successful?
274          *
275          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276          * @see   \Friendica\Database\DBA::update
277          */
278         public static function update(array $fields, array $conditions, Image $img = null, array $old_fields = []): bool
279         {
280                 if (!is_null($img)) {
281                         // get items to update
282                         $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
283
284                         foreach($items as $item) {
285                                 try {
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]);
292                                 }
293                         }
294                 }
295
296                 $fields['edited'] = DateTimeFormat::utcNow();
297
298                 return DBA::update('attach', $fields, $conditions, $old_fields);
299         }
300
301
302         /**
303          * Delete info from table and data from storage
304          *
305          * @param array $conditions Field condition(s)
306          * @param array $options    Options array, Optional
307          *
308          * @return boolean
309          *
310          * @throws \Exception
311          * @see   \Friendica\Database\DBA::delete
312          */
313         public static function delete(array $conditions, array $options = []): bool
314         {
315                 // get items to delete data info
316                 $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
317
318                 foreach($items as $item) {
319                         try {
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]);
326                         }
327                 }
328
329                 return DBA::delete('attach', $conditions, $options);
330         }
331 }