]> git.mxchange.org Git - friendica.git/blob - src/Model/Attach.php
ac8bca07f1f2f5c876a550d60883e79c7243892c
[friendica.git] / src / Model / Attach.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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\Database\DBStructure;
27 use Friendica\DI;
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;
33
34 /**
35  * Class to handle attach dabatase 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()
47         {
48                 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
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
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)
105         {
106                 return DBA::exists('attach', $conditions);
107         }
108
109         /**
110          * Retrive 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($id)
120         {
121                 return self::selectFirst([], ['id' => $id]);
122         }
123
124         /**
125          * Retrive 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($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  file data
159          * @throws \Exception
160          */
161         public static function getData($item)
162         {
163                 if (!empty($item['data'])) {
164                         return $item['data'];
165                 }
166
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']]);
171                         if ($i === false) {
172                                 return null;
173                         }
174                         return $i['data'];
175                 } else {
176                         $backendRef = $item['backend-ref'];
177                         try {
178                                 return $backendClass->get($backendRef);
179                         } catch (ReferenceStorageException $referenceStorageException) {
180                                 DI::logger()->debug('No data found for item', ['item' => $item, 'exception' => $referenceStorageException]);
181                                 return '';
182                         }
183                 }
184         }
185
186         /**
187          * Store new file metadata in db and binary in default backend
188          *
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 = ''
198          *
199          * @return boolean/integer Row id on success, False on errors
200          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
201          */
202         public static function store($data, $uid, $filename, $filetype = '' , $filesize = null, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '')
203         {
204                 if ($filetype === '') {
205                         $filetype = Mimetype::getContentType($filename);
206                 }
207
208                 if (is_null($filesize)) {
209                         $filesize = strlen($data);
210                 }
211
212                 $backend_ref = DI::storage()->put($data);
213                 $data = '';
214
215                 $hash = System::createGUID(64);
216                 $created = DateTimeFormat::utcNow();
217
218                 $fields = [
219                         'uid' => $uid,
220                         'hash' => $hash,
221                         'filename' => $filename,
222                         'filetype' => $filetype,
223                         'filesize' => $filesize,
224                         'data' => $data,
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
233                 ];
234
235                 $r = DBA::insert('attach', $fields);
236                 if ($r === true) {
237                         return DBA::lastInsertId();
238                 }
239                 return $r;
240         }
241
242         /**
243          * Store new file metadata in db and binary in default backend from existing file
244          *
245          * @param        $src
246          * @param        $uid
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
254          */
255         public static function storeFile($src, $uid, $filename = '', $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '')
256         {
257                 if ($filename === '') {
258                         $filename = basename($src);
259                 }
260
261                 $data = @file_get_contents($src);
262
263                 return self::store($data, $uid, $filename, '', null, $allow_cid, $allow_gid,  $deny_cid, $deny_gid);
264         }
265
266
267         /**
268          * Update an attached file
269          *
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)
274          *
275          * @return boolean  Was the update successful?
276          *
277          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
278          * @see   \Friendica\Database\DBA::update
279          */
280         public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
281         {
282                 if (!is_null($img)) {
283                         // get items to update
284                         $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
285
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'] ?? '');
290                                 } else {
291                                         $fields['data'] = $img->asString();
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 = [])
314         {
315                 // get items to delete data info
316                 $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
317
318                 foreach($items as $item) {
319                         $backend_class = DI::storageManager()->getWritableStorageByName($item['backend-class'] ?? '');
320                         if (!empty($backend_class)) {
321                                 try {
322                                         $backend_class->delete($item['backend-ref'] ?? '');
323                                 } catch (ReferenceStorageException $referenceStorageException) {
324                                         DI::logger()->debug('Item doesn\'t exist.', ['conditions' => $conditions, 'exception' => $referenceStorageException]);
325                                 }
326                         }
327                 }
328
329                 return DBA::delete('attach', $conditions, $options);
330         }
331 }