]> git.mxchange.org Git - friendica.git/blob - src/Model/Attach.php
Merge pull request #8148 from annando/remote-comment
[friendica.git] / src / Model / Attach.php
1 <?php
2
3 /**
4  * @file src/Model/Attach.php
5  * This file contains the Attach class for database interface
6  */
7 namespace Friendica\Model;
8
9 use Friendica\Core\System;
10 use Friendica\Database\DBA;
11 use Friendica\Database\DBStructure;
12 use Friendica\DI;
13 use Friendica\Object\Image;
14 use Friendica\Util\DateTimeFormat;
15 use Friendica\Util\Mimetype;
16 use Friendica\Util\Security;
17
18 /**
19  * Class to handle attach dabatase table
20  */
21 class Attach
22 {
23
24         /**
25          * Return a list of fields that are associated with the attach table
26          *
27          * @return array field list
28          * @throws \Exception
29          */
30         private static function getFields()
31         {
32                 $allfields = DBStructure::definition(DI::app()->getBasePath(), false);
33                 $fields = array_keys($allfields['attach']['fields']);
34                 array_splice($fields, array_search('data', $fields), 1);
35                 return $fields;
36         }
37
38         /**
39          * Select rows from the attach table and return them as array
40          *
41          * @param array $fields     Array of selected fields, empty for all
42          * @param array $conditions Array of fields for conditions
43          * @param array $params     Array of several parameters
44          *
45          * @return array
46          *
47          * @throws \Exception
48          * @see   \Friendica\Database\DBA::selectToArray
49          */
50         public static function selectToArray(array $fields = [], array $conditions = [], array $params = [])
51         {
52                 if (empty($fields)) {
53                         $fields = self::getFields();
54                 }
55
56                 return DBA::selectToArray('attach', $fields, $conditions, $params);
57         }
58
59         /**
60          * Retrieve a single record from the attach table
61          *
62          * @param array $fields     Array of selected fields, empty for all
63          * @param array $conditions Array of fields for conditions
64          * @param array $params     Array of several parameters
65          *
66          * @return bool|array
67          *
68          * @throws \Exception
69          * @see   \Friendica\Database\DBA::select
70          */
71         public static function selectFirst(array $fields = [], array $conditions = [], array $params = [])
72         {
73                 if (empty($fields)) {
74                         $fields = self::getFields();
75                 }
76
77                 return DBA::selectFirst('attach', $fields, $conditions, $params);
78         }
79
80         /**
81          * Check if attachment with given conditions exists
82          *
83          * @param array $conditions Array of extra conditions
84          *
85          * @return boolean
86          * @throws \Exception
87          */
88         public static function exists(array $conditions)
89         {
90                 return DBA::exists('attach', $conditions);
91         }
92
93         /**
94          * Retrive a single record given the ID
95          *
96          * @param int $id Row id of the record
97          *
98          * @return bool|array
99          *
100          * @throws \Exception
101          * @see   \Friendica\Database\DBA::select
102          */
103         public static function getById($id)
104         {
105                 return self::selectFirst([], ['id' => $id]);
106         }
107
108         /**
109          * Retrive a single record given the ID
110          *
111          * @param int $id Row id of the record
112          *
113          * @return bool|array
114          *
115          * @throws \Exception
116          * @see   \Friendica\Database\DBA::select
117          */
118         public static function getByIdWithPermission($id)
119         {
120                 $r = self::selectFirst(['uid'], ['id' => $id]);
121                 if ($r === false) {
122                         return false;
123                 }
124
125                 $sql_acl = Security::getPermissionsSQLByUserId($r['uid']);
126
127                 $conditions = [
128                         '`id` = ?' . $sql_acl,
129                         $id
130                 ];
131
132                 $item = self::selectFirst([], $conditions);
133
134                 return $item;
135         }
136
137         /**
138          * Get file data for given row id. null if row id does not exist
139          *
140          * @param array $item Attachment data. Needs at least 'id', 'backend-class', 'backend-ref'
141          *
142          * @return string  file data
143          * @throws \Exception
144          */
145         public static function getData($item)
146         {
147                 $backendClass = DI::storageManager()->getByName($photo['backend-class'] ?? '');
148                 if ($backendClass === null) {
149                         // legacy data storage in 'data' column
150                         $i = self::selectFirst(['data'], ['id' => $item['id']]);
151                         if ($i === false) {
152                                 return null;
153                         }
154                         return $i['data'];
155                 } else {
156                         $backendRef = $item['backend-ref'];
157                         return $backendClass->get($backendRef);
158                 }
159         }
160
161         /**
162          * Store new file metadata in db and binary in default backend
163          *
164          * @param string  $data      Binary data
165          * @param integer $uid       User ID
166          * @param string  $filename  Filename
167          * @param string  $filetype  Mimetype. optional, default = ''
168          * @param integer $filesize  File size in bytes. optional, default = null
169          * @param string  $allow_cid Permissions, allowed contacts. optional, default = ''
170          * @param string  $allow_gid Permissions, allowed groups. optional, default = ''
171          * @param string  $deny_cid  Permissions, denied contacts.optional, default = ''
172          * @param string  $deny_gid  Permissions, denied greoup.optional, default = ''
173          *
174          * @return boolean/integer Row id on success, False on errors
175          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
176          */
177         public static function store($data, $uid, $filename, $filetype = '' , $filesize = null, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '')
178         {
179                 if ($filetype === '') {
180                         $filetype = Mimetype::getContentType($filename);
181                 }
182
183                 if (is_null($filesize)) {
184                         $filesize = strlen($data);
185                 }
186
187                 $backend_ref = DI::storage()->put($data);
188                 $data = '';
189
190                 $hash = System::createGUID(64);
191                 $created = DateTimeFormat::utcNow();
192
193                 $fields = [
194                         'uid' => $uid,
195                         'hash' => $hash,
196                         'filename' => $filename,
197                         'filetype' => $filetype,
198                         'filesize' => $filesize,
199                         'data' => $data,
200                         'created' => $created,
201                         'edited' => $created,
202                         'allow_cid' => $allow_cid,
203                         'allow_gid' => $allow_gid,
204                         'deny_cid' => $deny_cid,
205                         'deny_gid' => $deny_gid,
206                         'backend-class' => (string)DI::storage(),
207                         'backend-ref' => $backend_ref
208                 ];
209
210                 $r = DBA::insert('attach', $fields);
211                 if ($r === true) {
212                         return DBA::lastInsertId();
213                 }
214                 return $r;
215         }
216
217         /**
218          * Store new file metadata in db and binary in default backend from existing file
219          *
220          * @param        $src
221          * @param        $uid
222          * @param string $filename
223          * @param string $allow_cid
224          * @param string $allow_gid
225          * @param string $deny_cid
226          * @param string $deny_gid
227          * @return boolean True on success
228          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
229          */
230         public static function storeFile($src, $uid, $filename = '', $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '')
231         {
232                 if ($filename === '') {
233                         $filename = basename($src);
234                 }
235
236                 $data = @file_get_contents($src);
237
238                 return self::store($data, $uid, $filename, '', null, $allow_cid, $allow_gid,  $deny_cid, $deny_gid);
239         }
240
241
242         /**
243          * Update an attached file
244          *
245          * @param array         $fields     Contains the fields that are updated
246          * @param array         $conditions Condition array with the key values
247          * @param Image         $img        Image data to update. Optional, default null.
248          * @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
249          *
250          * @return boolean  Was the update successful?
251          *
252          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
253          * @see   \Friendica\Database\DBA::update
254          */
255         public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
256         {
257                 if (!is_null($img)) {
258                         // get items to update
259                         $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
260
261                         foreach($items as $item) {
262                                 $backend_class = DI::storageManager()->getByName($item['backend-class'] ?? '');
263                                 if ($backend_class !== null) {
264                                         $fields['backend-ref'] = $backend_class->put($img->asString(), $item['backend-ref'] ?? '');
265                                 } else {
266                                         $fields['data'] = $img->asString();
267                                 }
268                         }
269                 }
270
271                 $fields['edited'] = DateTimeFormat::utcNow();
272
273                 return DBA::update('attach', $fields, $conditions, $old_fields);
274         }
275
276
277         /**
278          * Delete info from table and data from storage
279          *
280          * @param array $conditions Field condition(s)
281          * @param array $options    Options array, Optional
282          *
283          * @return boolean
284          *
285          * @throws \Exception
286          * @see   \Friendica\Database\DBA::delete
287          */
288         public static function delete(array $conditions, array $options = [])
289         {
290                 // get items to delete data info
291                 $items = self::selectToArray(['backend-class','backend-ref'], $conditions);
292
293                 foreach($items as $item) {
294                         $backend_class = DI::storageManager()->getByName($item['backend-class'] ?? '');
295                         if ($backend_class !== null) {
296                                 $backend_class->delete($item['backend-ref'] ?? '');
297                         }
298                 }
299
300                 return DBA::delete('attach', $conditions, $options);
301         }
302 }